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
25398d42ccf4a9919e3ba36663fb11eb6d198031
710bd922d612840b3dc64bd7c64d4eefe62d50f0
/scheme/scheme-posix/file.scm
51e3d5366f15b463beaf592885ee9df8e5af09f1
[ "MIT" ]
permissive
prefics/scheme
66c74b93852f2dfafd4a95e04cf5ec6b06057e16
ae615dffa7646c75eaa644258225913e567ff4fb
refs/heads/master
2023-08-23T07:27:02.254472
2023-08-12T06:47:59
2023-08-12T06:47:59
149,110,586
0
0
null
null
null
null
UTF-8
Scheme
false
false
11,688
scm
file.scm
;; file.scm -- file management functions ;;; ;; = File management procedure ;;; ;;; ;; Create a directory on the file system. `name` specifies the name of ;; the directory and `mode` defined the file mode to give to the directory. (define (create-directory! name mode) (let ((errno (with-process-aligned (lambda () (posix-mkdir name mode))))) errno)) ;;; ;; Create a FIFO on the file system. `name` specifies the name of the ;; FIFO file and `perm` specifies the permission of the created FIFO file. (define (create-fifo! name perm) (with-process-aligned (lambda () (posix-mknod name perm)))) ;;; ;; Create a hard link on the file system. `old-name` defines the file ;; pointed to by the hard link. `new-name` defines the name of the ;; created hard link file. (define (create-hard-link old-name new-name . override?) #f) ;;; ;; Create a symbolic link on the file system. `old-name` defines the ;; file pointed to by the symbolic link. `new-name` defines the name ;; of the created symbolic link file. (define (create-symlink! old-name new-name . override?) (let ((error? (with-process-aligned (lambda () (%posix-symlink old-name new-name))))) (if error? (error "Error ~a when creating symlink ~a to ~a" error? new-name old-name) error?))) ;;; ;; Deletes a the directory `name` from the file system. Note that ;; `name` should refer to a directory file. (define (delete-directory! name) (let ((errno (with-process-aligned (lambda () (posix-rmdir name))))) errno)) ;;; ;; Deletes the file pointed to by `name` from the file system. Note ;; that `name` should refer to a regular file. (define (delete-file! name) (let ((errno (with-process-aligned (lambda () (posix-unlink name))))) errno)) ;;; ;; Deletes the file pointed to by `name` without regards for its type ;; (directory or otherwise). (define (delete-filesys-object! name) #f) ;;; ;; Returns the file pointed to by the symbolic link file named `name`. (define (read-symlink name) (let ((errno? (with-process-aligned (lambda () (%posix-readlink name))))) (if (number? error?) (error "Error ~a reading symlink value for ~a" errno? name) errno?))) ;;; ;; Rename a file on the file system. `old-name` refers to the actual ;; name and `new-name` defines the new name of the file. (define (rename-file! old-name new-name) (let ((errno (with-process-aligned (lambda () (posix-rename old-name new-name))))) errno)) ;;; ;; Sets the file mode, given as `mode` on the file named `name`. (define (set-file-mode! name mode) (let ((errno (with-process-aligned (lambda () (posix-chmod name mode))))) errno)) ;;; ;; Sets the owner, given by its user id `uid` of the file pointed to ;; by `name`. (define (set-file-owner! name uid) (let ((errno (with-process-aligned (lambda () (posix-chown name uid (- 2 3)))))) errno)) ;;; ;; Sets the group, given by its group id `gid`, of the file pointed to ;; by `name`. (define (set-file-group! name gid) (let ((errno (with-process-aligned (lambda () (posix-chown name (- 2 3) gid))))) errno)) ;;; ;; Sets the file times associated with the file `name`. `access-time` ;; is the time to set for the last access time associated with the ;; file. `mod-time` is the time to set for the last modification time ;; associated with the file. (define (set-file-time! name &opt access-time mod-time) (with-process-aligned (lambda () (posix-utime name access-time mod-time)))) ;;; ;; Sync the file associated with the specified `port`. (define (sync-file! port) (if (channel-port? port) (let ((errno (posix-sync (channel-port-channel port)))) errno) (error "PORT in not a channel port"))) ;;; ;; Sync the complete file system on the machine. (define (sync-file-system!) #f) ;;; ;; Truncate the length of the file refered to by `name` to the ;; specified length `len` (define (truncate-file! name len) (let ((errno (with-process-aligned (lambda () (posix-truncate name len))))) errno)) ;;; ;; == File information ;;; ;; A record containing all information associated with a file. (define-record-type <file-info> (make-file-info type device inode mode nlinks uid gid size atime mtime ctime) file-info? (type file-info-type set-file-info-type!) (device file-info-device) (inode file-info-inode) (mode file-info-mode) (nlinks file-info-nlinks) (uid file-info-uid) (gid file-info-gid) (size file-info-size) (atime file-info-atime) (mtime file-info-mtime) (ctime file-info-ctime)) ;;; ;; Returns a `file-info` record of the file refered to by `name`. If ;; `name` does not exist, an error is raised. (define (file-info name . chase?) (let ((fileinfo (with-process-aligned (lambda () (posix-stat name (make-file-info #f #f #f #f #f #f #f #f #f #f #f)))))) (if (eq? fileinfo 2) (error "File does not exist" name) fileinfo))) ;; @todo should check for existence and accessibility of FILE-NAME ;;; ;; Returns the type of the file pointed to by `file-name`. (define (file-type file-name) (file-info-type (file-info file-name))) ;;; ;; Returns the device associated with the file pointed to by ;; `file-name`. (define (file-device file-name) (file-info-device (file-info file-name))) ;;; ;; Returns the device associated with the file pointed to by ;; `file-name`. (define (file-inode file-name) (file-info-inode (file-info file-name))) ;;; ;; Returns the mode associated with the file pointed to by ;; `file-name`. (define (file-mode file-name) (file-info-mode (file-info file-name))) ;;; ;; Returns the number of hard link associated with the file pointed to ;; by `file-name`. (define (file-nlinks file-name) (file-info-nlinks (file-info file-name))) ;;; ;; Returns the user id associated with the file pointed to by ;; `file-name`. (define (file-uid file-name) (file-info-uid (file-info file-name))) ;;; ;; Returns the group id associated with the file pointed to by ;; `file-name`. (define (file-gid file-name) (file-info-gid (file-info file-name))) ;;; ;; Returns the size of the file pointed to by `file-name`. (define (file-size file-name) (file-info-size (file-info file-name))) ;;; ;; Returns the last file access time of the file pointed to by ;; `file-name`. (define (file-atime file-name) (file-info-atime (file-info file-name))) ;;; ;; Returns the last modification time of the file pointed to by ;; `file-name`. (define (file-mtime file-name) (file-info-mtime (file-info file-name))) ;;; ;; Returns the creation time of the file pointed to by `file-name`. (define (file-ctime file-name) (file-info-ctime (file-info file-name))) ;; @todo should check what file-mtime returns and check that < apply ;;; ;; returns true is file `f1` is newer than file `f2`. A file is newer ;; than another one if its last modification time is before the last ;; modification time of the other one. (define (file-newer? f1 f2) (< (file-mtime f1) (file-mtime f2))) ;;; ;; Returns `#t` if the file pointed to by `name` is a directory. (define (file-directory? name) (= $mode/directory (file-info-type (file-info name)))) ;;; ;; Returns `#t` if the file pointed to by `name` is a FIFO. (define (file-fifo? name) (= $mode/fifo (file-info-type (file-info name)))) ;;; ;; Returns `#t` if the file pointed to by `name` is a regular file. (define (file-regular? name) (= $mode/file (file-info-type (file-info name))));;; ;; Returns `#t` if the file pointed to by `name` is a socket (define (file-socket? name) (= $mode/socket (file-info-type (file-info name)))) ;;; ;; Returns `#t` if the file pointed to by `name` is a special file. (define (file-special? name) (= $mode/block (file-info-type (file-info name)))) ;;; ;; Returns `#t` if the file pointed to by `name` is a symbolic link. (define (file-symlink? name) (= $mode/link (file-info-type (file-info name)))) ;;; ;; Returns `#t` if file `name` is not readable. (define (file-not-readable? name) (not (file-readable? name))) ;;; ;; Returns `#t` if file `name` is not writable. (define (file-not-writable? name) (not (file-writable? name))) ;;; ;; Returns `#t` if file `name` is not executable. (define (file-not-executable? name) (not (file-executable? name))) ;;; ;; Returns `#t` if file `name` is readable (define (file-readable? name) (let ((ok? (with-process-aligned (lambda () (posix-access name $access/read))))) (if ok? #f #t))) ;;; ;; Returns `#t` if file `name` is writeable (define (file-writable? name) (let ((ok? (with-process-aligned (lambda () (posix-access name $access/write))))) (if ok? #f #t))) ;;; ;; Returns `#t` if file `name` is executable. (define (file-executable? name) (let ((ok? (with-process-aligned (lambda () (posix-access name $access/execute))))) (if ok? #f #t))) ;;; ;; Returns `#t` if file pointed to by `name` does not exist on the ;; file system. (define (file-not-exists? name . chase?) (not (file-exists? name))) ;;; ;; Returns `#t` if file pointed to by `name` already exists on the ;; file system. (define (file-exists? name . chase?) (let ((ok? (with-process-aligned (lambda () (posix-access name $access/exist))))) (if ok? #f #t))) ;; not particularly efficient ;;; ;; Returns the file contents of file named `file-name`. `file-name` ;; should ultimately be a file having a contens (not be a directory). (define (file-contents file-name) (if (file-readable? file-name) (let* ((len (file-info-size (file-info file-name))) (str (make-string len #\space))) (with-input-from-file file-name (lambda () (let fill ((i 0)) (if (< i len) (let ((ch (read-char))) (string-set! str i ch) (fill (+ i 1))) str))))) (error "file ~a not readable" file-name))) ;;; ;; == Directory information ;;; ;; Returns the list of file names contained in the directory named ;; `dir`. (define (directory-files dir) (let ((files (with-process-aligned (lambda () (posix-dirfiles (if (string=? dir "") "." dir)))))) (if (number? files) (error "error ~a in DIRECTORY-FILES" files) files))) ;;; ;; Returns a list of file name matching the different patterns ;; specified as `patterns`. (define (glob . patterns) #f) (define (globe-quote str) #f) (define (file-match root dot-files? . patterns) #f) ;;; ;; Creates a temporary file. `prefix` specifies the prefix of the name ;; of the file. Note the temporary file is created under `/tmp`. (define (create-temp-file! prefix) (posix-tempnam "/tmp" prefix)) (define (temp-file-iterate maker &opt template) #f) (define *temp-file-template* #f) (define (temp-file-channel) #f) ;;; ;; Executes the procedure specified by `thunk` with a new temporary ;; file. `thunk` should expect one argument containing the name of ;; the temporary file. `name` is the prefix for the name of the ;; temporary file. (define (with-temporary-file name thunk) (let ((file-name (create-temp-file! name))) (dynamic-wind (lambda () #f) (thunk file-name) (lambda () (delete-file! file-name)))))
false
d1d93aa00d571222ad562a0b22c1f1f84957c92c
b26941aa4aa8da67b4a7596cc037b92981621902
/SICP/chapter_3/binary_tree.scm
478aa8d378d6b1aabe767a070e765c72a36e4074
[]
no_license
Alaya-in-Matrix/scheme
a1878ec0f21315d5077ca1c254c3b9eb4c594c10
bdcfcf3367b664896e8a7c6dfa0257622493e184
refs/heads/master
2021-01-01T19:42:32.633019
2015-01-31T08:24:02
2015-01-31T08:24:02
22,753,765
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,271
scm
binary_tree.scm
(define nil '()) (define (make-node entry left right) (list entry left right)) (define (empty-node? node) (null? node)) (define (entry-node node) (car node));;û�м����Ƿ�Ϊ��node (define (left-branch-node node) (cadr node)) (define (right-branch-node node) (caddr node)) (define (init-tree entry) (cons '*head* (make-node entry nil nil))) (define (root tree) (cdr tree)) (define (empty-tree? tree) (empty-node? (root tree))) (define (make-empty-tree) (list '*head*)) ;;-------------------------------------------------------------------------- (define (insert! rec tree) (define (insert-root! rec root) (let ((ent-value (entry-node root)) (left-node (left-branch-node root)) (right-node (right-branch-node root))) (cond ((< rec ent-value) (if (empty-node? left-node) (set-car! (cdr root) (make-node rec nil nil)) (insert-root! rec left-node))) ((> rec ent-value) (if (empty-node? right-node) (set-car! (cddr root) (make-node rec nil nil)) (insert-root! rec right-node)))))) (if (empty-tree? tree) (set-cdr! tree (make-node rec nil nil)) (insert-root! rec (root tree))))
false
0e2791026c355afd2e7e544b7792effbf67d3ec4
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/ws/scrap/passdraft_propogate-skeletons.ss
fc3292a0ff93715b89e9e4eebfc8ada97a4fe201
[ "BSD-3-Clause" ]
permissive
rrnewton/WaveScript
2f008f76bf63707761b9f7c95a68bd3e6b9c32ca
1c9eff60970aefd2177d53723383b533ce370a6e
refs/heads/master
2021-01-19T05:53:23.252626
2014-10-08T15:00:41
2014-10-08T15:00:41
1,297,872
10
2
null
null
null
null
UTF-8
Scheme
false
false
2,559
ss
passdraft_propogate-skeletons.ss
;; [2004.07.30] Pass propogate-skeletons ;; FOR NOW I USE THE GLOBAL TREE!! ;; This pass addresses the problem that a fold may use the ;; gradient-skeleton from a different token than the one from which it ;; gets its values. There's a seperate *What* and *Where*. ;; It changes primapps of this type: ;; (fold <Simple> <Simple> <Simple>) ;; into this: ;; (foldwith <Token> <Simple> <Simple> <Simple>) ;; Where the "with token" means "using the back-pointer skeleton from ;; that token channel". (define propogate-skeletons (lambda (expr) (match expr [(annotate-heartbeats-lang (quote (program (props ,proptable ...) ,(lazy-letrec ,binds ,fin)))) (define (simple? expr) (match expr [,var (guard (symbol? var)) #t] [(quote ,const) (guard (or (symbol? const) (simple-constant? const))) #t] [,else #f])) (define (check-prop p s) (let ((entry (assq s proptable))) (if entry (memq p (cdr entry)) (error 'pass10_deglobalize:check-prop "This should not happen! ~nName ~s has no entry in ~s." s proptable)))) (define process-let (lambda (expr) (match expr [(lazy-letrec ([,lhs* ,heartbeat* ,[process-expr -> rhs*]] ...) ,fin) `(lazy-letrec ([,lhs* ,heartbeat* ,rhs*] ...) ,fin)]))) ;; This only works because of the harsh restrictions on the ;; language. We have the whole datapath right there for us to ;; trace. As the language becomes more flexible, we'll need to do ;; this *dynamically*. (define (find-skeleton name) ; ;; If it's a *region* that means (FOR NOW) that means it has a skeleton. ; ;; <TODO> intersection and stuff will screw this up and require ; ;; a more principled approach. ;; (if (check-prop 'area name) ; (match (assq name binds) ;;FOR NOW I USE THE GLOBAL TREE... (define process-expr (lambda (expr) (match expr [,exp (guard (simple? exp)) exp] [(lambda ,formalexp ,[process-let -> letexp]) `(lambda ,formalexp ,letexp)] [(if ,test ,conseq ,altern) `(if ,test ,conseq ,altern)] [(fold ,fun ,seed ,region) `(foldwith ,(find-skeleton ,region) ,fun ,seed ,region)] [(,prim ,rand* ...) (guard (regiment-primitive? prim)) `(,prim ,rand* ...)] [,unmatched (error 'TEMPLATE "invalid syntax ~s" unmatched)]))) ;; Body of match case: `(propogate-skeletons-lang (quote (program (props ,proptable ...) ,(process-let `(lazy-letrec ,binds ,fin)))))])))))
false
49fa967ab43753574d7a4c63c38b2efbca6c2458
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/microsoft/win32/system-events.sls
61e4e5661cc5c64f43c836644624854c8821ab95
[]
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
728
sls
system-events.sls
(library (microsoft win32 system-events) (export is? system-events? invoke-on-events-thread create-timer kill-timer) (import (ironscheme-clr-port)) (define (is? a) (clr-is Microsoft.Win32.SystemEvents a)) (define (system-events? a) (clr-is Microsoft.Win32.SystemEvents a)) (define-method-port invoke-on-events-thread Microsoft.Win32.SystemEvents InvokeOnEventsThread (static: System.Void System.Delegate)) (define-method-port create-timer Microsoft.Win32.SystemEvents CreateTimer (static: System.IntPtr System.Int32)) (define-method-port kill-timer Microsoft.Win32.SystemEvents KillTimer (static: System.Void System.IntPtr)))
false
50b49d7b2b0f847b359ab10570c2bbe338c4edb1
784dc416df1855cfc41e9efb69637c19a08dca68
/src/gerbil/prelude/gambit.ss
0fdd3ebf04292f9f1d5226ad02fd9307434604d2
[ "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
danielsz/gerbil
3597284aa0905b35fe17f105cde04cbb79f1eec1
e20e839e22746175f0473e7414135cec927e10b2
refs/heads/master
2021-01-25T09:44:28.876814
2018-03-26T21:59:32
2018-03-26T21:59:32
123,315,616
0
0
Apache-2.0
2018-02-28T17:02:28
2018-02-28T17:02:28
null
UTF-8
Scheme
false
false
1,085
ss
gambit.ss
;;; -*- Gerbil -*- ;;; (C) vyzo at hackzen.org ;;; gambit specific runtime symbols package: gerbil (import "gambit/threads" "gambit/continuations" "gambit/bits" "gambit/fixnum" "gambit/flonum" "gambit/random" "gambit/hvectors" "gambit/ports" "gambit/bytes" "gambit/readtables" "gambit/hash" "gambit/exceptions" "gambit/os" "gambit/system" "gambit/foreign" "gambit/misc" "gambit/exact") (export (import: "gambit/threads" "gambit/continuations" "gambit/bits" "gambit/fixnum" "gambit/flonum" "gambit/random" "gambit/hvectors" "gambit/ports" "gambit/bytes" "gambit/readtables" "gambit/hash" "gambit/exceptions" "gambit/os" "gambit/system" "gambit/foreign" "gambit/misc" "gambit/exact"))
false
d78e49c24fa217ebf23012946c35e5d4ba678fe8
557c51d080c302a65e6ef37beae7d9b2262d7f53
/workspace/scheme-tester/a/ednoc.scm
a6fb894f08ff1150c5b966d3fb258b431ac093dd
[]
no_license
esaliya/SchemeStack
286a18a39d589773d33e628f81a23bcdd0fc667b
dcfa1bbfa63b928a7ea3fc244f305369763678ad
refs/heads/master
2020-12-24T16:24:08.591437
2016-03-08T15:30:37
2016-03-08T15:30:37
28,023,003
3
4
null
null
null
null
UTF-8
Scheme
false
false
3,558
scm
ednoc.scm
(load "nanokanren.scm") (load "ednoc.scm") (define-syntax test (syntax-rules () ((_ title tested-expression expected-result) (let* ((expected expected-result) (produced tested-expression)) (if (equal? expected produced) (printf "~s works!\n" title) (error 'test "Failed ~s: ~a\nExpected: ~a\nComputed: ~a" title 'tested-expression expected produced)))))) ;; ednoc tests (test 'ednoc-1 (run 10 (q) (ednoc [(== q 5) (== q 6)] [(== q 6) (== q 5)])) '(5 6)) (test 'ednoc-2 (run 10 (q) (ednoc [(== q 5)] [(== q 6)])) '()) (test 'ednoc-3 (run 5 (q) (ednoc [(== q 3) (== q 3) (== q 3) (== q 3)] [(== q 4)] [(== q 5) (== q 5)] [(== q 6)])) '()) (test 'ednoc-4 (run 10 (q) (ednoc [(== q 5) (== q 6) (== q 7)] [(== q 5) (== q 6) (== #f #f)] [(== q 5) (== q 6) (== #f #f)])) '(5 5 5 5 6 6 6 6 7)) (test 'ednoc-5 (let ([x (var 'x)] [y (var 'y)]) (run 10 (q) (ednoc [(== x 3) (== y 4)] [(== x 5) (== y 6)]) (== `(,x ,y) q))) '((3 6) (5 4))) (test 'ednoc-6 (let ([w (var 'w)] [x (var 'x)] [y (var 'y)]) (run 10 (q) (ednoc [(== w 2) (== x 3) (== y 4)] [(== w 5) (== x 6) (== y 7)]) (== `(,w ,x ,y) q))) '((2 6 _.0) (2 _.0 7) (5 3 _.0) (_.0 3 7) (5 _.0 4) (_.0 6 4))) (define foo (lambda (x) (ednoc ((== 1 x) (== 2 x)) ((== 2 x) (foo 2))))) (test 'ednoc-7 (run 2 (q) (foo q)) '(1 1)) (test 'ednoc-8 (run 3 (q) (foo q)) '(1 1 1)) (test 'ednoc-9 (letrec ([foo (lambda (a d) (ednoc [(== a 'x) (== a 'y)] [(== d '()) (foo a d)]))]) (let ([a (var 'a)] [d (var 'd)]) (run 10 (q) (foo a d) (== `(,a . ,d) q)))) '((x) (x) (x) (x) (x) (x) (x) (x) (x) (x))) (test 'ednoc-10 (letrec ([foo (lambda (a d) (ednoc [(== d '()) (foo a d)] [(== a 'x) (== a 'y)]))]) (let ([a (var 'a)] [d (var 'd)]) (run 10 (q) (foo a d) (== `(,a . ,d) q)))) '((x) (y) (x) (y) (x) (y) (x) (y) (x) (y))) (letrec ([alwayso (lambda (x) (conde [(== #f #f)] [(alwayso x)]))]) (test 'ednoc-11 (run 10 (q) (ednoc [(alwayso q)] [(== q 5)])) '(5 5 5 5 5 5 5 5 5 5))) ; Vanilla conde tests for completeness--no surprises here. (test 'conde-1 (run 3 (q) (conde [(== q 5) (== q 5)])) '(5)) (test 'conde-2 (run 5 (q) (conde [(== q 3) (== q 4)] [(== q 5)])) '(5)) (test 'conde-3 (run 5 (q) (conde [(== q 5)] [(== q 6)])) '(5 6)) (test 'conde-4 (run 5 (q) (conde [(== q 5) (== q 5)] [(== q 6) (== q 6)])) '(5 6)) (test 'conde-5 (run 5 (q) (conde [(== q 5) (== q 6)] [(== q 6) (== q 6)])) '(6)) (test 'conde-6 (run 5 (q) (conde [(== q 6) (== q 6)] [(== q 5) (== q 6)])) '(6)) (test 'conde-7 (run 10 (q) (conde [(== q 6)] [(== q 5)] [(== q 4)] [(== q 3)] [(== q 2)])) '(6 5 4 3 2)) (test 'conde-8 (run 10 (q) (conde [(== q 6) (== q 6) (== q 6) (== q 6)] [(== q 5) (== q 5) (== q 5) (== q 5)] [(== q 4) (== q 4) (== q 4) (== q 4)] [(== q 3) (== q 3) (== q 3) (== q 3)] [(== q 2) (== q 2) (== q 2) (== q 2)])) '(6 5 4 3 2))
true
94e96315f550fb7560a5033caf1ae7441ea19d6a
951b7005abfe3026bf5b3bd755501443bddaae61
/无穷连分式-递归.scm
ce408f106fcadc541d124d73d5ea233351907092
[]
no_license
WingT/scheme-sicp
d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61
a255f3e43b46f89976d8ca2ed871057cbcbb8eb9
refs/heads/master
2020-05-21T20:12:17.221412
2016-09-24T14:56:49
2016-09-24T14:56:49
63,522,759
2
0
null
null
null
null
UTF-8
Scheme
false
false
608
scm
无穷连分式-递归.scm
(define (cont-frac n d k) (define (cont-frac-iter i ans) (define (step i ans) (/ (n i) (+ (d i) ans))) (if (= i 0) ans (cont-frac-iter (- i 1) (step i ans)))) (cont-frac-iter k 0.0)) (define (n x) 1.0) (define (d x) (define r (remainder x 3)) (cond ((< r 2) 1.0) (else (* 2 (+ 1 (/ (- x r) 3)))))) ;; (define (test n) ;; (define (test-iter count) ;; (if (> count 1) ;; (begin ;; (display (d count)) ;; (display " ") ;; (test-iter (- count 1))) ;; (display (d count)))) ;; (test-iter n)) (cont-frac n d 1000)
false
6a7f6cf716dfcc33ea9e322da53bb2f2eb5f88d1
f0747cba9d52d5e82772fd5a1caefbc074237e77
/svc/sshd.scm
c873508b179b6034af7f2a87a8558f7e702832e2
[]
no_license
philhofer/distill
a3b024de260dca13d90e23ecbab4a8781fa47340
152cb447cf9eef3cabe18ccf7645eb597414f484
refs/heads/master
2023-08-27T21:44:28.214377
2023-04-20T03:20:55
2023-04-20T03:20:55
267,761,972
3
0
null
2021-10-13T19:06:55
2020-05-29T04:06:55
Scheme
UTF-8
Scheme
false
false
1,871
scm
sshd.scm
(import scheme (distill plan) (distill execline) (distill unix) (distill service) (distill fs) (distill text) (pkg openssh)) ;; sshd runs the sshd service ;; using the configuration from ;; $PWD/etc/sshd_config (define (sshd config-lines) (let* ((confpath "/etc/sshd_config") (config (interned confpath #o644 (lines config-lines)))) (make-service name: 'sshd users: (list (adduser 'sshd group: 'sshd home: "/var/empty")) groups: (list (addgroup 'sshd '(sshd))) ;; pre-emptively ensure that /root/.ssh ;; is not world-accessible inputs: (list openssh config (interned-dir "/root/.ssh" #o700)) after: (list var-mounted-rw) ;; TODO: after: if we are not doing ;; a wildcard bind, then we must wait ;; for interfaces to have the addresses ;; to which sshd will bind... spec: (longrun* run: `(fdmove -c 2 1 if (mkdir -p /var/empty) if (if -t -n (test -f /var/etc/ssh/ssh_host_ed25519_key) if (mkdir -p /var/etc/ssh) ;; NOTE: using ssh-keygen -A here doesn't work, ;; because it disagrees with sshd on where the ;; keys ought to be found relative to the install prefix foreground (echo "generating new host key") ssh-keygen -t ed25519 -P "" -f /var/etc/ssh/ssh_host_ed25519_key) ;; sshd needs to be invoked with an absolute path ;; in order for privsep re-exec to work /usr/sbin/sshd -e -h /var/etc/ssh/ssh_host_ed25519_key -D -f ,confpath)))))
false
f11ef1a08623a5248c6e0d9e225bcdbc018894f7
bde67688a401829ffb4a5c51394107ad7e781ba1
/ika-intro.scm
7c101215f2905cdfcab13c2e319c367a2eb1dadf
[]
no_license
shkmr/taco
1fad9c21284e12c9aae278f2e06de838363c3db9
8bbea1a4332d6d6773a3d253ee6c2c2f2bcf2b05
refs/heads/master
2021-01-10T03:50:55.411877
2016-08-11T03:37:53
2016-08-11T03:37:53
48,963,008
0
0
null
null
null
null
UTF-8
Scheme
false
false
12,711
scm
ika-intro.scm
;; ;; === 楽しい ika プログラミング === ;; ;;; 1. ika とは ;;; ;;; 機械語のプログラミングは実行したら即暴走するプログラムが簡単に書けます。 ;;; ika はそんな刺激的な火遊びをしてみたい、いけない子のアセンブラです。 ;;; ;;; ika プログラミングをしていると通常滅多に御目にかかることのない VM ;;; レジスタのダンプリストなどを拝むことができます。 ;;; ;;; 2. 遊び方 ;;; ;;; まずはコマンドラインにて、 ;;; ;;; $ git clone shkmr.github.gom/taco ;;; $ cd taco ;;; $ make ;;; ;;; すると vmhack モジュール、insn.html ができます。 ;;; ;;; 次に、Emacs で ika-intro.scm (このファイルのソース)を開き ;;; M-x run-scheme (もちろん gosh が起動しますよね? ね!) ;;; して、順番に C-x C-e して様子をみてみましょう。 ;; まずは読み込み (begin (add-load-path ".") (add-load-path "vmhack") (use ika) (use vmhack)) ;; ika->vm-code は ika プログラムをアセンブルして実行可能な ;; <compiled-code> を作ります。 (ika->vm-code '(%toplevel (0 0) (CONST) 2 (RET) )) ;; %toplevel (0 0) は後ほど 5. で説明するとして、このプログラムは ;; アキュムレータ(val0)に定数 2 をロードしてリータン、つまり、 ;; 単に 2 を返すプログラムです。 これを test1 としておきましょう。 (define test1 (ika->vm-code '(%toplevel (0 0) (CONST) 2 (RET) ))) ;; <compiled-code> を実行するには vmhack モジュールの ;; vm-code-execute! に渡せばオッケイ。 (vm-code-execute! test1 (interaction-environment)) ;; ちゃんと 2 が返ってきました。 ;; 第二引数には (interaction-environment) の代わりに ;; モジュールを渡して構いません。 今後変わるかもしれないけど。 (vm-code-execute! test1 (find-module 'user)) ;;; 3. Gauche VM の機械語その1 ;;; ;;; Gauche VM の機械語のフォーマットは次の6種類です。 ;;; ;;; 1. OPCODE ;;; 2. OPCODE OBJ ;;; 3. OPCODE ADDR ;;; 4. OPCODE CODE ;;; 5. OPCODE OBJ ADDR ;;; 6. OPCODE CODES ;;; ;;; OBJ は任意の Scheme オブジェクト、 ADDR はアドレス、 CODE は ;;; <compiled-code>、 CODES は <complied-code> のリストです。 ;;; アドレスは Scheme オブジェクトではないので、ika プログラムでは ;;; label 擬似命令で指定します。 ;;; ;;; OPECODE にはパラメータを一つか二つ取るものがあり、例えば ;;; パラメータなしの (CONST) に対してパラメータを一つ取る (CONTI n) ;;; があります。パラメータは小さめの整数でその範囲は1 integer-fits-insn-arg? ;;; で確認できます。 ;;; ;;; 1. の $ make でできた insn.html は機械語の命令(insn)の一覧です。 ;;; Gauche VM には複合命令(combined insn)という、頻出する複数の命令 ;;; を一つにまとめたものがあります。 例えば CONST-PUSH は CONST と PUSH ;;; を一つにまとめたものです。 ika プログラミングにおいては、これらを直接 ;;; 使うこともできますが、ika が呼び出す complied-code-builder (cc_builder) が ;;; 自動的にまとめてくれるので、とりあえずは基本形だけを使っていれば十分 ;;; かと思います。 ;; 先ほどの test1 を見てみましょう。 (vm-dump-code test1) ;; リスト形式で (vm-code->list test1) ;; ika プログラムでは 2語の (CONST) 2 としたところが 1語の (CONSTI 2) ;; に変わっています。 ;; また、文字列定数を返すプログラムは (vm-dump-code (ika->vm-code '(%toplevel (0 0) (CONST) "abracadabra" (RET)))) ;; のように (CONST) operand (RET) が (CONST-RET) operand に変換さてれます。 ;; 今回はオペランドが命令に埋め込める物ではないので代わりに複合命令(CONST-PUSH) ;; になりました。 ;;; 機械語は Gauche のコンパイラに教えてもらうのが手っ取り早いと思います。 ;;; ika を use すると Gauche のコンパイラも使えるようになります。 ;;; コンパイラは <compiled-code> を返します。 ;; 例えば先ほどの 2 を返すプログラムは (vm-dump-code (compile 2 (interaction-environment))) ;; vm-code->list で得られるリストに (%toplevel (0 0)) をくっつけると ;; ika プログラムになります。 (ika/pp `(%toplevel (0 0) ,@(vm-code->list (compile 2 (interaction-environment))))) ;; ika/pp は ika プログラムを見やすくインデントして表示します。 ;; 左端の数字はアドレスです。 ;;; ところで、後ほど 5. で説明しますが、ika プログラムには ;;; アドレスは不要なので出力は ika プログラムにはなってません。 ;;; これら complie と ika/pp の呼び出しをまとめた c という関数が ika ;;; モジュールの中にあるのでいろいろ試してみましょう。 ;; c は export されてないので取り込みます。 (define c (with-module ika c)) (c 2) (c 654321) (c "abracadabra") (c #t) (c #f) (c '()) (c '(+ 1 2)) (c '(+ x y)) (c '(print "abracadabra")) (c '(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))) ;;; 4. <compiled-code> ;;; ;;; <compiled-code> には次ような(Schemeからアクセス可能な)スロットがあります。 ;;; ;;; parent ; 親 <compiled-code> ;;; arg-info ; ソースコードにおける引数(シンボル、またはシンボルのリストまたは #f) ;;; info ; ソースコードの情報、code 内の相対アドレスと対応するソースコードの alist ;;; required-args ; 必須引数の数 ;;; optional-args ; 省略可能な引数の数 ;;; name ; 名前、シンボルまたは #f ;;; full-name ; 親の名前を含む名前 ;;; size ; code のワード数 ;;; max-stack ; 使用するスタックのワード数 ;;; intermediate-form ; inline 展開するときに使われる何か(よく調べてない) ;;; ;;; 機械語のプログラムは vm-code->list で取り出すことができます。 ;;; ;;; ika->vm-code は ika プログラムにしたがってこれらのスロットを設定します。 ;;; ;;; 5. ika の文法その1 ;;; ;;; ika プログラムは ;;; ;;; (name code-spec body) ;;; ;;; というリストです。 name はシンボル code-spec は基本的には ;;; ;;; (required-args optional-args) ;;; ;;; という形式で、オプションの kv-list でいくつかの <complied-code> スロット ;;; を設定することができます。(が私自身あまり試してません。) ;;; ;;; (required-args optional-args :key val ...) ;;; ;;; 現在指定可能なのは :arg-info :parent :intermediate-form です。 ;;; ;;; 例えば、先に見た test1 の場合は ;;; ;;; name = %toplevel ;;; code-spec = (0 0) ;;; body = (CONST) 2 (RET) ;;; ;;; となります。 ;;; ;;; それではもう少し複雑な ika のプログラムを組んでみましょう。 ;; 3. の終わりに示した (c '(print "abracadabra")) ;; に相当する ika プログラムは (define ika1 `(%toplevel (0 0) (CONST) "abracadabra" (PUSH) (GREF) ,(make-identifier 'print (find-module 'user) '()) (TAIL-CALL 1) (RET))) ;; となります。 ここで、(GREF) のオペランドは識別子(identifier)なので ;; make-identifer で user モジュールの識別子を作っています。 ;; これを ika->vm-code でアセンプルすると (vm-dump-code (ika->vm-code ika1)) ;; となりめでたくコンパイラの出力と同等になりました。 ;; ここでは vm-dump-code を使いましたが、もちろん、先ほどと同様に (ika/pp `(%top-level (0 0) ,@(vm-code->list (ika->vm-code ika1)))) ;; としても構いません。 ;;; 擬引用は煩わしいので ika では user モジュールの識別子を作る擬似命令 mkid ;;; を用意しています。(これは将来互換性破る形で変更するかもしれません。) (define ika2 '(%toplevel (0 0) (CONST) "abracadabra" (PUSH) (GREF) (mkid print) (TAIL-CALL 1) (RET))) (vm-dump-code (ika->vm-code ika2)) ;; 実行してみましょう (vm-code-execute! (ika->vm-code ika2) (interaction-environment)) ;;; 余談ですが、(CONST) (PUSH) -> (CONST-PUSH) などの合成は ika が ;;; やってるのではなく、Gauche の cc_builder がやってくれてます。 ;;; ありがたや、ありがたや。 ;;; 6. Gauche VM の機械語その2 ;;; ;; 次に手続きの定義を見てみましょう。 (c '(define (foo) (print "foo"))) ;; 手続き本体は <compiled-code> となって (CLOSURE) のオペランドに ;; なっています。その結果クロージャが val0 にロードされます。 ;; そして (DEFINE 0) で foo の束縛します。 ;; vm-dump-code すると 2つの <complied-code> があるのがわかりやすいです。 (vm-dump-code (compile '(define (foo) (print "foo")) (interaction-environment))) ;;; DEFINE のパラメータは 0 が通常の define、SCM_BINDING_CONST が ;;; define-constant、SCM_BINDING_INLINABLE が define-inline に ;;; 相当するんだと思います。 (まだ、あまり試してません Gauche/src/vminsn.scm 参照) ;;; ここで重要なのは機械語の DEFINE は Scheme のトップレベルの define ;;; に相当するということ。 Scheme 手続き内の define はコンパイラによって ;;; ローカル変数への代入に変換されます。 ;; ここでもう一度階乗を見てみましょう。 (c '(define (fact n) (if (= n 1) 1 (* n (fact (- n 1)))))) ;;; fact には引数が1つあるので (fact (1 0) ...) となってます。 ;;; 引き数(ローカル変数)の参照は (LREF depth offset) で行います。 ;;; (LREF0) は (LREF 0 0) に相当するショートカット命令です。 ;;; ローカル変数の指定はスタックフレームをある程度理解しないとできないので、 ;;; insn.html にリンクを張った shiro さんによるドキュメントを ;;; 読んで勉強しましょう。 実のところ、私はさらっと読んだだけだと ;;; よくわからず、実際に実装してみてようやくどういう構造になっているか ;;; 理解した感じです。(mgvm.scm) 要は時間をかけて一つずつ解きほぐす。 ;;; さて、(BNUMNEI 1) のオペランドはアドレスで相当する位置は ;;; 左側の数字が 5 の (LREF0-PUSH) がある所です。 ;;; (PRE-CALL 1) のオペランドも同様です。 ;;; ika ではアドレスは label 擬似命令で指定します。 ;; というわけで、fact を ika で書くとこうなります。 (define fact.ika '(%toplevel (0 0) (CLOSURE) (ikafact (1 0) (LREF 0 0) (BNUMNEI 1) (label 1) (CONST) 1 (RET) (label 1) (LREF 0 0) (PUSH) (PRE-CALL 1) (label 2) (LREF 0 0) (NUMADDI -1) (PUSH) (GREF) (mkid ikafact) (CALL 1) (label 2) (NUMMUL2) (RET)) (DEFINE 0) (mkid ikafact) (RET) )) (vm-dump-code (ika->vm-code fact.ika)) ;; 実行すると (vm-code-execute! (ika->vm-code fact.ika) (interaction-environment)) ;; ikafact が定義され、 (ikafact 5) ;; 階乗が計算できました。 ;;; おしまい
false
84146415bc75c907abdf08fdb0ad858a91455e1a
5420cb2baa06a7e507895768501c105e4742f912
/json/parser.scm
78dfade7cfcc43fb99d631804f3a6435f8e51fd4
[ "MIT" ]
permissive
tqtifnypmb/scm-json
6ace0d60585cad3eceb31aa31e5f63e3ec3e2d4b
a513721f0db5ba98ae505ca0a74d18b41d6605c4
refs/heads/master
2020-05-22T20:59:26.206933
2017-03-22T09:27:19
2017-03-22T09:27:19
84,724,221
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,311
scm
parser.scm
(library (json parser) (export json-parse) (import (rnrs)) ; parser with textual-input port (define-record-type parser (fields port)) (define (peek-next-char parser) (lookahead-char (parser-port parser))) (define (get-next-char parser) (get-char (parser-port parser))) (define (expect-char parser expected) (let ((ch (get-next-char parser))) (if (not (char-ci=? ch expected)) (raise (make-violation)) ch))) (define (expect-string parser expected) (for-each (lambda (ch) (expect-char parser ch)) (string->list expected)) #t) (define (parse-read-true parser) (expect-string parser "true") #t) (define (parse-read-false parser) (expect-string parser "false") #f) (define (parse-read-null parser) (expect-string parser "null") '()) ;parse string (define (parse-read-string parser) (parse-read-till parser #\") ;drop begining " (let loop ((str "") (ch (get-next-char parser))) (if (not (char=? ch #\")) (loop (string-append str (string ch)) (get-next-char parser)) str))) ;parse array (define (parse-read-till parser expect) (let loop ((ch (get-next-char parser))) (if (char=? ch expect) '() (loop (get-next-char parser))))) (define (parse-read-array parser) (parse-read-till parser #\[) ;drop begining [ (let loop ((ch (peek-next-char parser)) (acc '())) (cond ((char-whitespace? ch) (get-next-char parser) (loop (peek-next-char parser) acc)) ((eqv? ch #\,) (get-next-char parser) (loop (peek-next-char parser) acc)) ((eqv? ch #\]) (get-next-char parser) acc) (else (let ((r (append acc (cons (parse-read-value parser) '())))) (loop (peek-next-char parser) r)))))) ;parse object (define (parse-read-object-entry parser) (let ((key (parse-read-string parser))) (parse-read-till parser #\:) (cons key (parse-read-value parser)))) (define (parse-read-object parser) (parse-read-till parser #\{) ;drop begining { (let loop ((acc '()) (ch (peek-next-char parser))) (cond ((char-whitespace? ch) (get-next-char parser) (loop acc (peek-next-char parser))) ((eqv? ch #\,) (get-next-char parser) (loop acc (peek-next-char parser))) ((eqv? ch #\}) (get-next-char parser) acc) (else (let ((r (parse-read-object-entry parser))) (loop (append acc (cons r '())) (peek-next-char parser))))))) ;parse number (define (parse-read-number-realpart parser acc) (assert (not (char-ci=? (peek-next-char parser) #\e))) (let loop ((acc2 acc) (ch (peek-next-char parser))) (cond ((eof-object? ch) (string->number acc2)) ((or (char-ci=? #\e ch) (char-numeric? ch)) (get-next-char parser) (loop (string-append acc2 (string ch)) (peek-next-char parser))) ((not (char-numeric? ch)) (string->number acc2)) (else (raise (make-violation)))))) (define (parse-read-number parser) (let loop ((acc "") (ch (peek-next-char parser))) (cond ((eof-object? ch) (string->number acc)) ((eqv? ch #\.) (get-next-char parser) (parse-read-number-realpart parser (string-append acc (string ch)))) ((or (eqv? #\- ch) (eqv? #\+ ch) (char-numeric? ch)) (get-next-char parser) (loop (string-append acc (string ch)) (peek-next-char parser))) ((not (char-numeric? ch)) (string->number acc)) (else (raise (make-violation)))))) ;parse dispatch (define parse-read-value (lambda (parser) (let loop ((c (peek-next-char parser))) (cond ;skip white space ((char-whitespace? c) (get-next-char parser) (loop (peek-next-char parser))) ((eqv? #\t c) (parse-read-true parser)) ((eqv? #\f c) (parse-read-false parser)) ((eqv? #\" c) (parse-read-string parser)) ((eqv? #\[ c) (parse-read-array parser)) ((eqv? #\{ c) (parse-read-object parser)) ((eqv? #\n c) (parse-read-null parser)) ((or (eqv? #\+ c) (eqv? #\- c) (char-numeric? c)) (parse-read-number parser)) (else (raise (make-violation))))))) ;Interface (define json-parse (case-lambda (() (parse-read-value (make-parser (current-input-port)))) ((str) (call-with-port (open-string-input-port str) (lambda (port) (parse-read-value (make-parser port))))))) )
false
a4d51334dff115ecb7d7e6fc8c6828c1b21eae9b
d3e9eecbf7fa7e015ab8b9c357882763bf6d6556
/solutions/exercises/1.29-1.46.ss
6f842c5802e7122159b1ad78d5af3e132da93a13
[]
no_license
yangchenyun/learning-sicp
37d43f18836055274f78755ff93eb20fba63d383
99a19a06eddc282e0eb364536e297f27c32a9145
refs/heads/master
2021-01-19T02:15:15.634140
2017-02-13T22:26:58
2017-02-13T22:26:58
5,344,488
17
3
null
null
null
null
UTF-8
Scheme
false
false
7,561
ss
1.29-1.46.ss
#lang r5rs (#%require racket/include) (include "../lib/arithmetic.ss") ;; Exercise 1.29 (define (sum term a next b) (if (> a b) 0 (+ (term a) (sum term (next a) next b)))) (define (simpson-integral f a b n) (letrec ((h (/ (- b a) n)) (kth (lambda (u) (/ (- u a) h))) ;; get the kth (next (lambda (u) (+ u h))) (term (lambda (u) (cond ((or (= (kth u) 0) (= (kth u) n)) (f u)) ;; first and last item ((even? (kth u)) (* 2.0 (f u))) (else (* 4.0 (f u))))))) (* (/ h 3) (sum term a next b)))) (simpson-integral cube 0 1 10000) ;; Exercise 1.30 (define (sum-iter term a next b) (define (iter a result) (if (> a b) result (iter (next a) (+ result (term a))))) (iter a 0)) ;; Exercise 1.31 (define (prod term a next b) (if (> a b) 1 (* (term a) (prod term (next a) next b)))) (define (prod-iter term a next b) (define (iter a result) (if (> a b) result (iter (next a) (* (term a) result)))) (iter a 1)) (define (factorial n) (prod (lambda (x) x) 1 (lambda (x) (+ 1 x)) n)) ;; O(n^2), term is executed n times and * is executed n times (define (prod-pi n) (* 4.0 (prod-iter (lambda (i) (cond ((= i 1) (/ 2 3)) (else (/ (+ (* 2 (floor (/ i 2))) 2) (+ (* 2 (floor (/ (+ 1 i) 2))) 1))))) 1 (lambda (x) (+ 1 x)) n))) ;; Exercise 1.32 (define (accumulate combiner null-value term a next b) (if (> a b) null-value (combiner (term a) (accumulate combiner null-value term (next a) next b)))) (define (accumulate-iter combiner null-value term a next b) (define (iter a result) (if (> a b) result (iter (next a) (combiner (term a) result)))) (iter a null-value)) (define (sum term a next b) (accumulate + 0 term a next b)) (define (prod term a next b) (accumulate * 1 term a next b)) ;; Exercise 1.33 (define (filtered-accumulate combiner null-value term a next b filter) (cond ((> a b) null-value) ;; only accumulate when filter returns true ((filter a) (combiner (term a) (filtered-accumulate combiner null-value term (next a) next b filter))) (else (filtered-accumulate combiner null-value term (next a) next b filter)))) (define (smallest-divisor n) (define (divide? n test-dividor) (= 0 (remainder n test-dividor))) (define (find-divisor n test-dividor) (cond ((> (square test-dividor) n) n) ((divide? n test-dividor) test-dividor) (else (find-divisor n (+ 1 test-dividor))))) (find-divisor n 2)) (define (prime? n) (= (smallest-divisor n) n)) (define (prime-square-sum a b) (filtered-accumulate + 0 square a (lambda (x) (+ x 1)) b prime?)) (define (relative-prime-prod n) (filtered-accumulate * 1 (lambda (x) x) 1 (lambda (x) (+ x 1)) n (lambda (i) (= 1 (gcd i n))))) ;; Exercise 1.34 (define (f g) (g 2)) (f square) ;; (f f) ;; (f 2) ;; (2 2) ;; as 2 is not a procedure it would raise an issue ;; Exercise 1.35 (define tolerence 0.000001) (define (fixed-point f first-guess) (define (close-enough? u v) (< (abs (- u v)) tolerence)) (define (try guess) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) (fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0) ;; Exercise 1.36 (define (fixed-point-with-print f first-guess) (define (close-enough? u v) (< (abs (- u v)) tolerence)) (define (try guess number-of-attempt) (display number-of-attempt) (display ": ") (display guess) (newline) (let ((next (f guess))) (if (close-enough? guess next) next (try next (+ 1 number-of-attempt))))) (try first-guess 0)) (define (average-damp f) (lambda (x) (average (f x) x))) ;; with average-damp, it converges faster (fixed-point-with-print (lambda (x) (/ (log 1000) (log x))) 10.0) (fixed-point-with-print (average-damp (lambda (x) (/ (log 1000) (log x)))) 10.0) ;; Exercise 1.37 (define (cont-frac n d k) (define nextn (lambda (i) (n (+ i 1)))) (define nextd (lambda (i) (d (+ i 1)))) (if (= k 1) (/ (n k) (d k)) (/ (n 1) (+ (d 1) (cont-frac nextn nextd (- k 1)))))) (define golden-ratio 0.61803398874989484820458683436565) (define (steps-for-precision precision) (define (try n) (let ((estimate (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) n))) (if (< (abs (- golden-ratio estimate)) precision) n (try (+ n 1))))) (try 1)) (steps-for-precision 0.0001) ;; => 10 (define (cont-frac-iter n d k) (define (iter i frac) (if (= i 0) frac ;; accumulate on the frac part (iter (- i 1) (/ (n i) (+ (d i) frac))))) (iter (- k 1) (/ (n k) (d k)))) ;; Exercise 1.38 (define euler-number 2.7182818284590452353602874) (define (euler-number-cf steps) (cont-frac (lambda (i) 1) (lambda (i) (if (= (modulo i 3) 2) (* 2.0 (ceiling (/ i 3))) 1)) steps)) (- (- euler-number 2) (euler-number-cf 10)) ;; Exercise 1.39 (define (tan-cf x k) (cont-frac (lambda (i) (if (= i 1) x (- (square x)))) (lambda (i) (- (* 2 i) 1.0)) k)) (- (tan-cf 10 100) (tan 10)) (define pi 3.14159265) (tan-cf (/ pi 4) 10) ;; Exercise 1.40 (define dx 0.00001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) (define (newton-methods g guess) (fixed-point (newton-transform g) guess)) (define (cubic a b c) (lambda (x) (+ (cube x) (* a (square x)) (* b x) c))) (newton-methods (cubic 0 0 -1.0) 1.0) ;; Exercise 1.41 (define (double f) (lambda (x) (f (f x)))) (define inc (lambda (x) (+ 1 x))) ((double inc) 1) (((double (double double)) inc) 5) ;; Exercise 1.42 (define (compose f g) (lambda (x) (f (g x)))) ((compose square inc) 6) ;; Exercise 1.43 (define (repeated f n) (if (= n 1) (lambda (x) (f x)) (compose f (repeated f (- n 1))))) ;; Exercise 1.44 (define (smoothing f) (lambda (x) (/ (+ (f (- x dx)) (f x) (f (+ x dx))) 3))) (define (n-fold-smoothing f n) (repeated smoothing n) f) ;; Exercise 1.45 (define (log2-floor n) (define (iter m count) (if (= m 0) (- count 1) (iter (arithmetic-shift m -1) (+ 1 count)))) (iter n 0)) (define (nth-root x n) ;; assume log2(n) average-damp is required (fixed-point ((repeated average-damp (log2-floor n)) (lambda (y) (/ x (expt y (- n 1))))) 1.0)) (nth-root 64 6) (nth-root 1000000 6) ;; Exercise 1.46 (define (iterative-improve good-enough? improve-guess) (lambda (guess) (if (good-enough? guess) guess ((iterative-improve good-enough? improve-guess) (improve-guess guess))))) (define (sqrt x) ((iterative-improve (lambda (guess) (< (abs (- (square guess) x)) 0.0001)) (lambda (guess) (average guess (/ x guess)))) 1.0)) (define (fixed-point f first-guess) ((iterative-improve (lambda (guess) (< (abs (- guess (f guess))) 0.0001)) (lambda (guess) (f guess))) first-guess))
false
0fd4efd0cd76f7699e1f55836dd66d8a3e3fc5f3
fc070119c083d67c632e3f377b0585f77053331e
/exercises/07/symmetric.scm
7f300a1343a7bfc9213850e49926b69f3163ac31
[]
no_license
dimitaruzunov/fp-2018
abcd90396e9e8b73efe4e2b8a0634866948269a8
f75f0cd009cc7f41ce55a5ec71fb4b8eadafc4eb
refs/heads/master
2020-03-31T11:01:55.426456
2019-01-08T20:22:16
2019-01-08T20:22:16
152,160,081
9
3
null
null
null
null
UTF-8
Scheme
false
false
1,923
scm
symmetric.scm
(require rackunit rackunit/text-ui) (define (every? p l) (or (null? l) (and (p (car l)) (every? p (cdr l))))) (define (flatmap fn l) (apply append (map fn l))) (define (search p l) (and (not (null? l)) (or (p (car l)) (search p (cdr l))))) (define (add-if-missing x l) (if (member x l) l (cons x l))) (define (keys alist) (map car alist)) (define (assoc key alist) (search (lambda (key-value-pair) (and (equal? (car key-value-pair) key) key-value-pair)) alist)) (define (del-assoc key alist) (filter (lambda (key-value-pair) (not (equal? (car key-value-pair) key))) alist)) (define (add-assoc key value alist) (cons (cons key value) (del-assoc key alist))) (define (empty-graph) '()) (define vertices keys) (define (children v g) (cdr (assoc v g))) (define (edge? u v g) (member v (children u g))) (define (add-vertex v g) (if (assoc v g) g (add-assoc v '() g))) (define (add-edge u v g) (let ((g-with-u-v (add-vertex v (add-vertex u g)))) (add-assoc u (add-if-missing v (children u g-with-u-v)) g-with-u-v))) (define (edges g) (flatmap (lambda (vertex) (map (lambda (child) (list vertex child)) (children vertex g))) (vertices g))) (define (symmetric? g) (every? (lambda (edge) (edge? (cadr edge) (car edge) g)) (edges g))) (define graph (add-vertex 'd (add-edge 'c 'b (add-edge 'b 'c (add-edge 'a 'c (add-edge 'a 'b (empty-graph))))))) (define symmetric-graph (add-edge 'c 'a (add-edge 'b 'a graph))) (define symmetric?-tests (test-suite "Tests for symmetric?" (check-false (symmetric? graph)) (check-true (symmetric? symmetric-graph)))) (run-tests symmetric?-tests)
false
d31b624bafcb6c7c44fef7afaa8f71bbeef8d663
d474cce91812fbcdf351f8c27ddfb999e5b4b29b
/sdl2/keyboard-types.ss
0b3a0d3849dc258e522e2f2a0368785151411450
[]
no_license
localchart/thunderchez
8c70ccb2d55210207f0ee1a5df88a52362d2db27
9af3026617b1fb465167d3907416f482e25ef791
refs/heads/master
2021-01-22T00:20:15.576577
2016-08-17T11:49:37
2016-08-17T11:49:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
158
ss
keyboard-types.ss
(define-ftype sdl-keysym-t (struct (scancode sdl-scancode-t) (sym sdl-keycode-t) (mod unsigned-16) (unused unsigned-32)))
false
cb7635f73da42a0f7fc538559397f91116dea034
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/algorithm/random/extract.scm
74bb34c2d2d66841e4623a7916b9a111c2b58a9b
[ "MIT" ]
permissive
alvatar/spheres
c0601a157ddce270c06b7b58473b20b7417a08d9
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
refs/heads/master
2021-06-01T15:59:32.277602
2021-03-18T21:21:43
2021-03-18T21:21:43
25,094,121
13
3
null
null
null
null
UTF-8
Scheme
false
false
858
scm
extract.scm
;;!!! Reservoir sampling, random selection ;; .author Alvaro Castro-Castilla, 2012-2014 ;;! Pick a random element and return also the list without that element ;; .parameter l input list ;; .parameter len (optional) give the length of the list, if known in advance (define* (random-extract l (len #f)) (let ((random-pick+rember/length (lambda (l len) (let ((rnd (random-integer len))) (let recur ((rest l) (i 0)) (if (fx= i rnd) (values (car rest) (cdr rest)) (receive (head tail) (recur (cdr rest) (fx+ 1 i)) (values head (cons (car rest) tail))))))))) (random-pick+rember/length l (or len (length l)))))
false
a563c02e6e3b54e23f20ccff10ad97dd5e0703c7
beac83b9c75b88060f4af609498541cf84437fd3
/site/content/centralized-people/galen-williamson.ss
23a0acba57828ece66241514b76bf5789c0412a4
[]
no_license
nuprl/prl-website
272ce3b9edd5b3ada23798a694f6cb7c6d510776
31a321f629a62f945968c3e4c59d180de0f656f6
refs/heads/master
2021-05-16T02:06:38.847789
2016-09-16T14:41:22
2016-09-16T14:41:22
412,044
1
0
null
null
null
null
UTF-8
Scheme
false
false
157
ss
galen-williamson.ss
#lang scheme (provide me)(define me (quote (person "Galen Williamson" (group "Alumni") (graduated 2004) (homepage "http://www.ccs.neu.edu/home/gwilliam"))))
false
fdef88b0b32f0605ffe9cdee70caa597dd8749b8
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
/sicp/ch2/exercises/2.68.scm
e714e7e67359d5a2492c8ef80363e24bb0cc161b
[]
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
605
scm
2.68.scm
(define (member? x ls) (member x ls)) (define (encode-symbol s tree) (cond ((null? tree) '()) ((leaf? tree) '()) ((member? s (syms (left-branch tree))) (cons '0 (encode-symbol s (left-branch tree)))) ((member? s (syms (right-branch tree))) (cons '1 (encode-symbol s (right-branch tree)))) (else (error "bad symbol -- encode-sympol" s)))) (define (encode message tree) (if (null? message) '() (append (encode-symbol (car message) tree) (encode (cdr message) tree)))) (define code '(A D A B B C A)) (encode code sample-tree)
false
554ef579cb50d354941829a4726c470278d1a683
784dc416df1855cfc41e9efb69637c19a08dca68
/src/bootstrap/gerbil/core__1.scm
0f603b9145f5fe11b590b24e30c3ed41f4e0787c
[ "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
danielsz/gerbil
3597284aa0905b35fe17f105cde04cbb79f1eec1
e20e839e22746175f0473e7414135cec927e10b2
refs/heads/master
2021-01-25T09:44:28.876814
2018-03-26T21:59:32
2018-03-26T21:59:32
123,315,616
0
0
Apache-2.0
2018-02-28T17:02:28
2018-02-28T17:02:28
null
UTF-8
Scheme
false
false
249
scm
core__1.scm
(declare (block) (standard-bindings) (extended-bindings) (inlining-limit 200)) (begin (define |gerbil/core$<syntax-case>[:0:]#syntax| gx#macro-expand-syntax) (define |gerbil/core$<syntax-case>[:0:]#syntax-case| gx#macro-expand-syntax-case))
false
69830695e56e6d2d1984056773bbd6499c2d134c
c5bbb46557468161af156cf3c66a9b8509bbf135
/a1/Scheme/rush-hour/.#state.ss
33f437a6ed15c68fb7f1578a23928f6e21879f52
[]
no_license
jy477274/PPL-Assignments
8083c66a5d49d4fa9bb3fc508f3af59c47b055e4
74cfe0d6561108b353b198ef7e383592deabeb56
refs/heads/master
2020-04-17T18:45:56.907228
2019-02-19T21:54:49
2019-02-19T21:54:49
166,840,150
0
0
null
2019-02-19T01:02:56
2019-01-21T15:52:28
Scheme
UTF-8
Scheme
false
false
30
ss
.#state.ss
false
53f05f56510e3ab760ebc0055e1cb100a5146773
295dbd430419a7c36df8d2fd033f8e9afdc308c3
/Computing_with_Register_Machines/ex/27.scm
f5cbfa4cd4f66fc389f2c5793d23f6e4a0c93052
[]
no_license
ojima-h/sicp
f76b38a46a4f413d6a33f1ba0df4f6af28208fa1
4bbcd6a011076aef6fe36071958b76e05f653c75
refs/heads/master
2016-09-05T17:36:32.319932
2014-06-09T00:30:37
2014-06-09T00:30:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
292
scm
27.scm
(load "compat") (load "load-eceval") (define the-global-environment (setup-environment)) (start eceval) (define (factorial n) (if (= n 1) 1 (* (factorial (- n 1)) n))) (factorial 1) (factorial 9) (factorial 10) ;; maximum depth = 5 * n + 3 ;; total pushes = 32 * n - 16
false
0b746c42894a144601525973e88ce6b32b990869
b5783aa5c2b23c870b8729af3ba55b5718d1aa43
/symbolic/simplify-dot.sls
29396e19137eaf80fae8885c55f8a15bec101d26
[]
no_license
dharmatech/numero
562a4a91d17d41f7e553a1295aa6b73316316e8c
d69357e1d8840511e167103d6eb46080ede46d72
refs/heads/master
2020-04-01T13:40:31.194701
2009-08-02T20:29:33
2009-08-02T20:29:33
252,486
2
0
null
null
null
null
UTF-8
Scheme
false
false
472
sls
simplify-dot.sls
(library (numero symbolic simplify-dot) (export simplify-dot) (import (rnrs) (only (srfi :43) vector-fold) (xitomatl AS-match)) (define (simplify-dot expr) (match expr (('dot (? vector? u) (? vector? v)) (vector-fold (lambda (i x y) `(+ ,x ,y)) 0 (vector-map (lambda (a b) `(* ,a ,b)) u v))) (else expr))) )
false
397aafbb815218723703eb0737e93f47e7448b31
2c291b7af5cd7679da3aa54fdc64dc006ee6ff9b
/ch3/exercise.3.6.scm
0381d82bc27ea44bfc8867df4db00756d2c4f20f
[]
no_license
etscrivner/sicp
caff1b3738e308c7f8165fc65a3f1bc252ce625a
3b45aaf2b2846068dcec90ea0547fd72b28f8cdc
refs/heads/master
2021-01-10T12:08:38.212403
2015-08-22T20:01:44
2015-08-22T20:01:44
36,813,957
1
0
null
null
null
null
UTF-8
Scheme
false
false
450
scm
exercise.3.6.scm
(define random-init 1019823) ;; Linear congruential generator with constants from Wikipedia (define (rand-update x) (modulo (+ (* 1664525 x) 1013904223) (expt 2 32))) (define rand (let ((x random-init)) (lambda (op . args) (cond ((eq? op 'generate) (set! x (rand-update x)) x) ((eq? op 'reset) (set! x (car args))) (else (error "Uncrecognized operation -- RAND" op))))))
false
070426428dd5f9f9a3131016a59d3fff9cf9f211
32130475e9aa1dbccfe38b2ffc562af60f69ac41
/04_01_02.scm
5f7517b5fa9c00c8fc306c1d8a8cd100b8b9bafb
[]
no_license
cinchurge/SICP
16a8260593aad4e83c692c4d84511a0bb183989a
06ca44e64d0d6cb379836d2f76a34d0d69d832a5
refs/heads/master
2020-05-20T02:43:30.339223
2015-04-12T17:54:45
2015-04-12T17:54:45
26,970,643
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,175
scm
04_01_02.scm
(use test) (use extras) (load "metacircular.scm") ; Exercise 4.2: (printf "Exercise 4.2: see comments~N") (newline) ; a: Louis's plan is flawed because the application? test will match ; any pair, thus treating EVERYTHING as an application. Assignment ; in this case will be executed at all. (define x 3) will result ; in an attempt to apply the 'define' procedure with arguments x and 3. ; b: Simply redefine the application? test as: (define (application? exp) (tagged-list? exp 'call)) ; Exercise 4.3: ; micro-eval (data-directed) (define (test-eval-apply eval-fn) (let ((env '())) (begin (test "Self-evaluating: numeric" 1 (eval-fn 1 env)) (test "Self-evaluating: string" "hello, world!" (eval-fn "hello, world!" env)) ;(define foo 42) ;(define bar 24) ;(test "Variable: foo" 'foo (eval-fn 'foo env)) ;(test "Variable: bar" 'bar (eval-fn 'bar env)) (test "Quoted: 'foo" ''foo (eval-fn '''foo env)) (test "Quoted: 'bar" ''bar (eval-fn '''bar env)) (test "Assignment: 'bar" ''bar (eval-fn '''bar env)) ))) (test-eval-apply micro-eval) ; Exercise 4.4: ; Exercise 4.5: ; micro-eval with modified cond (define (micro-eval expr env) (cond ((self-evaluating? expr) expr) ((true? expr) #t) ((false? expr) #f) ((variable? expr) (lookup-variable-value expr env)) ((and? expr) (eval-and expr env)) ((or? expr) (eval-or expr env)) ((quoted? expr) (text-of-quotation expr)) ((assignment? expr) (eval-assignment expr env)) ((definition? expr) (eval-definition expr env)) ((if? expr) (eval-if expr env)) ((lambda? expr) (make-procedure (lambda-parameters expr) (lambda-body expr) env)) ((begin? expr) (eval-sequence (begin-actions expr) env)) ((cond? expr) (micro-eval (cond->if expr env) env)) ((application? expr) (micro-apply (micro-eval (operator expr) env) (list-of-values (operands expr) env))) (else (error "Unknown expression type: EVAL" expr)))) (let ((env (setup-environment)) (expr '(cond ((cons 1 2) => car)))) (test '(b 2) (micro-eval '(assoc 'b '((a 1) (b 2))) env))) (define (cond->if expr env) (expand-clauses (cond-clauses expr) env)) (define (expand-clauses clauses env) (if (null? clauses) 'false (let ((first (car clauses)) ; Let's work on the first clause (rest (cdr clauses))) (display "expand-clauses") (cond ((cond-else-clause? first) ; What to do if we see an else clause (if (null? rest) ; Nothing after else, doh! (sequence->exp (cond-actions first)) (error "ELSE clause isn't last: COND->IF" clauses))) ((cond-testapply-clause? first) ; What to do when we see the test => recipient syntax (let* ((test (cond-testapply-test first)) (test-result (micro-eval test env)) (recipient (micro-eval (cond-testapply-recipient first) env))) (make-if test-result (micro-apply recipient (list test-result)) (expand-clauses rest env)))) (else (make-if (cond-predicate first) (sequence->exp (cond-actions first)) (expand-clauses rest env))))))) (define (cond-testapply-clause? clause) (and (= (length clause) 3) (eq? (cadr clause) '=>))) (define (cond-testapply-recipient clause) (caddr clause)) (define (cond-testapply-test clause) (car clause)) ;(load "test-metacircular.scm") (let ((env (setup-environment)) (expr '(cond ((cons 1 2) => car)))) (display (micro-eval '(assoc 'b '((a 1) (b 2))) env))(newline) (test "(assoc 'b '((a 1) (b 2)))" '(b 2) (micro-eval '(assoc 'b '((a 1) (b 2))))) (test "cond-testapply-clause?" #t (cond-testapply-clause? expr)) (micro-eval '(cond ('(1 2) => car)) env) (test "cond: test => recipient" (expand-clauses '(((cons 1 2) => car)) env)))
false
63156d2edc4e720b7f38749c2de2d416a0a3c33a
18fb2e9f5ce1a5c876d9e0694ed001d8932b2fde
/examples/questionnaires/language.scm
89b5de373a16e828b0326562dffab4df086b2764
[ "MIT", "X11" ]
permissive
christoff-buerger/racr
0669a0ba537c6b6d7e4379dbb453c42ff8456d25
b83e18d751bb11f844e8face7a81770819f1a3a9
refs/heads/master
2023-09-04T05:25:04.113295
2023-08-19T22:29:23
2023-08-19T22:29:23
32,183,687
33
10
null
2017-02-13T20:38:03
2015-03-13T22:19:59
Scheme
UTF-8
Scheme
false
false
14,859
scm
language.scm
; This program and the accompanying materials are made available under the ; terms of the MIT license (X11 license) which accompanies this distribution. ; Author: C. Bürger #!r6rs (library (questionnaires language) (export ql Form If ?? ~? ~> ~! ~~ ->Body ->Expression ->Operands ->name ->label ->type ->value ->operator ->* <- index count =root =error-question =error-question? =g-Lookup =l-Lookup =type =valid? =l-valid? =s-expr =find-active =active? =shown? =value =dialog-type =dialog-printer =value-printer =widget =render Boolean Number String ErrorType && // != load-questionnaire save-questionnaire) (import (rnrs) (rnrs eval) (compatibility mlist) (racr core) (prefix (racket base) r:) (racket format) (racket class) (racket gui base)) (define ql (create-specification)) (define ql-env (environment '(rnrs) '(questionnaires language))) ;;; AST accessors: (define (->Body n) (ast-child 'Body n)) (define (->Expression n) (ast-child 'Expression n)) (define (->name n) (ast-child 'name n)) (define (->label n) (ast-child 'label n)) (define (->type n) (ast-child 'type n)) (define (->value n) (ast-child 'value n)) (define (->operator n) (ast-child 'operator n)) (define (->Operands n) (ast-child 'Operands n)) (define (->* n) (ast-children n)) (define (<- n) (ast-parent n)) (define (index n) (ast-child-index n)) (define (count n) (ast-num-children n)) ;;; Attribute accessors: (define (=root n) (att-value 'root n)) (define (=error-question n) (att-value 'error-question n)) (define (=error-question? n) (att-value 'error-question? n)) (define (=g-Lookup n name) (att-value 'g-Lookup n name)) (define (=l-Lookup n name) (att-value 'l-Lookup n name)) (define (=type n) (att-value 'type n)) (define (=valid? n) (att-value 'valid? n)) (define (=l-valid? n) (att-value 'l-valid? n)) (define (=s-expr n) (att-value 's-expr n)) (define (=find-active n name) (att-value 'find-active n name)) (define (=active? n) (att-value 'active? n)) (define (=shown? n) (att-value 'shown? n)) (define (=value n) (att-value 'value n)) (define (=dialog-type n) (att-value 'dialog-type n)) (define (=dialog-printer n) (att-value 'dialog-printer n)) (define (=value-printer n) (att-value 'value-printer n)) (define (=widget n) (att-value 'widget n)) (define (=render n) (att-value 'render n)) ;;; AST constructors: (define (Form . e) (create-ast ql 'Form (list (create-ast-list (cons (~? (list #f) "" (~! ErrorValue)) e))))) (define (If c . e) (create-ast ql 'Group (list c (create-ast-list e)))) (define ?? (case-lambda ((n l t) (create-ast ql 'OrdinaryQuestion (list n l t ErrorValue))) ((n l t v) (create-ast ql 'OrdinaryQuestion (list n l t v))))) (define (~? n l e) (create-ast ql 'ComputedQuestion (list n l e))) (define (~> n) (create-ast ql 'Use (list n))) (define (~! v) (create-ast ql 'Constant (list v))) (define (~~ o . a) (create-ast ql 'Computation (list o (create-ast-list a)))) ;;; Type & operator support: (define (Boolean v) (boolean? v)) (define (Number v) (number? v)) (define (String v) (string? v)) (define valid-types (list Boolean Number String)) (define (type->acceptor t) (find (lambda (e) (eq? e t)) valid-types)) (define (value->type v) (find (lambda (e) (e v)) valid-types)) (define (ErrorType) (list 'ErrorType)) (define (ErrorValue) (list 'ErrorValue)) (define (&& . a) (for-all (lambda (x) x) a)) (define (// . a) (find (lambda (x) x) a)) (define (!= . a) (or (null? a) (and (not (memq (car a) (cdr a))) (apply != (cdr a))))) ;;; Exceptions: (define-condition-type ql-error &non-continuable make-ql-error ql-error?) (define (ql-error: . messages) (define (object->string o) (call-with-string-output-port (lambda (port) (display o port)))) (define message (fold-left (lambda (result m) (string-append result (if (string? m) m (string-append " [" (object->string m) "] ")))) "IMPLEMENTATION ERROR: " messages)) (raise (condition (make-ql-error) (make-message-condition message)))) ;;; Loading and saving: (define (load-questionnaire) (define (update-questions n) ; Set the initial value the widgets of ordinary questions show. (case (ast-node-type n) ((Form Group) (for-each update-questions (->* (->Body n)))) ((ComputedQuestion) #f) (else (send (=widget n) set-value ((=dialog-printer n) (=value n)))))) (define file? (get-file "Select questionnaire" #f #f #f #f (list) (list))) (and file? (let ((form (eval (with-input-from-file file? (lambda () (read))) ql-env))) (update-questions form) (=render form) form))) (define (save-questionnaire form) (define file? (put-file "Select questionnaire" #f #f #f #f (list) (list))) (when file? (when (file-exists? file?) (delete-file file?)) (with-output-to-file file? (lambda () (write (=s-expr form)))))) (with-specification ql ;;; AST scheme: (ast-rule 'Form->Element*<Body) (ast-rule 'Element->) (ast-rule 'Group:Element->Expression-Element*<Body) (ast-rule 'Question:Element->name-label) (ast-rule 'OrdinaryQuestion:Question->type-value) (ast-rule 'ComputedQuestion:Question->Expression) (ast-rule 'Expression->) (ast-rule 'Use:Expression->name) (ast-rule 'Constant:Expression->value) (ast-rule 'Computation:Expression->operator-Expression*<Operands) (compile-ast-specifications 'Form) ;;; Support attributes: (ag-rule root ; The root of a questionnaire. (Form (lambda (n) n))) (ag-rule error-question ; Question representing undeclared uses. (Form (lambda (n) (ast-child 1 (->Body n))))) (ag-rule error-question? ; Is a question the error question? (Element (lambda (n) (eq? n (=error-question n))))) ;;; Name analysis: (define (find-L name l i) (ast-find-child* (lambda (i e) (=l-Lookup e name)) l (cons 1 i))) (ag-rule g-Lookup ; Find question w.r.t. context (error question if no hit, declare before use). ((Form Body) (lambda (n name) (or (find-L name (<- n) (- (index n) 1)) (=error-question n)))) ((Group Body) (lambda (n name) (or (find-L name (<- n) (- (index n) 1)) (=g-Lookup (<- n) name))))) (ag-rule l-Lookup ; Find question in subtree (#f if no hit). (Question (lambda (n name) (if (eq? (->name n) name) n #f))) (Group (lambda (n name) (find-L name (->Body n) (count (->Body n)))))) ;;; Type analysis: (ag-rule type ; Type of questions & expressions. (OrdinaryQuestion (lambda (n) (if (type->acceptor (->type n)) (->type n) ErrorType))) (ComputedQuestion (lambda (n) (=type (->Expression n)))) (Use (lambda (n) (=type (=g-Lookup n (->name n))))) (Constant (lambda (n) (or (value->type (->value n)) ErrorType))) (Computation (lambda (n) (let ((ops (->* (->Operands n)))) (define (in . l) (memq (->operator n) l)) (define (ensure-type t l) (for-all (lambda (n) (eq? (=type n) t)) l)) (cond ((in && // not) (if (ensure-type Boolean ops) Boolean ErrorType)) ((in = < > <= >= !=) (if (ensure-type Number ops) Boolean ErrorType)) ((in + - * /) (if (ensure-type Number ops) Number ErrorType)) ((in string-append) (if (ensure-type String ops) String ErrorType)) ((in string=? string<? string>? string<=? string>=?) (if (ensure-type String ops) Boolean ErrorType)) (else ErrorType)))))) ;;; Well-formedness: (ag-rule valid? ; Is the form well-formed? (Form (lambda (n) (for-all =valid? (cdr (->* (->Body n)))))) (Group (lambda (n) (and (=l-valid? n) (for-all =valid? (->* (->Body n)))))) (Question =l-valid?)) (ag-rule l-valid? ; Is a form element well-formed? (Group (lambda (n) (eq? (=type (->Expression n)) Boolean))) (Question (lambda (n) (and (not (eq? (=type n) ErrorType)) (let ((previous (=g-Lookup n (->name n)))) (or (=error-question? previous) (eq? (=type n) (=type previous)))))))) ;;; Persistency: (define (: p) (string->symbol (substring (~a p) 12 (- (string-length (~a p)) 1)))) (ag-rule s-expr ; Symbolic expression representing form. (Form (lambda (n) `(Form ,@(map =s-expr (cdr (->* (->Body n))))))) (Group (lambda (n) `(If ,(=s-expr (->Expression n)) ,@(map =s-expr (->* (->Body n)))))) (ComputedQuestion (lambda (n) `(~? ',(->name n) ,(->label n) ,(=s-expr (->Expression n))))) (Use (lambda (n) `(~> ',(->name n)))) (Constant (lambda (n) `(~! ,(->value n)))) (Computation (lambda (n) `(~~ ,(: (->operator n)) ,@(map =s-expr (->* (->Operands n)))))) (OrdinaryQuestion (lambda (n) `(?? ',(->name n) ,(->label n) ,(: (->type n)) ,@(if (eq? (->value n) ErrorValue) (list) (list (->value n))))))) ;;; Interpretation: (ag-rule find-active ; Find active question (error question if no hit). (Element (lambda (n name) (define (find-active current) (or (and (=active? current) current) (find-active (=g-Lookup current name)))) (find-active (=g-Lookup n name))))) (ag-rule active? ; Is a form part active (the error question is active)? (Form (lambda (n) #t)) (Group (lambda (n) (let ((v (=value (->Expression n)))) (and (boolean? v) v)))) (Question (lambda (n) (or (=error-question? n) (and (=active? (<- n)) (=error-question? (=find-active n (->name n)))))))) (ag-rule shown? ; Is a form part shown (the error question is not shown)? (Element (lambda (n) (and (not (=error-question? n)) (=active? n))))) (ag-rule value ; Value of questions & expressions. (ComputedQuestion (lambda (n) (=value (->Expression n)))) (Constant (lambda (n) (if (eq? (=type n) ErrorType) ErrorValue (->value n)))) (Use (lambda (n) (if (or (eq? (=type n) ErrorType) (not (eq? (=type (=find-active n (->name n))) (=type n)))) ErrorValue (=value (=find-active n (->name n)))))) (OrdinaryQuestion (lambda (n) (if (or (eq? (=type n) ErrorType) (not ((type->acceptor (=type n)) (->value n)))) ErrorValue (->value n)))) (Computation (lambda (n) (or (and (eq? (=type n) ErrorType) ErrorValue) (let ((args (map =value (->* (->Operands n))))) (find (lambda (value) (eq? value ErrorValue)) args) (guard (x (error? ErrorValue)) (apply (->operator n) args))))))) ;;; Graphical user interface: (ag-rule dialog-type ; Widget type used to represent question. (Question (lambda (n) (cond ((eq? (=type n) Boolean) check-box%) ((eq? (=type n) String) text-field%) ((eq? (=type n) Number) text-field%) ((eq? (=type n) ErrorType) text-field%) (else (ql-error: "no dialog for" (=type n) "implemented")))))) (ag-rule dialog-printer ; Function pretty printing AST values for the question's dialog. (Question (lambda (n) (cond ((eq? (=dialog-type n) check-box%) (lambda (v) (and (boolean? v) v))) ((eq? (=dialog-type n) text-field%) ; (lambda (v) (if (eq? v ErrorValue) "" (~a v))) (let ((fits? (type->acceptor (=type n)))) (cond ((eq? (=type n) Number) (lambda (v) (if (fits? v) (number->string v) ""))) ((eq? (=type n) String) (lambda (v) (if (fits? v) v ""))) ((eq? (=type n) ErrorType) (lambda (v) "")) (else (ql-error: "no" (=type n) "printer for" (=dialog-type n) "implemented"))))) (else (ql-error: "no dialog-printer for" (=dialog-type n) "implemented")))))) (ag-rule value-printer ; Function pretty printing dialog values for the question's ast. (OrdinaryQuestion (lambda (n) (cond ((eq? (=dialog-type n) check-box%) (lambda (v) v)) ((eq? (=dialog-type n) text-field%) (if (eq? (=type n) Number) (lambda (v) (let ((number? (r:string->number v))) (if number? number? v))) (lambda (v) v))) (else (ql-error: "no value-printer for" (=dialog-type n) "implemented")))))) (ag-rule widget ; Widget representing form element. (Form (lambda (n) (define frame (new frame% [label "Questionnaire"] [border 5])) (define menu-bar (new menu-bar% [parent frame])) (define menu (new menu% [parent menu-bar] [label "File"])) (new menu-item% [parent menu] [label "Save"] [callback (lambda x (save-questionnaire n))]) (new menu-item% [parent menu] [label "Load"] [callback (lambda x (load-questionnaire))]) (unless (=valid? n) (new message% [parent frame] [label 'caution])) (new vertical-panel% [parent frame]))) (Group (lambda (n) (new vertical-panel% [parent (=widget (<- n))] [border 5] [style (r:list 'border)]))) (ComputedQuestion (lambda (n) (new (=dialog-type n) [parent (=widget (<- n))] [label (->label n)] [enabled #f]))) (OrdinaryQuestion (lambda (n) (define (callback widget event) (rewrite-terminal 'value n ((=value-printer n) (send widget get-value))) (=render (=root n))) (new (=dialog-type n) [parent (=widget (<- n))] [label (->label n)] [callback callback])))) (ag-rule render ; Incrementally render form. (OrdinaryQuestion (lambda (n) #f)) (ComputedQuestion (lambda (n) (send (=widget n) set-value ((=dialog-printer n) (=value n))))) (Form (lambda (n) (send (=widget n) begin-container-sequence) (let ((shown (filter =shown? (->* (->Body n))))) (send (=widget n) change-children (lambda x (mlist->list (map =widget shown)))) (map =render shown)) (send (send (=widget n) get-parent) show #t) (send (=widget n) end-container-sequence))) (Group (lambda (n) (let ((shown (filter =shown? (->* (->Body n))))) (send (=widget n) change-children (lambda x (mlist->list (map =widget shown)))) (map =render shown))))) (compile-ag-specifications)))
false
a47c982ca9fb9de88dfc00201c21b375796e6198
4b570eebce894b4373cba292f09883932834e543
/ch1/1.42.scm
a2defa381ef23ddac8707716808fdda72f304d43
[]
no_license
Pulkit12083/sicp
ffabc406c66019e5305ad701fbc022509319e4b1
8ea6c57d2b0be947026dd01513ded25991e5c94f
refs/heads/master
2021-06-17T13:44:06.381879
2021-05-14T16:52:30
2021-05-14T16:52:30
197,695,022
0
0
null
2021-04-14T17:04:01
2019-07-19T03:25:41
Scheme
UTF-8
Scheme
false
false
1,078
scm
1.42.scm
;;1.42 ;;Newton's method ;; f(x) = x - g(x)/Dg(x) ;; Dg(x) = (g(x+dx) - g(x))/dx (define (fixedPoint func guess precision) (let ((fixedVal (func guess))) (cond ((< (abs (- fixedVal guess)) precision) guess) (else (fixedPoint func fixedVal precision))))) (define dx 0.00001) (define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) (define (newtons-method g guess) (fixedPoint (newton-transform g) guess 0.0001)) (define (sqroot x) (newton-method (lambda (y) (- (square y) x)) 1.0)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Approximate zeros of cubic x^3 +ax^2 +bc+ c ;; use the fixed point ;; 1.40 (define (cubic a b c) (lambda (x) (+ (* x x x) (* a x x) (* b x) c))) (newtons-method (cubic 4 3 8) 1) ((cubic 4 3 8) -3.76734) ;; 1.41 (define (double f) (lambda (x) (f (f x)))) (define (inc x) (+ x 1)) (((double (double double)) inc) 5) ;; 21 ;; 1.42 implement composition (define (compose f g) (lambda (x) (f (g x)))) ((compose square inc) 6) ;;49
false
408de4154f1cec51b6ec9d3a3ceacd40cfb7f230
ebc5db754946092d65c73d0b55649c50d0536bd9
/2020/day10.scm
9341849d371c26ca96768446e8aca2d8da5526bb
[]
no_license
shawnw/adventofcode
6456affda0d7423442d0365a2ddfb7b704c0aa91
f0ecba80168289305d438c56f3632d8ca89c54a9
refs/heads/master
2022-12-07T22:54:04.957724
2022-12-02T07:26:06
2022-12-02T07:26:06
225,129,064
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,580
scm
day10.scm
#!/usr/local/bin/csi -s (import (chicken format) (chicken io) (chicken sort) (srfi 1)) (declare (fixnum-arithmetic) (block)) (define (vector-update! v i f) (vector-set! v i (f (vector-ref v i))) v) (define (count-differences adapters) (let loop ((adapters adapters) (previous 0) (counts (vector 0 0 0 1))) (if (null? adapters) counts (let* ((adapter (car adapters)) (diff (- adapter previous))) (if (> diff 3) (error "Too large a different between adapter " previous " and " adapter) (loop (cdr adapters) adapter (vector-update! counts diff add1))))))) (define (solve1 adapters) (let ((diffs (count-differences adapters))) (* (vector-ref diffs 1) (vector-ref diffs 3)))) ;;; Won't work well with large lists (define (count-arrangements adapters prev) (cond ((null? adapters) 1) ; No more ((null? (cdr adapters)) 1) ; One more ((null? (cddr adapters)) ; Two more (if (> (- (cadr adapters) prev) 3) 1 2)) (else ; Three or more left (let ((gt3 (> (- (caddr adapters) prev) 3)) (gt2 (> (- (cadr adapters) prev) 3))) (cond ((and gt3 gt2) (count-arrangements (cdr adapters) (car adapters))) (gt3 (+ (count-arrangements (cdr adapters) (car adapters)) (count-arrangements (cddr adapters) (cadr adapters)))) (else (+ (count-arrangements (cdr adapters) (car adapters)) (count-arrangements (cddr adapters) (cadr adapters)) (count-arrangements (cdddr adapters) (caddr adapters))))))))) (define (partition-adapters adapters) (let* ((adapters (cons 0 adapters)) (device (+ 3 (last adapters))) (adapters (append! adapters (list device)))) (let loop ((adapters adapters) (acc1 '()) (acc2 '())) (if (null? (cdr adapters)) (reverse! (cons (reverse! (cons (car adapters) acc1)) acc2)) (let ((current (car adapters))) (if (= (- (cadr adapters) current) 3) (loop (cdr adapters) '() (cons (reverse! (cons current acc1)) acc2)) (loop (cdr adapters) (cons current acc1) acc2))))))) (define (solve2 adapters) (let ((partitions (partition-adapters adapters))) (fold (lambda (part acc) (* acc (count-arrangements (cdr part) (car part)))) 1 partitions))) (define input (sort! (read-list) <)) (printf "Part 1: ~A~%" (solve1 input)) (printf "Part 2: ~S~%" (solve2 input))
false
68b03f20af805d7781ba5b101ea63c8f7398d5ed
f40f97c37847103138c82d3f1b3956d9c2592b76
/mvp/synthesis.scm
39876a22e9617bf378ddd00ab672568a3bc1ade7
[ "MIT" ]
permissive
k-tsushima/Shin-Barliman
34df6868aafcd2d36dbbc57ef56eab555da05a5c
abea8511d18273196ac806dcf14b88d4098e18f8
refs/heads/master
2021-06-25T13:47:22.721816
2020-01-24T04:11:24
2020-01-24T04:11:24
182,607,716
16
1
MIT
2020-12-02T00:12:39
2019-04-22T02:18:17
Scheme
UTF-8
Scheme
false
false
4,426
scm
synthesis.scm
(load "pmatch.scm") (load "common-chez.scm") (load "mk-chez.scm") (load "mk.scm") (load "interp.scm") (load "synthesis-template.scm") ;; Loading will occur at first use if not explicitly forced like this. (load-config #f) (define PROGRAM-NAME "synthesis") (define FUEL 100000) ; ticks (define *engine-box* (box #f)) (define *start-time* (box #f)) #| begin logging infrastructure definitions (how to abstract this?) |# (define ENABLE-LOGGING (config-ref 'enable-synthesis-subprocess-logging)) (define LOG-FILE-NAME (format "~a-pid-~s.log" PROGRAM-NAME (get-process-id))) (define LOG-FILE-OUTPUT-PORT-BOX (box #f)) (define (logf format-str . args) (when ENABLE-LOGGING (unless (unbox LOG-FILE-OUTPUT-PORT-BOX) (let ((output-port (open-output-file LOG-FILE-NAME 'replace))) (set-box! LOG-FILE-OUTPUT-PORT-BOX output-port))) (apply fprintf (unbox LOG-FILE-OUTPUT-PORT-BOX) format-str args) (flush-output-port (unbox LOG-FILE-OUTPUT-PORT-BOX)))) #| end logging infrastructure definitions |# (logf "started ~a\n" PROGRAM-NAME) (logf "writing synthesis-subprocess-ready to stdout\n") (write '(synthesis-subprocess-ready)) (flush-output-port) (logf "wrote synthesis-subprocess-ready to stdout\n") (let loop ((msg (read))) (cond ((eof-object? msg) (write `(unexpected-eof) (current-error-port)) (flush-output-port (current-error-port)) (exit)) (else (pmatch msg [(stop-synthesis) (logf "read message ~s from stdin\n" msg) (set-box! *engine-box* #f) (set-box! *start-time* #f) (write `(stopped-synthesis)) (flush-output-port) (loop (read))] [(get-status) (logf "read message ~s from stdin\n" msg) (write `(status ,(if (unbox *engine-box*) 'synthesizing 'waiting))) (flush-output-port) (if (input-port-ready? (current-input-port)) (loop (read)) (loop `(no-message-to-read)))] [(synthesize (,definitions ,inputs ,outputs) ,synthesis-id) (logf "read message ~s from stdin\n" msg) (logf "definitions:\n\n~s\n\n\n" definitions) (logf "inputs:\n\n~s\n\n\n" inputs) (logf "outputs:\n\n~s\n\n\n" outputs) (let ((expr (fill-in-template definitions inputs outputs))) (logf "filled in template for synthesis:\n\n~s\n\n\n" expr) (let ((e (make-engine (lambda () (list (eval expr) synthesis-id))))) (set-box! *engine-box* e) (set-box! *start-time* (current-time)) (if (input-port-ready? (current-input-port)) (loop (read)) (loop `(no-message-to-read)))))] [(no-message-to-read) ;; don't use 'logf' to log this "dummy" message, since it will ;; fill up the log file quickly! (let ((e (unbox *engine-box*))) (when e (pmatch (e FUEL (lambda (remaining-fuel val/synthesis-id) (pmatch val/synthesis-id [(,val ,synthesis-id) `(completed ,remaining-fuel ,val ,synthesis-id)])) (lambda (e) `(expired ,e))) [(completed ,remaining-fuel ,val ,synthesis-id) (set-box! *engine-box* #f) (let ((elapsed-time (time-difference (current-time) (unbox *start-time*)))) (let ((elapsed-seconds (time-second elapsed-time)) (elapsed-nanoseconds (time-nanosecond elapsed-time))) (let ((statistics `(elapsed-time (seconds ,elapsed-seconds) (nanoseconds ,elapsed-nanoseconds)))) (let ((msg `(synthesis-finished ,synthesis-id ,val ,statistics))) (write msg) (logf "wrote msg ~s\n" msg) (set-box! *start-time* #f) (flush-output-port) (loop (read))))))] [(expired ,e) (set-box! *engine-box* e)]))) (if (input-port-ready? (current-input-port)) (loop (read)) (loop `(no-message-to-read)))] [,msg (logf "read unknown message ~s from stdin\n" msg) (write `(unknown-message-type ,msg) (current-error-port)) (flush-output-port (current-error-port)) (exit)]))))
false
2b1422771b168cf8e3a28836709c1783a5cd45a8
dae624fc36a9d8f4df26f2f787ddce942b030139
/chapter-09/let.scm
ea3a4ac4a752816d3ef85c63f3c6ceb0d2992b06
[ "MIT" ]
permissive
hshiozawa/gauche-book
67dcd238c2edeeacb1032ce4b7345560b959b243
2f899be8a68aee64b6a9844f9cbe83eef324abb5
refs/heads/master
2020-05-30T20:58:40.752116
2019-10-01T08:11:59
2019-10-01T08:11:59
189,961,787
0
0
null
null
null
null
UTF-8
Scheme
false
false
557
scm
let.scm
(use util.match) (define (make-player . args) (define (loop lis) (match lis [() '()] [(attr value . rest) (cons (cons attr value) (loop rest))])) (loop args)) (make-player 'hp 320 'mp 66 'position #f 'inventory '(potion potion dagger cookie dagger)) (define (make-player . args) (let loop ((lis args)) (match lis [() '()] [(attr value . rest) (cons (cons attr value) (loop rest))]))) (define *player* (make-player 'hp 320 'mp 66 'position #f 'inventory '(potion potion dagger cookie dagger)))
false
f5fcab0004dc961265bef9c133c2a9428abd4aea
2d19dc910d6635700bac6a1e5326edaa28979810
/ext/crypto/math/ec.scm
e19a40f8be271b80e325a8425774bbc6ed63a7ac
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "BSD-2-Clause", "MIT" ]
permissive
spurious/sagittarius-scheme-mirror
e88c68cd4a72c371f265f5174d4e5f7c9189fff5
53f104188934109227c01b1e9a9af5312f9ce997
refs/heads/master
2021-01-23T18:00:33.235458
2018-11-27T21:03:18
2018-11-27T21:03:18
2,843,561
5
2
null
null
null
null
UTF-8
Scheme
false
false
24,309
scm
ec.scm
;;; -*- mode: scheme; coding: utf-8 -*- ;;; ;;; ec.scm - Elliptic curve ;;; ;; this library provides 3 things ;; - curve parameters ;; - constructors (ec point and curve) ;; - and arithmetic procedure for ec points ;; ;; there are 2 curves used, one is Fp and other one is F2m. ;; Fp is ;; y^2 = x^3 + ax + b (mod p) ;; F2m is ;; y^2 + xy = x^3 + ax^2 + b (mod p) #!core (library (math ec) (export make-ec-point ec-point-infinity? ec-point? ec-point-x ec-point-y ec-point-add ec-point-twice ec-point-negate ec-point-sub ec-point-mul encode-ec-point decode-ec-point ;; NIST parameters NIST-P-192 (rename (NIST-P-192 secp192r1)) NIST-P-224 (rename (NIST-P-224 secp224r1)) NIST-P-256 (rename (NIST-P-256 secp256r1)) NIST-P-384 (rename (NIST-P-384 secp384r1)) NIST-P-521 (rename (NIST-P-521 secp521r1)) NIST-K-163 (rename (NIST-K-163 sect163k1)) NIST-K-233 (rename (NIST-K-233 sect233k1)) NIST-K-283 (rename (NIST-K-283 sect283k1)) NIST-K-409 (rename (NIST-K-409 sect409k1)) NIST-K-571 (rename (NIST-K-571 sect571k1)) NIST-B-163 (rename (NIST-B-163 sect163r2)) NIST-B-233 (rename (NIST-B-233 sect233r1)) NIST-B-283 (rename (NIST-B-283 sect283r1)) NIST-B-409 (rename (NIST-B-409 sect409r1)) NIST-B-571 (rename (NIST-B-571 sect571r1)) ;; SEC 2 parameters sect113r1 ;; ellitic curve accessors elliptic-curve? elliptic-curve-field elliptic-curve-a elliptic-curve-b ;; field ec-field-fp? ec-field-fp-p ec-field-f2m? ec-field-f2m-m ec-field-f2m-k1 ec-field-f2m-k2 ec-field-f2m-k3 ec-field-size ;; parameter accessors ec-parameter? ec-parameter-curve ec-parameter-g ec-parameter-n ec-parameter-h ec-parameter-seed ec-parameter-oid lookup-ec-parameter make-ec-parameter make-fp-ec-parameter make-f2m-ec-parameter ;; for testing make-elliptic-curve make-ec-field-fp make-ec-field-f2m ec-infinity-point ) (import (core) (core base) (core errors) (core syntax) (core inline) (core record) (sagittarius)) ;; modular arithmetic ;; these are needed on for Fp ;; a + b (mod p) (define (mod-add a b p) (mod (+ a b) p)) ;; a - b (mod p) (define (mod-sub a b p) (mod (- a b) p)) ;; a * b (mod p) ;;(define (mod-mul a b p) (mod (* a b) p)) (define (mod-mul a b p) (* (mod a p) (mod b p))) ;; a / b (mod p) (define (mod-div a b p) (mod (* a (mod-inverse b p)) p)) ;; a^2 (mod p) (define (mod-square a p) (mod-expt a 2 p)) ;; -a (mod p) (define (mod-negate a p) (mod (- a) p)) ;; mod-inverse is defined in (sagittarius) ;; mod-expt is defined in (sagittarius) ;; to make constant foldable, we use vectors to represent ;; data structure ;;; ;; EC Curve ;; curve is a vector which contains type and parameters ;; for the curve. ;; make my life easier (define-syntax define-vector-type (lambda (x) (define (order-args args fs) (map (lambda (a) (cond ((memp (lambda (f) (bound-identifier=? a f)) fs) => car) (else (syntax-violation 'define-vector-type "unknown tag" a)))) args)) (define (generate-accessor k acc) ;; starting from 1 because 0 is type tag (let loop ((r '()) (i 1) (acc acc)) (syntax-case acc () ((name rest ...) (with-syntax ((n (datum->syntax k i))) (loop (cons #'(define (name o) (vector-ref o n)) r) (+ i 1) #'(rest ...)))) (() r)))) (syntax-case x () ((k type (ctr args ...) pred (field accessor) ...) (and (identifier? #'pred) (identifier? #'type) (identifier? #'ctr)) (with-syntax (((ordered-args ...) (order-args #'(args ...) #'(field ...))) ((acc ...) (generate-accessor #'k #'(accessor ...)))) #'(begin (define (ctr args ...) (vector 'type ordered-args ...)) (define (pred o) (and (vector? o) (= (vector-length o) (+ (length #'(field ...)) 1)) (eq? (vector-ref o 0) 'type))) acc ...)))))) ;;; Finite field ;; Fp (define-vector-type ec-field-fp (make-ec-field-fp p) ec-field-fp? (p ec-field-fp-p)) ;; F2m ;; TODO check valid reduction polynominal ;; It must be either trinominal (X^m + X^k + 1 with m > k >= 1) or ;; pentanominal (X^m X^k3 + X^k2 + X^k1 + 1 with m > k3 > k2 > k1 >= 1) (define-vector-type ec-field-f2m (make-ec-field-f2m m k1 k2 k3) ec-field-f2m? (m ec-field-f2m-m) (k1 ec-field-f2m-k1) (k2 ec-field-f2m-k2) (k3 ec-field-f2m-k3)) ;; F2m field operations (define (f2m-ppb? f) (not (or (zero? (ec-field-f2m-k2 f)) (zero? (ec-field-f2m-k3 f))))) (define (f2m-add field x y) (if (zero? y) x (bitwise-xor x y))) (define (f2m-mul field x y) (define ax x) (define bx y) (define cz (if (bitwise-bit-set? ax 0) bx 0)) (define ash bitwise-arithmetic-shift-left) (define m (ec-field-f2m-m field)) (define mm (ash 1 (ec-field-f2m-m field))) (define k1m (ash 1 (ec-field-f2m-k1 field))) (define k2m (ash 1 (ec-field-f2m-k2 field))) (define k3m (ash 1 (ec-field-f2m-k3 field))) (define pbp? (f2m-ppb? field)) (define (mult-z-mod pbp? m mm k1m k2m k3m a) (define az (bitwise-arithmetic-shift-left a 1)) (if (bitwise-bit-set? az m) (let* ((bl (bitwise-length az)) (bm (- (- (bitwise-arithmetic-shift-left 1 bl) 1) mm)) (cm 1) (r (bitwise-and az bm))) (if pbp? (bitwise-xor r cm k1m k2m k3m) (bitwise-xor r cm k1m))) az)) (do ((i 1 (+ i 1)) (bx (mult-z-mod pbp? m mm k1m k2m k3m bx) (mult-z-mod pbp? m mm k1m k2m k3m bx)) (cz cz (if (bitwise-bit-set? ax i) (bitwise-xor cz bx) cz))) ((= i m) cz))) (define (f2m-div field x y) (f2m-mul field x (f2m-inverse field y))) (define (f2m-square field x) (f2m-mul field x x)) (define (f2m-inverse field x) (define m (ec-field-f2m-m field)) (define k1 (ec-field-f2m-k1 field)) (define k2 (ec-field-f2m-k2 field)) (define k3 (ec-field-f2m-k3 field)) (define uz x) (define vz (let ((ppb? (f2m-ppb? field))) (bitwise-ior (bitwise-arithmetic-shift-left 1 m) 1 (bitwise-arithmetic-shift-left 1 k1) (if ppb? (bitwise-arithmetic-shift-left 1 k2) 0) (if ppb? (bitwise-arithmetic-shift-left 1 k3) 0)))) (when (<= uz 0) (assertion-violation 'f2m-inverse "x is zero or negative" x)) (let loop ((uz uz) (vz vz) (g1z 1) (g2z 0)) (if (= uz 0) g2z (let ((j (- (bitwise-length uz) (bitwise-length vz)))) (let-values (((uz vz g1z g2z j) (if (< j 0) (values vz uz g2z g1z (- j)) (values uz vz g1z g2z j)))) (loop (bitwise-xor uz (bitwise-arithmetic-shift-left vz j)) vz (bitwise-xor g1z (bitwise-arithmetic-shift-left g2z j)) g2z)))))) (define-vector-type ec-curve (make-elliptic-curve field a b) elliptic-curve? (field elliptic-curve-field) (a elliptic-curve-a) (b elliptic-curve-b)) (define-record-type predicate-generic (fields name table) (protocol (lambda (p) (lambda (n) (p n (make-eq-hashtable)))))) (define-syntax define-predicate-generic (syntax-rules () ((_ name) (begin (define dummy (make-predicate-generic 'name)) (define-syntax name (lambda (x) (syntax-case x () ((_ self args (... ...)) #'(let* ((table (predicate-generic-table dummy)) (target self) (eof (cons #f #f)) (itr (%hashtable-iter table))) (let loop () (let-values (((k v) (itr eof))) (when (eq? k eof) (assertion-violation 'name "predicate for given argument is not registered" self)) (if (k target) (v target args (... ...)) (loop)))))) (n (identifier? #'n) #'dummy)))))))) (define-syntax define-predicate-method (syntax-rules () ((_ name pred (self args ...) body ...) (define dummy (let ((table (predicate-generic-table name)) (name (lambda (self args ...) body ...))) (when (hashtable-contains? table pred) (assertion-violation 'name "specified predicate is already registered" pred)) (hashtable-set! table pred name)))))) (define (ec-curve=? a b) (equal? a b)) (define-predicate-generic field-size) (define-predicate-method field-size ec-field-fp? (field) (bitwise-length (ec-field-fp-p field))) (define-predicate-method field-size ec-field-f2m? (field) (ec-field-f2m-m field)) (define (ec-field-size field) (field-size field)) ;; EC point (define-vector-type ec-point (make-ec-point x y) ec-point? (x ec-point-x) (y ec-point-y)) ;; keep it immutable... (define ec-infinity-point '#(ec-point #f #f)) ;; we don't check x and y, these can be #f for infinite point (define (ec-point-infinity? p) (or (not (ec-point-x p)) (not (ec-point-y p)))) (define (ec-point=? a b) (equal? a b)) (define (encode-ec-point curve ep) (if (ec-point-infinity? ep) #vu8(00) (let ((size (div (+ (ec-field-size (elliptic-curve-field curve)) 7) 8))) (bytevector-append #vu8(#x04) (integer->bytevector (ec-point-x ep) size) (integer->bytevector (ec-point-y ep) size))))) (define (decode-ec-point curve bv) (define size (div (+ (ec-field-size (elliptic-curve-field curve)) 7) 8)) (case (bytevector-u8-ref bv 0) ((#x00) ec-infinity-point) ;; TODO support compressed 0x02 and 0x03 ((#x04) (let ((x (bytevector->integer bv 1 (+ 1 size))) (y (bytevector->integer bv (+ 1 size)))) (make-ec-point x y))) (else (implementation-restriction-violation 'decode-ec-point "not supported")))) ;; Twice (define-predicate-generic field-ec-point-twice) (define-predicate-method field-ec-point-twice ec-field-fp? (field curve x) (if (zero? (ec-point-y x)) ec-infinity-point (let* ((xx (ec-point-x x)) (xy (ec-point-y x)) (p (ec-field-fp-p field)) ;; gamma = ((xx^2)*3 + curve.a)/(xy*2) (gamma (mod-div (mod-add (mod-mul (mod-square xx p) 3 p) (elliptic-curve-a curve) p) (mod-mul xy 2 p) p)) ;; x3 = gamma^2 - x*2 (x3 (mod-sub (mod-square gamma p) (mod-mul xx 2 p) p)) ;; y3 = gamma*(xx - x3) - xy (y3 (mod-sub (mod-mul gamma (mod-sub xx x3 p) p) xy p))) (make-ec-point x3 y3)))) (define-predicate-method field-ec-point-twice ec-field-f2m? (field curve x) (if (zero? (ec-point-x x)) ec-infinity-point (let* ((xx (ec-point-x x)) (xy (ec-point-y x)) (l1 (f2m-add field (f2m-div field xy xx) xx)) (x3 (f2m-add field (f2m-add field (f2m-square field l1) l1) (elliptic-curve-a curve))) (y3 (f2m-add field (f2m-add field (f2m-square field xx) (f2m-mul field l1 x3)) x3))) (make-ec-point x3 y3)))) (define (ec-point-twice curve x) (if (ec-point-infinity? x) x (field-ec-point-twice (elliptic-curve-field curve) curve x))) ;; Add (define-predicate-generic field-ec-point-add) (define-predicate-method field-ec-point-add ec-field-fp? (field curve x y) (if (equal? (ec-point-x x) (ec-point-x y)) (if (equal? (ec-point-y x) (ec-point-y y)) (ec-point-twice curve x) ec-infinity-point) (let* ((xx (ec-point-x x)) (xy (ec-point-y x)) (yx (ec-point-x y)) (yy (ec-point-y y)) (p (ec-field-fp-p field)) ;; gamma = (yy - xy)/(yx-xx) (gamma (mod-div (mod-sub yy xy p) (mod-sub yx xx p) p)) ;; x3 = gamma^2 - xx - yx (x3 (mod-sub (mod-sub (mod-square gamma p) xx p) yx p)) ;; y3 = gamma*(xx - x3) - xy (y3 (mod-sub (mod-mul gamma (mod-sub xx x3 p) p) xy p))) (make-ec-point x3 y3)))) (define-predicate-method field-ec-point-add ec-field-f2m? (field curve x y) (let* ((xx (ec-point-x x)) (xy (ec-point-y x)) (yx (ec-point-x y)) (yy (ec-point-y y)) (dx (f2m-add field xx yx)) (dy (f2m-add field xy yy))) (if (zero? dx) (if (zero? dy) (ec-point-twice curve x) ec-infinity-point) (let* ((L (f2m-div field dy dx)) (x3 (f2m-add field (f2m-add field (f2m-add field (f2m-square field L) L) dx) (elliptic-curve-a curve))) (y3 (f2m-add field (f2m-add field (f2m-mul field L (f2m-add field xx x3)) x3) xy))) (make-ec-point x3 y3))))) (define (ec-point-add curve x y) (cond ((ec-point-infinity? x) y) ((ec-point-infinity? y) x) (else (field-ec-point-add (elliptic-curve-field curve) curve x y)))) ;; Negate (define-predicate-generic field-ec-point-negate) (define-predicate-method field-ec-point-negate ec-field-fp? (field x) (make-ec-point (ec-point-x x) (mod-negate (ec-point-y x) (ec-field-fp-p field)))) (define-predicate-method field-ec-point-negate ec-field-f2m? (field x) (let ((xx (ec-point-x x))) (make-ec-point xx (f2m-add field xx (ec-point-y x))))) (define (ec-point-negate curve x) (field-ec-point-negate (elliptic-curve-field curve) x)) (define (ec-point-sub curve x y) (if (ec-point-infinity? y) x ;; add -y (ec-point-add curve x (ec-point-negate curve y)))) ;; http://en.wikipedia.org/wiki/Non-adjacent_form ;; this is probably super slow but for now... (define (ec-point-mul curve p k) (unless (integer? k) (error 'ec-point-mul "integer required for k" k)) (let ((h (* k 3)) (neg (ec-point-negate curve p))) (let loop ((R p) (i (- (bitwise-length h) 2))) (if (zero? i) R (let ((R (ec-point-twice curve R)) (hbit? (bitwise-bit-set? h i))) (if (eqv? hbit? (bitwise-bit-set? k i)) (loop R (- i 1)) (loop (ec-point-add curve R (if hbit? p neg)) (- i 1)))))))) ;;;; ;;; Parameters ;; Parameter contains followings ;; - curve ;; - base point x y (as ec-point) ;; - Order q of the point G (and of the elliptic curve group E) ;; - h = (l - 1) / 160 where l is bit length of prime p ;; - seed (define (ec-parameter? o) (and (vector? o) (= (vector-length o) 7) (eq? (vector-ref o 0) 'ec-parameter))) (define (ec-parameter-curve o) (vector-ref o 1)) (define (ec-parameter-g o) (vector-ref o 2)) ;; as EC point (define (ec-parameter-n o) (vector-ref o 3)) (define (ec-parameter-h o) (vector-ref o 4)) (define (ec-parameter-seed o) (vector-ref o 5)) (define (ec-parameter-oid o) (vector-ref o 6)) ;;; Parameters (define *lookup-table* (make-string-hashtable)) (define (register-ec-parameter oid value) (when (string? oid) (hashtable-set! *lookup-table* oid value))) (define (lookup-ec-parameter oid) (hashtable-ref *lookup-table* oid #f)) ;; from ;; https://www.nsa.gov/ia/_files/nist-routines.pdf (gone) ;; http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf (*) ;; http://koclab.cs.ucsb.edu/teaching/cren/docs/w02/nist-routines.pdf ;; http://www.secg.org/sec2-v2.pdf ;; ;; (*) is not used (define (make-ec-parameter curve base n h S :optional (oid #f)) (let ((p `#(ec-parameter ,curve ,base ,n ,h ,S ,oid))) (when oid (register-ec-parameter oid p)) p)) (define (make-fp-ec-parameter p a b Gx Gy n h S :optional (oid #f)) (make-ec-parameter (make-elliptic-curve (make-ec-field-fp p) a b) (make-ec-point Gx Gy) n h S oid)) ;;; Fp (define-syntax define-fp-parameter (syntax-rules () ((_ name p a b Gx Gy n h S oid) (define-constant name (make-fp-ec-parameter p a b Gx Gy n h (uinteger->bytevector S) oid))))) (define-fp-parameter NIST-P-192 #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC #x64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1 #x188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012 #x07192B95FFC8DA78631011ED6B24CDD573F977A11E794811 #xFFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831 1 #x3045AE6FC8422F64ED579528D38120EAE12196D5 "1.2.840.10045.3.1.1") (define-fp-parameter NIST-P-224 #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001 #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE #xB4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4 #xB70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21 #xBD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34 #xFFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D 1 #xBD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5 "1.3.132.0.33") (define-fp-parameter NIST-P-256 #xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF #xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC #x5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B #x6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296 #x4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5 #xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 1 #xC49D360886E704936A6678E1139D26B7819F7E90 "1.2.840.10045.3.1.7") (define-fp-parameter NIST-P-384 #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC #xB3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF #xAA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7 #x3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFc7634d81f4372ddf581a0db248b0a77aecec196accc52973 1 #xA335926AA319A27A1D00896A6773A4827ACDAC73 "1.3.132.0.34") (define-fp-parameter NIST-P-521 #x000001FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF #x000001FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC #x00000051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00 #x000000c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66 #x0000011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650 #x000001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409 1 #xD09E8800291CB85396CC6717393284AAA0DA64BA "1.3.132.0.35") ;;; F2m (define (make-f2m-ec-parameter m k1 k2 k3 a b Gx Gy n h S :optional (oid #f)) (make-ec-parameter (make-elliptic-curve (make-ec-field-f2m m k1 k2 k3) a b) (make-ec-point Gx Gy) n h S oid)) (define-syntax define-f2m-parameter (syntax-rules () ((_ "body" name (m k1 k2 k3) a b Gx Gy n h S oid) (define-constant name (make-f2m-ec-parameter m k1 k2 k3 a b Gx Gy n h S oid))) ((_ name (m k1 k2 k3) a b Gx Gy n h S oid) (define-f2m-parameter "body" name (m k1 k2 k3) a b Gx Gy n h (uinteger->bytevector S) oid)) ((_ name (m k1 k2 k3) a b Gx Gy n h oid) (define-f2m-parameter "body" name (m k1 k2 k3) a b Gx Gy n h #vu8() oid)))) ;; f(x) = x^163 + x^7 + x^6 + x^3 + 1 (define-f2m-parameter NIST-K-163 (163 3 6 7) 1 1 #x02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8 #x0289070FB05D38FF58321F2E800536D538CCDAA3D9 #x04000000000000000000020108A2E0CC0D99F8A5EF 2 "1.3.132.0.1") (define-f2m-parameter NIST-B-163 (163 3 6 7) 1 #x020a601907b8c953ca1481eb10512f78744a3205fd #x03f0eba16286a2d57ea0991168d4994637e8343e36 #x00d51fbc6c71a0094fa2cdd545b11c5c0c797324f1 #x040000000000000000000292fe77e70c12a4234c33 2 #x85E25BFE5C86226CDB12016F7553F9D0E693A268 "1.3.132.0.15") (define-f2m-parameter NIST-K-233 (233 74 0 0) 0 1 #x017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126 #x01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3 #x8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF 4 "1.3.132.0.26") (define-f2m-parameter NIST-B-233 (233 74 0 0) 1 #x0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD #x00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B #x01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052 #x1000000000000000000000000000013E974E72F8A6922031D2603CFE0D7 2 #x74D59FF07F6B413D0EA14B344B20A2DB049B50C3 "1.3.132.0.27") (define-f2m-parameter NIST-K-283 (283 5 7 12) 0 1 #x0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836 #x01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259 #x01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61 4 "1.3.132.0.16") (define-f2m-parameter NIST-B-283 (283 5 7 12) 1 #x027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5 #x05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053 #x03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4 #x03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307 2 #x77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE "1.3.132.0.17") (define-f2m-parameter NIST-K-409 (409 87 0 0) 0 1 #x0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746 #x01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B #x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF 4 "1.3.132.0.36") (define-f2m-parameter NIST-B-409 (409 87 0 0) 1 #x0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F #x015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7 #x0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706 #x010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173 2 #x4099B5A457F9D69F79213D094C4BCD4D4262210B "1.3.132.0.37") (define-f2m-parameter NIST-K-571 (571 2 5 10) 0 1 #x026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972 #x0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3 #x020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001 4 "1.3.132.0.38") (define-f2m-parameter NIST-B-571 (571 2 5 10) 1 #x02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A #x0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19 #x037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B #x03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47 2 #x2AA058F73A0E33AB486B0F610410C53A7F132310 "1.3.132.0.39") ;; f(x) = x^113 + x^9 + 1 (define-f2m-parameter sect113r1 (163 9 0 0) #x003088250CA6E7C7FE649CE85820F7 #x00E8BEE4D3E2260744188BE0E9C723 #x009D73616F35F4AB1407D73562C10F #x00A52830277958EE84D1315ED31886 #x0100000000000000D9CCEC8A39E56F 2 #x10E723AB14D696E6768756151756FEBF8FCB49A9 #f) )
true
e6e8fce9f527821524d2c0e0e15b97c831eb3189
ece1c4300b543df96cd22f63f55c09143989549c
/Chapter2/Exercise 2.47.scm
cd8443508e5eb0fb657932835908342c6bbe1bce
[]
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,088
scm
Exercise 2.47.scm
; Exercise 2.47: Here are two possible constructors for frames: ; (define (make-frame origin edge1 edge2) ; (list origin edge1 edge2)) ; (define (make-frame origin edge1 edge2) ; (cons origin (cons edge1 edge2))) ; For each constructor supply the appropriate selectors to produce an implementation for frames. (define (make_frame1 origin edge1 edge2) (list origin edge1 edge2)) (define (make_frame2 origin edge1 edge2) (cons origin (cons edge1 edge2))) (define (origin_frame frame) (car frame) ) (define (edge1_frame frame) (cadr frame) ) (define (edge2_frame1 frame) (caddr frame) ) (define (edge2_frame2 frame) (cddr frame) ) (define a (make_frame1 1 2 3)) (define b (make_frame2 1 2 3)) (define (multiplay . args) (for-each (lambda (x) (display x) (newline)) args) ) (multiplay a (origin_frame a) (edge1_frame a) (edge2_frame1 a) b (origin_frame b) (edge1_frame b) (edge2_frame2 b) ) Welcome to DrRacket, version 6.7 [3m]. Language: SICP (PLaneT 1.18); memory limit: 128 MB. (1 2 3) 1 2 3 (1 2 . 3) 1 2 3 >
false
e98b3178460662ce0e56060af58f05ea62722b69
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch5/5.09.scm
f7c5b82590c703952a66bea43928177f9bfbaa7c
[]
no_license
lythesia/sicp-sol
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
169394cf3c3996d1865242a2a2773682f6f00a14
refs/heads/master
2021-01-18T14:31:34.469130
2019-10-08T03:34:36
2019-10-08T03:34:36
27,224,763
2
0
null
null
null
null
UTF-8
Scheme
false
false
461
scm
5.09.scm
(define (make-operation-exp exp machine lables operations) (let ((op (lookup-operation (operation-exp-op exp) operations)) (a-procs (map (lambda (e) (if (label-exp? e) (error "cannot operate on label -- MAKE-OPERATION-EXP" e) (make-primitive-exp e machine labels)) ) (operation-exp-operands exp) ) )) (lambda () (apply op (map (lambda (p) (p)) a-procs))) ) )
false
40323f3596de69deda4d42eb3f3a3e820aa6c120
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/ice-9/rdelim.scm
a406f4e554ec0486d0e82e50e222912e3a6376ca
[ "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
7,648
scm
rdelim.scm
;;; installed-scm-file ;;;; Copyright (C) 1997, 1999, 2000, 2001, 2006, 2010, 2013, ;;;; 2014 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 ;;;; ;;; This is the Scheme part of the module for delimited I/O. It's ;;; similar to (scsh rdelim) but somewhat incompatible. (define-module (ice-9 rdelim) #:export (read-line read-line! read-delimited read-delimited! read-string read-string! %read-delimited! %read-line write-line)) (%init-rdelim-builtins) (define* (read-line! string #:optional (port current-input-port)) ;; corresponds to SCM_LINE_INCREMENTORS in libguile. (define scm-line-incrementors "\n") (let* ((rv (%read-delimited! scm-line-incrementors string #t port)) (terminator (car rv)) (nchars (cdr rv))) (cond ((and (= nchars 0) (eof-object? terminator)) terminator) ((not terminator) #f) (else nchars)))) (define* (read-delimited! delims buf #:optional (port (current-input-port)) (handle-delim 'trim) (start 0) (end (string-length buf))) (let* ((rv (%read-delimited! delims buf (not (eq? handle-delim 'peek)) port start end)) (terminator (car rv)) (nchars (cdr rv))) (cond ((or (not terminator) ; buffer filled (eof-object? terminator)) (if (zero? nchars) (if (eq? handle-delim 'split) (cons terminator terminator) terminator) (if (eq? handle-delim 'split) (cons nchars terminator) nchars))) (else (case handle-delim ((trim peek) nchars) ((concat) (string-set! buf (+ nchars start) terminator) (+ nchars 1)) ((split) (cons nchars terminator)) (else (error "unexpected handle-delim value: " handle-delim))))))) (define* (read-delimited delims #:optional (port (current-input-port)) (handle-delim 'trim)) (let loop ((substrings '()) (total-chars 0) (buf-size 100)) ; doubled each time through. (let* ((buf (make-string buf-size)) (rv (%read-delimited! delims buf (not (eq? handle-delim 'peek)) port)) (terminator (car rv)) (nchars (cdr rv)) (new-total (+ total-chars nchars))) (cond ((not terminator) ;; buffer filled. (loop (cons (substring buf 0 nchars) substrings) new-total (* buf-size 2))) ((and (eof-object? terminator) (zero? new-total)) (if (eq? handle-delim 'split) (cons terminator terminator) terminator)) (else (let ((joined (string-concatenate-reverse (cons (substring buf 0 nchars) substrings)))) (case handle-delim ((concat) (if (eof-object? terminator) joined (string-append joined (string terminator)))) ((trim peek) joined) ((split) (cons joined terminator)) (else (error "unexpected handle-delim value: " handle-delim))))))))) (define-syntax-rule (check-arg exp message arg ...) (unless exp (error message arg ...))) (define (index? n) (and (integer? n) (exact? n) (>= n 0))) (define* (read-string! buf #:optional (port (current-input-port)) (start 0) (end (string-length buf))) "Read all of the characters out of PORT and write them to BUF. Returns the number of characters read. This function only reads out characters from PORT if it will be able to write them to BUF. That is to say, if BUF is smaller than the number of available characters, then BUF will be filled, and characters will be left in the port." (check-arg (string? buf) "not a string" buf) (check-arg (index? start) "bad index" start) (check-arg (index? end) "bad index" end) (check-arg (<= start end) "start beyond end" start end) (check-arg (<= end (string-length buf)) "end beyond string length" end) (let lp ((n start)) (if (< n end) (let ((c (read-char port))) (if (eof-object? c) (- n start) (begin (string-set! buf n c) (lp (1+ n))))) (- n start)))) (define* read-string (case-lambda* "Read all of the characters out of PORT and return them as a string. If the COUNT argument is present, treat it as a limit to the number of characters to read. By default, there is no limit." ((#:optional (port (current-input-port))) ;; Fast path. ;; This creates more garbage than using 'string-set!' as in ;; 'read-string!', but currently that is faster nonetheless. (let loop ((chars '())) (let ((char (read-char port))) (if (eof-object? char) (list->string (reverse! chars)) (loop (cons char chars)))))) ((port count) ;; Slower path. (let loop ((chars '()) (total 0)) (let ((char (read-char port))) (if (or (eof-object? char) (>= total count)) (list->string (reverse chars)) (loop (cons char chars) (+ 1 total)))))))) ;;; read-line [PORT [HANDLE-DELIM]] reads a newline-terminated string ;;; from PORT. The return value depends on the value of HANDLE-DELIM, ;;; which may be one of the symbols `trim', `concat', `peek' and ;;; `split'. If it is `trim' (the default), the trailing newline is ;;; removed and the string is returned. If `concat', the string is ;;; returned with the trailing newline intact. If `peek', the newline ;;; is left in the input port buffer and the string is returned. If ;;; `split', the newline is split from the string and read-line ;;; returns a pair consisting of the truncated string and the newline. (define* (read-line #:optional (port (current-input-port)) (handle-delim 'trim)) (let* ((line/delim (%read-line port)) (line (car line/delim)) (delim (cdr line/delim))) (case handle-delim ((trim) line) ((split) line/delim) ((concat) (if (and (string? line) (char? delim)) (string-append line (string delim)) line)) ((peek) (if (char? delim) (unread-char delim port)) line) (else (error "unexpected handle-delim value: " handle-delim)))))
true
bdee38688cadb8534ece9c53fdc812d851c63f05
d369542379a3304c109e63641c5e176c360a048f
/brice/utils.scm
23973ce7fbddeb0882c02cbff02d5744ac6359aa
[]
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
3,223
scm
utils.scm
#lang racket (provide (all-defined-out)) (define nil '()) (define (inc x) (+ x 1)) (define (dec x) (- x 1)) (define (square x) (* x x)) (define (str . parts) (define strParts (map (lambda (p) (format "~a " p)) parts)) (apply string-append strParts )) (define (prn . lines) (for-each (lambda (line) (and (display (str line)) (display "\n"))) lines)) (define (title ti) (let ((long (make-string 60 #\-))) (prn "" long ti long ""))) (define (show smth) (display (format "~a\n" smth))) (define (reporterr msg) (display "ERROR: ") (display msg) (newline)) (define (reportok msg) (display "OK: ") (display msg) (newline)) (define (assert msg b) (if b (reportok msg) (reporterr msg))) (define (asserteq msg a b) (let ((pass (> 0.0001 (abs ( - a b))))) (assert msg pass) (cond ((not pass) (display (format " Expected ~a got ~a\n" a b)))))) (define (assertequal? msg a b) (if (equal? a b) (reportok msg) (begin (reporterr msg) (display (format " Expected: ~a\n" a)) (display (format " Got: ~a\n" b))))) (define-syntax assert-raises-error (syntax-rules () [(assertraises msg body) (with-handlers ([exn:fail? (lambda (ex) (reportok msg))]) (begin body (reporterr msg)))])) ; (require macro-debugger/expand) (define (average a b) (/ (+ a b) 2)) (define (repeat x n) (define (intern i seq) (if (> i 0) (intern (dec i) (cons x seq)) seq)) (intern n '())) (define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) (define (sign n) (/ n (abs n))) (define accumulate foldr) (define (accumulate-n op init seqs) (if (null? (car seqs)) nil (cons (foldr op init (map first seqs)) (accumulate-n op init (map rest seqs))))) (define (flatten xs) (foldr append (map first xs) '())) (define (any? pred xs) (not (empty? (filter identity (map pred xs))))) (define (zip . xs) (if (any? empty? xs) '() (cons (map first xs) (apply zip (map rest xs))))) ;; Naive primality testing (define (smallest-divisor n) (find-divisor n 2)) (define (find-divisor n test-divisor) (cond ((> (square test-divisor) n) n) ((divides? test-divisor n) test-divisor) (else (find-divisor n (inc test-divisor))))) (define (divides? a b) (= (remainder b a) 0)) (define (prime? n) (= n (smallest-divisor n))) (define (reduce func xs) (if (empty? (cdr xs)) (car xs) (func (car xs) (reduce func (cdr xs))))) (define (inspect fn) (lambda args (let ((output (apply fn args))) (prn (str "function:" fn) (str " inputs:" (apply str args)) (str " output:" output)) output))) (define (flatmap proc seq) (accumulate append nil (map proc seq))) (define (enumerate-interval low high) (if (> low high) nil (cons low (enumerate-interval (+ low 1) high)))) (define (all-equal? . xs) (define (inner item xs) (if (empty? xs) #t (if (equal? item (first xs)) (inner (first xs) (rest xs)) #f))) (inner (first xs) (rest xs))) (define (Q: . txt) (apply prn (append '("QUESTION:") txt '("")))) (define (A: . txt) (apply prn (append '("ANSWER:") txt '("")))) (define (log2 n) (/ (log n) (log 2))) (define π pi)
true
7ac3fd6c845d2e39dcfe7c2e47badf6225b68a26
1dfe3abdff4803aee6413c33810f5570d0061783
/.chezscheme_libs/spells/test-runner.sls
acb639a43664fa44bb022f129a4c4589c67c612f
[]
no_license
Saigut/chezscheme-libs
73cb315ed146ce2be6ae016b3f86cf3652a657fc
1fd12abbcf6414e4d50ac8f61489a73bbfc07b9d
refs/heads/master
2020-06-12T14:56:35.208313
2016-12-11T08:51:15
2016-12-11T08:51:15
75,801,338
6
2
null
null
null
null
UTF-8
Scheme
false
false
8,229
sls
test-runner.sls
#!r6rs ;;; run.sls --- Utilities for running testcases ;; Copyright (C) 2009, 2010, 2015 Andreas Rottmann <[email protected]> ;; This program is free software, you can redistribute it and/or ;; modify it under the terms of the new-style BSD license. ;; You should have received a copy of the BSD license along with this ;; program. If not, see <http://www.debian.org/misc/bsd.license>. ;;; Commentary: ;;; Code: ;;@ Utilities for running testcases. (library (spells test-runner) (export run-tests run-tests-in-directory run-tests-in-file main) (import (except (rnrs base) string-copy string->list string-for-each) (rnrs eval) (rnrs control) (rnrs io simple) (rnrs lists) (rnrs exceptions) (rnrs programs) (only (srfi srfi-1 lists) span) (srfi srfi-8 receive) (spells misc) (srfi srfi-39 parameters) (spells match) (spells filesys) (spells pathname) (spells condition) (only (wak trc-testing) test-verbosity with-test-verbosity test-debug-errors? with-test-debug-errors?) (spells test-runner env)) ;;@ Run specified tests. ;; ;; @1 must be a list whose elements can be either directories or ;; single file names: @code{run-tests-in-directory} or ;; @code{run-tests-in-file} is applied accordingly. If empty is ;; provided, the current directory is used. (define (run-tests tests env) (for-each (lambda (f) (cond ((file-directory? f) (run-tests-in-directory f env)) ((file-regular? f) (run-tests-in-file f env)) (else (display (list "skipping non-existing" f)) (newline)))) tests)) ;;@ Call @code{run-tests-in-file} for each file in the given ;; directory. If the directory contains a file named @file{tests.scm}, ;; the list of files is read from it. (define (run-tests-in-directory dir env) (let* ((dir (pathname-as-directory dir)) (listing (pathname-with-file dir (make-file "tests" "scm")))) (cond ((file-regular? listing) (eval-test-spec dir (with-input-from-file (->namestring listing) read))) (else (for-each (lambda (f) (run-tests-in-file f env)) (directory-fold dir cons '())))))) (define (run-tests-in-file file env) (let ((filename (->namestring file))) (define (evaluate-forms forms) (cond (env (eval `(let () ,@forms) env)) (else (match forms ((('import . imports) . body) (and=> (construct-test-environment #f imports) (lambda (env) (parameterize ((test-environment env)) (eval `(let () ,@body) env))))) (_ (error 'run-tests-in-file "Invalid test file, expected leading import form" filename (car forms))))))) (display "\n;") (display (list "Loading " filename "... ")) (newline) (let ((forms (call-with-input-file filename (lambda (port) (let loop ((forms '())) (let ((form (read port))) (if (eof-object? form) (reverse forms) (loop (cons form forms))))))))) (receive results (evaluate-forms forms) (display ";") (display (list "..." filename "done")) (newline) (apply values results))))) (define (construct-test-environment defaults? imports) (guard (c (#t (display ";#(Error constructing environment: ") (newline) (display-condition c) (display ")") (newline) #f)) (apply environment (append (if defaults? '((except (rnrs base) error string-copy string-for-each string->list) (rnrs io simple) (wak trc-testing) (spells test-runner env)) '()) imports)))) ;; test spec grammar: ;; ;; <test spec> -> (<clause> ...) ;; <clause> -> (files <file spec> ...) ;; <file spec> -> <filename> ;; (<filename> [<options+imports>]) ;; ((code <scheme expr> ...) <filename> [<options+imports>]) ;; <options+imports> -> ['<option> ...] <library-name> ... (define (eval-test-spec pathname test-spec) (for-each (lambda (spec) (case (car spec) ((files) (for-each (lambda (clause) (eval-test-clause clause pathname (test-verbosity) (test-debug-errors?))) (cdr spec))))) test-spec)) (define (parse-options options+rest) (receive (options rest) (span (match-lambda (('quote option) #t) (_ #f)) options+rest) (values (map cadr options) (if (null? rest) #f rest)))) (define (with-test-options verbosity debug-errors? thunk) (with-test-verbosity verbosity (lambda () (with-test-debug-errors? debug-errors? thunk)))) (define (eval-test-clause clause directory verbosity debug-errors?) (define (run-test code filename options+imports) (receive (options imports) (parse-options options+imports) (let ((default-imports? (not (memq 'no-default-imports options))) (debug-errors? (or (and (memq 'debug-errors options) #t) debug-errors?)) (test-pathnames (list (pathname-with-file directory filename)))) (with-test-options verbosity debug-errors? (lambda () (cond (imports (and=> (construct-test-environment default-imports? imports) (lambda (env) (parameterize ((test-environment env)) (when code (eval `(let () ,@code) env)) (run-tests test-pathnames env))))) (code (error 'eval-test-clause "Invalid clause; specifies code, but no imports given" clause)) (else (run-tests test-pathnames #f)))))))) (match clause ((('code . code) filename . options+imports) (run-test code filename options+imports)) ((filename . options+imports) (run-test #f filename options+imports)) (filename (run-test #f filename '())))) (define (main args) (define (process-tests-files files) (for-each (lambda (tests-file) (call-with-input-file tests-file (lambda (port) (let* ((test-spec (read port)) (pathname (->pathname tests-file)) (directory (pathname-with-file pathname #f))) (parameterize ((this-directory (->namestring directory))) (eval-test-spec directory test-spec)))))) files)) (define (parse-options args run) (match args (("--debug" . rest) (parse-options rest (lambda (args) (with-test-debug-errors? #t (lambda () (run args)))))) (("--verbosity" verbosity . rest) (parse-options rest (lambda (args) (with-test-verbosity (string->symbol verbosity) (lambda () (run args)))))) (_ (run args)))) (with-test-options 'quiet #f (lambda () (parse-options (cdr args) (lambda (files) (process-tests-files files))))))) ;; Local Variables: ;; scheme-indent-styles: ((match 1) (parameterize 1)) ;; End:
false
d25efa21a60ba641aba6c3abf1cfaf2ba3e9d2c2
f59b3ca0463fed14792de2445de7eaaf66138946
/section-5/5_47.scm
5aee9f88901654879a01499f4546b1d8a69c2391
[]
no_license
uryu1994/sicp
f903db275f6f8c2da0a6c0d9a90c0c1cf8b1e718
b14c728bc3351814ff99ace3b8312a651f788e6c
refs/heads/master
2020-04-12T01:34:28.289074
2018-06-26T15:17:06
2018-06-26T15:17:06
58,478,460
0
1
null
2018-06-20T11:32:33
2016-05-10T16:53:00
Scheme
UTF-8
Scheme
false
false
3,307
scm
5_47.scm
(load "./compile-eceval") (define eceval (make-machine '(exp env val proc argl continue unev compapp) eceval-operations '( ;; Question 5.47 (assign compapp (label compound-apply)) (branch (label external-entry)) ; flagが設定してあれば分岐する read-eval-print-loop (perform (op initialize-stack)) ... ))) ;; Question 5.47 (define (compile-procedure-call target linkage) (let ((primitive-branch (make-label 'primitive-branch)) (compiled-branch (make-label 'compiled-branch)) (compound-branch (make-label 'compound-branch)) (after-call (make-label 'after-call))) (let ((compiled-linkage (if (eq? linkage 'next) after-call linkage))) (append-instruction-sequences (make-instruction-sequence '(proc) '() `((test (op primitive-procedure?) (reg proc)) (branch (label ,primitive-branch)))) (make-instruction-sequence '(proc) '() `((test (op compiled-procedure?) (reg proc)) (branch (label ,compiled-branch)))) (parallel-instruction-sequences (append-instruction-sequences compound-branch (compound-proc-appl target compiled-linkage)) (parallel-instruction-sequences (append-instruction-sequences compiled-branch (compile-proc-appl target compiled-linkage)) (append-instruction-sequences primitive-branch (end-with-linkage linkage (make-instruction-sequence '(proc argl) (list target) `((assign ,target (op apply-primitive-procedure) (reg proc) (reg argl)))))))) after-call)))) (define (compound-proc-appl target linkage) (cond ((and (eq? target 'val) (not (eq? linkage 'return))) (make-instruction-sequence '() all-regs `((assign continue (label ,linkage)) (save continue) (goto (reg compapp))))) ((and (not (eq? target 'val)) (not (eq? linkage 'return))) (let ((proc-return (make-label 'proc-return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,proc-return)) (save continue) (goto (reg compapp)) ,proc-return (assign ,target (reg val)) (goto (label ,linkage)))))) ((and (eq? target 'val) (eq? linkage 'return)) (make-instruction-sequence '(proc continue) all-regs `((save continue) (goto (reg compapp))))) ((and (not (eq? target 'val)) (eq? linkage 'return)) (error "return linkage, target not val -- COMPILE" target))))
false
8ff00bd2d903d839325491e1790fbf721d748203
a41cb942209866829e099521458f1fd7565008c0
/srfi-114/srfi/114/comparison-utils.scm
fdd1fbcf518abcc51a2a4d872b8a0046f8ba52db
[ "BSD-3-Clause" ]
permissive
ilammy/srfi-114
2f34cfa0bf44aaa2b919f82be5fb0aae4c6bc977
03c38400ddd13ab2bb0b62d9e23b14740ef33a02
refs/heads/master
2016-09-07T18:48:22.889612
2015-04-22T20:14:56
2015-04-22T20:14:56
32,109,224
1
0
null
2015-04-16T20:48:05
2015-03-12T23:35:44
Scheme
UTF-8
Scheme
false
false
4,918
scm
comparison-utils.scm
;; comparison-utils.scm -- comparison constructors, combinators, syntax ;; Copyright (c) 2015 ilammy <[email protected]> ;; 3-clause BSD license: http://github.com/ilammy/srfi-114/blob/master/LICENSE ;; Comparison syntax ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-syntax if3 (syntax-rules () ((_ expr less equal greater) (case expr ((-1) less) (( 0) equal) ((+1) greater) (else (error "if3: invalid comparison result" expr)))))) (define-syntax define-comparison-syntax (syntax-rules () ((_ binding yes no error-message) (define-syntax binding (syntax-rules () ((_ expr consequent) (binding expr consequent (when #f #f))) ((_ expr consequent alternate) (case expr (yes consequent) (no alternate) (else (error error-message expr))))))))) (define-comparison-syntax if=? (0) (-1 +1) "if=?: invalid comparison result") (define-comparison-syntax if<? (-1) (0 +1) "if<?: invalid comparison result") (define-comparison-syntax if>? (+1) (0 -1) "if>?: invalid comparison result") (define-comparison-syntax if<=? (-1 0) (+1) "if<=?: invalid comparison result") (define-comparison-syntax if>=? (0 +1) (-1) "if>=?: invalid comparison result") (define-comparison-syntax if-not=? (-1 +1) (0) "if-not=?: invalid comparison result") ;; Comparison predicate constructors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (make= comparator) (comparator-equality-predicate comparator)) (define-syntax define-comparison-predicate-constructor (syntax-rules () ((_ binding if-in-order?) (define (binding comparator) (let ((compare (comparator-comparison-procedure comparator))) (lambda (obj1 obj2) (if-in-order? (compare obj1 obj2) #t #f))))))) (define-comparison-predicate-constructor make< if<?) (define-comparison-predicate-constructor make> if>?) (define-comparison-predicate-constructor make<= if<=?) (define-comparison-predicate-constructor make>= if>=?) ;; Comparison procedure constructors ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (make-comparison< <) (lambda (obj1 obj2) (cond ((< obj1 obj2) -1) ((< obj2 obj1) +1) (else 0)))) (define (make-comparison> >) (lambda (obj1 obj2) (cond ((> obj1 obj2) +1) ((> obj2 obj1) -1) (else 0)))) (define (make-comparison<= <=) (lambda (obj1 obj2) (if (<= obj1 obj2) (if (<= obj2 obj1) 0 -1) +1))) (define (make-comparison>= >=) (lambda (obj1 obj2) (if (>= obj1 obj2) (if (>= obj2 obj1) 0 +1) -1))) (define (make-comparison=/< = <) (lambda (obj1 obj2) (cond ((= obj1 obj2) 0) ((< obj2 obj1) +1) (else -1)))) (define (make-comparison=/> = >) (lambda (obj1 obj2) (cond ((= obj1 obj2) 0) ((> obj2 obj1) -1) (else +1)))) ;; Comparison predicates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (make-comparison-predicate make-relation) (lambda (comparator obj1 obj2 . objs) (let ((relation (make-relation comparator))) (if (null? objs) (relation obj1 obj2) (let loop ((objs (cons obj1 (cons obj2 objs)))) (if (null? (cdr objs)) #t (if (relation (car objs) (cadr objs)) (loop (cdr objs)) #f))))))) (define =? (make-comparison-predicate make=)) (define <? (make-comparison-predicate make<)) (define >? (make-comparison-predicate make>)) (define <=? (make-comparison-predicate make<=)) (define >=? (make-comparison-predicate make>=)) ;; Interval comparison predicates ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (make-interval-comparison-predicate left-relation right-relation) (define predicate (case-lambda ((obj1 obj2 obj3) (predicate default-comparator obj1 obj2 obj3)) ((comparator obj1 obj2 obj3) (and (left-relation comparator obj1 obj2) (right-relation comparator obj2 obj3))))) predicate) (define in-open-interval? (make-interval-comparison-predicate <? <?)) (define in-open-closed-interval? (make-interval-comparison-predicate <? <=?)) (define in-closed-open-interval? (make-interval-comparison-predicate <=? <?)) (define in-closed-interval? (make-interval-comparison-predicate <=? <=?)) ;; Min/max comparison procedures ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (comparator-min comparator obj . objs) (let ((< (make< comparator))) (let loop ((min obj) (objs objs)) (if (null? objs) min (loop (if (< (car objs) min) (car objs) min) (cdr objs)))))) (define (comparator-max comparator obj . objs) (let ((> (make> comparator))) (let loop ((max obj) (objs objs)) (if (null? objs) max (loop (if (> (car objs) max) (car objs) max) (cdr objs))))))
true
ecb501af22a7033d1989924d6e0aef95ce74faac
99f659e747ddfa73d3d207efa88f1226492427ef
/datasets/srfi/srfi-114/comparators/constructors.scm
b51b43de9038c4662bf8d6476e075ffba6826676
[ "MIT" ]
permissive
michaelballantyne/n-grams-for-synthesis
241c76314527bc40b073b14e4052f2db695e6aa0
be3ec0cf6d069d681488027544270fa2fd85d05d
refs/heads/master
2020-03-21T06:22:22.374979
2018-06-21T19:56:37
2018-06-21T19:56:37
138,215,290
0
0
MIT
2018-06-21T19:51:45
2018-06-21T19:51:45
null
UTF-8
Scheme
false
false
10,573
scm
constructors.scm
;;;; Standard comparators and comparator constructors ;;; Standard atomic comparators (define (boolean-comparison a b) (cond ((and a b) 0) (a 1) (b -1) (else 0))) (define (boolean-hash obj) (if obj 1 0)) (define boolean-comparator (make-comparator boolean? boolean=? boolean-comparison boolean-hash)) (define char-comparison (make-comparison=/< char=? char<?)) (define (char-hash obj) (abs (char->integer obj))) (define char-comparator (make-comparator char? char=? char-comparison char-hash)) (define char-ci-comparison (make-comparison=/< char-ci=? char-ci<?)) (define (char-ci-hash obj) (abs (char->integer (char-foldcase obj)))) (define char-ci-comparator (make-comparator char? char-ci=? char-ci-comparison char-ci-hash)) (define string-comparison (make-comparison=/< string=? string<?)) (define string-ci-comparison (make-comparison=/< string-ci=? string-ci<?)) (define (symbol<? a b) (string<? (symbol->string a) (symbol->string b))) (define symbol-comparison (make-comparison=/< symbol=? symbol<?)) ;; Comparison procedure for real numbers only (define (real-comparison a b) (cond ((< a b) -1) ((> a b) 1) (else 0))) ;; Comparison procedure for non-real numbers. (define (complex-comparison a b) (let ((real-result (real-comparison (real-part a) (real-part b)))) (if (= real-result 0) (real-comparison (imag-part a) (imag-part b)) real-result))) (define (number-hash obj) (exact (abs obj))) (define number-comparator (make-comparator number? = complex-comparison number-hash)) (define complex-comparator (make-comparator complex? = complex-comparison number-hash)) (define real-comparator (make-comparator real? = real-comparison number-hash)) (define rational-comparator (make-comparator rational? = real-comparison number-hash)) (define integer-comparator (make-comparator integer? = real-comparison number-hash)) (define exact-integer-comparator (make-comparator exact-integer? = real-comparison number-hash)) ;;; Inexact real comparator ;; Test procedure for inexact reals (define (inexact-real? obj) (and (number? obj) (inexact? obj) (real? obj))) ;; Return a number appropriately rounded to epsilon (define (rounded-to x epsilon rounding) (let ((quo (/ x epsilon))) (cond ((procedure? rounding) (rounding x epsilon)) ((eq? rounding 'round) (round quo)) ((eq? rounding 'ceiling) (ceiling quo)) ((eq? rounding 'floor) (floor quo)) ((eq? rounding 'truncate) (truncate quo)) (else (error "invalid rounding specification" rounding))))) ;; Returns result of comparing a NaN with a non-NaN (define (nan-comparison nan-handling which other) (cond ((procedure? nan-handling) (nan-handling other)) ((eq? nan-handling 'error) (error "Attempt to compare NaN with non-NaN")) ((eq? nan-handling 'min) (if (eq? which 'a-nan) -1 1)) ((eq? nan-handling 'max) (if (eq? which 'a-nan) 1 -1)) (else (error "Invalid nan-handling specification")))) (define (make-inexact-real-comparison epsilon rounding nan-handling) (lambda (a b) (let ((a-nan? (nan? a)) (b-nan? (nan? b))) (cond ((and a-nan? b-nan?) 0) (a-nan? (nan-comparison nan-handling 'a-nan b)) (b-nan? (nan-comparison nan-handling 'b-nan a)) (else (real-comparison (rounded-to a epsilon rounding) (rounded-to b epsilon rounding))))))) ;; Return 0 for NaN, number-hash otherwise (define (make-inexact-real-hash epsilon rounding) (lambda (obj) (if (nan? obj) 0 (number-hash (rounded-to obj epsilon rounding))))) (define (make-inexact-real-comparator epsilon rounding nan-handling) (make-comparator inexact-real? #t (make-inexact-real-comparison epsilon rounding nan-handling) (make-inexact-real-hash epsilon rounding))) ;;; Sequence comparator constructors and comparators ;;; The hash functions are based on djb2, but ;;; modulo 2^20 instead of 2^32 in hopes of sticking to fixnums. (define limit (expt 2 20)) ;; Makes a comparison procedure that works listwise (define (make-listwise-comparison comparison null? car cdr) (letrec ((proc (lambda (a b) (let ((a-null? (null? a)) (b-null? (null? b))) (cond ((and a-null? b-null?) 0) (a-null? -1) (b-null? 1) (else (let ((result (comparison (car a) (car b)))) (if (= result 0) (proc (cdr a) (cdr b)) result)))))))) proc)) ;; Makes a hash function that works listwise (define (make-listwise-hash hash null? car cdr) (lambda (obj) (let loop ((obj obj) (result 5381)) (if (null? obj) 0 (let* ((prod (modulo (* result 33) limit)) (sum (+ prod (hash (car obj))))) (loop (cdr obj) sum)))))) ;; Makes a comparison procedure that works vectorwise (define (make-vectorwise-comparison comparison length ref) (lambda (a b) (let* ((a-length (length a)) (b-length (length b)) (last-index (- a-length 1))) (cond ((< a-length b-length) -1) ((> a-length b-length) 1) (else (call/cc (lambda (return) (let loop ((index 0)) (let ((result (comparison (ref a index) (ref b index)))) (if (= result 0) (if (= index last-index) 0 (loop (+ index 1))) result)))))))))) ;; Makes a hash function that works vectorwise (define (make-vectorwise-hash hash length ref) (lambda (obj) (let loop ((index (- (length obj) 1)) (result 5381)) (if (= index 0) result (let* ((prod (modulo (* result 33) limit)) (sum (modulo (+ prod (hash (ref obj index))) limit))) (loop (- index 1) sum)))))) (define string-hash (make-vectorwise-hash char-hash string-length string-ref)) (define string-comparator (make-comparator string? string=? string-comparison string-hash)) (define (string-ci-hash obj) (string-hash (string-foldcase obj))) (define string-ci-comparator (make-comparator string? string-ci=? string-ci-comparison string-ci-hash)) (define (symbol-hash obj) (string-hash (symbol->string obj))) (define symbol-comparator (make-comparator symbol? symbol=? symbol-comparison symbol-hash)) (define (make-listwise-comparator test comparator null? car cdr) (make-comparator test #t (make-listwise-comparison (comparator-comparison-procedure comparator) null? car cdr) (make-listwise-hash (comparator-hash-function comparator) null? car cdr))) (define (make-vectorwise-comparator test comparator length ref) (make-comparator test #t (make-vectorwise-comparison (comparator-comparison-procedure comparator) length ref) (make-vectorwise-hash (comparator-hash-function comparator) length ref))) (define (make-list-comparator comparator) (make-listwise-comparator (lambda (obj) (or (null? obj) (pair? obj))) comparator null? car cdr)) (define list-comparator (make-list-comparator default-comparator)) (define (make-vector-comparator comparator) (make-vectorwise-comparator vector? comparator vector-length vector-ref)) (define vector-comparator (make-vector-comparator default-comparator)) (define vector-comparison (comparator-comparison-procedure vector-comparator)) (define vector-hash (comparator-hash-function vector-comparator)) (define (make-bytevector-comparator comparator) (make-vectorwise-comparator bytevector? comparator bytevector-length bytevector-u8-ref)) (define bytevector-comparator (make-bytevector-comparator default-comparator)) (define bytevector-comparison (comparator-comparison-procedure bytevector-comparator)) (define bytevector-hash (comparator-hash-function bytevector-comparator)) ;;; Pair comparator constructors (define (make-car-comparator comparator) (make-comparator pair? #t (lambda (a b) (comparator-compare comparator (car a) (car b))) (lambda (obj) (comparator-hash-function comparator)))) (define (make-cdr-comparator comparator) (make-comparator pair? #t (lambda (a b) (comparator-compare comparator (cdr a) (cdr b))) (lambda (obj) (comparator-hash comparator obj)))) (define (make-pair-comparison car-comparator cdr-comparator) (lambda (a b) (let ((result (comparator-compare car-comparator (car a) (car b)))) (if (= result 0) (comparator-compare cdr-comparator (cdr a) (cdr b)) result)))) (define pair-comparison (make-pair-comparison default-comparator default-comparator)) (define (make-pair-hash car-comparator cdr-comparator) (lambda (obj) (+ (comparator-hash car-comparator (car obj)) (comparator-hash cdr-comparator (cdr obj))))) (define (make-pair-comparator car-comparator cdr-comparator) (make-comparator pair? #t (make-pair-comparison car-comparator cdr-comparator) (make-pair-hash car-comparator cdr-comparator))) (define pair-comparator (make-pair-comparator default-comparator default-comparator)) (define pair-hash (comparator-hash-function pair-comparator)) ;; Compute type index for inexact list comparisons (define (improper-list-type obj) (cond ((null? obj) 0) ((pair? obj) 1) (else 2))) (define (make-improper-list-comparison comparator) (let ((pair-comparison (make-pair-comparison comparator comparator))) (lambda (a b) (let* ((a-type (improper-list-type a)) (b-type (improper-list-type b)) (result (real-comparison a-type b-type))) (cond ((not (= result 0)) result) ((null? a) 0) ((pair? a) (pair-comparison a b)) (else (comparator-compare comparator a b))))))) (define (make-improper-list-hash comparator) (lambda (obj) (cond ((null? obj) 0) ((pair? obj) (+ (comparator-hash comparator (car obj)) (comparator-hash comparator (cdr obj)))) (else (comparator-hash comparator obj))))) (define (make-improper-list-comparator comparator) (make-comparator #t #t (make-improper-list-comparison comparator) (make-improper-list-hash comparator))) ;;; Wrapped equality predicates ;;; These comparators don't have comparison functions. (define eq-comparator (make-comparator #t eq? #f default-hash-function)) (define eqv-comparator (make-comparator #t eqv? #f default-hash-function)) (define equal-comparator (make-comparator #t equal? #f default-hash-function))
false
0b341496011e571bbf1aa83ea43cf8a2c531508b
1f48fb14898799bf9ee1118bf691586b430c5e9e
/257.scm
0fa7ff1029c2ef14a81d5a311ad64e940c5a5ede
[]
no_license
green-93-nope/sicp
0fa79dd59414808a9cdcbfa18bd3a1c7f0b8191c
59241b6c42621c2ef967efebdd281b845f98e923
refs/heads/master
2021-01-10T10:51:22.328123
2017-05-21T08:33:25
2017-05-21T08:33:25
48,210,972
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,022
scm
257.scm
(load "ch232.scm") (define (augend x) (let ((rest (cddr x))) (if (atom-in-list rest) (car rest) (cons '+ rest)))) (define (make-sum x . y) (let ((first-atom (car y))) (if (not (atom-in-list y)) (cons '+ (cons x y)) (cond ((=number? x 0) first-atom) ((=number? first-atom 0) x) ((and (number? x) (number? first-atom)) (+ x first-atom)) (else (list '+ x first-atom)))))) (define (multiplicand x) (let ((rest (cddr x))) (if (atom-in-list rest) (car rest) (cons '* rest)))) (define (make-product x y) (let ((first-atom (car y))) (if (not (atom-in-list y)) (cons '* (cons x y)) (cond ((or (=number? x 0) (=number? first-atom 0)) 0) ((=number? x 1) first-atom) ((=number? first-atom 1) x) ((and (number? x) (number? first-atom)) (* x first-atom)) (else (list '* x first-atom))))))
false
15c1f5b99c95841d56d411bb2312758a06cfa228
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/digital/simple/bus.scm
8994068065b477bdf5f33f53109e39a884bf911d
[]
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
2,785
scm
bus.scm
(load "wire.scm") (load "binary.scm") (define (bus size) ; creates a bus with a number of bits equal to 'size' (let ((wire-vect (make-vector size))) (define (dispatch m) (cond ((eq? m 'get-signal) (get-signal)) ((eq? m 'set-signal!) set-signal!) ((eq? m 'size) size) ((eq? m 'get-wire) get-wire) (else (display "bus: unknown operation error\n"i)))) ;; private methods ;; (define (init-bus) ; initilizes vector of wires (let loop ((i 0)) (if (< i size) (begin (vector-set! wire-vect i (wire)) ; wire-vect[i] = new wire() (loop (+ i 1)))))) ;; (define (get-signal) (let ((vect (make-vector size))) (let loop ((i 0)) (if (< i size) (begin (vector-set! vect i ((vector-ref wire-vect i) 'get-signal)) (loop (+ i 1))))) (boolean-vect->integer vect))) ;; (define (set-signal! num) ;; converts num to binary and sets bus accordingly (let ((vect (integer->boolean-vect num size))) (let loop ((i 0)) (if (< i size) (begin (((vector-ref wire-vect i) 'set-signal!) (vector-ref vect i)) (loop (+ i 1))))))) ;; (define (get-wire bit) ; 'bit' is index between 0 and size-1 (vector-ref wire-vect bit)) ;; ;; bus initialization (init-bus) ;; ;; returning public interface dispatch)) ;; connects bus a b and sum to a ripple-adder ;; c-in and c-out are simple wires (single bits) (define (ripple-adder a b c-in sum c-out) (let ((size (a 'size))) (cond ((not (= size (b 'size))) (display "bus: ripple-adder: bus size error\n")) ((not (= size (sum 'size))) (display "bus: ripple-adder: bus size error\n")) (else (let ((carry (make-vector (+ size 1)))) ; need vector of wires (vector-set! carry 0 c-in) ; first carry wire is input (vector-set! carry size c-out) ; last carry wire is output (let loop ((i 1)) (if (< i size) (begin (vector-set! carry i (wire)) ; new internal wire (loop (+ i 1))))) (let loop ((i 0)) ; looping through all bits (if (< i size) (begin (let ((ai ((a 'get-wire) i)) (bi ((b 'get-wire) i)) (si ((sum 'get-wire) i)) (cin (vector-ref carry i)) (cout(vector-ref carry (+ i 1)))) (full-adder ai bi cin si cout)) (loop (+ i 1))))))))))
false
d37dbb1cfb022e4916885478dd4fa0058094fb72
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/sicp/exercices/3.08.scm
5f8151c04be085fc251f274d958a1587eaeb2766
[]
no_license
Phantas0s/playground
a362653a8feb7acd68a7637334068cde0fe9d32e
c84ec0410a43c84a63dc5093e1c214a0f102edae
refs/heads/master
2022-05-09T06:33:25.625750
2022-04-19T14:57:28
2022-04-19T14:57:28
136,804,123
19
5
null
2021-03-04T14:21:07
2018-06-10T11:46:19
Racket
UTF-8
Scheme
false
false
1,045
scm
3.08.scm
; When we defined the evaluation model in ; Section 1.1.3, we said that the first step in evaluating an ; expression is to evaluate its subexpressions. But we never ; specified the order in which the subexpressions should be ; evaluated (e.g., left to right or right to left). When we in- ; troduce assignment, the order in which the arguments to a ; procedure are evaluated can make a difference to the result. ; Define a simple procedure f such that evaluating (+ (f 0) (f 1)) ; will return 0 if the arguments to + are evaluated from left to ; right but will return 1 if the arguments are evaluated from ; right to left. (define pass 0) (define (f num) (set! pass (+ pass 1)) (if (= pass 1) num 0)) (+ (f 0) (f 1)) ; (+ (f 1) (f 0)) (define f (let ((state 0)) (lambda (arg) (begin state (set! state arg))))) ; **GOOD** ; I use a global var here; but we could use a local one. Something like (even simpler): (define f (let ((count 1)) (lambda (x) (set! count (* count x)) count)))
false
ff7d8931b71ae9f282f85f83134ef013841b39d1
b9d0fc9d5d0d135aadd1e4644b45004fd2c94b94
/scheme/functional-postscript/ps.path.scm
deea62c9fc7dbe49c55f03bb6e5ba94fa67cc5cc
[]
no_license
alvatar/snippets
f704413d39b6c9363e1c435444ec82e270184f75
89ce0c71ff1554a9307ed0726b84dfa5782babe6
refs/heads/master
2021-06-28T21:59:15.358791
2016-10-25T16:26:52
2016-10-25T16:26:52
2,073,559
1
0
null
null
null
null
UTF-8
Scheme
false
false
11,877
scm
ps.path.scm
;; =============================================================== ;; Functional PostScript ;; Copyright (C) 1996 by Wandy Sae-Tan and Olin Shivers ;; ps.path.scm ;; This file contains procedures contained in this file are all PS ;; text backend procdures that are part of the PS2-text-channel. ;; (ps2-text-channel port-or-filename . options) -> channel ;; (show-w/ps2-text-channel* port-or-filename thunk) ;; (close-channel channel) ;; =============================================================== ;; This resources record is part of the ps2-text-channel (define-record ps2-text-resources (format #f) (last-picture #f) (total-pages 0) (font-list '())) ;; ps2-text-channel maker (define (ps2-text-channel port-or-filename . options) (let* ((channel (make-channel ; interface (if (output-port? port-or-filename) port-or-filename (open-output-file port-or-filename)) (make-ps2-text-resources) (make-default-style) ; current style #f ; current font (lambda (c) c) ; current colormap function #f ; current drawing method #f ; current p PSmoveto PSline PSrect PSarc PStangent-arc PScurve PScharpath PSglyphnamepath PSshow PSglyphshow PSclose-path PSstroke-outline-path PSsavetm PSrestoretm PSsavegstate PSrestoregstate PSconcat PSsetcolor PSsetlinewidth PSsetlinejoin PSsetlinecap PSsetmiterlimit PSsetdash PSselectfont PSpaint PSclip PSimage PSimagemask PSshowpage PSread-show-options PScheck-picture-resources PSclosechannel)) (interface (channel:interface channel))) (read-channel-options channel options) (PSheader interface) channel)) ;; process options that come with the channel and make ;; output conform to DSC (define (read-channel-options channel options) (let ((interface (channel:interface channel)) (resources (channel:resources channel)) (doc-opts (filter doc-option? options)) (print-opts (filter print-option? options)) (format-opt (filter format-option? options))) (cond ((null? format-opt) (format interface "%!PS-Adobe-3.0~%") (if (not (null? print-opts)) (begin (format interface "%%Requirements: ") (for-each (lambda (opt) (PSprint-req opt interface)) print-opts) (format interface "~%")))) ((null? (cdr format-opt)) (if (equal? (option:data (car format-opt)) "EPS") (begin (format interface "%!PS-Adobe-3.0 EPSF-3.0~%") (format interface "%%BoundingBox: (atend)~%") (set-ps2-text-resources:format resources "EPS")) (error ps2-text-channel "format not recognized" (cdr format-opt)))) (else (error ps2-text-channel "Cannot specify more than one format options"))) (for-each (lambda (opt) (PSdocumentation opt interface)) doc-opts) (format interface "%%LanguageLevel: 2~%") (format interface "%%Pages: (atend)~%") (format interface "%%DocumentNeededResources: (atend)~%") (format interface "%%EndComments~%") (if (not (equal? (ps2-text-resources:format resources) "EPS")) (for-each (lambda (opt) (PSactivate-req opt interface)) print-opts)))) ;; closes the port of a ps2-text channel, thereby closing the channel ;; (since channel is no longer able to output to anywhere. (define (close-channel channel) ((channel:close-channel channel) channel)) (define (PSclosechannel channel) (PStrailer channel) (close-output-port (channel:interface channel))) ;; given a port of filename and a thunk that takes the argument channel, ;; this procedure creates a temporary channel from the port-or-filename ;; argument, and exec thunk. If a filename were given as the arg, the ;; temp port created for the temp channel gets wiped out at the end. ;; If a port were given, everything is left alone. (define (show-w/ps2-text-channel port-or-filename picture . options) (let ((channel (apply ps2-text-channel port-or-filename options))) (show channel picture) (close-channel channel))) ;===== Geometric Path Constructors ======================================== ;; (PSmoveto newpt port) ;; (PSline pts port) ;; (PSrect ll-pt ur-pt method port) ;; (PSarc center radius start-ang-end-ang port) ;; (PSartc pt1 pt2 pt3 radius port) ;; (PScurve start-pt ctrl-pt2 ctrl-pt2 end-pt port) ;; (PScharpath lst port) ;; (PSglyphnamepath glyph font port) ;; (PSshow str port) ;; (PSglyphshow glyph port) ;; (PSclose-path str port) ;; (PSstroke-outline-path port) ;; move the currentpoint to the newpt (define (PSmoveto newpt port) (format port " ~d ~d m~%" (PSnum (pt:x newpt)) (PSnum (pt:y newpt)))) ;; append a line from currentpoint to pt (define (PSline pts port) (for-each (lambda (pt) (format port " ~d ~d l~%" (PSnum (pt:x pt)) (PSnum (pt:y pt)))) pts)) ;; draws a rectangle (define (PSrect p w h method port) (let* ((px (PSnum (pt:x p))) (py (PSnum (pt:y p))) (llx (PSnum (min px (+ px w)))) (lly (PSnum (min py (+ py h)))) (urx (PSnum (max px (+ px w)))) (ury (PSnum (max py (+ py h))))) (if (eq? method 'clip) (format port "~d ~d m ~d ~d l ~d ~d l ~d ~d l closepath" llx lly urx lly urx ury llx ury) (format port "~d ~d ~d ~d ~a" px py w h (case method ((stroke-show stroke-stroke stroke-fill) "rectstroke") ((fill-show fill-stroke fill-fill) "rectfill")))))) ;; draws a counterclockwise arc (define (PSarc center radius start-ang end-ang port) (format port " ~d ~d ~d ~d ~d arc~%" (PSnum (pt:x center)) (PSnum (pt:y center)) (PSnum radius) (PSnum (rad->deg start-ang)) (PSnum (rad->deg end-ang)))) ;; draw a tangent arc (define (PStangent-arc pt1 pt2 pt3 radius port) (format port " ~d ~d ~d ~d ~d arct~%" (PSnum (pt:x pt2)) (PSnum (pt:y pt2)) (PSnum (pt:x pt3)) (PSnum (pt:y pt3)) (PSnum radius))) ;; append Bezier curveto (define (PScurve start-pt ctrl-pt1 ctrl-pt2 end-pt port) (format port " ~d ~d ~d ~d ~d ~d curveto~%" (PSnum (pt:x ctrl-pt1)) (PSnum (pt:y ctrl-pt1)) (PSnum (pt:x ctrl-pt2)) (PSnum (pt:y ctrl-pt2)) (PSnum (pt:x end-pt)) (PSnum (pt:y end-pt)))) (define (PScharpath str method port) (format port "(~a) ~a charpath~%" (PSadd-escape str) (case method ((stroke stroke-stroke fill-stroke) "false") (else "true")))) (define (PSglyphnamepath glyph method font port) (let ((fontname (font:fontname font)) (fontsize (font:fontsize font)) (glyphname (glyph:glyphname glyph))) (format port "/~a findfont~%" fontname) (format port "dup length dict begin~%") (format port "{1 index /FID ne {def} {pop pop} ifelse} forall~%") (format port "/Encoding 256 array def~%") (format port "0 1 255 {Encoding exch /.notdef put} for~%") (format port "Encoding 97 /~a put~%" glyphname) (format port "currentdict end /tmp-font exch definefont pop~%") (format port "/tmp-font ~d selectfont~%" fontsize) (format port "(a) ~a charpath~%" (case method ((stroke stroke-stroke fill-stroke) "false") (else "true"))))) (define (PSshow str port) (format port "(~a) show~%" (PSadd-escape str))) ;; Specialized procedure used to make PS string. This procedure takes a ;; string and adds \ where needed for PS escape chars. (define (PSadd-escape str) (let* ((new-len (string-reduce (lambda (sum ch) (+ sum (if (memq ch '(#\\ #\( #\))) 2 1))) 0 str)) (new-str (make-string new-len))) (string-reduce (lambda (new-str-index ch) (string-set! new-str new-str-index ch) (if (memq ch '(#\) #\( #\\)) (begin (string-set! new-str (- new-str-index 1) #\\) (- new-str-index 2)) (- new-str-index 1))) (- new-len 1) str) new-str)) (define (PSglyphshow glyph port) (format port " /~a glyphshow~%" (glyph:glyphname glyph))) ;; connect subpath back to its starting point (define (PSclose-path port) (format port " closepath~%")) ;; compute outline of path. problem .. (define (PSstroke-outline-path port) (format port " strokepath~%")) ;===== Image =================================================== ;; (PSimagemask row col trasparent-val color-array port) ;; (PSimage row col resolution colorspace color-array port) ;; output image mask using dictionary structure and filter (define (PSimagemask row col transparent-val color-array port) (let ((array-size (* row col))) (format port " << /ImageType 1 /Width ~d /Height ~d /Decode ~a /ImageMatrix ~a /DataSource currentfile /ASCIIHexDecode filter >> imagemask~%" col row (if (= transparent-val 1) "[1 0]" "[0 1]") (PSmatrix (matrix row 0 0 (- 0 col) 0 col))) (output-hex-string port array-size 1 color-array))) ;; output image using dictionary structure and filter (define (PSimage row col resolution colorspace color-array port) (let ((array-size (* (if (eq? colorspace 'gray) 1 3) row col))) (if (eq? colorspace 'color) (format port "/DeviceRGB setcolorspace~%")) (format port "<< /ImageType 1 /Width ~d /Height ~d /BitsPerComponent ~d /Decode ~a /ImageMatrix ~a /DataSource currentfile /ASCIIHexDecode filter >> image~%" col row resolution (if (eq? colorspace 'gray) "[0 1]" "[0 1 0 1 0 1]") (PSmatrix (matrix row 0 0 (- 0 col) 0 col))) (output-hex-string port array-size resolution color-array))) ;;=== Bitmap hex string output section ================================== ;; converts the color-array into hex values with the appropirate ;; resolution and display the hex digit out to the port (define (output-hex-string port size resolution color-array) (receive (display-proc step) (case resolution ((1) (values output-1 4)) ((2) (values output-2 2)) ((4) (values output-4 1)) ((8) (values output-8 1)) ((12) (values output-12 1))) (let lp ((n 0)) (if (< n size) (begin (display-proc port n color-array size) (lp (+ n step)))))) (display ">" port)) ;used to output sample points of resolution of 1 bits/sample (define (output-1 port n color-array size) (display (number->string (+ (if (= (vector-ref color-array n) 0) 0 8) (if (or (>= (+ 1 n) size) (= (vector-ref color-array (+ 1 n)) 0)) 0 4) (if (or (>= (+ 2 n) size) (= (vector-ref color-array (+ 2 n)) 0)) 0 2) (if (or (>= (+ 3 n) size) (= (vector-ref color-array (+ 3 n)) 0)) 0 1)) 16) port)) ;used to output sample points of resolution of 2 bits/sample (define (output-2 port n color-array size) (display (number->string (+ (* 4 (vector-ref color-array n)) (if (< (+ 1 n) size) (vector-ref color-array (+ 1 n)) 0)) 16) port)) ;used to output sample points of resolution of 4 bits/sample (define (output-4 port n color-array size) (display (number->string (vector-ref color-array n) 16) port)) ;; used to output sample point of resolution of 8 bits/sample (define (output-8 port n color-array size) (let* ((hex-string (number->string (vector-ref color-array n) 16)) (len (string-length hex-string))) (display (if (= 2 len) hex-string (string-append "0" hex-string)) port))) ;; used to output sample point of resolution of 12 bits/sample (define (output-12 port n color-array size) (let* ((hex-string (number->string (vector-ref color-array n) 16)) (len (string-length hex-string))) (display (if (= 3 len) hex-string (string-append (make-string (- 3 len) #\0) hex-string)) port))) ;===== End of ps.path.scm ======================================
false
86271eff9f4ead0349625b384c9fbf7dbbc81f95
7a170e71eaf140155926f57281be7f3f6cf57d88
/main.scm
e7558a78520a858ace77fd30d1e04feb74fc1fdd
[]
no_license
hellcoderz/jit-scheme
fcee353fbaa35d2386078a555c9ef6637782eb3d
9ade822d7d8ac70767e3639b2b741a000319c13b
refs/heads/master
2021-01-15T20:38:17.279154
2011-07-29T16:22:12
2011-07-29T16:22:12
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
27,662
scm
main.scm
(use srfi-1) (use srfi-4) (use srfi-38) (use matchable) (use numbers) (use lolevel) (define test 88) (define type '(! type)) (define type-namespace `( (int_62 . (,type int_62)) (cons . (,type cons)) (procedure . (,type procedure)) (object . (,type object)))) (define tag-namespace `( (0 . ,(cdr (assq 'int_62 type-namespace))) (1 . ,(cdr (assq 'cons type-namespace))) (2 . ,(cdr (assq 'procedure type-namespace))) (3 . ,(cdr (assq 'object type-namespace))))) (define (map-with-index proc lis) (map-with-index% proc 0 lis)) (define (map-with-index% proc i lis) (if (pair? lis) (cons (proc i (car lis)) (map-with-index% proc (+ i 1) (cdr lis))) '())) (define (element? elem set) (any (cut eq? elem <>) set)) (define (append-map proc lis) (apply append (map proc lis))) (define (tree-walk walker proc tree) (walker (lambda (elem) (if (list? elem) (tree-walk walker proc elem) (proc elem))) tree)) (define (find-tree proc tree) (tree-walk append-map (lambda (x) (if (proc x) (list x) (list))) tree)) (define (find-vars code class) (delete-duplicates! (find-tree (lambda (x) (and (pair? x) (eq? (cdr x) class))) code))) (define logior bitwise-ior) (define lognot bitwise-not) (define logand bitwise-and) (define ash arithmetic-shift) (define mod modulo) (require 'posix) (define-syntax let1 ;single variable bind (syntax-rules () [(let1 var exp . body) (let ((var exp)) . body)])) (define-syntax begin0 (syntax-rules () [(begin0 ret . rest) (let ((var ret)) (begin . rest) var)])) (define-syntax push! (syntax-rules () [(push! place value) (set! place (cons value place))])) (define (write-byte b) (display (integer->char b))) (define genid (let1 counter 0 (lambda () (set! counter (+ 1 counter)) counter))) (define (eq$ x) (cut eq? <> x)) (define (pa x) (display "a:") (print (format "~x" x)) x) (define (pb x) (display "b:") (print (format "~x" x)) x) (define (p x) x) (define (p-i x) x) (define (px x) x) (define (free-vars t) (free-vars% t '())) (define (free-vars% term bound-vars) (cond ((and (pair? term) (or (eq? (car term) 'fn) (eq? (car term) 'lambda))) (free-vars% (cddr term) (cons bound-vars (cadr term)))) ((pair? term) (apply append (map (lambda (x) (free-vars% x bound-vars)) term))) (else (if (and (not (any (cut eq? term <>) bound-vars)) (symbol? term)) (list term) '())))) (define (heap-vars term vars) (cond ((and (pair? term) (or (eq? (car term) 'lambda) (eq? (car term) 'fn))) (filter (lambda (x) (any (cut eq? <> x) vars)) (free-vars term))) ((pair? term) (apply append (map (cut heap-vars <> vars) term))) (else '()))) (define (stack-vars heap-vars vars) (filter (lambda (x) (not (any (lambda (y) (eq? x y)) heap-vars))) vars)) (define (compile-to-tagged s) (match s (((or 'lambda 'fn) args body ...) (%compile-to-tagged body args '() args)))) ; (sexp (%compile-to-tagged (list sexp) '() '() '())))) (define (%compile-to-tagged body args frame vars) (let* ((heap (heap-vars body args)) (stack (stack-vars heap args))) (receive (codes procs) (%%compile-to-tagged body heap stack frame vars) (cons `((lambda . syntax) ,(%%compile-to-tagged args heap stack frame vars) ,@codes) procs)))) ; heap - variables that should be allocated on heap (i.e. variables to be captured in other lambdas) ; stack - variables that could be allocated on stack. ; frame - variables refering outer frame. (define (%%compile-to-tagged s heap stack frame vars) (p vars) (define procs '()) (define (loop s) (match s (((or 'lambda 'fn) args body ...) (let1 p (%compile-to-tagged body args frame (append vars args)) (set! procs (append p procs)) `((close . syntax) ,(map loop (filter (lambda (x) (any (cut eq? <> x) (free-vars s))) vars)) (,(car p) . procedure)))) (('if p t f) `((if . syntax) ,(loop p) ,(loop t) ,(loop f))) (('quote expr) (encode-value expr)) ((s ...) (map loop s)) ((? (cut element? <> heap)) `(,s . heap)) ((? (cut element? <> stack)) `(,s . stack)) ((? (cut element? <> vars)) `(,s . frame)) ((? number? x) (fixnum x)) ((? lookup) (lookup s)) (s `(,s . gref)))) (define proc (loop s)) (values proc procs)) (define (fixnum x) x) (define (disp-tree term) (cond ((and (pair? term) (eq? (cdr term) 'stack)) (display (format "~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'gref)) (display (format "~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'frame)) (display (format "~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'syntax)) (display (format "~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'builtin)) (display (format "~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'heap)) (display (format "~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'in)) (display (format "in~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'frame-in)) (display (format "frame-in~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'out)) (display (format "out~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'sys)) (display (format "sys~a " (car term)))) ((and (pair? term) (eq? (cdr term) 'procedure)) (display "#proc ")) ((and (pair? term) (eq? (cdr term) 'ref)) (display "[") (for-each disp-tree (car term)) (display "] ")) ((and (pair? term) (not (pair? (cdr term))) (not (null? (cdr term)))) (display "(") (disp-tree (car term)) (display ". ") (disp-tree (cdr term)) (display ") ")) ((pair? term) (display "(") (for-each disp-tree term) (display ") ")) (else (display term) (display " ")))) (define (disp-inst insts) (for-each (lambda (x) (disp-tree (first x)) (newline) (for-each (lambda (y) (display " ") (disp-tree y) (newline)) (second x)) (or (null? (cddr x)) (for-each (lambda (x) (if (number? x) (display (format " ~x" x)) (display (format " ~a" x)))) (third x))) (newline)) insts)) ; compile tagged to vm (define (compile-to-vm s) (define (%compile-to-vm c j) (match c (('(lambda . syntax) (args ...) body ...) `( ,@(map-with-index (lambda (i arg) `((<- . syntax) ,arg (,i . in))) args) ,@(apply append (map (cut %compile-to-vm <> j) body)))) ((`(close . syntax) (args ...) body) `( ((close . syntax) ,args ,body))) (('(set! . gref) sym arg) `( ,@(%compile-to-vm arg (+ j 1)) ((<- . syntax) ,sym (0 . out)))) (('(builtin read) arg1) `( ,@(%compile-to-vm arg1 (+ j 1)) ((<- . syntax) (0 . tmp) #xfffffffffffff) (and (0 . out) (0 . tmp)) ((<- . syntax) (0 . out) ((0 . out))))) (('(builtin write) arg1 arg2) `( ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg1 (+ j 1)) ((<- . syntax) (1 . out) ((,j 0) . stack)) ((<- . syntax) (0 . tmp) #xfffffffffffff) (and (0 . out) (0 . tmp)) ((<- . syntax) ((0 . out)) (1 . out)))) (('(builtin cons) arg1 arg2) `( ,@(%compile-to-vm arg1 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg2 (+ j 1)) (cons ((,j 0) . stack) (0 . out)))) (('(builtin tri) arg1 arg2 arg3) `( ,@(%compile-to-vm arg1 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 1) . stack) (0 . out)) ,@(%compile-to-vm arg3 (+ j 1)) (tri ((,j 0) . stack) ((,j 1) . stack) (0 . out)))) (('(builtin +) arg1 arg2) `( ,@(%compile-to-vm arg1 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg2 (+ j 1)) (add (0 . out) ((,j 0) . stack)))) (('(builtin *) arg1 arg2) `( ,@(%compile-to-vm arg1 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg2 (+ j 1)) (imul (0 . out) ((,j 0) . stack)))) (('(builtin -) arg1 arg2) `( ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg1 (+ j 1)) (sub (0 . out) ((,j 0) . stack)))) (('(builtin and) arg1 arg2) `( ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg1 (+ j 1)) (and (0 . out) ((,j 0) . stack)))) (('(builtin xor) arg1 arg2) `( ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg1 (+ j 1)) (xor (0 . out) ((,j 0) . stack)))) (('(builtin ior) arg1 arg2) `( ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg1 (+ j 1)) (ior (0 . out) ((,j 0) . stack)))) (('(builtin >) arg1 arg2) `( ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg1 (+ j 1)) (cmp (0 . out) ((,j 0) . stack)) (movflag g))) (('(builtin =) arg1 arg2) `( ,@(%compile-to-vm arg2 (+ j 1)) ((<- . syntax) ((,j 0) . stack) (0 . out)) ,@(%compile-to-vm arg1 (+ j 1)) (cmp (0 . out) ((,j 0) . stack)))) (('(builtin not) arg1) `( ,@(%compile-to-vm arg1 (+ j 1)) (not))) (('(if . syntax) pred true-case false-case) (let* ((i (genid)) (ii (genid))) `( ,@(%compile-to-vm pred j) ,@(let1 label1 `(rel-label-ref ,(lambda (table self base) (- (px (cdr (assq i table))) (p self))) (0 0 0 0)) `((jnz ,label1))) ,@(%compile-to-vm true-case j) (jmp (rel-label-ref ,(lambda (table self base) (- (px (cdr (assq ii table))) (p self))) (0 0 0 0))) (label ,i) ,@(%compile-to-vm false-case j) (label ,ii)))) ((proc args ...) `( ,@(apply append (map-with-index (lambda (i arg) `( ,@(%compile-to-vm arg (+ j 1)) ((<- . syntax) ((,j ,i) . stack) (0 . out)))) args)) ,@(%compile-to-vm proc (+ j 1)) ,@(apply append (map-with-index (lambda (i arg) `( ((<- . syntax) (,i . in) ((,j ,i) . stack)))) args)) ((call . syntax) (0 . out)))) (sym `(((<- . syntax) (0 . out) ,sym))))) (list s (%compile-to-vm s 0))) (define (ssa c) (define lis '(())) (define (inc var) (if (assoc var lis) (set! (cadr (assoc var lis)) (+ 1 (cadr (assoc var lis)))) (push! lis (list var 1)))) (define (ref var) (list-copy (or (assoc var lis) (list var 0)))) (define (loop c) (if (null? c) '() (match (car c) (('(assign . syntax) out in) (let1 in (ref in) (inc out) `(((assign . syntax) ,(ref out) ,in) ,@(loop (cdr c))))) ((`(close . syntax) arg ... ) `(((close . syntax) ,@arg) ,@(loop (cdr c)))) ((`(call . syntax) arg) (let1 a (ref arg) (inc '(0 . out)) `(((assign . syntax) ,(ref arg) ((call . syntax) ,a)) ,@(loop (cdr c)))))))) (loop c)) (define (optimize c) (define lis '(())) (define lis2 '(())) (define (ref var) (if (assoc var lis) (cdr (assoc var lis)) var)) (define (loop c) (if (null? c) '() (match (car c) (('(assign . syntax) out ('(call . syntax) arg)) `(((call . syntax) ,(ref arg)) ,@(loop (cdr c)))) (('(assign . syntax) out in) (push! lis (cons out (ref in))) `(((assign . syntax) ,out ,(ref in)) ,@(loop (cdr c)))) (((proc . 'builtin) in ...) `((,proc ,@(map (cut ref <>) in)) ,@(loop (cdr c)))) (('(call . syntax) in ...) `(((call . syntax) ,@(map (cut ref <>) in)) ,@(loop (cdr c)))) (('(close . syntax) in ...) `(((close . syntax) ,@in) ,@(loop (cdr c))))))) (define (loop4 c) (if (null? c) '() (match (car c) ('((call . syntax) ((+ . gref) 0)) `((add ((0 . out) #f) ((0 . in) #f) ((1 . in) #f)) ,@(loop4 (cdr c)))) ('((call . syntax) ((* . gref) 0)) `((mul ((0 . out) #f) ((0 . in) #f) ((1 . in) #f)) ,@(loop4 (cdr c)))) (s (cons s (loop4 (cdr c))))))) (define (loop5 c) (if (null? c) '() `((,(caar c) ,@(map (cut car <>) (cdar c))) ,@(loop5 (cdr c))))) (define (loop2 c) (if (null? c) '() (match (car c) (('(assign . syntax) out in) (set! lis2 (remove! (cut eq? in <>) lis2)) (push! lis2 out) (loop2 (cdr c))) (((proc . 'builtin) in ...) (for-each (lambda (i) (set! lis2 (remove! (cut eq? i <>) lis2))) in) (loop2 (cdr c))) (('(call . syntax) in) (set! lis2 (remove! (cut eq? in <>) lis2)) (loop2 (cdr c)))))) (define (loop3 c) (if (null? c) '() (match (car c) (('(assign . syntax) out in) (if (and (or (eq? (cdar out) 'out) (eq? (cdar out) 'stack)) (any (cut eq? <> out) lis2)) (loop3 (cdr c)) `(((assign . syntax) ,out ,in) ,@(loop3 (cdr c))))) (('(call . syntax) in) `(((call . syntax) ,in) ,@(loop3 (cdr c))))))) (define (loop6 c) (if (null? c) '() (match (car c) (('(assign . syntax) out in) (if (and (or (eq? (cdr out) 'in) (eq? (cdr out) 'out)) (any (cut eq? <> out) lis2)) (loop6 (cdr c)) `(((assign . syntax) ,out ,in) ,@(loop6 (cdr c))))) (('(call . syntax) in) `(((call . syntax) ,in) ,@(loop6 (cdr c)))) (((proc . 'builtin) in ...) `((,proc ,@in) ,@(loop6 (cdr c))))))) (define ssa-p (loop c)) (define a #f) ssa-p ;(loop2 ssa-p) ;(set! a (loop (loop5 (loop4 (loop3 ssa-p))))) ;(loop2 a) ;(loop6 a)) ) (define size-of-ptr 8) (define (compile-to-assembly c) (define (instruction-to-assembly c) (match c (('(close . syntax) vars body) `( (add (1 . sys) ,(* size-of-ptr (+ 1 (length vars)))) (mov (0 . out) (label-ref (,(car body) . proc) (0 0 0 0 0 0 0 0))) (mov ((1 . sys)) (0 . out)) ,@(apply append (map-with-index (lambda (i x) `( (lea (0 . out) ,x) (mov (- (1 . sys) ,(* size-of-ptr (+ i 1))) (0 . out)))) vars)) (mov (0 . out) (1 . sys)))) (('cons arg1 arg2) `( ; allocate (add (1 . sys) ,(* size-of-ptr 2)) (mov ((1 . sys)) ,arg2) (mov (0 . out) ,arg1) (mov (- (1 . sys) ,size-of-ptr) (0 . out)) ; return (mov (0 . out) (1 . sys)))) (('tri arg1 arg2 arg3) `( ; allocate (add (1 . sys) ,(* size-of-ptr 3)) (mov (0 . out) ,arg3) (mov ((1 . sys)) (0 . out)) (mov (0 . out) ,arg2) (mov (- (1 . sys) ,size-of-ptr) (0 . out)) (mov (0 . out) ,arg1) (mov (- (1 . sys) ,(* 2 size-of-ptr)) (0 . out)) ; return (mov (0 . out) (1 . sys)))) (('string str) `( (add (1 . sys) ,(align 8 (string-length str))) ,@(let loop ((i (floor (/ (string-length str) 8))) (s str)) `((mov (0 . out) ,(task8 str)) (mov (- (1 . sys) ,(* i size-of-ptr)) (0 . out)) ,@(if (= 0 i) '() (loop (- i 1) (drop8 str))))) (mov (0 . out) #x0400000000000000) (ior (0 . out) (1 . sys)))) (('not) `( (setz al) (test al 1))) (('movflag src) (case src ((g) '((setng al) (test al 1))) ((le) '((setg al) (test al 1))) ((c) '((setnc al) (test al 1))))) (('(<- . syntax) dest src) `((mov ,dest ,src))) (('(call . syntax) proc) `( (push (0 . frame-in)) (mov (0 . frame-in) (- ,proc ,(* size-of-ptr 1))) ;(mov (1 . frame-in) (- ,proc ,(* size-of-ptr 2)) ) (call (,proc)) (pop (0 . frame-in)))) (x (list x)))) (let1 asm (append-map instruction-to-assembly (second c)) (let ((s (find-vars asm 'stack)) (h (find-vars asm 'heap)) (f (find-vars asm 'frame))) (define (rep x) (if (pair? x) (case (cdr x) ((stack) `(+ (0 . sys) ,(* size-of-ptr (list-index (cut equal? <> x) s)))) ((heap) `(- (2 . sys) ,(* size-of-ptr (list-index (cut equal? <> x) h)))) ((frame) `((,(list-index (cut equal? <> x) f) . frame-in))) (else x)) x)) (list (first c) `(,@(if (= 0 (length h)) '() `((push (2 . sys)) (add (1 . sys) ,(* size-of-ptr (length h))) (mov (2 . sys) (1 . sys)))) (sub (0 . sys) ,(* size-of-ptr (length s))) ,@(tree-walk map rep (append-map instruction-to-assembly (second c))) (add (0 . sys) ,(* size-of-ptr (length s))) ,@(if (= 0 (length h)) '() '((pop (2 . sys)))) (ret)))))) (define (link-label base codes) (define table '()) (define x 0) (for-each (lambda (code) (push! table (cons (cons (first code) 'proc) x)) (let loop ((binary (second code))) (for-each (lambda (b) (cond ((label-ref? b) (loop (third b))) ((rel-label-ref? b) (loop (third b))) ((label? b) (push! table (cons (second b) x))) (else (set! x (+ x 1))))) binary))) codes) (set! x 0) (append-map (lambda (code) (append-map (lambda (b) (cond ((label-ref? b) (set! x (+ x (length (third b)))) ;XXX (enc 8 (length (third b)) (p (+ base (p (cdr (assoc (second b) (p table)))))))) ((rel-label-ref? b) (set! x (+ x (length (third b)))) (enc 8 (length (third b)) ((second b) table x base))) ((label? b) '()) (else (set! x (+ x 1)) (list b)))) (second code))) codes)) (define (map-second proc lis) (map (lambda (x) (cons (car x) (cons (proc (cadr x)) (cddr x)))) lis)) (define (compile-and-eval expr) (define c (map-second (cut append-map compile-to-binary <>) (p-i (map render-register (map compile-to-assembly (p-i (map compile-to-vm (compile-to-tagged expr)))))))) (define b (list->u8vector (link-label (binary-address) c))) (define a ((foreign-safe-lambda unsigned-long "exec_binary" integer u8vector) (u8vector-length b) b)) (channel)) ; Due to poor support of 64-bit variables in chicken scheme ... (define (binary-address) (+ (ash (modulo ((foreign-safe-lambda integer "binary_address_higher32")) #x100000000) 32) (modulo ((foreign-safe-lambda integer "binary_address_lower32")) #x100000000))) (define (repl) (define expr #f) (define result #f) (display "scheme> ") (set! expr (read)) (set! result (eval* expr)) (if (integer? result) (set! result (decode-value result))) (cond ((number? result) (display (format " => ~a (0x~x)\n" result result))) ((any (cut eq? <> result) namespaces) (display (format " => #<namespace>\n"))) ((pair? result) (display (format " => ~a\n" (with-output-to-string (lambda () (write/ss result)))))) (else (display (format " => ~a\n" result)))) (repl)) (define (add-to-namespace name value) (push! (car current-namespace) (cons name value))) (define (syntax-define name tree) (add-to-namespace name (eval* tree))) (define (get-current-namespace) current-namespace) (define (select-namespace namespace) (set! current-namespace namespace)) (define namespaces '()) (define (make-namespace) (let1 ns (list (list)) (push! namespaces ns) ns)) (define (import-namespace-to dest src) (set-cdr! (last-pair dest) (list (car src)))) (define current-namespace (make-namespace)) (define (export-to-namespace alist name) (let1 ns (list alist) (push! namespaces ns) (add-to-namespace name ns) ns)) (define (dummy) (foreign-code " return 0;} #include <dlfcn.h> static C_word foo () { ")) (define dlerror (foreign-lambda c-string "dlerror")) (define (dlopen file) ((foreign-lambda c-pointer "dlopen" c-string integer) file (foreign-code "return C_fix(RTLD_LAZY);"))) (define (dlsym handle str) (define return (allocate 8)) (define-external x c-pointer) (set! x ((foreign-lambda c-pointer "dlsym" c-pointer c-string) handle str)) ((foreign-safe-lambda void "assign" c-pointer c-pointer) return x) (pointer->address return)) (define channel (let1 value 0 (lambda x (if (null? x) value (set! value (car x)))))) (define-external (Chicken_to_C_higher32) unsigned-int (ash (channel) -32)) (define-external (Chicken_to_C_lower32) unsigned-int (bitwise-and (channel) #xffffffff)) (define-external (C_to_Chicken_higher32 (unsigned-int h)) void (channel (bitwise-and (channel) #x00000000ffffffff)) (channel (bitwise-ior (channel) (ash h 32)))) (define-external (C_to_Chicken_lower32 (unsigned-int l)) void (channel (bitwise-and (channel) #xffffffff00000000)) (channel (bitwise-ior (channel) l))) (define-external (system_eval) void (channel (encode-value (eval (decode-value (channel)))))) (define-external (system_print (integer n)) void (print (decode-value n))) (define dummy2 (foreign-code " return 0;} #include \"jit.h\" static C_word bar () { ")) (define system-print (foreign-code "return C_fix((long) system_print);")) (define system-eval (foreign-code "return C_fix((long) exec_eval);")) (define (export-proc proc) (define return (allocate 8)) ((foreign-safe-lambda void "assign" c-pointer int) return proc) (pointer->address return)) (define (make-macro x) `(,macro ,(lambda args (eval* (cons x (encode args)))))) (define (define-to-sys-define name value) (if (pair? name) `(,sys-define ,(car name) (fn ,(cdr name) ,value)) `(,sys-define ,name ,value))) (define system '(! system)) (define (system? a) (and (pair? a) (eq? (car a) system))) (define sys-define `(,system define)) (define sys-make-namespace `(,system ,make-namespace)) (define sys-select-namespace `(,system ,select-namespace)) (define sys-import-namespace-to `(,system ,import-namespace-to)) (define sys-current-namespace `(,system ,get-current-namespace)) (define sys-exit `(,system ,exit)) (define sys-dlopen `(,system ,dlopen)) (define sys-dlsym `(,system ,dlsym)) (define sys-macro `(,system ,make-macro)) (define sys-display `(,system ,display)) (define sys-eval `(,system eval)) (define builtin-add '(builtin +)) (define builtin-sub '(builtin -)) (define builtin-imul '(builtin *)) (define builtin-div '(builtin /)) (define builtin-eq '(builtin =)) (define builtin-gt '(builtin >)) (define builtin-and '(builtin and)) (define builtin-ior '(builtin ior)) (define builtin-xor '(builtin xor)) (define builtin-not '(builtin not)) (define builtin-read '(builtin read)) (define builtin-write '(builtin write)) (define builtin-cons '(builtin cons)) (define builtin-tri '(builtin tri)) (define macro '(! macro)) (define (macro? a) (and (pair? a) (eq? (car a) macro))) (define macro-define `(,macro ,define-to-sys-define)) (define namespace-function-namespace `((internal-define . ,sys-define) (make-namespace . ,sys-make-namespace) (select-namespace . ,sys-select-namespace) (import-namespace-to . ,sys-import-namespace-to) (current-namespace . ,sys-current-namespace))) (define internal-namespace `((internal-eval . ,sys-eval) (dlopen . ,sys-dlopen) (dlsym . ,sys-dlsym) (display . ,sys-display) (print . ,(export-proc system-print)) (meta-eval . ,(export-proc system-eval)) (exit . ,sys-exit ))) (define arithmetic-namespace `((+ . ,builtin-add) (- . ,builtin-sub) (* . ,builtin-imul) (/ . ,builtin-div) (and . ,builtin-and) (ior . ,builtin-ior) (xor . ,builtin-xor) (not . ,builtin-not) (= . ,builtin-eq) (> . ,builtin-gt))) (define machine-namespace `((read . ,builtin-read) (write . ,builtin-write))) (define builtin-namespace `((pair . ,builtin-cons) (tri . ,builtin-tri))) (define macro-namespace `((make-macro . ,sys-macro) (define . ,macro-define))) (define (assq-ref lis sym false-case) (or (and (assq sym lis) (cdr (assq sym lis))) false-case)) (define (assq-ref-list lis sym) (or (and (assq sym lis) (list (cdr (assq sym lis)))) '())) (define (lookup sym) (define (car* maybe-lis) (if (null? maybe-lis) #f (car maybe-lis))) (car* (append-map (cut assq-ref-list <> sym) current-namespace))) (define external-table '()) (define (encode x) (let ((res (cond ((pair? x) (let ((m (allocate 16))) (assign m (external (car x))) (assign (pointer+ m 8) (external (cdr x))) (address->number m))) ((number? x) x)))) (push! external-table (cons x res)) res)) (define (eval* expr) (cond ((system? expr) expr) ((macro? expr) expr) ((pair? expr) (let1 f (eval* (car expr)) (cond ((assq f system-syntax) => (lambda (x) (apply (cdr x) (cdr expr)))) ((system? f) (apply (cadr f) (map eval* (cdr expr)))) ((macro? f) (eval* (apply (cadr f) (cdr expr)))) (else (compile-and-eval `(lambda () ,expr)))))) ((symbol? expr) (lookup expr)) (else expr))) (define (@pair? x) (= (bitwise-and #xff0000000000000 x) #x0100000000000000)) (define (@null? x) (= (symbol->integer '()) x)) (define (@integer? x) (= (bitwise-and #xff0000000000000 x) #x0000000000000000)) (define (@symbol? x) (= (bitwise-and #xff0000000000000 x) #x0800000000000000)) (define (decode-value val) (cond ((@pair? val) (cons (decode-value (eval* `(car ,val))) (decode-value (eval* `(cdr ,val))))) ((@null? val) '()) ((@integer? val) val) ((@symbol? val) (integer->symbol val)) (else 'unknown-object))) (define (encode-value val) (cond ((pair? val) (eval* `(cons ,(encode-value (car val)) ,(encode-value (cdr val))))) ((null? val) (symbol->integer '())) ((integer? val) val) ((symbol? val) (symbol->integer val)) (else (encode-value 'not-available)))) (define exported-symbols '()) (define (symbol->integer x) (bitwise-ior #x0800000000000000 (if (any (eq$ x) exported-symbols) (- (length exported-symbols) (list-index (eq$ x) exported-symbols) 1) (begin (push! exported-symbols x) (- (length exported-symbols) 1))))) (symbol->integer '()) (define (integer->symbol integer) (list-ref exported-symbols (- (length exported-symbols) (bitwise-and #x00ffffffffffffff integer) 1))) (import-namespace-to current-namespace (export-to-namespace namespace-function-namespace 'namespace-function)) (import-namespace-to current-namespace (export-to-namespace macro-namespace 'macro)) (export-to-namespace arithmetic-namespace 'arithmetic) (export-to-namespace machine-namespace 'machine) (export-to-namespace builtin-namespace 'builtin) (export-to-namespace internal-namespace 'internal) (export-to-namespace tag-namespace 'tag) (export-to-namespace type-namespace 'type) (define system-syntax `((,sys-define . ,syntax-define) (,sys-eval . ,eval))) (with-input-from-file "default.scm" (lambda () (let loop ((s (read))) (cond ((eof-object? s) #t) (else (eval* s) (loop (read))))))) (repl)
true
4c09bb1fa377bf16192930fcee955d14379f38ad
efd7022e1828df563d1a88f4bc72f5fc2dbad018
/src/compiler/package-s48.scm
b94ad791d2cbed18cce6d38df6d93dfaac12baff
[]
no_license
pierredepascale/native
936ba53f55b171e665404dbcf8c90f3f6386cda1
f782115725e4c609e6cb7a561c63b563dccf7850
refs/heads/master
2021-01-10T06:18:00.597045
2017-08-10T20:48:21
2017-08-10T20:48:21
8,397,369
1
0
null
null
null
null
UTF-8
Scheme
false
false
217
scm
package-s48.scm
;;; package-s48.scm -- Scheme48 package definition for Scheme like compiler (define-structure native-compiler (export) (open scheme scsh) (files compat-s48 arch-x86 asm-x86 front back-x86))
false
2eb01dad9410824cdc626783fc52cb0c53de7543
2d754c5649bfe0cf9f670696ce82768b1c13c211
/lib/carp.scm
f2dfcb38621ccdcef03cd32df8f0f6e3eb8e1cd3
[ "MIT" ]
permissive
PlumpMath/guile-carp
5de7f38ba87e82f76a33dc44dace0cf33e2f73f3
e93975224c3c6cd2e0c3ae45aa36107f0faa6e4a
refs/heads/master
2021-01-18T19:00:30.680055
2016-11-01T08:58:30
2016-11-01T08:58:30
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
561
scm
carp.scm
(define-module (carp) #:use-module (srfi srfi-13) #:export (confess)) (define (localize-path path) (string-append (basename (dirname path)) "/" (basename path))) (define (long-message message location) (let* ((filename (localize-path (assq-ref location 'filename))) (line (assq-ref location 'line))) (format (current-error-port) "~a at ~a line ~a~%" message filename line))) (define-syntax confess (syntax-rules () ((_ message) (begin (long-message message (current-source-location)) (exit EXIT_FAILURE)))))
true
1fffc2ac48625ff5b12d124531fcceca768ec820
d51c8c57288cacf9be97d41079acc7c9381ed95a
/scheme/composer.scm
39fac0f15328f73c85fa723a9d217051e2507667
[]
no_license
yarec/svm
f926315fa5906bd7670ef77f60b7ef8083b87860
d99fa4d3d8ecee1353b1a6e9245d40b60f98db2d
refs/heads/master
2020-12-13T08:48:13.540156
2020-05-04T06:42:04
2020-05-04T06:42:04
19,306,837
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,137
scm
composer.scm
(define (new-controller d od) (let* ((value (oret:value d)) (out-file (string-append value "Controller.php")) (tpl (string-append svm-path "/tpl/yii/RestController.php")) (sed-cmd (string-append "s/Rest/" value "/g")) ) (run (sed -e ,sed-cmd ,tpl) (> 1 ,out-file)) )) (define (new-yii1 d od) (let* ((value (oret:value d)) (appname (if (string=? value "") "yii-rest-app" value)) (tpl "yarec/yii-rest")) (run (composer create-project --prefer-dist --stability=dev ,tpl ,appname) (= 2 1)))) (define (new-yii2 d od) (let* ((value (oret:value d)) (appname (if (string=? value "") "yiiapp" value)) (arg4 (get-argn 4)) (tpl (if (string=? arg4 "") "basic" arg4)) (full-tpl (cond ((or (string=? tpl "basic") (string=? tpl "advanced")) (string-append "yiisoft/yii2-app-" tpl)) (else (string-append "yarec/yii2-app-" tpl))))) (run (composer create-project --prefer-dist --stability=dev ,full-tpl ,appname) (= 2 1)))) (define (check-composer) (if (has-no-cmd "composer") (run (ins "composer")))) (define (install-composer-pkg d od) (check-composer) (run (composer install))) (define (update-composer-pkg d od) (check-composer) (run (composer update))) (define (composer d od) (get-opt `( (--new-c -c|s|t " new c ex: phc -c Model " , new-controller) (--new-yii -Y|s|t " new yii1 app ex: phc -Y [app] " , new-yii1) (--new-yii2 -y|s|t " new yii2 app ex: phc -y [app rest] " , new-yii2) (--ins-pkg -i| " install deps " , install-composer-pkg) (--up-pkg -u| " update deps " , update-composer-pkg) (--debug -d||f " debug " #f) (--default - " default action " , get-opt-usage) (--help -h " bprint this usage message " , get-opt-usage))))
false
6f0749c3c268c55ad8a6e9ff31e0697e381aefc3
697716cdb4ffe03bb54839701e163cdd9627adb8
/host.sls
ee7784668b07a74ae3f449634d308e1c8958ec26
[ "X11-distribute-modifications-variant" ]
permissive
DerickEddington/vifne
1153a2c775a459109503f4cd2d674cc92597bff9
077fc0afa2f5d4bab93ecc4ee043f4d971ea830e
refs/heads/master
2020-05-05T09:14:32.369208
2019-04-06T22:57:19
2019-04-06T22:57:19
179,895,896
0
0
null
null
null
null
UTF-8
Scheme
false
false
642
sls
host.sls
#!r6rs ; Copyright 2012 Derick Eddington. My MIT-style license is in the file named ; LICENSE from the original collection this file is distributed with. ; This library exports values that might differ across different host platforms. ; Import the (vifne host <name>) library for your host platform. (library (vifne host) (export number-host-processors message-queue-library-name message-queue-msgsize_max PROT_READ PROT_WRITE MAP_SHARED MAP_FAILED O_RDONLY O_WRONLY O_RDWR O_CREAT O_EXCL S_IRUSR S_IWUSR SIGTERM) (import (vifne host linux) #;(vifne host freebsd)) )
false
92af656862e3830a7a9494b190fe092597603e96
d8bdd07d7fff442a028ca9edbb4d66660621442d
/scam/tests/20-scam/00-base/dictops.scm
8fd9fa095812cae9ccfb472ee31ea8214fb6d76f
[]
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
438
scm
dictops.scm
(import (test narc)) (narc-label "Dictionary Operations") (define aDict {}) (narc-expect ({ :key 22 } (begin (aDict :put :key 22) aDict)) ({ :key 22 fun "hello" } (begin (aDict :put fun "hello") aDict)) ({ :key -1.5 fun "hello" } (begin (aDict :put :key -1.5) aDict)) (-1.5 (aDict :get :key)) (1 (begin (aDict :remove :key) (aDict :length))) ({ fun "hello" } aDict)) (narc-report)
false
eb7cb227d9553f33c684fd14dbdf6b94adb1e0ff
b988c4dc2d52e30d7c915a0613d365697503e598
/te/conditions/common/test-utils.sld
84fc07067817e12c57748486c8e5c6caca4db044
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
ilammy/te
26ba60b9b0a85217623b920b8723bb753292b176
5d982b1abba0e1268fa58750c29012f2de6e043e
refs/heads/master
2021-01-13T01:54:42.842587
2014-09-08T19:07:43
2014-09-08T19:07:43
19,642,274
0
0
null
null
null
null
UTF-8
Scheme
false
false
848
sld
test-utils.sld
(define-library (te conditions common test-utils) (export assert-fails) (import (scheme base) (te conditions define-assertion) (te internal test-conditions)) (begin (define-assertion (assert-thunk-fails thunk) (let ((unique-object (list 'unique))) (guard (condition ((test-condition? condition) (if (eq? 'failed (condition-type condition)) (assert-success) (assert-failure "Invalid condition type") )) ((eq? unique-object condition) (assert-failure "Should not return") ) (else (assert-success)) ) (thunk) (raise unique-object) ) ) ) (define-syntax assert-fails (syntax-rules () ((_ form) (assert-thunk-fails (lambda () form))) ) ) ) )
true
ab3433c7d3e92089469d214f3d47287ae24eba18
0a0b1cdae21384ca702289c7b2b5a663ed2294f4
/s48-table.scm
7f0bd1195846c205222f62eab7b8dc6a4438be91
[ "BSD-2-Clause" ]
permissive
sharplispers/pseudoscheme
7cfbf63ce9e94d3f11ccc1c78e864800ed3fe233
239d9ee072a61c314af22a2678031472abe1e11a
refs/heads/master
2016-09-06T05:18:19.260992
2011-12-02T01:13:57
2011-12-02T01:13:57
2,895,386
18
5
null
null
null
null
UTF-8
Scheme
false
false
419
scm
s48-table.scm
; Scheme 48's table package, replicated for Pseudoscheme. ; Somewhat redundant with p-utils.scm. (define (make-table) (lisp:make-hash-table)) (define (table-ref table key) (let ((probe (lisp:gethash key table))) (lisp:if probe probe #f))) (define (table-set! table key val) (lisp:setf (lisp:gethash key table) val)) (define (table-walk proc table) (lisp:maphash proc table))
false
84b4087bbf9175137467577a1cf25fc8c04537be
7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107
/ex-3.7.scm
6878657708c95492e9fa863b85d6a345cc335bd7
[]
no_license
jiakai0419/sicp-1
75ec0c6c8fe39038d6f2f3c4c6dd647a39be6216
974391622443c07259ea13ec0c19b80ac04b2760
refs/heads/master
2021-01-12T02:48:12.327718
2017-01-11T12:54:38
2017-01-11T12:54:38
78,108,302
0
0
null
2017-01-05T11:44:44
2017-01-05T11:44:44
null
UTF-8
Scheme
false
false
2,387
scm
ex-3.7.scm
;;; Exercise 3.7. Consider the bank account objects created by make-account, ;;; with the password modification described in exercise 3.3. Suppose that our ;;; banking system requires the ability to make joint accounts. Define ;;; a procedure make-joint that accomplishes this. Make-joint should take three ;;; arguments. The first is a password-protected account. The second argument ;;; must match the password with which the account was defined in order for the ;;; make-joint operation to proceed. The third argument is a new password. ;;; Make-joint is to create an additional access to the original account using ;;; the new password. For example, if peter-acc is a bank account with password ;;; open-sesame, then ;;; ;;; (define paul-acc ;;; (make-joint peter-acc 'open-sesame 'rosebud)) ;;; ;;; will allow one to make transactions on peter-acc using the name paul-acc ;;; and the password rosebud. You may wish to modify your solution to exercise ;;; 3.3 to accommodate this new feature. (define (make-account balance the-password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch password m) (cond [(eq? m 'authorize) (eq? password the-password)] [(eq? password the-password) (cond [(eq? m 'withdraw) withdraw] [(eq? m 'deposit) deposit] [else (error "Unknown request -- MAKE-ACCOUNT" m)])] [else (lambda _ "Incorrect password")])) dispatch) (define (make-joint account old-password new-password) (define (dispatch password m) (if (eq? password new-password) (account old-password m) (lambda _ "Incorrect password"))) (if (account old-password 'authorize) dispatch (error "Incorrect password"))) (define peter-acc (make-account 100 'open-sesame)) (define paul-acc (make-joint peter-acc 'open-sesame 'rosebud)) (print ((peter-acc 'open-sesame 'withdraw) 10)) ;=> 90 (print ((paul-acc 'rosebud 'withdraw) 10)) ;=> 80 (print ((peter-acc 'open-sesame 'withdraw) 15)) ;=> 65 (print ((paul-acc 'rosebud 'withdraw) 10)) ;=> 55 (print ((peter-acc 'rosebud 'withdraw) 10)) ;=> Incorrect password (print ((paul-acc 'open-sesame 'withdraw) 10)) ;=> Incorrect password
false
592b31e626864d3d8ff3e5da18472dceada6125a
ef8d4cdebaa1851053dde4da280023eb2d3b5836
/src/main.scm
e84448b805becc73cc663ee01377a0212cb7e840
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
cadets/hypertrace-test
8447a2c89feec77820257c36ff2320ffe547af47
01f96af9eae36119c4905d84e0ca05482873290e
refs/heads/master
2023-07-14T20:09:01.985565
2021-08-29T19:08:25
2021-08-29T19:08:25
390,856,253
1
0
null
null
null
null
UTF-8
Scheme
false
false
8,033
scm
main.scm
(import scheme (chicken process-context) (chicken pathname) test args srfi-1 (hypertrace util) (hypertrace reporters)) (declare (uses hypertrace-util)) (declare (uses hypertrace-reporters)) (declare (uses hypertrace-test-runner)) (declare (uses hypertrace-test)) (declare (uses hypertrace-option-parser)) (declare (uses hypertrace-stager-loader)) ;; ;; Global variable only used for testing error reporting of the test framework ;; itself. ;; (define hypertrace-test-nonproc 'non-proc) ;; ;; Global variable describing the verbosity at which we will be reporting test ;; results and program actions to the user. ;; (define hypertrace-test-verbosity 0) ;; ;; Directory containing all of the necessary HyperTrace stagers and tests. ;; (define hypertrace-test-dir #f) ;; ;; Stager currently being processed. This variable can contain any information ;; in a stager that we wish to expose to consumers (e.g. macros or procedures). ;; Currently, it contains the directory path when loading stagers, and ;; the stager name when running tests. ;; (define current-stager #f) ;; ;; Write report to /tmp? Default: no. ;; (define hypertrace-test-tmp? #f) ;; ;; Default hypertrace report path. ;; (define hypertrace-report-path #f) ;; ;; Main entry point of the program. ;; (define (main args) ;; ;; If the user set HYPERTRACE_TESTPATH, we will use that. Otherwise, we set it ;; to a default value of /../libexec/hypertrace-test/tests/ assuming that both ;; the build path and the installed binary path will be in the correct ;; structure that our Makefile creates. ;; (with-environment-variable-if-not-f "HYPERTRACE_TESTPATH" (string-append (pathname-directory (executable-pathname)) "/../libexec/hypertrace-test/tests/") (set! hypertrace-test-dir (get-environment-variable "HYPERTRACE_TESTPATH"))) ;; Create a canonical path name. (set! hypertrace-test-dir (normalize-pathname hypertrace-test-dir)) (receive (options operands) (args:parse (args) hypertrace-options) ;; Default to verbosity 1 (print all of the tests as they get executed). (set! hypertrace-test-verbosity (or (alist-ref 'verbose options) 1)) (when (<= hypertrace-test-verbosity 0) (set! (current-test-verbosity) #f)) (when (and (> hypertrace-test-verbosity 0) (alist-ref 'bare options)) (print "Running tests in bare mode...")) (set! hypertrace-report-path (or (alist-ref 'report-path options) "hypertrace-test.report")) (set! hypertrace-test-tmp? (or (alist-ref 'use-tmpfs options) #f)) (let* ((report (alist-ref 'report options)) (report-path hypertrace-report-path)) (when report (with-loaded-contents report-path results (let* ((pass-and-fail (fold (lambda (result buckets) (let ((stager (vector-ref result 0)) (name (vector-ref result 1)) (p-or-f (vector-ref result 2)) (t (vector-ref result 3))) (case p-or-f ;; Prepend to pass list. ('pass `(,(cons `(,stager ,name ,t) (car buckets)) ,(cadr buckets))) ;; Prepend to fail list. ('fail `(,(car buckets) ,(cons `(,stager ,name ,t) (cadr buckets)))) ;; We hit some *really* weird case, so we just bail out ;; of the program all together with an exit code of 1. (else (begin (print "Expected 'pass' or 'fail', but got " p-or-f) (exit 1)))))) (list '() '() '()) results)) (pass (if (alist-ref 'only-failed options) '() (car pass-and-fail))) (fail (cadr pass-and-fail))) (cond ((equal? report "html") (report-html pass fail)) ((equal? report "json") (report-json pass fail)) ((equal? report "junit") (report-junit pass fail)) ((equal? report "text") (report-text pass fail ansi-support?))) (exit 0))))) (test-group "Field tests" (define test-test (mk-hypertrace-test '((name "Foo") (expected-out "Bar")))) (test "Foo" (hypertrace-test-name test-test)) (test "Bar" (hypertrace-test-expected-out test-test)) (test #f (hypertrace-test-in-file test-test)) (test 'default-cmp-method (hypertrace-test-cmp-method test-test)) (test 'default-run-method (hypertrace-test-run-method test-test))) (test-group "Unbound inputs" (test-error (mk-hypertrace-test '((unbound-symbol "FAIL")))) (test-error (mk-hypertrace-test '((name "foo") (unbound-symbol "FAIL")))) (test-error (mk-hypertrace-test '((unbound-symbol "FAIL") (name "foo"))))) (test-group "Non-symbols" (test-error (mk-hypertrace-test '(("string" "FAIL")))) (test-error (mk-hypertrace-test '((name "foo") ("string" "FAIL")))) (test-error (mk-hypertrace-test '(("string" "FAIL") (name "foo"))))) (test-group "Non-procedures" (test-error (mk-hypertrace-test '((nonproc "FAIL")))) (test-error (mk-hypertrace-test '((name "foo") (nonproc "FAIL")))) (test-error (mk-hypertrace-test '((nonproc "FAIL") (name "foo"))))) (bare-run-test (mk-hypertrace-test '((name "Bare-run test")))) (test-group "Stager fields" (define test-stager (mk-hypertrace-stager '((name "Foo") (tests (1 2 3)) (directory-path "Bar")))) (test "Foo" (hypertrace-stager-name test-stager)) (test '(1 2 3) (hypertrace-stager-tests test-stager)) (test "Bar" (hypertrace-stager-directory-path test-stager))) (when (not (alist-ref 'no-stagers options)) (let ((stagers (load-stagers hypertrace-test-dir))) (for-each (lambda (stager) (stage-tests stager)) stagers) (let* ((runner (if (alist-ref 'bare options) bare-run-test run-test)) (result (flatten (fold (lambda (stager result) (cons* (stager-run stager runner) result)) '() stagers))) (report-file (if hypertrace-test-tmp? "/tmp/hypertrace-test.report" "hypertrace-test.report"))) ;; Print a newline after we're done with all the stagers. (display "\n") (call-with-output-file report-file (lambda (port) (write result port) (when (>= hypertrace-test-verbosity 2) (print "Written report to " report-file))) #:binary)))))) (main command-line-arguments)
false
0f73cc053934948c3a1e28a10de39e3e8c4ee3a2
33ddda5f7a742807cbdc6c6114e0d93e5f272f18
/echo.scm
a943c6ddc751bcd1df16d267aecd10d133b9ad49
[ "MIT" ]
permissive
k16shikano/Gauche-XMPP
fd252df2c147e3eac7982ec9a7c0f60c6ca4a533
5b2558e3b09fba07d4344c9a504f66c14e0687ad
refs/heads/master
2020-04-07T23:17:10.003480
2009-07-31T03:54:30
2009-07-31T03:54:30
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
783
scm
echo.scm
#!/usr/bin/env gosh (use sxml.sxpath) (use rfc.xmpp) (define-constant hostname "localhost") (define-constant yourname "romeo") (define-constant yourpass "romeo") (define-constant yourresource "Home") (define (parse-message sxml) (and-let* ((from ((if-car-sxpath '(jabber:client:message @ from *text*)) sxml)) (body ((if-car-sxpath '(jabber:client:message jabber:client:body *text*)) sxml))) (cons from body))) (define (main args) (call-with-xmpp-connection hostname (lambda (c) (xmpp-auth c yourname yourpass) (xmpp-bind c yourresource) (xmpp-session c) (xmpp-presence c) (while #t (and-let* ((m (parse-message (xmpp-receive-stanza c)))) (xmpp-message (c :to (car m)) (cdr m)))))))
false
523220442af1a003743beae091bb747935279d1e
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/dbnull.sls
ad965b5e48b61a28cea284a5686b54e2f0dc3441
[]
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
756
sls
dbnull.sls
(library (system dbnull) (export is? dbnull? get-object-data get-type-code to-string value) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.DBNull a)) (define (dbnull? a) (clr-is System.DBNull a)) (define-method-port get-object-data System.DBNull GetObjectData (System.Void System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port get-type-code System.DBNull GetTypeCode (System.TypeCode)) (define-method-port to-string System.DBNull ToString (System.String System.IFormatProvider) (System.String)) (define-field-port value #f #f (static:) System.DBNull Value System.DBNull))
false
01c0f7be197f18a77517c6f0836b39cd8852b2d5
db66297c51268dbfc5323febc7d074e6b7371d8e
/sound.ss
31daa7de23b25d1ad0df20b7c8c3e6f3ff61e258
[]
no_license
kazzmir/racket-allegro-4
d7431f9af45833aa9a6a47a69b81fc116e7c0069
d4f7949ed09027512a5234ee0ea6a86214cd874d
refs/heads/master
2021-01-01T19:52:39.329611
2012-04-27T22:39:34
2012-04-27T22:39:34
4,163,202
1
0
null
null
null
null
UTF-8
Scheme
false
false
713
ss
sound.ss
(module sound mzscheme (require (lib "foreign.ss")) (unsafe!) (require (prefix a: "private/allegro.ss")) (provide (rename a:load-sample load-sound) (rename a:destroy-sample destroy-sound) (rename a:stop-sample stop-sound)) (define (play-sound-internal loop) (letrec ((fun (case-lambda ((sound) (fun sound 255)) ((sound volume) (fun sound volume 128)) ((sound volume pan) (fun sound volume pan 1000)) ((sound volume pan frequency) (a:play-sample sound volume pan frequency loop))))) fun)) (provide play-sound-looped play-sound) (define play-sound-looped (play-sound-internal 1)) (define play-sound (play-sound-internal 0)) )
false
854b9ca9a1e6c5196ab434113cbf6d66d9dbbe56
2e50e13dddf57917018ab042f3410a4256b02dcf
/contrib/30.optional/t/test.scm
5ac0b45c485180afefc2a199b6067d0611b50982
[ "MIT" ]
permissive
koba-e964/picrin
c0ca2596b98a96bcad4da9ec77cf52ce04870482
0f17caae6c112de763f4e18c0aebaa73a958d4f6
refs/heads/master
2021-01-22T12:44:29.137052
2016-07-10T16:12:36
2016-07-10T16:12:36
17,021,900
0
0
MIT
2019-05-17T03:46:41
2014-02-20T13:55:33
Scheme
UTF-8
Scheme
false
false
554
scm
test.scm
(import (scheme base) (picrin optional) (picrin test)) (test 0 (optional '() 0)) (test 1 (optional '(1) 0)) (test '(0 0) (let-optionals* '() ((a 0) (b 0)) (list a b))) (test '(1 0) (let-optionals* '(1) ((a 0) (b 0)) (list a b))) (test '(1 2) (let-optionals* '(1 2) ((a 0) (b 0)) (list a b))) (test '(1 1) (let-optionals* '(1) ((a 0) (b a)) (list a b))) (test '(0 ()) (let-optionals* '() ((a 0) . r) (list a r))) (test '(1 ()) (let-optionals* '(1) ((a 0) . r) (list a r))) (test '(1 (2)) (let-optionals* '(1 2) ((a 0) . r) (list a r)))
false
b6b26f3af7f2838b5cfea10fb1b40ffb2417fab4
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/cs61a/course/library/localmr.scm
15ef1f77cd8ed67420ca82b234672c7fb503189c
[]
no_license
Phantas0s/playground
a362653a8feb7acd68a7637334068cde0fe9d32e
c84ec0410a43c84a63dc5093e1c214a0f102edae
refs/heads/master
2022-05-09T06:33:25.625750
2022-04-19T14:57:28
2022-04-19T14:57:28
136,804,123
19
5
null
2021-03-04T14:21:07
2018-06-10T11:46:19
Racket
UTF-8
Scheme
false
false
3,193
scm
localmr.scm
#| Three steps of map reduce: 1. apply mapper to each kv pair in input.. 2. sort them into buckets (sort-into-buckets) 3. run a reduce on each bucket (groupreduce) This version internally operates on association lists, and converts to and from stream as necesary to match the real mapreduce. NOTE: use this file for testing locally to weed out trivial errors. You will not be able to answer parallelization questions just by using this code. USAGE: (lmapreduce <mapper> <reducer> <base-case> <input>) <input> is either a stream of key-value pairs, or: "/sample-emails" - a bunch of emails keyed by a single key, sample-emails "/beatles-songs" - beatles song titles keyed by album These are NOT the same as what the real mapreduce uses (obviously, much smaller) |# ;; kv-pair abstraction (define make-kv-pair cons) (define kv-key car) (define kv-value cdr) ;; Load data (load "~cs61a/lib/localmr-beatles.scm") (load "~cs61a/lib/localmr-emails.scm") ;; lmapreduce is like mapreduce, but local. So far can only handle input: ; 1. /sample-emails very small email sample (see small reader for format) ; 2. /beatles-songs beatles song titles keyed by album ; 3. a stream of key-value pairs (define (lmapreduce mapper reducer base-case input) (cond ((equal? input "/beatles-songs") (local-map-reduce mapper reducer base-case beatles-songs)) ((equal? input "/sample-emails") (local-map-reduce mapper reducer base-case sample-emails)) (else (local-map-reduce mapper reducer base-case (stream->list input))))) ;; input to mapreduce is a STREAM of key-value pairs. ;; internally uses lists, and converts back to stream at the end. (define (local-map-reduce mapper reducer base-case input) (list->stream (groupreduce (sort-into-buckets (flatmap mapper input)) reducer base-case))) ; Bucket ADT ; a bucket looks like ( key . <values>) (define (make-bucket key) (list key)) (define (bucket-key bucket) (car bucket)) (define (add-to-bucket! bucket value) (set-cdr! bucket (cons value (cdr bucket)))) ;; not in any order whatsoever.. just go through all of them, and ;; put them into buckets. ;; returns a LIST of BUCKETS sorted by key ;; if both keys are numbers, it will use <= as ;; a comparator, otherwise it will use string<=? (define (sort-into-buckets kv-pairs) (let ((buckets nil)) ;; a list of buckets (for-each (lambda (kvp) (let ((bucket (assoc (kv-key kvp) buckets))) (if bucket (add-to-bucket! bucket (kv-value kvp)) (let ((new-bucket (make-bucket (kv-key kvp)))) (add-to-bucket! new-bucket (kv-value kvp)) (set! buckets (cons new-bucket buckets)))))) kv-pairs) (sort buckets (lambda (b1 b2) (let ((k1 (bucket-key b1)) (k2 (bucket-key b2))) (if (and (number? k1) (number? k2)) (<= k1 k2) (string<=? (word->string k1) (word->string k2))))) ))) ;; accumulates for every bucket (define (groupreduce buckets reducer base-case) (map (lambda (kvp) (cons (kv-key kvp) (accumulate reducer base-case (kv-value kvp)))) buckets)) ;; for finite streams (define (stream->list S) (if (stream-null? S) nil (cons (stream-car S) (stream->list (stream-cdr S)))))
false
f81a3624a34b80193a1f2b8a9776feccaaccd98c
894c73f545af0ae7c4ff8e1689fb06ced2ce5d9e
/make-boot-file.ss
b20b4b4d5c6cbd715daa9114c1a8c47d1e6feec3
[ "0BSD" ]
permissive
t-triobox/chez-exe
5300fb0d3d883892e6fa28518b8b62b978cbf3d0
25f52a8137331f3a65c16b40e260b8f72dfe45ef
refs/heads/master
2022-12-12T08:27:07.141428
2020-08-13T03:52:52
2020-08-13T03:52:52
254,805,397
0
0
NOASSERTION
2020-08-13T03:52:53
2020-04-11T06:14:18
null
UTF-8
Scheme
false
false
153
ss
make-boot-file.ss
(define output-file (car (command-line-arguments))) (define bootfiles (cdr (command-line-arguments))) (apply make-boot-file output-file '() bootfiles)
false
c34460230e2c450f14b0700a51b34ba8e23588de
e565c8e8d16935673647ecfbb7f1c674a260cb00
/lib/chibi/optional-test.sld
1755831e3dc10e5144fa5191ff9db801a10206f3
[ "BSD-3-Clause" ]
permissive
tomelam/chibi-scheme
2997c9d53e2166ebf485934696b1661c37c19f9c
6f28159667212fffc9df4383dc773ea129f106d0
refs/heads/master
2020-12-01T19:05:39.952425
2019-12-28T14:48:44
2019-12-28T14:48:44
230,738,272
1
0
NOASSERTION
2019-12-29T11:03:00
2019-12-29T11:02:59
null
UTF-8
Scheme
false
false
1,081
sld
optional-test.sld
(define-library (chibi optional-test) (import (scheme base) (chibi optional) (chibi test)) (export run-tests) (begin (define (run-tests) (test-begin "optional") (test '(0 11 12) (let-optionals '(0) ((a 10) (b 11) (c 12)) (list a b c))) (test '(0 11 12) ((opt-lambda ((a 10) (b 11) (c 12)) (list a b c)) 0)) (test '(0 11 12) ((opt-lambda (a (b 11) (c 12)) (list a b c)) 0)) (test '(0 1 (2 3 4)) (let-optionals* '(0 1 2 3 4) ((a 10) (b 11) . c) (list a b c))) (test '(0 1 (2 3 4)) (let-optionals '(0 1 2 3 4) ((a 10) (b 11) . c) (list a b c))) (test-error '(0 11 12) ((opt-lambda (a (b 11) (c 12)) (list a b c)))) (let () (define-opt (f a (b 11) (c 12)) (list a b c)) (test-error (f)) (test '(0 11 12) (f 0)) (test '(0 1 12) (f 0 1)) (test '(0 1 2) (f 0 1 2)) (test '(0 1 2) (f 0 1 2 3))) (test-end))))
false
d85023357a8f5b8735776163be50fe3675745a5e
dd4cc30a2e4368c0d350ced7218295819e102fba
/vendored_parsers/vendor/tree-sitter-javascript/queries/injections.scm
5539241a68d835cb13ae407f9d67c28fe252304b
[ "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
523
scm
injections.scm
; Parse the contents of tagged template literals using ; a language inferred from the tag. (call_expression function: [ (identifier) @injection.language (member_expression property: (property_identifier) @injection.language) ] arguments: (template_string) @injection.content) ; Parse regex syntax within regex literals ((regex_pattern) @injection.content (#set! injection.language "regex")) ; Parse JSDoc annotations in comments ((comment) @injection.content (#set! injection.language "jsdoc"))
false
c1c5c9e9befd888211fd95a75367916391369367
33e6648cbbd57bd24ef9acb2709277595a5836e7
/scm/scratch.scm
5d53c18f7428bad42558a1ad38c3562d258b282c
[]
no_license
OurDeadSea/deep-learning
e00c3ceb3efd41530643d7d7c2ce1e8eeb9c3313
b254d9bae87a7ada61e9d441ebb888ac7b52a742
refs/heads/master
2021-01-19T18:28:15.378968
2017-08-24T15:16:07
2017-08-24T15:16:07
101,137,406
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,640
scm
scratch.scm
;; Trivial (define null '()) ;; HOF (define (reduce op nil seq) (if (null? seq) nil (op (car seq) (reduce op nil (cdr seq))))) (define (fold op nil seq) (let recur ((acc nil) (seq seq)) (if (null? seq) acc (recur (op acc (car seq)) (cdr seq))))) (define (any pred seq) (fold (lambda (acc x) (or acc (pred x))) #f seq)) (define (every pred seq) (fold (lambda (acc x) (and acc (pred x))) #t seq)) ;; Cantrips (define (identity x) x) (define (always x) (lambda args x)) (define (project n) (lambda args (list-ref args n))) (define (complement pred) (lambda args (not (apply pred args)))) (define (disjoin . preds) (lambda args (fold (lambda (acc pred) (or acc (apply pred args))) #f preds))) (define (conjoin . preds) (lambda args (fold (lambda (acc pred) (and acc (apply pred args))) #t preds))) (define (compose . procs) (lambda (val) (reduce (lambda (proc acc) (proc acc)) val procs))) (define true (always #t)) (define false (always #f)) (define (take seq n) (if (or (zero? n) (null? seq)) null (cons (car seq) (take (cdr seq) (- n 1))))) (define (drop seq n) (if (or (zero? n) (null? seq)) seq (drop (cdr seq) (- n 1)))) ;; Macrology (define-syntax ignore (syntax-rules () ((ignore forms ...) (void)))) (ignore (put 'ignore 'scheme-indent-function 0)) (define-syntax pipe (syntax-rules () ((pipe in) in) ((pipe in (f args ...) fs ...) (pipe (f in args ...) fs ...)) ((pipe in f fs ...) (pipe (f in) fs ...)))) (define-syntax pipe* (syntax-rules () ((pipe* in) in) ((pipe* in (f args ...) fs ...) (pipe* (f args ... in) fs ...)) ((pipe* in f fs ...) (pipe* (f in) fs ...)))) (define-syntax let-if (syntax-rules () ((let-if (name expr pred) consequent alternative) (let ((name expr)) (if (pred name) consequent alternative))) ((let-if (name expr) consequent alternative) (let-if (name expr identity) consequent alternative)))) (ignore (put 'let-if 'scheme-indent-function 1)) (define-syntax receive (syntax-rules () ((receive formals expression body ...) (call-with-values (lambda () expression) (lambda formals body ...))))) (ignore (put 'receive 'scheme-indent-function 2)) ;; Predicates (define (list-of pred xs) (every pred xs))
true
ecb8967bc42995b852313dffb16724aaa366c59a
d3e9eecbf7fa7e015ab8b9c357882763bf6d6556
/solutions/projects/project5/code.ss
39b284c606cabbb04b5e349f43b6516d03bd1abd
[]
no_license
yangchenyun/learning-sicp
37d43f18836055274f78755ff93eb20fba63d383
99a19a06eddc282e0eb364536e297f27c32a9145
refs/heads/master
2021-01-19T02:15:15.634140
2017-02-13T22:26:58
2017-02-13T22:26:58
5,344,488
17
3
null
null
null
null
UTF-8
Scheme
false
false
19,778
ss
code.ss
#lang racket ;; ;; eval.scm - 6.037 ;; (require r5rs) (define first car) (define second cadr) (define third caddr) (define fourth cadddr) (define rest cdr) ;; Tell DrRacket to print mutable pairs using the compact syntax for ;; ordinary pairs. (print-as-expression #f) (print-mpair-curly-braces #f) ;; mutable cons cell version of mmap (define (mmap f lst) (if (null? lst) '() (cons (f (car lst)) (mmap f (cdr lst))))) (define (tagged-list? exp tag) (and (pair? exp) (eq? (car exp) tag))) (define (self-evaluating? exp) (or (number? exp) (string? exp) (boolean? exp))) (define (quoted? exp) (tagged-list? exp 'quote)) (define (text-of-quotation exp) (cadr exp)) (define (variable? exp) (symbol? exp)) (define (assignment? exp) (tagged-list? exp 'set!)) (define (assignment-variable exp) (cadr exp)) (define (assignment-value exp) (caddr exp)) (define (make-assignment var expr) (list 'set! var expr)) (define (unassignment? exp) (tagged-list? exp 'unset!)) (define (unassignment-variable exp) (cadr exp)) (define (make-unassignment var) (list 'unset! var)) (define (definition? exp) (tagged-list? exp 'define)) (define (definition-variable exp) (if (symbol? (cadr exp)) (cadr exp) (caadr exp))) (define (definition-value exp) (if (symbol? (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) ; formal params, body (define (make-define var expr) (list 'define var expr)) (define (lambda? exp) (tagged-list? exp 'lambda)) (define (lambda-parameters lambda-exp) (cadr lambda-exp)) (define (lambda-body lambda-exp) (cddr lambda-exp)) (define (make-lambda parms body) (cons 'lambda (cons parms body))) (define (if? exp) (tagged-list? exp 'if)) (define (if-predicate exp) (cadr exp)) (define (if-consequent exp) (caddr exp)) (define (if-alternative exp) (cadddr exp)) (define (make-if pred conseq alt) (list 'if pred conseq alt)) (define (cond? exp) (tagged-list? exp 'cond)) (define (cond-clauses exp) (cdr exp)) (define first-cond-clause car) (define rest-cond-clauses cdr) (define (make-cond seq) (cons 'cond seq)) (define (let? expr) (tagged-list? expr 'let)) (define (let-bound-variables expr) (mmap first (second expr))) (define (let-values expr) (mmap second (second expr))) (define (let-body expr) (cddr expr)) ;differs from lecture--body may be a sequence (define (make-let bindings body) (cons 'let (cons bindings body))) (define (begin? exp) (tagged-list? exp 'begin)) (define (begin-actions begin-exp) (cdr begin-exp)) (define (last-exp? seq) (null? (cdr seq))) (define (first-exp seq) (car seq)) (define (rest-exps seq) (cdr seq)) (define (sequence->exp seq) (cond ((null? seq) seq) ((last-exp? seq) (first-exp seq)) (else (make-begin seq)))) (define (make-begin exp) (cons 'begin exp)) (define (application? exp) (pair? exp)) (define (operator app) (car app)) (define (operands app) (cdr app)) (define (no-operands? args) (null? args)) (define (first-operand args) (car args)) (define (rest-operands args) (cdr args)) (define (make-application rator rands) (cons rator rands)) (define (and? expr) (tagged-list? expr 'and)) (define and-exprs cdr) (define (make-and exprs) (cons 'and exprs)) (define (or? expr) (tagged-list? expr 'or)) (define or-exprs cdr) (define (make-or exprs) (cons 'or exprs)) (define (time? exp) (tagged-list? exp 'time)) ;; ;; this section is the actual implementation of meval ;; (define (m-eval exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((unassignment? exp) (eval-unassignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (m-eval (cond->if exp) env)) ((let? exp) (m-eval (let->application exp) env)) ((and? exp) (m-eval (and->if exp) env)) ((or? exp) (m-eval (or->if exp) env)) ((time? exp) (time (m-eval (second exp) env))) ((application? exp) (m-apply (m-eval (operator exp) env) (list-of-values (operands exp) env))) (else (error "Unknown expression type -- EVAL" exp)))) (define (m-apply procedure arguments) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (make-frame (procedure-parameters procedure) arguments) (procedure-environment procedure)))) (else (error "Unknown procedure type -- APPLY" procedure)))) (define (list-of-values exps env) (cond ((no-operands? exps) '()) (else (cons (m-eval (first-operand exps) env) (list-of-values (rest-operands exps) env))))) (define (eval-if exp env) (if (m-eval (if-predicate exp) env) (m-eval (if-consequent exp) env) (m-eval (if-alternative exp) env))) (define (eval-sequence exps env) (cond ((last-exp? exps) (m-eval (first-exp exps) env)) (else (m-eval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (define (eval-assignment exp env) (set-variable-value! (assignment-variable exp) (m-eval (assignment-value exp) env) env)) (define (eval-unassignment exp env) (unset-variable! (unassignment-variable exp) env)) (define (eval-definition exp env) (define-variable! (definition-variable exp) (m-eval (definition-value exp) env) env)) (define (let->application expr) (let ((names (let-bound-variables expr)) (values (let-values expr)) (body (let-body expr))) (make-application (make-lambda names body) values))) (define (cond->if expr) (let ((clauses (cond-clauses expr))) (if (null? clauses) #f (if (eq? (car (first-cond-clause clauses)) 'else) (sequence->exp (cdr (first-cond-clause clauses))) (make-if (car (first-cond-clause clauses)) (sequence->exp (cdr (first-cond-clause clauses))) (make-cond (rest-cond-clauses clauses))))))) (define (and->if expr) (define (expand-clauses clauses) (cond ((null? clauses) 'true) ((last-exp? clauses) (make-if (first-exp clauses) (first-exp clauses) 'false)) (else (let ((first (car clauses)) (rest (cdr clauses))) (make-if first (expand-clauses rest) 'false))))) (expand-clauses (and-exprs expr))) (define (or->if expr) (define (expand-clauses clauses) (if (null? clauses) 'false (let ((first (car clauses)) (rest (cdr clauses))) (make-let (list (cons '_result first)) (list (make-if '_result '_result (expand-clauses rest))))))) (expand-clauses (or-exprs expr))) (define input-prompt ";;; M-Eval input level ") (define output-prompt ";;; M-Eval value:") (define (driver-loop) (repl #f)) (define (repl port) (if port #f (prompt-for-input input-prompt)) (let ((input (if port (read port) (read)))) (cond ((eof-object? input) 'meval-done) ((eq? input '**quit**) 'meval-done) (else (let ((output (m-eval input the-global-environment))) (if port #f (begin (announce-output output-prompt) (pretty-display output))) (repl port)))))) (define (prompt-for-input string) (newline) (newline) (display string) (display meval-depth) (newline)) (define (announce-output string) (newline) (display string) (newline)) ;; ;; ;; implementation of meval environment model ;; ; double bubbles (define (make-procedure parameters body env) (list 'procedure parameters body env)) (define (compound-procedure? proc) (tagged-list? proc 'procedure)) (define (procedure-parameters proc) (second proc)) (define (procedure-body proc) (third proc)) (define (procedure-environment proc) (fourth proc)) ; bindings (define (make-binding var val) (list 'binding var (list val))) (define (binding? b) (tagged-list? b 'binding)) (define last-binding-value car) (define rest-binding-values cdr) (define (binding-value-list binding) (if (binding? binding) (third binding) (error "Not a binding: " binding))) (define (binding-variable binding) (if (binding? binding) (second binding) (error "Not a binding: " binding))) (define (binding-value binding) (last-binding-value (binding-value-list binding))) (define (set-binding-value! binding val) (if (binding? binding) (set-car! (cddr binding) (cons val (binding-value-list binding))) (error "Not a binding: " binding))) (define (unset-binding-value! binding) (if (binding? binding) (let ((rest-value-list (rest-binding-values (binding-value-list binding)))) (if (null? rest-value-list) (void) (set-car! (cddr binding) rest-value-list))) (error "Not a binding: " binding))) ; frames (define (make-frame variables values) (define (make-frame-bindings rest-vars rest-vals) (cond ((and (null? rest-vars) (null? rest-vals)) '()) ((null? rest-vars) (error "Too many args supplied" variables values)) ((symbol? rest-vars) (list (make-binding rest-vars rest-vals))) ((null? rest-vals) (error "Too few args supplied" variables values)) (else (cons (make-binding (car rest-vars) (car rest-vals)) (make-frame-bindings (cdr rest-vars) (cdr rest-vals)))))) (make-frame-from-bindings (make-frame-bindings variables values))) (define (make-frame-from-bindings list-of-bindings) (cons 'frame list-of-bindings)) (define (frame? frame) (tagged-list? frame 'frame)) (define (frame-variables frame) (if (frame? frame) (mmap binding-variable (cdr frame)) (error "Not a frame: " frame))) (define (frame-values frame) (if (frame? frame) (mmap binding-value (cdr frame)) (error "Not a frame: " frame))) (define (add-binding-to-frame! binding frame) (if (frame? frame) (if (binding? binding) (set-cdr! frame (cons binding (cdr frame))) (error "Not a binding: " binding)) (error "Not a frame: " frame))) (define (find-in-frame var frame) (define (search-helper var bindings) (if (null? bindings) #f (if (eq? var (binding-variable (first bindings))) (first bindings) (search-helper var (rest bindings))))) (if (frame? frame) (search-helper var (cdr frame)) (error "Not a frame: " frame))) ; environments (define the-empty-environment '(environment)) (define (extend-environment frame base-env) (if (environment? base-env) (if (frame? frame) (list 'environment frame base-env) (error "Not a frame: " frame)) (error "Not an environment: " base-env))) (define (environment? env) (tagged-list? env 'environment)) (define (enclosing-environment env) (if (environment? env) (if (eq? the-empty-environment env) (error "No enclosing environment of the empty environment") (third env)) (error "Not an environment: " env))) (define (environment-first-frame env) (if (environment? env) (second env) (error "Not an environment: " env))) (define (find-in-environment var env) (if (eq? env the-empty-environment) #f (let ((frame (environment-first-frame env))) (let ((binding (find-in-frame var frame))) (if binding binding (find-in-environment var (enclosing-environment env))))))) ; name rule (define (lookup-variable-value var env) (let ((binding (find-in-environment var env))) (if binding (binding-value binding) (error "Unbound variable -- LOOKUP" var)))) (define (set-variable-value! var val env) (let ((binding (find-in-environment var env))) (if binding (set-binding-value! binding val) (error "Unbound variable -- SET" var)))) (define (define-variable! var val env) (let ((frame (environment-first-frame env))) (let ((binding (find-in-frame var frame))) (if binding (set-binding-value! binding val) (add-binding-to-frame! (make-binding var val) frame))))) (define (unset-variable! var env) (let ((binding (find-in-environment var env))) (if binding (unset-binding-value! binding) (error "Unbound variable -- UNSET!" var)))) ; primitives procedures - hooks to underlying Scheme procs (define (make-primitive-procedure implementation) (list 'primitive implementation)) (define (primitive-procedure? proc) (tagged-list? proc 'primitive)) (define (primitive-implementation proc) (cadr proc)) (define (primitive-procedures) (list (list 'car car) (list 'cdr cdr) (list 'cadr cadr) (list 'caddr caddr) (list 'cadddr cadddr) (list 'list list) (list 'cons cons) (list 'set-car! set-car!) (list 'set-cdr! set-cdr!) (list 'null? null?) (list '+ +) (list '- -) (list '< <) (list '> >) (list '= =) (list 'display display) (list 'not not) (list 'true true) (list 'false false) (list 'eq? eq?) (list 'pair? pair?) (list 'newline newline) (list 'number? number?) (list 'string? string?) (list 'boolean? boolean?) ; ... more primitives )) (define (primitive-procedure-names) (mmap car (primitive-procedures))) (define (primitive-procedure-objects) (mmap make-primitive-procedure (mmap cadr (primitive-procedures)))) (define (apply-primitive-procedure proc args) (apply (primitive-implementation proc) args)) ; used to initialize the environment (define (setup-environment) (extend-environment (make-frame (primitive-procedure-names) (primitive-procedure-objects)) the-empty-environment)) (define the-global-environment (setup-environment)) (define (refresh-global-environment) (set! the-global-environment (setup-environment)) 'done) ;;;;;;;; Code for implementing unset! ;; change a binding to a pair of var and a list of vals ;; related changes on the binding data structure ;; (define (make-binding var val) ;; (list 'binding var (list val))) ;; (define last-binding-value car) ;; (define rest-binding-values cdr) ;; (define (binding-value-list binding) ;; (if (binding? binding) ;; (third binding) ;; (error "Not a binding: " binding))) ;; (define (binding-value binding) ;; (last-binding-value (binding-value-list binding))) ;; (define (set-binding-value! binding val) ;; (if (binding? binding) ;; (set-car! (cddr binding) ;; (cons val (binding-value-list binding))) ;; (error "Not a binding: " binding))) ;; (define (unset-binding-value! binding val) ;; (if (binding? binding) ;; (let ((rest-value-list (rest-binding-values (binding-value-list binding)))) ;; (if (null? rest-value-list) ;; (void) ;; (set-car! (cddr binding) rest-value-list))) ;; (error "Not a binding: " binding))) ;; ;; environment operations ;; (define (unset-variable! var env) ;; (let ((binding (find-in-environment var env))) ;; (if binding ;; (unset-binding-value! binding) ;; (error "Unbound variable -- UNSET!" var)))) ;; ;; syntaxes ;; (define (unassignment? exp) (tagged-list? exp 'unset!)) ;; (define (unassignment-variable exp) (cadr exp)) ;; (define (make-unassignment var) ;; (list 'unset! var)) ;; ;; eval rules ;; (define (eval-unassignment exp env) ;; (unset-variable! (unassignment-variable exp) ;; env)) ;;;;;;;; Making environments first-class ;; 1. add 'procedure-env and 'current-env to build-in primitives ;; 2. define the env-variables and env-parent, env-value procedures ;; and declare them in primitives ;; 3. use the `box' to wrap the environment data structure (define (env-variables env) (let ((frame (environment-first-frame env))) (frame-variables frame))) (define environment-primitives (list (list 'procedure-env (lambda (proc) (box (procedure-environment proc)))) (list 'current-env (lambda () (box the-global-environment))) (list 'env-variables (lambda (env) (env-variables (unbox env)))) (list 'env-parent (lambda (env) (enclosing-environment (unbox env)))) (list 'env-value (lambda (var env) (find-in-environment var (unbox env)))))) (define environment-names (mmap first environment-primitives)) (define environment-values (mmap make-primitive-procedure (mmap second environment-primitives))) (set! the-global-environment (extend-environment (make-frame environment-names environment-values) the-global-environment)) ;;;;;;;; Code necessary for question 6 ;; ;; This section doesn't contain any user-servicable parts -- you ;; shouldn't need to edit it for any of the questions on the project, ;; including question 5. However, if you're curious, comments provide a ;; rough outline of what it does. ;; Keep track of what depth we are into nesting ;; These procedures are needed to make it possible to run inside meval (define additional-primitives (list (list 'eof-object? eof-object?) (list 'read read) (list 'read-line read-line) (list 'open-input-file open-input-file) (list 'this-expression-file-name (lambda () (this-expression-file-name))) (list 'pretty-display pretty-display) (list 'error error) (list 'apply m-apply))) ;; <-- This line is somewhat interesting (define stubs '(require r5rs mzlib/etc print-as-expression print-mpair-curly-braces)) (define additional-names (mmap first additional-primitives)) (define additional-values (mmap make-primitive-procedure (mmap second additional-primitives))) (define meval-depth 1) (require mzlib/etc) (define (load-meval-defs) ;; Jam some additional bootstrapping structures into the global ;; environment (set! the-global-environment (extend-environment (make-frame stubs (mmap (lambda (name) (m-eval '(lambda (x) x) the-global-environment)) stubs)) (extend-environment (make-frame additional-names additional-values) the-global-environment))) ;; Open this file for reading (let ((stream (open-input-file (this-expression-file-name)))) (read-line stream) ;; strip off "#lang racket" line (repl stream) ;; feed the rest of the definitions into meval ;; Update the meval-depth variable inside the environment we're simulating (set-variable-value! 'meval-depth (+ meval-depth 1) the-global-environment) 'loaded)) ;; just keep adding primitives used in this file
false
a90c5110d812d54657224e6a13e7c303b1135aca
16807220b95bf9a559b97ec0de16665ff31823cb
/mission/tests/bins.scm
0edfc9086d75ba65ac62a2e93b7644924e0d17d5
[ "BSD-3-Clause" ]
permissive
cuauv/software
7263df296e01710cb414d340d8807d773c3d8e23
5ad4d52d603f81a7f254f365d9b0fe636d03a260
refs/heads/master
2021-12-22T07:54:02.002091
2021-11-18T01:26:12
2021-11-18T02:37:55
46,245,987
76
34
null
2016-08-03T05:31:00
2015-11-16T02:02:36
C++
UTF-8
Scheme
false
false
887
scm
bins.scm
(include "peacock-prelude") (peacock "Bins Test" (setup (define sub-initial-pos #(0 0 1.5)) (vehicle-set! x: sub-initial-pos q: (hpr->quat #(/ (* 3 pi) 2) 0 0) ) (>>= (after 120) (lambda (_) (fail "Timed out."))) (camera down q: (hpr->quat (vector 0 (- (/ pi 2)) 0)) w: 1024 h: 768 f: 440) (camera forward q: (hpr->quat (vector 0 0 0)) w: 1020 h: 1020 f: 440) (goals markers-in-bin ) (shape down >> covered-bin (bin1.p-set! bin1.x-set! bin1.y-set!) x: #(2 -0.5 0) r: 0.08) (shape down >> uncovered-bin (bin2.p-set! bin2.x-set! bin2.y-set!) x: #(2 0.5 0) r: 0.08) ) (mission module: "bins" task: "BinsTask") (mission module: "bins" task: "BinsTask") (options debug: #f) )
false
794da2dac7eb2d5b20c96df92fcdae7743587677
ece1c4300b543df96cd22f63f55c09143989549c
/Chapter3/Exercise3.47.scm
ae1ba085c1d0d4bef629e347a937908ad6ccd4fc
[]
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
2,182
scm
Exercise3.47.scm
; Exercise 3.47: A semaphore (of size nn) is a generalization of a mutex. Like a mutex, a semaphore supports acquire and release operations, but it is more general in that up to nn processes can acquire it concurrently. Additional processes that attempt to acquire the semaphore must wait for release operations. Give implementations of semaphores ; in terms of mutexes ; in terms of atomic test-and-set! operations. #lang racket (require sicp) (require "git/SICP/Chapter3/parallel-execute.scm") (define (make-mutex-semaphore n) (let ((lock-numbers n) (the-mutex (make-mutex))) (define (the-semaphore m) (cond ((eq? m 'acquire) (begin (the-mutex 'acquire) (if (> lock-numbers 0) (begin (set! lock-numbers (- lock-numbers 1)) (the-mutex 'release)) (the-semaphore 'acquire)))) ((eq? m 'release) (begin (the-mutex 'acquire) (if (>= lock-numbers n) (error "no semaphore to be release") (set! lock-numbers (+ lock-numbers 1))) (the-mutex 'release))))) the-semaphore)) (define (test-and-set! cell) (if (car cell) true (begin (set-car! cell true) false))) (define (make-test-semaphore n) (let ((lock-numbers n) (cell (list false))) (define (the-semaphore m) (cond ((eq? m 'acquire) (if (and (> lock-numbers 0) (test-and-set! cell)) (begin (set! lock-numbers (- lock-numbers 1)) (set-car! cell false)) (the-semaphore 'acquire))) ((eq? m 'release) (if (and (>= lock-numbers n) (test-and-set! cell)) (error "no semaphore to be release") (set! lock-numbers (+ lock-numbers 1))) (set-car! cell false)))) the-semaphore)) (define a (make-mutex-semaphore 2)) (a 'acquire) (a 'acquire) (define b (make-test-semaphore 2)) (b 'acquire) (b 'acquire)
false
433defbf8eee3edf1a51b44e08f63bf64f4ceb60
d474cce91812fbcdf351f8c27ddfb999e5b4b29b
/sdl2/assert-functions.ss
4bdced1096d5a073c966b61c8f0ab2b20ea96e0e
[]
no_license
localchart/thunderchez
8c70ccb2d55210207f0ee1a5df88a52362d2db27
9af3026617b1fb465167d3907416f482e25ef791
refs/heads/master
2021-01-22T00:20:15.576577
2016-08-17T11:49:37
2016-08-17T11:49:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
672
ss
assert-functions.ss
(define-sdl-func sdl-assert-state-t sdl-report-assertion ((data (* sdl-assert-data-t)) (a string) (b string) (c int)) "SDL_ReportAssertion") (define-sdl-func void sdl-set-assertion-handler ((handler sdl-assertion-handler-t) (userdata void*)) "SDL_SetAssertionHandler") (define-sdl-func sdl-assertion-handler-t sdl-get-default-assertion-handler () "SDL_GetDefaultAssertionHandler") (define-sdl-func sdl-assertion-handler-t sdl-get-assertion-handler ((puserdata (* void*))) "SDL_GetAssertionHandler") (define-sdl-func (* sdl-assert-data-t) sdl-get-assertion-report () "SDL_GetAssertionReport") (define-sdl-func void sdl-reset-assertion-report () "SDL_ResetAssertionReport")
false
98189f96463faece1bee03d2a367cced6d3c2d3e
685d0fcfef3077b4327f2155b48207fd4809ee57
/source/core.ss
d09b972d8b13d4474b337f486e07e8a5040c46ba
[ "Apache-2.0" ]
permissive
ChillMagic/ICM-Scheme
f172c6e4d393e97cc2553f837176ca9f42ef71f8
0bfe82067dcf6f639fc009f1b012ee9d2f727686
refs/heads/master
2021-01-19T03:56:38.399883
2017-04-06T16:21:27
2017-04-06T16:21:27
84,420,360
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,250
ss
core.ss
;; ICM on Scheme ;; core.ss ;; Author : Chill (load-relative "basic.ss") (load-relative "common/analysisbase.ss") (library (ICM-Core) (export expr-eval if-expr) (import (rnrs) (Output) (ICM-AnalysisBase) (prefix (Symbol) Symbol.) (prefix (HashTable) HashTable.) (prefix (GlobalFunc) GlobalFunc.) (prefix (List) List.)) (define-syntax if-expr (syntax-rules () ((_ env b-expr f-expr l-expr e-expr) (let ((b-value (expr-evalf b-expr env))) (cond ((Symbol.=? b-value 'T) (expr-evalf f-expr env)) ((Symbol.=? b-value 'F) (expr-evalf l-expr env)) (else e-expr)))))) (define (errors) (display "Error Occur.\n") `nil) ;; eval (define (expr-eval code env) (when (not (procedure? expr-evalf)) (init-eval-func (make-eq-hashtable))) (expr-evalf code env)) (define expr-evalf) (define (init-eval-func efm) ; efm : Eval Func Map (HashTable.insert! efm 'do expr-do ) (HashTable.insert! efm '? expr-? ) (HashTable.insert! efm 'if expr-if ) (HashTable.insert! efm 'loop expr-loop ) (HashTable.insert! efm 'while expr-while ) (HashTable.insert! efm 'for expr-for ) (HashTable.insert! efm 'let expr-let ) (HashTable.insert! efm 'set expr-set ) (HashTable.insert! efm 'cpy expr-cpy ) (HashTable.insert! efm 'ref expr-ref ) (HashTable.insert! efm 'dim expr-dim ) (HashTable.insert! efm 'restrict expr-restrict ) (HashTable.insert! efm 'define expr-define ) (HashTable.insert! efm 'defunc expr-defunc ) (HashTable.insert! efm 'defstruct expr-defstruct) (HashTable.insert! efm 'function expr-function ) (HashTable.insert! efm 'struct expr-struct ) (let ((f (lambda (sym) (HashTable.get efm sym (lambda (code env) (expr-fcall sym code env)))))) (set! expr-evalf (lambda (code env) (do-execute f code env))))) (define (expr-evals code env) (let loop ((lst code) (rlist `())) (if (null? lst) rlist (loop (cdr lst) (List.push-back rlist (expr-evalf (car lst) env)))))) ;; (fexpr <sexpr ...>) (define (expr-fcall fexpr code env) (GlobalFunc.call env (expr-evalf fexpr env) (expr-evals code env) (lambda (s) (display "Error to find Identifer '") (display s) (display "'.\n") 'nil))) ;; (do ;; <sexpr ...> ;; ) (define (expr-do code env) (let loop ((lst code) (last `nil)) (if (null? lst) last (loop (cdr lst) (expr-evalf (car lst) env))))) ;; (? bexpr sexpr1 <sexpr2>) (define (expr-? code env) (if-expr env (car code) (cadr code) (caddr code) (errors))) ;; (if bexpr0 ;; sexpr0 ... ;; <elsif bexprk ;; sexprk ...>* ;; <else ;; sexprn ...> ;; ) (define (expr-if code env) code ) ;; (loop ;; sexpr ... ;; ) (define (expr-loop code env) code ) ;; (while bexpr ;; sexpr ... ;; ) (define (expr-while code env) code ) ;; (for I in rexpr ;; sexpr ... ;; ) (define (expr-for code env) code ) ;; (let I vexpr) (define (expr-let code env) code ) ;; (set I vexpr) (define (expr-set code env) code ) ;; (cpy <I> vexpr) (define (expr-cpy code env) code ) ;; (ref I I2) (define (expr-ref code env) code ) ;; (dim I texpr) (define (expr-dim code env) code ) ;; (restrict I texpr) (define (expr-restrict code env) code ) ;; (define I cexpr) (define (expr-define code env) code ) ;; (defunc ident [<(ident : texpr)|ident>* <(ident : texpr ...)|(... : texpr)|...>] <-> texpr> ;; sexpr ... ;; ) (define (expr-defunc code env) code ) ;; (function <I> [<(I <: Type>)>*] <-> Type> ;; sexpr ... ;; ) (define (expr-function code env) code ) ;; (defstruct I ;; <[(I <: Type>)]>* ;; ) (define (expr-defstruct code env) code ) ;; (struct <I> ;; <[(I <: Type>)]>* ;; ) (define (expr-struct code env) code ) )
true
d85b26bc6d50559edaa64fc18b6345f5ccb5eca4
c1bd77e99e38cbd3e8f18399fd117aa6a1721177
/services/init.scm
c595e8b188061f82c89037a5a8d7de4734827fbd
[]
no_license
jkopanski/guix
b016a57d95968042644aa56a4d1dda876ad96ac8
a6be12a1af7b76793314c7c04881948ca947c059
refs/heads/master
2021-08-31T23:30:03.126909
2017-12-23T13:29:48
2017-12-23T13:29:48
104,381,903
2
0
null
null
null
null
UTF-8
Scheme
false
false
167
scm
init.scm
(use-modules (nat guix services keybase)) (apply register-services (list keybase-service kbfs-service)) (action 'shepherd 'daemonize)
false
0e261a445c8c2947ff25b0e445b226b3dcd17c60
a23f41d6de12a268b129a6b5c2e932325fe674f6
/src/swish/pregexp.ss
1da95942d42d12041c380c2ba665319680b6cc89
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
becls/swish
89ee48b783b6b67b7077e09a78b3005fb44a8c54
3165b6a40c33774b263941314a7975b08dddf0e2
refs/heads/dev
2022-11-05T01:55:29.530457
2022-10-14T20:49:18
2022-10-14T20:55:37
113,237,913
134
27
MIT
2022-10-17T13:04:13
2017-12-05T22:04:27
Scheme
UTF-8
Scheme
false
false
30,078
ss
pregexp.ss
;;; Portable regular expressions for Scheme ;;; Copyright (c) 1999-2005, Dorai Sitaram. ;;; All rights reserved. ;;; http://www.ccs.neu.edu/~dorai ;;; [email protected] ;;; Oct 2, 1999 ;;; Permission to copy, modify, distribute, and use this work or ;;; a modified copy of this work, for any purpose, is hereby ;;; granted, provided that the copy includes this copyright ;;; notice, and in the case of a modified copy, also includes a ;;; notice of modification. This work is provided as is, with ;;; no warranty of any kind. ;;; Ported to Chez Scheme by Bob Burger ;;; - added library wrapper ;;; - added re macro for compile-time parsing ;;; - updated replace functions to use a string output port for efficiency ;;; - removed unused sn argument from pregexp-match-positions-aux ;;; - lookbehind matching handles newlines and honors non-zero start ;;; - removed *pregexp-version* ;;; - inlined *pregexp-comment-char*, *pregexp-nul-char-int*, ;;; *pregexp-return-char*, and *pregexp-tab-char* ;;; - renamed pregexp-reverse! to reverse! ;;; - rewrote pregexp-error as a macro that calls throw ;;; - updated multiple-arity procedures to use case-lambda ;;; - used a process parameter for *pregexp-space-sensitive?* ;;; - used brackets where appropriate (library (swish pregexp) (export pregexp pregexp-match pregexp-match-positions pregexp-quote pregexp-replace pregexp-replace* pregexp-split re ) (import (chezscheme) (swish erlang) ) ;; compile static regular expressions at expand time (define-syntax re (syntax-rules () [(_ e) ;; work around out-of-phase identifier (let-syntax ([re re-transformer]) (re e))])) (define (re-transformer x) (syntax-case x () [(re pat) (let ([s (datum pat)]) (if (string? s) #`(quote #,(datum->syntax #'re (pregexp s))) #`(pregexp pat)))])) (define *pregexp-comment-char* #\;) (define pregexp-space-sensitive? (make-process-parameter #t (lambda (x) (and x #t)))) (define-syntax *pregexp-space-sensitive?* (identifier-syntax [id (pregexp-space-sensitive?)] [(set! id val) (pregexp-space-sensitive? val)])) (define-syntax pregexp-error (syntax-rules () [(_ e1 e2 ...) (throw `#(pregexp-error ,e1 ,e2 ...))])) (define (pregexp-read-pattern s i n) (if (>= i n) (list (list ':or (list ':seq)) i) (let loop ([branches '()] [i i]) (if (or (>= i n) (char=? (string-ref s i) #\))) (list (cons ':or (reverse! branches)) i) (let ([vv (pregexp-read-branch s (if (char=? (string-ref s i) #\|) (+ i 1) i) n)]) (loop (cons (car vv) branches) (cadr vv))))))) (define (pregexp-read-branch s i n) (let loop ([pieces '()] [i i]) (cond [(>= i n) (list (cons ':seq (reverse! pieces)) i)] [(let ((c (string-ref s i))) (or (char=? c #\|) (char=? c #\)))) (list (cons ':seq (reverse! pieces)) i)] [else (let ([vv (pregexp-read-piece s i n)]) (loop (cons (car vv) pieces) (cadr vv)))]))) (define (pregexp-read-piece s i n) (let ([c (string-ref s i)]) (case c [(#\^) (list ':bos (+ i 1))] [(#\$) (list ':eos (+ i 1))] [(#\.) (pregexp-wrap-quantifier-if-any (list ':any (+ i 1)) s n)] [(#\[) (let ([i+1 (+ i 1)]) (pregexp-wrap-quantifier-if-any (case (and (< i+1 n) (string-ref s i+1)) [(#\^) (let ((vv (pregexp-read-char-list s (+ i 2) n))) (list (list ':neg-char (car vv)) (cadr vv)))] [else (pregexp-read-char-list s i+1 n)]) s n))] [(#\() (pregexp-wrap-quantifier-if-any (pregexp-read-subpattern s (+ i 1) n) s n)] [(#\\) (pregexp-wrap-quantifier-if-any (cond [(pregexp-read-escaped-number s i n) => (lambda (num-i) (list (list ':backref (car num-i)) (cadr num-i)))] [(pregexp-read-escaped-char s i n) => (lambda (char-i) (list (car char-i) (cadr char-i)))] [else (pregexp-error 'pregexp-read-piece 'backslash)]) s n)] [else (if (or *pregexp-space-sensitive?* (and (not (char-whitespace? c)) (not (char=? c *pregexp-comment-char*)))) (pregexp-wrap-quantifier-if-any (list c (+ i 1)) s n) (let loop ([i i] [in-comment? #f]) (if (>= i n) (list ':empty i) (let ([c (string-ref s i)]) (cond [in-comment? (loop (+ i 1) (not (char=? c #\newline)))] [(char-whitespace? c) (loop (+ i 1) #f)] [(char=? c *pregexp-comment-char*) (loop (+ i 1) #t)] [else (list ':empty i)])))))]))) (define (pregexp-read-escaped-number s i n) ;; s[i] = \ (and (< (+ i 1) n) ;; must have at least something following \ (let ([c (string-ref s (+ i 1))]) (and (char-numeric? c) (let loop ([i (+ i 2)] [r (list c)]) (if (>= i n) (list (string->number (list->string (reverse! r))) i) (let ([c (string-ref s i)]) (if (char-numeric? c) (loop (+ i 1) (cons c r)) (list (string->number (list->string (reverse! r))) i))))))))) (define (pregexp-read-escaped-char s i n) ;; s[i] = \ (and (< (+ i 1) n) (let ([c (string-ref s (+ i 1))]) (case c [(#\b) (list ':wbdry (+ i 2))] [(#\B) (list ':not-wbdry (+ i 2))] [(#\d) (list ':digit (+ i 2))] [(#\D) (list '(:neg-char :digit) (+ i 2))] [(#\n) (list #\newline (+ i 2))] [(#\r) (list #\return (+ i 2))] [(#\s) (list ':space (+ i 2))] [(#\S) (list '(:neg-char :space) (+ i 2))] [(#\t) (list #\tab (+ i 2))] [(#\w) (list ':word (+ i 2))] [(#\W) (list '(:neg-char :word) (+ i 2))] [else (list c (+ i 2))])))) (define (pregexp-read-posix-char-class s i n) ;; lbrack, colon already read (let ([neg? #f]) (let loop ([i i] [r (list #\:)]) (if (>= i n) (pregexp-error 'pregexp-read-posix-char-class) (let ([c (string-ref s i)]) (cond [(char=? c #\^) (set! neg? #t) (loop (+ i 1) r)] [(char-alphabetic? c) (loop (+ i 1) (cons c r))] [(char=? c #\:) (if (or (>= (+ i 1) n) (not (char=? (string-ref s (+ i 1)) #\]))) (pregexp-error 'pregexp-read-posix-char-class) (let ([posix-class (string->symbol (list->string (reverse! r)))]) (list (if neg? (list ':neg-char posix-class) posix-class) (+ i 2))))] [else (pregexp-error 'pregexp-read-posix-char-class)])))))) (define (pregexp-read-cluster-type s i n) ;; s[i-1] = left-paren (let ([c (string-ref s i)]) (case c [(#\?) (let ([i (+ i 1)]) (case (string-ref s i) ((#\:) (list '() (+ i 1))) ((#\=) (list '(:lookahead) (+ i 1))) ((#\!) (list '(:neg-lookahead) (+ i 1))) ((#\>) (list '(:no-backtrack) (+ i 1))) ((#\<) (list (case (string-ref s (+ i 1)) ((#\=) '(:lookbehind)) ((#\!) '(:neg-lookbehind)) (else (pregexp-error 'pregexp-read-cluster-type))) (+ i 2))) (else (let loop ([i i] [r '()] [inv? #f]) (let ([c (string-ref s i)]) (case c ((#\-) (loop (+ i 1) r #t)) ((#\i) (loop (+ i 1) (cons (if inv? ':case-sensitive ':case-insensitive) r) #f)) ((#\x) (set! *pregexp-space-sensitive?* inv?) (loop (+ i 1) r #f)) ((#\:) (list r (+ i 1))) (else (pregexp-error 'pregexp-read-cluster-type))))))))] [else (list '(:sub) i)]))) (define (pregexp-read-subpattern s i n) (let* ([remember-space-sensitive? *pregexp-space-sensitive?*] [ctyp-i (pregexp-read-cluster-type s i n)] [ctyp (car ctyp-i)] [i (cadr ctyp-i)] [vv (pregexp-read-pattern s i n)]) (set! *pregexp-space-sensitive?* remember-space-sensitive?) (let ([vv-re (car vv)] [vv-i (cadr vv)]) (if (and (< vv-i n) (char=? (string-ref s vv-i) #\))) (list (let loop ([ctyp ctyp] [re vv-re]) (if (null? ctyp) re (loop (cdr ctyp) (list (car ctyp) re)))) (+ vv-i 1)) (pregexp-error 'pregexp-read-subpattern))))) (define (pregexp-wrap-quantifier-if-any vv s n) (let ([re (car vv)]) (let loop ([i (cadr vv)]) (if (>= i n) vv (let ([c (string-ref s i)]) (if (and (char-whitespace? c) (not *pregexp-space-sensitive?*)) (loop (+ i 1)) (case c [(#\* #\+ #\? #\{) (let* ([new-re (list ':between 'minimal? 'at-least 'at-most re)] [new-vv (list new-re 'next-i)]) (case c ((#\*) (set-car! (cddr new-re) 0) (set-car! (cdddr new-re) #f)) ((#\+) (set-car! (cddr new-re) 1) (set-car! (cdddr new-re) #f)) ((#\?) (set-car! (cddr new-re) 0) (set-car! (cdddr new-re) 1)) ((#\{) (let ([pq (pregexp-read-nums s (+ i 1) n)]) (if (not pq) (pregexp-error 'pregexp-wrap-quantifier-if-any 'left-brace-must-be-followed-by-number)) (set-car! (cddr new-re) (car pq)) (set-car! (cdddr new-re) (cadr pq)) (set! i (caddr pq))))) (let loop ([i (+ i 1)]) (if (>= i n) (begin (set-car! (cdr new-re) #f) (set-car! (cdr new-vv) i)) (let ([c (string-ref s i)]) (cond [(and (char-whitespace? c) (not *pregexp-space-sensitive?*)) (loop (+ i 1))] [(char=? c #\?) (set-car! (cdr new-re) #t) (set-car! (cdr new-vv) (+ i 1))] [else (set-car! (cdr new-re) #f) (set-car! (cdr new-vv) i)])))) new-vv)] [else vv]))))))) (define (pregexp-read-nums s i n) ;; s[i-1] = { ;; returns (p q k) where s[k] = } (let loop ([p '()] [q '()] [k i] [reading 1]) (if (>= k n) (pregexp-error 'pregexp-read-nums)) (let ([c (string-ref s k)]) (cond [(char-numeric? c) (if (= reading 1) (loop (cons c p) q (+ k 1) 1) (loop p (cons c q) (+ k 1) 2))] [(and (char-whitespace? c) (not *pregexp-space-sensitive?*)) (loop p q (+ k 1) reading)] [(and (char=? c #\,) (= reading 1)) (loop p q (+ k 1) 2)] [(char=? c #\}) (let ([p (string->number (list->string (reverse! p)))] [q (string->number (list->string (reverse! q)))]) (cond [(and (not p) (= reading 1)) (list 0 #f k)] [(= reading 1) (list p p k)] [else (list p q k)]))] [else #f])))) (define (pregexp-invert-char-list vv) (set-car! (car vv) ':none-of-chars) vv) (define (pregexp-read-char-list s i n) (let loop ([r '()] [i i]) (if (>= i n) (pregexp-error 'pregexp-read-char-list 'character-class-ended-too-soon) (let ([c (string-ref s i)]) (case c [(#\]) (if (null? r) (loop (cons c r) (+ i 1)) (list (cons ':one-of-chars (reverse! r)) (+ i 1)))] [(#\\) (let ([char-i (pregexp-read-escaped-char s i n)]) (if char-i (loop (cons (car char-i) r) (cadr char-i)) (pregexp-error 'pregexp-read-char-list 'backslash)))] [(#\-) (if (or (null? r) (let ([i+1 (+ i 1)]) (and (< i+1 n) (char=? (string-ref s i+1) #\])))) (loop (cons c r) (+ i 1)) (let ([c-prev (car r)]) (if (char? c-prev) (loop (cons (list ':char-range c-prev (string-ref s (+ i 1))) (cdr r)) (+ i 2)) (loop (cons c r) (+ i 1)))))] [(#\[) (if (char=? (string-ref s (+ i 1)) #\:) (let ([posix-char-class-i (pregexp-read-posix-char-class s (+ i 2) n)]) (loop (cons (car posix-char-class-i) r) (cadr posix-char-class-i))) (loop (cons c r) (+ i 1)))] [else (loop (cons c r) (+ i 1))]))))) (define (pregexp-string-match s1 s i n sk fk) (let ([n1 (string-length s1)]) (if (> n1 n) (fk) (let loop ([j 0] [k i]) (cond [(>= j n1) (sk k)] [(>= k n) (fk)] [(char=? (string-ref s1 j) (string-ref s k)) (loop (+ j 1) (+ k 1))] [else (fk)]))))) (define (pregexp-char-word? c) ;; too restrictive for Scheme but this ;; is what \w is in most regexp notations (or (char-alphabetic? c) (char-numeric? c) (char=? c #\_))) (define (pregexp-at-word-boundary? s i n) (or (= i 0) (>= i n) (let ([c/i (string-ref s i)] [c/i-1 (string-ref s (- i 1))]) (let ([c/i/w? (pregexp-check-if-in-char-class? c/i ':word)] [c/i-1/w? (pregexp-check-if-in-char-class? c/i-1 ':word)]) (or (and c/i/w? (not c/i-1/w?)) (and (not c/i/w?) c/i-1/w?)))))) (define (pregexp-check-if-in-char-class? c char-class) (case char-class [(:any) (not (char=? c #\newline))] [(:alnum) (or (char-alphabetic? c) (char-numeric? c))] [(:alpha) (char-alphabetic? c)] [(:ascii) (< (char->integer c) 128)] [(:blank) (or (char=? c #\space) (char=? c #\tab))] [(:cntrl) (< (char->integer c) 32)] [(:digit) (char-numeric? c)] [(:graph) (and (>= (char->integer c) 32) (not (char-whitespace? c)))] [(:lower) (char-lower-case? c)] [(:print) (>= (char->integer c) 32)] [(:punct) (and (>= (char->integer c) 32) (not (char-whitespace? c)) (not (char-alphabetic? c)) (not (char-numeric? c)))] [(:space) (char-whitespace? c)] [(:upper) (char-upper-case? c)] [(:word) (or (char-alphabetic? c) (char-numeric? c) (char=? c #\_))] [(:xdigit) (or (char-numeric? c) (char-ci=? c #\a) (char-ci=? c #\b) (char-ci=? c #\c) (char-ci=? c #\d) (char-ci=? c #\e) (char-ci=? c #\f))] [else (pregexp-error 'pregexp-check-if-in-char-class?)])) (define (pregexp-list-ref s i) ;; like list-ref but returns #f if index is out of bounds (let loop ([s s] [k 0]) (cond [(null? s) #f] [(= k i) (car s)] [else (loop (cdr s) (+ k 1))]))) ;; re is a compiled regexp. It's a list that can't be ;; nil. pregexp-match-positions-aux returns a 2-elt list whose ;; car is the string-index following the matched ;; portion and whose cadr contains the submatches. ;; The proc returns false if there's no match. (define (pregexp-make-backref-list re) (let sub ([re re]) (if (pair? re) (let ([car-re (car re)] [sub-cdr-re (sub (cdr re))]) (if (eq? car-re ':sub) (cons (cons re #f) sub-cdr-re) (append (sub car-re) sub-cdr-re))) '()))) (define (pregexp-match-positions-aux re s start n i) (let ([identity (lambda (x) x)] [backrefs (pregexp-make-backref-list re)] [case-sensitive? #t]) (let sub ([re re] [i i] [sk identity] [fk (lambda () #f)]) (cond [(eq? re ':bos) (if (= i start) (sk i) (fk))] [(eq? re ':eos) (if (>= i n) (sk i) (fk))] [(eq? re ':empty) (sk i)] [(eq? re ':wbdry) (if (pregexp-at-word-boundary? s i n) (sk i) (fk))] [(eq? re ':not-wbdry) (if (pregexp-at-word-boundary? s i n) (fk) (sk i))] [(and (char? re) (< i n)) (if ((if case-sensitive? char=? char-ci=?) (string-ref s i) re) (sk (+ i 1)) (fk))] [(and (not (pair? re)) (< i n)) (if (pregexp-check-if-in-char-class? (string-ref s i) re) (sk (+ i 1)) (fk))] [(and (pair? re) (eq? (car re) ':char-range) (< i n)) (let ([c (string-ref s i)]) (if (let ([c< (if case-sensitive? char<=? char-ci<=?)]) (and (c< (cadr re) c) (c< c (caddr re)))) (sk (+ i 1)) (fk)))] [(pair? re) (case (car re) [(:char-range) (if (>= i n) (fk) (pregexp-error 'pregexp-match-positions-aux))] [(:one-of-chars) (if (>= i n) (fk) (let loop-one-of-chars ([chars (cdr re)]) (if (null? chars) (fk) (sub (car chars) i sk (lambda () (loop-one-of-chars (cdr chars)))))))] [(:neg-char) (if (>= i n) (fk) (sub (cadr re) i (lambda (i1) (fk)) (lambda () (sk (+ i 1)))))] [(:seq) (let loop-seq ([res (cdr re)] [i i]) (if (null? res) (sk i) (sub (car res) i (lambda (i1) (loop-seq (cdr res) i1)) fk)))] [(:or) (let loop-or ([res (cdr re)]) (if (null? res) (fk) (sub (car res) i (lambda (i1) (or (sk i1) (loop-or (cdr res)))) (lambda () (loop-or (cdr res))))))] [(:backref) (let* ([c (pregexp-list-ref backrefs (cadr re))] [backref (cond [c => cdr] [else (pregexp-error 'pregexp-match-positions-aux 'non-existent-backref re) #f])]) (if backref (pregexp-string-match (substring s (car backref) (cdr backref)) s i n (lambda (i) (sk i)) fk) (sk i)))] [(:sub) (sub (cadr re) i (lambda (i1) (set-cdr! (assv re backrefs) (cons i i1)) (sk i1)) fk)] [(:lookahead) (let ([found-it? (sub (cadr re) i identity (lambda () #f))]) (if found-it? (sk i) (fk)))] [(:neg-lookahead) (let ([found-it? (sub (cadr re) i identity (lambda () #f))]) (if found-it? (fk) (sk i)))] [(:lookbehind) (let ([found-it? (fluid-let ([n i]) (let loop-lookbehind ([re (cadr re)] [i i]) (sub re i (lambda (i) (= i n)) (lambda () (and (> i start) (loop-lookbehind re (- i 1)))))))]) (if found-it? (sk i) (fk)))] [(:neg-lookbehind) (let ([found-it? (fluid-let ([n i]) (let loop-lookbehind ([re (cadr re)] [i i]) (sub re i (lambda (i) (= i n)) (lambda () (and (> i start) (loop-lookbehind re (- i 1)))))))]) (if found-it? (fk) (sk i)))] [(:no-backtrack) (let ([found-it? (sub (cadr re) i identity (lambda () #f))]) (if found-it? (sk found-it?) (fk)))] [(:case-sensitive :case-insensitive) (let ([old case-sensitive?]) (set! case-sensitive? (eq? (car re) ':case-sensitive)) (sub (cadr re) i (lambda (i1) (set! case-sensitive? old) (sk i1)) (lambda () (set! case-sensitive? old) (fk))))] [(:between) (let* ([maximal? (not (cadr re))] [p (caddr re)] [q (cadddr re)] [could-loop-infinitely? (and maximal? (not q))] [re (car (cddddr re))]) (let loop-p ([k 0] [i i]) (if (< k p) (sub re i (lambda (i1) (if (and could-loop-infinitely? (= i1 i)) (pregexp-error 'pregexp-match-positions-aux 'greedy-quantifier-operand-could-be-empty)) (loop-p (+ k 1) i1)) fk) (let ([q (and q (- q p))]) (let loop-q ([k 0] [i i]) (let ([fk (lambda () (sk i))]) (if (and q (>= k q)) (fk) (if maximal? (sub re i (lambda (i1) (if (and could-loop-infinitely? (= i1 i)) (pregexp-error 'pregexp-match-positions-aux 'greedy-quantifier-operand-could-be-empty)) (or (loop-q (+ k 1) i1) (fk))) fk) (or (fk) (sub re i (lambda (i1) (loop-q (+ k 1) i1)) fk))))))))))] [else (pregexp-error 'pregexp-match-positions-aux)])] [(>= i n) (fk)] [else (pregexp-error 'pregexp-match-positions-aux)])) (let ([backrefs (map cdr backrefs)]) (and (car backrefs) backrefs)))) (define (put-substring p str start end) (put-string p str start (- end start))) (define (pregexp-replace-aux str ins n backrefs p) (let loop ([i 0]) (when (< i n) (let ([c (string-ref ins i)]) (cond [(char=? c #\\) (let* ([br-i (pregexp-read-escaped-number ins i n)] [br (if br-i (car br-i) (if (char=? (string-ref ins (+ i 1)) #\&) 0 #f))] [i (if br-i (cadr br-i) (if br (+ i 2) (+ i 1)))]) (if (not br) (let ([c2 (string-ref ins i)]) (unless (char=? c2 #\$) (put-char p c2)) (loop (+ i 1))) (let ([backref (pregexp-list-ref backrefs br)]) (when backref (put-substring p str (car backref) (cdr backref))) (loop i))))] [else (put-char p c) (loop (+ i 1))]))))) (define (pregexp s) (set! *pregexp-space-sensitive?* #t) ;; in case it got corrupted (list ':sub (car (pregexp-read-pattern s 0 (string-length s))))) (define pregexp-match-positions (case-lambda [(pat str) (pregexp-match-positions pat str 0)] [(pat str start) (pregexp-match-positions pat str start (string-length str))] [(pat str start end) (let ([pat (cond [(string? pat) (pregexp pat)] [(pair? pat) pat] [else (pregexp-error 'pregexp-match-positions 'pattern-must-be-compiled-or-string-regexp pat)])]) (let loop ([i start]) (and (<= i end) (or (pregexp-match-positions-aux pat str start end i) (loop (+ i 1))))))])) (define pregexp-match (case-lambda [(pat str) (pregexp-match pat str 0)] [(pat str start) (pregexp-match pat str start (string-length str))] [(pat str start end) (let ([ix-prs (pregexp-match-positions pat str start end)]) (and ix-prs (map (lambda (ix-pr) (and ix-pr (substring str (car ix-pr) (cdr ix-pr)))) ix-prs)))])) (define (pregexp-split pat str) ;; split str into substrings, using pat as delimiter (let ([n (string-length str)]) (let loop ([i 0] [r '()] [picked-up-one-undelimited-char? #f]) (cond [(>= i n) (reverse! r)] [(pregexp-match-positions pat str i n) => (lambda (y) (let ([jk (car y)]) (let ([j (car jk)] [k (cdr jk)]) (cond [(= j k) (loop (+ k 1) (cons (substring str i (+ j 1)) r) #t)] [(and (= j i) picked-up-one-undelimited-char?) (loop k r #f)] [else (loop k (cons (substring str i j) r) #f)]))))] [else (loop n (cons (substring str i n) r) #f)])))) (define (pregexp-replace pat str ins) (let* ([n (string-length str)] [pp (pregexp-match-positions pat str 0 n)]) (if (not pp) str (let ([ins-len (string-length ins)] [m-i (caar pp)] [m-n (cdar pp)] [p (open-output-string)]) (put-substring p str 0 m-i) (pregexp-replace-aux str ins ins-len pp p) (put-substring p str m-n n) (get-output-string p))))) (define (pregexp-replace* pat str ins) ;; return str with every occurrence of pat ;; replaced by ins (let ([pat (if (string? pat) (pregexp pat) pat)] [n (string-length str)] [ins-len (string-length ins)] [p (open-output-string)]) (let loop ([i 0]) ;; i = index in str to start replacing from ;; r = already calculated prefix of answer (if (>= i n) (get-output-string p) (let ([pp (pregexp-match-positions pat str i n)]) (cond [pp (put-substring p str i (caar pp)) (pregexp-replace-aux str ins ins-len pp p) (loop (cdar pp))] [(= i 0) ;; this implies pat didn't match str at ;; all, so let's return original str str] [else ;; all matches already found and ;; replaced in r, so let's just ;; append the rest of str (put-substring p str i n) (get-output-string p)])))))) (define (pregexp-quote s) (let loop ([i (- (string-length s) 1)] [r '()]) (if (< i 0) (list->string r) (loop (- i 1) (let ([c (string-ref s i)]) (if (memv c '(#\\ #\. #\? #\* #\+ #\| #\^ #\$ #\[ #\] #\{ #\} #\( #\))) (cons #\\ (cons c r)) (cons c r))))))))
true
2371113faa99b9c2b9a4ae092fe8605da76fa03f
15b3f9425594407e43dd57411a458daae76d56f6
/bin/compiler/test/if.scm
da7a57299f0d70b673012715051c824427d90bd6
[]
no_license
aa10000/scheme
ecc2d50b9d5500257ace9ebbbae44dfcc0a16917
47633d7fc4d82d739a62ceec75c111f6549b1650
refs/heads/master
2021-05-30T06:06:32.004446
2015-02-12T23:42:25
2015-02-12T23:42:25
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
22
scm
if.scm
(display (if 1 2 3) )
false
2f631fc3008541c73f004c3dbff4222ac37c5260
a0c856484b0cafd1d7c428fb271a820dd19be577
/lab6/parse-a.ss
5879da1e008b3b59a80ceb5f21fb2216e26d5585
[]
no_license
ctreatma/scheme_exercises
b13ba7743dfd28af894eb54429297bad67c14ffa
94b4e8886b2500a7b645e6dc795c0d239bf2a3bb
refs/heads/master
2020-05-19T07:30:58.538798
2012-12-03T23:12:22
2012-12-03T23:12:22
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
307
ss
parse-a.ss
;; parse-a.ss ;; Datatype and parser for Mini-Scheme-A (require (lib "eopl.ss" "eopl")) (define-datatype exp-a exp-a? (exp-a-lit (datum number?))) (define parse (lambda (exp) (cond ((number? exp) (exp-a-lit exp)) (else (error 'parse "Invalid concrete syntax ~s" exp)))))
false
f5c94257c8dcde9ac0cefabb64b0bc4c8e3bde6a
cca999903bc2305da28e598c46298e7d31dbdef5
/src/web/collections/test/tiina-2-6.ss
8e82d7e5d868a38a1b282d7d16dee314ec84708d
[ "Apache-2.0" ]
permissive
ds26gte/kode.pyret.org
211183f7045f69cf998a8ebd8a9373cd719d29a1
534f2d4b61a6d6c650a364186a4477a52d1cd986
refs/heads/master
2021-01-11T14:56:43.120765
2018-05-02T22:27:55
2018-05-02T22:27:55
80,234,747
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,609
ss
tiina-2-6.ss
; Ufo laskeutuu ; ; Tehtävä 1: ; Korjaa alla oleva piirrä-ufo funktion koodi niin, että ufo laskeutuu ; alaspäin (nyt se on jumissa taivaalla kohdassa x=150 ja y=0). ; ; Tehtävä 2: ; Korjaa pysähdy? funktiota niin, että se huomaa milloin ufo ; on maassa ja lopettaa animaation. ; ; Tehtävä 3: ; Saatko ufon lentämään nopeammin? Muokkaa siirrä-ufo funktiota. ; ; Tehtävä 4: ; Keksitkö jo miten saat ufon lentämään alhaalta ylös ja pysähtymään ; yläreunaan (vinkki: ufo lähtee liikkeelle kohdasta LÄHTÖ). ; ; Tehtävä 5: ; Keksitkö jo, miten ufon saa lentämään vaakatasossa, vasemmalta oikealle? ; ; Tehtävä 6: ; Entäpä ufo, joka tulee esiin uudelleen ja uudelleen (rullaa). ; Vinkki: ehtolause... ; ---------------------------------------------------------------- (define LÄHTÖ 0) ; Tehtävä 4 ---> (define LÄHTÖ 466) (define UFO (overlay/xy (ellipse 120 40 "solid" "violet") 30 -25 (circle 30 "outline" "black"))) (define TAUSTA (empty-scene 300 500)) ;; piirrä-ufo : Luku -> Kuva (define (piirrä-ufo y) (place-image UFO 150 y TAUSTA)) ;; pysähdy? : Luku -> Totuusarvo (define (pysähdy? y) (> y 465)) ; Tehtävä 4 ---> (< y 0) ;; siirrä-ufo : Luku -> Luku (define (siirrä-ufo y) (+ y 3)) ; Tehtävä 4 ---> (- y 3) ;; Tehtävä 6 (rullaava): ;(define (siirrä-ufo y) ; (if (>= y 460) ; 0 ; (+ y 3))) ;; ---------------- älä muokkaa tästä alaspäin ------------------ (big-bang LÄHTÖ (to-draw piirrä-ufo) (on-tick siirrä-ufo) (stop-when pysähdy?))
false
e2077ae9a215aa09e00a0411f9488d0f40a54b47
fe0de995a95bcf09cd447349269dc0e550851b5a
/tests/0015-lambda-multiple-arguments.scm
9b3f0c0962d07dbf284909ec770ac58fe7071fa8
[ "MIT" ]
permissive
mugcake/ruse-scheme
4974021858be5b7f2421212ec2eeafd34c53bce8
dd480e17edd9a233fd2bc4e8b41ff45d13fcc328
refs/heads/master
2022-02-12T04:31:55.031607
2019-08-01T21:44:14
2019-08-01T21:44:14
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
85
scm
0015-lambda-multiple-arguments.scm
(import (tests)) (let ((proc (lambda (a b c) (add (add a b) c)))) (proc 40 1 1))
false
9682015e1b1ecfe4fd5f8de884f301127bf821e3
2c01a6143d8630044e3629f2ca8adf1455f25801
/xitomatl/persistence/transcoded-serializing.sls
acdff5a97b587373180c1ac730397876679f58dd
[ "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
662
sls
transcoded-serializing.sls
#!r6rs ;; Copyright 2009 Derick Eddington. My MIT-style license is in the file named ;; LICENSE from the original collection this file is distributed with. (library (xitomatl persistence transcoded-serializing) (export transcoded-serializer transcoded-deserializer) (import (rnrs)) (define transcoded-serializer (case-lambda ((s) (transcoded-serializer s (native-transcoder))) ((s t) (lambda (x p) (s x (transcoded-port p t)))))) (define transcoded-deserializer (case-lambda ((ds) (transcoded-deserializer ds (native-transcoder))) ((ds t) (lambda (p) (ds (transcoded-port p t)))))) )
false
206d8813bda78f05e60ff4b9bb315d72b10104c5
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/math/matrix.sld
906768dcf69373a2058ae1fd3441703bb372ca4a
[ "MIT" ]
permissive
alvatar/spheres
c0601a157ddce270c06b7b58473b20b7417a08d9
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
refs/heads/master
2021-06-01T15:59:32.277602
2021-03-18T21:21:43
2021-03-18T21:21:43
25,094,121
13
3
null
null
null
null
UTF-8
Scheme
false
false
624
sld
matrix.sld
(define-library (spheres/math matrix) (export make-matrix matrix? matrix-rows matrix-columns matrix-ref matrix-set! matrix:+matrix matrix:+scalar matrix:+ matrix:-matrix matrix:-scalar matrix:- matrix:*matrix matrix:*scalar matrix:* matrix:transpose matrix:minor-submatrix matrix:determinant matrix:cofactor matrix:inverse matrix:cholesky matrix:inverse/cholesky matrix:map) (include "matrix.scm"))
false
f3f5e1200a6da8b0842d7842ccc2069090eb9986
8eb21733f83949941fadcb268dd4f0efab594b7f
/100/srfi-104/library-files-utilities/srfi/%3A%104/rename-old-style.r6rs-prog
403239ce341b55c9cafa4ba3fae15de3e79bf787
[]
no_license
srfi-explorations/final-srfis
d0994d215490333062a43241c57d0c2391224527
bc8e7251d5b52bf7b11d9e8ed8b6544a5d973690
refs/heads/master
2020-05-02T07:29:24.865266
2019-03-26T19:02:18
2019-03-26T19:02:18
177,819,656
1
0
null
null
null
null
UTF-8
Scheme
false
false
6,791
rename-old-style.r6rs-prog
#!r6rs ;; Required by PLT Scheme. ;; Requires Xitomatl revision at least 194. ;; Usually, this is run with a "searched directory" as the current directory. #| Usage: rename-old-style directory rename-command delete-command Rename old-style .sls and .SYS.sls to .r6rs-lib and .SYS-r6rs-lib. Rename and normalize old-style UTF-8 encoding to code-point encoding. Ask to remove PLT-style versions. Ask to rename implicit "main" files to non-implicit. Ask to rename directories which may need normalizing. Ask to delete or rename symbolic links. Examples: rename-old-style a-collection mv rm rename-old-style a-collection "bzr mv" "bzr rm" rename-old-style a-collection "echo rename" "echo delete" Arguments: directory: A directory containing library-file names to process. It may be renamed itself, its contents may be renamed, and it is recursively descended to maybe rename in its sub-directories. rename-command: A shell command prefix which renames files. It must take two arguments: the old file name and the new file name. delete-command: A shell command prefix which deletes files. It must take one argument: the file name to delete. |# (import (rnrs) (only (srfi :104 library-files-utilities) library-name->file-name) (only (xitomatl enumerators) fold/enumerator) (only (xitomatl file-system base) directory-walk-enumerator file-regular? file-directory?) (only (xitomatl file-system paths) path-join) (only (xitomatl irregex) irregex) (only (xitomatl common) system fprintf) (only (xitomatl lists) intersperse) (only (xitomatl match) match)) (define transcoder (make-transcoder (utf-8-codec) 'none 'raise)) (define (decode-string s) (define encoded-u8-prefix #\%) (define (hex? c) (or (char<=? #\0 c #\9) (char<=? #\A c #\F) (char<=? #\a c #\f))) (define (hex->u8 x y) (string->number (string x y) 16)) (let loop ((l (string->list s)) (a '())) (if (null? l) (apply string-append (reverse a)) (if (char=? (car l) encoded-u8-prefix) (let decode ((l l) (u8s '())) (if (and (pair? l) (char=? (car l) encoded-u8-prefix)) (and (pair? (cdr l)) (pair? (cddr l)) (let ((x (cadr l)) (y (caddr l))) (and (hex? x) (hex? y) (decode (cdddr l) (cons (hex->u8 x y) u8s))))) (loop l (cons (bytevector->string (u8-list->bytevector (reverse u8s)) transcoder) a)))) (loop (cdr l) (cons (string (car l)) a)))))) (define (encode-string s) (let ((fn (library-name->file-name (list (string->symbol s)) "e"))) (substring fn 0 (- (string-length fn) 2)))) (define (normalize s) (let ((d (decode-string s))) (if d (encode-string d) s))) (define implicit-component "main") (define (prompt fmt . args) (let loop () (apply fprintf (current-error-port) (string-append fmt " [yes/no] ") args) (flush-output-port (current-error-port)) (let ((ans (get-line (current-input-port)))) (or (string-ci=? "yes" ans) (if (string-ci=? "no" ans) #F (loop)))))) (define (shell cmd . args) (system (apply string-append (intersperse (cons cmd args) " ")))) (define sls-rx (irregex '(: ($ (**? 1 #F any)) ;; library name last part (? ($ (+ #\- (+ (/ #\0 #\9))))) ;; PLT-style version (? #\. ($ (+ (~ #\.)))) ;; Scheme system specific ".sls"))) (define ext "r6rs-lib") (define (main dir rename-command delete-command) (define (rename-dir) (define norm (normalize dir)) (if (and (not (string=? dir norm)) (prompt "Rename directory ~a ?" dir)) (begin (shell rename-command dir norm) norm) dir)) (fold/enumerator (directory-walk-enumerator 'top-down) (rename-dir) (lambda (path dirs files syms) (define (rename from to) (shell rename-command (path-join path from) (path-join path to))) (define (delete x) (shell delete-command (path-join path x))) (define (rename-file fn) (define full (path-join path fn)) (match fn ((:regex sls-rx name ver sys) (let* ((ext (if sys (string-append sys "-" ext) ext)) (append-ext (lambda (s) (string-append s "." ext))) (name (if (or (not ver) (prompt "Remove version of ~a ?" full)) name (string-append name ver)))) (if (and (string=? implicit-component name) (prompt "Rename ~a to non-implicit?" full)) (shell rename-command full (append-ext path)) (rename fn (append-ext (normalize name)))))) (_ (values)))) (define (rename-dir dn) (define norm (normalize dn)) (if (and (not (string=? dn norm)) (prompt "Rename directory ~a ?" (path-join path dn))) (begin (rename dn norm) norm) dn)) (define (rename-sym sn) (define full (path-join path sn)) (cond ((prompt "Delete symlink ~a ?" full) (delete sn)) ((prompt "Rename symlink ~a ?" full) (cond ((file-regular? full) (rename-file sn)) ((file-directory? full) (rename-dir sn)))))) (for-each rename-sym syms) (for-each rename-file files) (map rename-dir dirs)))) (define (usage) (fprintf (current-error-port) " Usage: rename-old-style directory rename-command delete-command Rename old-style .sls and .SYS.sls to .~a and .SYS-~a. Rename and normalize old-style UTF-8 encoding to code-point encoding. Ask to remove PLT-style versions. Ask to rename implicit \"main\" files to non-implicit. Ask to rename directories which may need normalizing. Ask to delete or rename symbolic links. Examples: rename-old-style a-collection mv rm rename-old-style a-collection \"bzr mv\" \"bzr rm\" rename-old-style a-collection \"echo rename\" \"echo delete\" Arguments: directory: A directory containing library-file names to process. It may be renamed itself, its contents may be renamed, and it is recursively descended to maybe rename in its sub-directories. rename-command: A shell command prefix which renames files. It must take two arguments: the old file name and the new file name. delete-command: A shell command prefix which deletes files. It must take one argument: the file name to delete. " ext ext) (flush-output-port (current-error-port))) (let ((args (cdr (command-line)))) (if (= 3 (length args)) (apply main args) (usage)))
false
70acce1d23c8348c5dc431ee71303cfccab3dfb9
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/023/023.scm
4635b2f0e6031b8206b0ecf951bd29d509c6a109
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,356
scm
023.scm
(define sum-of-divisors (lambda (n) (cond ((= n 1) 0) (else (let loop ([i 2] [n n] [sum 1]) (cond ((and (<= (* i i) n) (> n 1)) (cond ((zero? (remainder n i)) (let f ([p (* i i)] [num (/ n i)]) (cond ((zero? (remainder num i)) (f (* p i) (/ num i))) (else (if (= i 2) (loop 3 num (* sum (- p 1))) (loop (+ i 2) num (/ (* sum (- p 1)) (- i 1)))))))) (else (if (= i 2) (loop 3 n sum) (loop (+ i 2) n sum))))) (else (if (= n 1) sum (* (+ n 1) sum))))))))) (define sod (lambda (n) (- (sum-of-divisors n) n))) (define alist (let f ([i 12] [ls '()]) (cond ((> i 30000) (reverse ls)) (else (if (< i (sod i)) (f (+ i 1) (cons i ls)) (f (+ i 1) ls)))))) ;;(length alist) => 7428 (define avec (list->vector alist)) (define find-vec (make-vector 30000 0)) (let f ([i 0]) (cond ((> i 7427)) (else (let g ([j i]) (cond ((> j 7427) (f (+ i 1))) (else (let ([a (vector-ref avec i)] [b (vector-ref avec j)]) (cond ((< (+ a b) 30000) (vector-set! find-vec (+ a b) 1) (g (+ j 1))) (else (g (+ j 1))))))))))) (let pro ([i 1] [sum 0]) (cond ((> i 28123) sum) ((= (vector-ref find-vec i) 1) (pro (+ i 1) sum)) (else (pro (+ i 1) (+ sum i)))))
false
b95a3b3c1dcfa40a233db552747c815eb873e3ee
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/genealogy/2/main.scm
2c6b0216450869621ddf55e8b0a221bbc9243b48
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
763
scm
main.scm
(load "lines.scm") ; defines thunk `x' -- reads a ; gedcom file and ; returns a big fat list (load "gedcom-record.scm") (load "kdp.scm") ; defines a record that ; represents one line in the ; gedcom file (load "blood.scm") ; code to walk through a ; family tree and return some ; sort of collection of those ; people who are blood ; relatives of a particular ; person
false
953f469712c74076908ffbb92c904c5a27933d05
3d46fd2cc52b030a2f3cbb9af48a4db73db96010
/assets/examples/shadow-map/blinn-phong-with-shadow.scm
d3db60cef5599a3e9cb3e499551fb2575ca21557
[]
no_license
Shihira/shader-tool
15ec3ec8f6342efbce5529818c2b63713f0b5afc
a701054edddbe147b996739e22bf4eda19bb10a0
refs/heads/master
2020-05-25T20:26:16.904172
2018-02-08T19:16:33
2018-02-08T19:16:33
83,651,827
1
0
null
null
null
null
UTF-8
Scheme
false
false
5,021
scm
blinn-phong-with-shadow.scm
(use-modules (shrtool)) `((name . "blinn-phong-with-shadow") ,shader-def-attr-mesh ,(shader-def-prop-transfrm) ,(shader-def-prop-camera) ,(shader-def-prop-camera #:name "lightCamera" #:prefix "light_") (property-group (name . "illum") (layout (tex2d . "shadowMap") (tex2d . "geometryMap") (float . "sampleOffset") (int . "sampleRadius") (color . "lightColor"))) (property-group (name . "material") (layout (color . "ambientColor") (color . "diffuseColor") (color . "specularColor"))) (sub-shader (type . fragment) (source . " in vec4 fragPosition; in vec3 fragNormal; layout (location = 0) out vec4 outColor; #define BIAS 0.0001 #define E 2.71828182846 #define PI 3.14159265359 void main() { vec4 lightPosition = vec4(light_vMatrix_inv[3].xyz / light_vMatrix_inv[3].w, 1); vec4 cameraPosition = vec4(vMatrix_inv[3].xyz / vMatrix_inv[3].w, 1); vec3 lightDir = normalize((fragPosition - lightPosition).xyz); vec3 viewDir = normalize((fragPosition - cameraPosition).xyz); vec4 light_FragCoord = light_vpMatrix * fragPosition; light_FragCoord /= light_FragCoord.w; vec3 texCoord = light_FragCoord.xyz / 2 + vec3(0.5, 0.5, 0.5); float shadow = 0; float fragDepth = texCoord.z; /* float fragDepth = texCoord.z - BIAS; for(int i = -sampleRadius; i <= sampleRadius; i++) { for(int j = -sampleRadius; j <= sampleRadius; j++) { float shelterDepth = texture(shadowMap, texCoord.xy + vec2(i * sampleOffset, j * sampleOffset)).r; shadow += step(fragDepth, shelterDepth); } } // not proven. practical value. shadow /= pow(sampleRadius * 2 + 1, 2) / 2; shadow = min(shadow + 0.1, 1); */ //fragDepth = exp(fragDepth); vec2 vsm = texture(shadowMap, texCoord.xy).rg; float var = max(vsm.y - vsm.x * vsm.x, 0.00002); float dist = fragDepth - vsm.x; float pmax = var / (var + dist * dist); shadow = pmax;//clamp((pmax - 0.3) / (1 - 0.3), 0, 1); if(fragDepth < vsm.x) shadow = 1; /* float esm = 0; float k = 50; for(int i = -sampleRadius; i <= sampleRadius; i++) { for(int j = -sampleRadius; j <= sampleRadius; j++) { esm += texture(shadowMap, texCoord.xy + vec2(i * sampleOffset, j * sampleOffset)).r; } } esm /= (sampleRadius * 2 + 1) * (sampleRadius * 2 + 1); shadow = pow(E, k * texture(shadowMap, texCoord.xy).r) * pow(E, -k * fragDepth); */ // AO calculation vec4 screenPosition = vpMatrix * fragPosition; vec2 geometryMap_uv = (screenPosition / screenPosition.w).xy / 2 + vec2(0.5, 0.5); float occ_factor = 0; /* float r = 0.001; float a = 0.5; for(int i = 0; i <= 50; i++) { vec2 off = vec2(r * cos(a), r * sin(a)); vec3 nml = texture(geometryMap, geometryMap_uv + off).xyz; float dpth = texture(geometryMap, geometryMap_uv + off).w; occ_factor += max(0, (-dot(nml, fragNormal) + 0.1) * (1 / (1 + abs(dpth - fragPosition.z)))); r *= 1.1; a += 0.77; } */ for(float i = -4 * sampleOffset; i <= 4 * sampleOffset; i += sampleOffset) for(float j = -4 * sampleOffset; j <= 4 * sampleOffset; j += sampleOffset) { vec2 off = vec2(i, j); vec3 nml = texture(geometryMap, geometryMap_uv + off).xyz; float dpth = texture(geometryMap, geometryMap_uv + off).w; occ_factor += max(0, (-dot(nml, fragNormal) + 0.1) * (1 / (1 + abs(dpth - fragPosition.z)))); } occ_factor /= 8; float intAmbient = max(0, 1 - occ_factor); float intDiffuse = dot(-fragNormal, lightDir); float intSpecular = dot(-fragNormal, normalize(lightDir + viewDir)); intDiffuse = max(intDiffuse, 0) * shadow; intSpecular = pow(intSpecular, 3); intSpecular = max(intSpecular, 0) * shadow; outColor = ambientColor * intAmbient + diffuseColor * intDiffuse + specularColor * intSpecular; }")) (sub-shader (type . vertex) (source . " out vec4 fragPosition; out vec3 fragNormal; void main() { fragNormal = (transpose(mMatrix_inv) * vec4(normal, 0)).xyz; fragNormal = normalize(fragNormal); gl_Position = vpMatrix * mMatrix * position; fragPosition = mMatrix * position; fragPosition /= fragPosition.w; }")))
false
0ea0148db17cd2fa30be9acad0ddd6c7f5d6128e
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch4/4.70.scm
5ba185027b9b6d153e6b7888701aa4602772a85b
[]
no_license
lythesia/sicp-sol
e30918e1ebd799e479bae7e2a9bd4b4ed32ac075
169394cf3c3996d1865242a2a2773682f6f00a14
refs/heads/master
2021-01-18T14:31:34.469130
2019-10-08T03:34:36
2019-10-08T03:34:36
27,224,763
2
0
null
null
null
null
UTF-8
Scheme
false
false
465
scm
4.70.scm
;; `THE-ASSERTIONS` in `(cons-stream assertion THE-ASSERTIONS)` is not even evaluated(即便作为实际参数, 他仍然 ;; 没有被 eval), so when this part gets evaluated acturally(e.g: in some stream-cdr), it finds itself ;; `(cons-stream assertion THE-ASSERTIONS)`, in stream-car it produce assertion, and in stream-cdr it once again ;; find itself cons-steam, which is inf loop. ;; ;; just like (define ones (cons-stream 1 ones)), it's an inf repeat stream.
false
941ba712ebacba269a577a79dada907be8bd2b74
b8034221175e02a02307ef3efef129badecda527
/tests/doc-properties.scm
edcbda1e95686a49a20d4c66fb9d01ba3385eb8d
[]
no_license
nobody246/xlsxWriterScm
ded2410db122dfbe8bbb5e9059239704ee9a5b32
d02ed10c3e8c514cc1b6a9eaf793a2cde34c4c47
refs/heads/master
2022-04-27T23:29:45.258892
2022-04-15T22:04:02
2022-04-15T22:04:02
153,357,109
0
1
null
null
null
null
UTF-8
Scheme
false
false
601
scm
doc-properties.scm
(use xlsxwriterscm) (create-workbook "doc-properties.xlsx") (add-worksheet "") (set-doc-properties "This is an example spreadsheet" "With document properties" "Alex S" "Dr. Heinz Doofenshmirtz" "of Wolves" "Example spreadsheets" "Sample, Example, Properties" "Created with libxlsxwriter & xlsxwriterscm" "Quo") (worksheet-set-column 50 0 0) (worksheet-write-string "Select 'Workbook Properties' to see properties.") (close-workbook) (exit)
false
67a93933d20b6d75747b37fca558efd1be2dd91f
9046fb7fa896d41aecd0f98c8cdd26447ccf9a1a
/product-cps.ss
798af0b073b95a0fd6e1210131a918a81761f18a
[]
no_license
Joycexuy2/CSSE304
25743e01c1fb7e743ba0a83145872517229617b5
6e405e5a277ad14228d031d9fcbdc54325e9a88a
refs/heads/master
2021-01-11T06:59:53.372832
2016-10-25T22:27:11
2016-10-25T22:27:11
71,944,384
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,166
ss
product-cps.ss
(define product-cps (lambda (x y k) (if (null? y) (apply-continuation k '()) (let loop ([x x] [accum '()]) (if (null? x) (apply-continuation k accum) (loop (cdr x) (map-cps (lambda (s) (list (car x) s)) y (lambda (v) (append-cps v accum k))))))))) (define product-cps (lambda (x y k) (if (null? y) (apply-continuation k '()) (product-cps x (cdr y) (lambda (cdr-y) (combine-cps (car y) x (lambda (one-y) (append-cps one-y cdr-y k)))))))) (define combine-cps (lambda (item ls k) (if (null? ls) (apply-continuation k ls) (combine-cps item (cdr ls) (lambda (combined-cdr) (append-cps (list (list item (car ls))) combined-cdr k)))))) (define apply-continuation (lambda (k . v) (apply k v))) (define map-cps (lambda (proc-cps ls k) (cond [(null? ls) (apply-continuation k '())] [else (map-cps proc-cps (cdr ls) (lambda (cdr-ls) (proc-cps (car ls) (lambda (result) (apply-continuation k (cons result cdr-ls))))))]))) (define loop-cps (lambda (setX setY proc k) (if (null? setX) (apply-continuation k setY) (d)
false
7a3431dbe547707802649500ec578cd9e29f9797
2f88dd127122c2444597a65d8b7a23926aebbac1
/define-structure.scm
47b64b47ba18a2b299b80953ce816285158fa6b1
[ "BSD-2-Clause" ]
permissive
KenDickey/Crosstalk
6f980b7188c1cc6bd176a8e0cd10b032f768b4e6
b449fb7c711ad287f9b49e7167d8cedd514f5d81
refs/heads/master
2023-05-26T10:07:12.674162
2023-05-21T22:59:26
2023-05-21T22:59:26
58,777,987
11
1
null
null
null
null
UTF-8
Scheme
false
false
2,203
scm
define-structure.scm
(import (rnrs syntax-case)) ;; (define-structure (name field ...)) ;; (name field ...) --> structure w constructor 'name ;; (define-structure (Block args temps seq)) ;; (define b (Block '(1 2) '(a b) '((1)(2)(3)))) ;; (Block-args b) --> (1 2) ;; (Block-seq b) --> ((1) (2) (3)) ;; b --> #(Block (1 2) (a b) ((1) (2) (3))) ;; This is an altered form of an example in ;; _The Scheme Programming Language_, 4th Ed. ;; by R Kent Dyvbig (define-syntax define-structure (lambda (x) (define gen-id (lambda (template-id . args) (datum->syntax template-id (string->symbol (apply string-append (map (lambda (x) (if (string? x) x (symbol->string (syntax->datum x)))) args)))))) (syntax-case x () [(_ (name field ...)) (with-syntax ([constructor #'name] [predicate (gen-id #'name #'name "?")] [(access ...) (map (lambda (x) (gen-id x #'name "-" x)) #'(field ...))] [(assign ...) (map (lambda (x) (gen-id x "set-" #'name "-" x "!")) #'(field ...))] [structure-length (+ (length #'(field ...)) 1)] [(index ...) (let f ([i 1] [ids #'(field ...)]) (if (null? ids) '() (cons i (f (+ i 1) (cdr ids)))))]) #'(begin (define constructor (lambda (field ...) (vector 'name field ...))) (define predicate (lambda (x) (and (vector? x) (= (vector-length x) structure-length) (eq? (vector-ref x 0) 'name)))) (define access (lambda (x) (vector-ref x index))) ... (define assign (lambda (x update) (vector-set! x index update))) ...))]))) ;;; --- E O F --- ;;;
true
fa9d1f5d9a23e20a060d7f4072111541ffe591ba
ecfd9ed1908bdc4b099f034b121f6e1fff7d7e22
/old1/sicp/2/p41.scm
bfd6bdbc6f7ff015d693f1527d303a898243bd44
[ "MIT" ]
permissive
sKabYY/palestra
36d36fc3a03e69b411cba0bc2336c43b3550841c
06587df3c4d51961d928bd8dd64810c9da56abf4
refs/heads/master
2021-12-14T04:45:20.661697
2021-11-25T08:29:30
2021-11-25T08:29:30
12,856,067
6
3
null
null
null
null
UTF-8
Scheme
false
false
397
scm
p41.scm
(load "lib.scm") (define (unique-3-tuple n) (flatmap (lambda (k) (map (lambda (p) (list (car p) (cadr p) k)) (unique-pairs (- k 1)))) (enumerate-interval 1 n))) (define (sum-s n s) (define (sum-equal-s? tuple) (= s (+ (car tuple) (cadr tuple) (caddr tuple)))) (filter sum-equal-s? (unique-3-tuple n))) (display (sum-s 6 10)) (newline)
false
93cbd6474d9e4a7287323fca01656602a5e823ab
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-02/ex2.83-falsetru.scm
0d5dd37f3b73a4ab8cd8a58844c2f9d57de8ed8b
[]
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
236
scm
ex2.83-falsetru.scm
(load "ex2.77-falsetru.scm") (define (raise x) (apply-generic 'raise x)) (put 'raise '(scheme-number) (lambda (n) (make-rational n 1))) (put 'raise '(rational) (lambda (r) (make-complex-from-real-imag (/ (numer r) (denom r)) 0)))
false
fe405685dd5f31119df65f8f05e8e24dd94505cc
d81bc497716f0c1b4793148c2325ec6e94922e97
/reflect.scm
9aea59cd79c844e2197a66b64cf7a3a2a37e1814
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jar398/w7
96a78817bdcfc346a2587955f46419c705366aa4
801e268c44f68845f2ac0ed9ddd87dd37a35944d
refs/heads/master
2021-01-10T08:53:34.561395
2019-12-24T03:32:46
2019-12-24T03:32:46
48,116,337
11
0
null
null
null
null
UTF-8
Scheme
false
false
350
scm
reflect.scm
; Kludge... would be better if no reference to command processor (define innocuous-features (environment-ref (config-package) 'innocuous-features)) (define usual-w7-features (environment-ref (config-package) 'usual-w7-features)) ; Innocuous environment (define innocuous-environment (make-simple-package (list innocuous-features) #t #f))
false
082d776b6e9bb82b93e2071fd50ad36adabd1025
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/test/tests/text/xml/dom/writer.scm
0ced5423912536747da2ddfa7984a0f3442a5b5a
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
6,771
scm
writer.scm
(import (rnrs) (text xml dom writer) (text xml dom nodes) (text xml dom factory) (srfi :1) (srfi :64)) (test-begin "DOM writer") (define (writer-test expected proc) (let-values (((out extract) (open-string-output-port))) (test-equal expected (begin (proc out) (extract))))) ;; historical reason... (define legazy-options (xml-write-options-builder (omit-xml-declaration? #f) (standalone? #f))) (define xml-writer (make-dom-writer legazy-options)) (writer-test "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n\ <foo:foo xmlns:foo=\"urn:foo\" foo:buz=\"buzzz\" foo:bla=\"blabla\">\ <foo:bar/>\ </foo:foo>" (lambda (out) (let* ((document (make-xml-document)) (e (document:create-element-ns document "urn:foo" "foo:foo"))) (node:append-child! document e) (element:set-attribute-ns! e "urn:foo" "foo:bla" "blabla") (element:set-attribute! e "foo:buz" "buzzz") (node:append-child! e (document:create-element-ns document "urn:foo" "foo:bar")) (xml-writer document out)))) ;; it's rather weird to put here to test insert/replace node but ;; it's easier to do it here. (let* ((document (make-xml-document)) (e (document:create-element document "foo"))) (node:append-child! document e) (node:insert-before! document e (document:create-comment document "boo")) (let ((e2 (document:create-element document "foo2")) (e3 (document:create-element document "foo3")) (e4 (document:create-element document "foo4")) (e5 (document:create-element document "foo5"))) (node:append-child! e e2) (node:insert-before! e e2 e3) (node:insert-before! e e2 e4) (node:insert-before! e #f e5) (writer-test "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n\ <!--boo-->\n\ <foo><foo3/><foo4/><foo2/><foo5/></foo>" (lambda (out)(xml-writer document out))) (node:replace-child! e e5 (document:create-element document "foo6")) (writer-test "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n\ <!--boo-->\n\ <foo><foo3/><foo4/><foo2/><foo6/></foo>" (lambda (out)(xml-writer document out))) (node:remove-child! e e2) (writer-test "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n\ <!--boo-->\n\ <foo><foo3/><foo4/><foo6/></foo>" (lambda (out)(xml-writer document out))) )) ;; canonicalisation (define c14n-write (make-dom-writer *xml:c14n*)) (define c14n/comment-write (make-dom-writer *xml:c14n-w/comment*)) (define input-section-3.1 "<?xml version=\"1.0\"?> <?xml-stylesheet href=\"doc.xsl\" type=\"text/xsl\" ?> <!DOCTYPE doc SYSTEM \"doc.dtd\"> <doc>Hello, world!<!-- Comment 1 --></doc> <?pi-without-data ?> <!-- Comment 2 --> <!-- Comment 3 -->") (define input-section-3.2 "<doc> <clean> </clean> <dirty> A B </dirty> <mixed> A <clean> </clean> B <dirty> A B </dirty> C </mixed> </doc>") (define input-section-3.3 "<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]> <doc> <e1 /> <e2 ></e2> <e3 name = \"elem3\" id=\"elem3\" /> <e4 name=\"elem4\" id=\"elem4\" ></e4> <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I'm\" xmlns:b=\"http://www.ietf.org\" xmlns:a=\"http://www.w3.org\" xmlns=\"http://example.org\"/> <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\"> <e7 xmlns=\"http://www.ietf.org\"> <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\"> <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/> </e8> </e7> </e6> </doc>") (define input-section-3.4 "<!DOCTYPE doc [ <!ATTLIST normId id ID #IMPLIED> <!ATTLIST normNames attr NMTOKENS #IMPLIED> ]> <doc> <text>First line&#x0d;&#10;Second line</text> <value>&#x32;</value> <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute> <compute expr='value>\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"'>valid</compute> <norm attr=' &apos; &#x20;&#13;&#xa;&#9; &apos; '/> <normNames attr=' A &#x20;&#13;&#xa;&#9; B '/> <normId id=' &apos; &#x20;&#13;&#xa;&#9; &apos; '/> </doc>") ;; we don't handle SYSTEM entity #;(define input-section-3.5 "<!DOCTYPE doc [ <!ATTLIST doc attrExtEnt ENTITY #IMPLIED> <!ENTITY ent1 \"Hello\"> <!ENTITY ent2 SYSTEM \"world.txt\"> <!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif> <!NOTATION gif SYSTEM \"viewgif.exe\"> ]> <doc attrExtEnt=\"entExt\"> &ent1;, &ent2;! </doc> <!-- Let world.txt contain \"world\" (excluding the quotes) -->") (define input-section-3.6 "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><doc>&#169;</doc>") (define (string->dom s) (input-port->dom-tree (open-string-input-port s))) (define (test-canonicalization writer input expect) (let-values (((out e) (open-string-output-port))) (writer (string->dom input) out) (let ((r (e))) (unless (string=? expect r) (display expect) (newline) (display r) (newline)) (test-equal input expect r)))) (test-canonicalization c14n-write input-section-3.1 "<?xml-stylesheet href=\"doc.xsl\" type=\"text/xsl\" ?> <doc>Hello, world!</doc> <?pi-without-data?>") (test-canonicalization c14n/comment-write input-section-3.1 "<?xml-stylesheet href=\"doc.xsl\" type=\"text/xsl\" ?> <doc>Hello, world!<!-- Comment 1 --></doc> <?pi-without-data?> <!-- Comment 2 --> <!-- Comment 3 -->") (test-canonicalization c14n-write input-section-3.2 "<doc> <clean> </clean> <dirty> A B </dirty> <mixed> A <clean> </clean> B <dirty> A B </dirty> C </mixed> </doc>") (test-canonicalization c14n-write input-section-3.3 "<doc> <e1></e1> <e2></e2> <e3 id=\"elem3\" name=\"elem3\"></e3> <e4 id=\"elem4\" name=\"elem4\"></e4> <e5 xmlns=\"http://example.org\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I'm\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5> <e6 xmlns:a=\"http://www.w3.org\"> <e7 xmlns=\"http://www.ietf.org\"> <e8 xmlns=\"\"> <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9> </e8> </e7> </e6> </doc>") (test-canonicalization c14n-write input-section-3.4 "<doc> <text>First line&#xD; Second line</text> <value>2</value> <compute>value&gt;\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"</compute> <compute expr=\"value>&quot;0&quot; &amp;&amp; value&lt;&quot;10&quot; ?&quot;valid&quot;:&quot;error&quot;\">valid</compute> <norm attr=\" ' &#xD;&#xA;&#x9; ' \"></norm> <normNames attr=\"A &#xD;&#xA;&#x9; B\"></normNames> <normId id=\"' &#xD;&#xA;&#x9; '\"></normId> </doc>") (test-end)
false
320976906b6b6ac8c51e65bc0f2404211bc978e5
b8c57f31ad241eb9ce17678725921cb0fba65db9
/test/test.scm
2acb7f69f95f0e0689c2cfb8cb97e38aa7e7d00e
[]
no_license
AtsukiYokota/meevax
130ab5cb892ae7399970a7d421c4cc96df1e8388
2781b4277b436fdbf85174830b477a07688c1ce1
refs/heads/master
2020-12-09T23:43:20.633092
2019-11-22T23:34:07
2019-11-22T23:34:07
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
15,749
scm
test.scm
(load "../test/expect.scm") ; ------------------------------------------------------------------------------ ; 4.1.1 Variable References ; ------------------------------------------------------------------------------ (define x 28) (expect 28 x) ; ------------------------------------------------------------------------------ ; 4.1.2 Literal Expressions ; ------------------------------------------------------------------------------ (expect a (quote a)) ; (expect ; #(a b c) ; (quote #(a b c))) ; unimplemented (expect (+ 1 2) (quote (+ 1 2))) (expect a 'a) ; (expect ; #(a b c) ; '#(a b c)) ; unimplemented (expect () '()) (expect (+ 1 2) '(+ 1 2)) (expect (quote a) '(quote a)) (expect (quote a) ''a) (expect 145932 '145932) (expect 145932 145932) ; (expect "abc" '"abc") ; (expect "abc" "abc") ; マクロ中で文字列の挙動がおかしいバグあり ; (expect # '#) ; (expect # #) ; unimplemented ; (expect #(a 10) '#(a 10)) ; (expect #(a 10) #(a 10)) ; unimplemented ; (expect #u8(64 65) '#u8(64 65)) ; (expect #u8(64 65) #u8(64 65)) ; unimplemented (expect #t '#t) (expect #t #t) ; ------------------------------------------------------------------------------ ; 4.1.3 Procedure Calls ; ------------------------------------------------------------------------------ (expect 7 (+ 3 4)) (expect 12 ((if #false + *) 3 4)) ; ------------------------------------------------------------------------------ ; 4.1.4 Procedures ; ------------------------------------------------------------------------------ ; (lambda (x) (+ x x)) ; untestable output (expect 8 ((lambda (x) (+ x x)) 4)) (define reverse-subtract (lambda (x y) (- y x))) (expect 3 (reverse-subtract 7 10)) (define add4 (let ((x 4)) (lambda (y) (+ x y)))) (expect 10 (add4 6)) (expect (3 4 5 6) ((lambda x x) 3 4 5 6)) (expect (5 6) ((lambda (x y . z) z) 3 4 5 6)) ; ------------------------------------------------------------------------------ ; 4.1.5 Conditionals ; ------------------------------------------------------------------------------ (expect yes (if (> 3 2) 'yes 'no)) (expect no (if (> 2 3) 'yes 'no)) (expect 1 (if (> 3 2) (- 3 2) (+ 3 2))) ; ------------------------------------------------------------------------------ ; 4.1.6 Assignments ; ------------------------------------------------------------------------------ (define x 2) (expect 3 (+ x 1)) (set! x 4) ; #unspecified (expect 5 (+ x 1)) ; ------------------------------------------------------------------------------ ; 4.2.1 Conditionals ; ------------------------------------------------------------------------------ (expect greater (cond ((> 3 2) 'greater) ((< 3 2) 'less))) (expect equal (cond ((> 3 3) 'greater) ((< 3 3) 'less) (else 'equal))) ; (expect ; (cond ((assv 'b '((a 1) (b 2))) => cadr) ; (else #f)) ; 2) (expect composite (case (* 2 3) ((2 3 5 7) 'prime) ((1 4 6 8 9) 'composite))) ; (expect ; (case (car '(c d)) ; ((a) 'a) ; ((b) 'b)) ; undefined) ; (expect ; (case (car '(c d)) ; ((a e i o u) 'vowel) ; ((w y) 'semivowel) ; (else => (lambda (x) x))) ; c) (expect #true (and (= 2 2) (> 2 1))) (expect #false (and (= 2 2) (< 2 1))) (expect (f g) (and 1 2 'c '(f g))) (expect #true (and)) (expect #true (or (= 2 2) (> 2 1))) (expect #true (or (= 2 2) (< 2 1))) (expect #false (or #false #false #false)) ; (expect ; (or (memq 'b '(a b c)) ; memq unimplemented ; (/ 3 0)) ; (b c)) ; (when (= 1 1.0) ; (display "1") ; (display "2")); => #unspecified and prints 12 ; (unless (= 1 1.0) ; (display "1") ; (display "2")); => #unspecified and prints nothing ; ------------------------------------------------------------------------------ ; 4.2.2 Binding Constructs ; ------------------------------------------------------------------------------ (expect 6 (let ((x 2) (y 3)) (* x y))) (expect 35 (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x)))) (expect 70 (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x)))) (expect 3628800 (letrec ((factorial (lambda (n) (if (zero? n) 1 (* n (factorial (- n 1))))))) (factorial 10))) (expect #true (letrec ((even? (lambda (n) (if (zero? n) #true (odd? (- n 1))))) (odd? (lambda (n) (if (zero? n) #false (even? (- n 1)))))) (even? 88))) ; ------------------------------------------------------------------------------ ; 4.2.3 Sequencing ; ------------------------------------------------------------------------------ (define x 0) (expect 6 (and (= x 0) (begin (set! x 5) (+ x 1)))) (begin (display "4 plus 1 equals ") (display (+ 4 1))) ; ------------------------------------------------------------------------------ ; 4.2.4 Iteration ; ------------------------------------------------------------------------------ ; (expect ; (do ((vec (make-vector 5)) ; (i 0 (+ i 1))) ; ((= i 5) vec) ; (vector-set! vec i i)) ; #(0 1 2 3 4)) (expect 25 (let ((x '(1 3 5 7 9))) (do ((x x (cdr x)) (sum 0 (+ sum (car x)))) ((null? x) sum)))) ; ------------------------------------------------------------------------------ ; 4.2.5 Delayed Evaluation ; ------------------------------------------------------------------------------ ; ------------------------------------------------------------------------------ ; 4.2.6 Dynamic Bindings ; ------------------------------------------------------------------------------ ; ------------------------------------------------------------------------------ ; 4.2.7 Exception Handling ; ------------------------------------------------------------------------------ ; ------------------------------------------------------------------------------ ; 4.2.8 Quasiquotation ; ------------------------------------------------------------------------------ (expect (list 3 4) `(list ,(+ 1 2) 4)) (expect (list a (quote a)) (let ((name 'a)) `(list ,name ',name))) ; (expect ; `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b) ; abs unimplemented ; (a 3 4 5 6 b)) (expect ((foo 7) . cons) `((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons)))) ; (expect ; `#(10 5 ,(sqrt 4) ,@(map sqrt '(16 9)) 8) ; #(10 5 2 4 3 8)) (expect (list foo bar baz) (let ((foo '(foo bar)) (@baz 'baz)) `(list ,@foo , @baz))) ; (expect ; `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f) ; (a `(b ,(+ 1 2) ,(foo 4 d) e) f)) ; (expect ; (let ((name1 'x) ; (name2 'y)) ; `(a `(b ,,name1 ,',name2 d) e)) ; (a `(b ,x ,'y d) e)) ; ------------------------------------------------------------------------------ ; 4.2.9 Case-Lambda ; ------------------------------------------------------------------------------ ; ------------------------------------------------------------------------------ ; 4.3.1 Binding Constructs for Syntactic Keywords ; ------------------------------------------------------------------------------ ; ------------------------------------------------------------------------------ ; 4.3.2 Pattern Language ; ------------------------------------------------------------------------------ ; ------------------------------------------------------------------------------ ; 4.3.3 Signaling Errors in Macro Transformers ; ------------------------------------------------------------------------------ ; ------------------------------------------------------------------------------ ; 5.3.1 Top Level Definitions ; ------------------------------------------------------------------------------ (define add3 (lambda (x) (+ x 3))) (expect 6 (add3 3)) (define first car) (expect 1 (first '(1 2))) ; ------------------------------------------------------------------------------ ; 5.3.2 Internal Definitions ; ------------------------------------------------------------------------------ (expect 45 (let ((x 5)) (define foo (lambda (y) (bar x y))) (define bar (lambda (a b) (+ (* a b) a))) (foo (+ x 3)))) (expect 45 (let ((x 5)) (letrec* ((foo (lambda (y) (bar x y))) (bar (lambda (a b) (+ (* a b) a)))) (foo (+ x 3))))) ; ------------------------------------------------------------------------------ ; 6.1 Equivalence Predicates ; ------------------------------------------------------------------------------ (expect #true (eqv? 'a 'a)) (expect #false (eqv? 'a 'b)) (expect #true (eqv? '() '())) (expect #true (eqv? 2 2)) ; (expect ; unimplemented ; (eqv? 2 2.0) ; #false) (expect #true (eqv? 100000000 100000000)) ; (expect ; unimplemented ; (eqv? 0.0 +nan.0) ; #false) (expect #false (eqv? (cons 1 2) (cons 1 2))) (expect #false (eqv? (lambda () 1) (lambda () 2))) (expect #true (let ((p (lambda (x) x))) (eqv? p p))) (expect #false (eqv? #false 'nil)) ; (eqv? "" ""); unspecified ; (eqv? '#() '#()); #unspecified ; (eqv? (lambda (x) x) ; (lambda (x) x)); #unspecified ; (eqv? (lambda (x) x) ; (lambda (x) y)); #unspecified ; (eqv? 1.0e0 1.0f0); #unspecified ; (eqv? +nan.0 +nan.0); #unspecified (define generate-counter (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) n)))) (expect #true (let ((g (generate-counter))) (eqv? g g))) (expect #false (eqv? (generate-counter) (generate-counter))) (define generate-loser (lambda () (let ((n 0)) (lambda () (set! n (+ n 1)) 27)))) (expect #true (let ((g (generate-loser))) (eqv? g g))) ; (eqv? (generate-loser) (generate-loser)); #unspecified ; (letrec ((f (lambda () (if (eqv? f g) 'both 'f))) ; (g (lambda () (if (eqv? f g) 'both 'g)))) ; (eqv? f g)); #unspecified (expect #false (letrec ((f (lambda () (if (eqv? f g) 'f 'both))) (g (lambda () (if (eqv? f g) 'g 'both)))) (eqv? f g))) ; (eqv? '(a) '(a)); #unspecified ; (eqv? "a" "a"); #unspecified ; (eqv? '(b) (cdr '(a b))); #unspecified (expect #true (let ((x '(a))) (eqv? x x))) (expect #true (eq? 'a 'a)) ; (eq? '(a) '(a)); #unspecified (expect #false (eq? (list 'a) (list 'a))) ; (eq? "a" "a"); #unspecified ; (eq? "" ""); #unspecified (expect #true (eq? '() '())) ; (eq? 2 2); #unspecified ; (eq? #\A #\A); #unspecified (expect #true (eq? car car)) ; (let ((n (+ 2 3))) ; (eq? n n)); #unspecified (expect #true (let ((x '(a))) (eq? x x))) ; (expect ; (let ((x '#())) ; #unimplemented ; (eq? x x)) ; #true) (expect #true (let ((p (lambda (x) x))) (eq? p p))) (expect #true (equal? 'a 'a)) (expect #true (equal? '(a) '(a))) (expect #true (equal? '(a (b) c) '(a (b) c))) ; (expect ; (equal? "abc" ; "abc") ; not fully supported yet ; #true) (expect #true (equal? 2 2)) ; (equal? (make-vector 5 'a) ; (make-vector 5 'a)); #true ; ; (equal? '#1=(a b . #1#) ; '#2=(a b a b . #2#)); #true ; ; (equal? (lambda (x) x) ; (lambda (y) y)); #unspecified ; ------------------------------------------------------------------------------ ; 6.4 Pair and List ; ------------------------------------------------------------------------------ (expect (a b c d e) '(a . (b . (c . (d . (e . ())))))) (expect (a b c . d) '(a . (b . (c . d)))) (expect (3 3) (make-list 2 3)) (expect (a 7 c) (list 'a (+ 3 4) 'c)) (expect () (list)) (expect 3 (length '(a b c))) (expect 3 (length '(a (b) (c d e)))) (expect 0 (length '())) (expect (x y) (append '(x) '(y))) (expect (a b c d) (append '(a) '(b c d))) (expect (a (b) (c)) (append '(a (b)) '((c)))) (expect (a b c . d) (append '(a b) '(c . d))) (expect a (append '() 'a)) (expect (c b a) (reverse '(a b c))) (expect ((e (f)) d (b c) a) (reverse '(a (b c) d (e (f))))) (expect c (list-ref '(a b c d) 2)) ; (expect c ; (list-ref '(a b c d) ; (exact (round 1.8)))) (expect (a b c) (memq 'a '(a b c))) (expect (b c) (memq 'b '(a b c))) (expect #false (memq 'a '(b c d))) (expect #false (memq (list 'a) '(b (a) c))) (expect ((a) c) (member (list 'a) '(b (a) c))) ; (expect ("B" "C") ; (member "B" '("a" "b" "c") string-ci=?)) (expect #false ; #unspecified (memq 101 '(100 101 102))) (expect (101 102) (memv 101 '(100 101 102))) (define e '((a 1) (b 2) (c 3))) (expect (a 1) (assq 'a e)) (expect (b 2) (assq 'b e)) (expect #false (assq 'd e)) (expect #false (assq (list 'a) '(((a)) ((b)) ((c))))) (expect ((a)) (assoc (list 'a) '(((a)) ((b)) ((c))))) (expect (2 4) (assoc 2.0 '((1 1) (2 4) (3 9)) =)) (expect #false ; unspecified (assq 5 '((2 3) (5 7) (11 13)))) (expect (5 7) (assv 5 '((2 3) (5 7) (11 13)))) ; ------------------------------------------------------------------------------ ; 6.10 Control Features ; ------------------------------------------------------------------------------ (expect 7 (apply + (list 3 4))) (define compose (lambda (f g) (lambda args (f (apply g args))))) ; (expect 30 ; ((compose sqrt *) 12 75)) (expect (b e h) (map cadr '((a b) (d e) (g h)))) ; (expect (1 4 27 256 3125) ; (map (lambda (n) ; (expt n n)) ; '(1 2 3 4 5))) (expect (5 7 9) (map + '(1 2 3) '(4 5 6 7))) (expect (1 2) ; or (2 1) (let ((count 0)) (map (lambda (ignored) (set! count (+ count 1)) count) '(a b)))) (expect -3 (call-with-current-continuation (lambda (exit) (for-each (lambda (x) (if (negative? x) (exit x))) '(54 0 37 -3 245 19)) #false))) (define list-length (lambda (object) (call-with-current-continuation (lambda (return) (letrec ((r (lambda (object) (cond ((null? object) 0) ((pair? object) (+ (r (cdr object)) 1)) (else (return #false)))))) (r object)))))) (expect 4 (list-length '(1 2 3 4))) (expect #false (list-length '(a b . c))) (expect 5 (call-with-values (lambda () (values 4 5)) (lambda (a b) b))) (expect -1 (call-with-values * -)) ; ------------------------------------------------------------------------------ ; Miscellaneous ; ------------------------------------------------------------------------------ (define x 42) (expect 42 x) (set! x 100) (expect 100 x) (define y 'hoge) (expect hoge y) (set! y 100) (expect 100 y) (define accumulator (lambda (n) (lambda () (set! n (+ n 1))))) (define acc (accumulator x)) (expect 101 (acc)) (expect 102 (acc)) (expect 103 (acc)) (define a 1) (define b 2) (expect (2 . 1) (begin (swap! a b) (cons a b))) (define x 42) (expect (42 . 2) ; this test knows swap! uses 'x' as temporary variable. (begin (swap! a x) (cons a x))) ; (define fib ; (lambda (n) ; (if (< n 2) n ; (+ (fib (- n 1)) ; (fib (- n 2)))))) ; ; (define fib-i ; (lambda (n) ; (if (< n 2) ; (values 1 1) ; (reverive (current previous) ; (fib-i (- n 1)) ; (values (+ current previous) current))))) ; ; (fib 20) (begin (newline) (display "test ") (display passed) (display " expression passed (completed).") (newline))
false
a32eb09d848f3926341d669796b7e2d6e17cad65
29ea7c27a13dfcd0c7273619d0d915442298764f
/lib/hpdf/doc.scm
80d040cbefa2edf91fdc9c8f1100f0f71aa2ac3b
[]
no_license
kenhys/gauche-hpdf
f637fc85a9a54a8112913b348daa8e04aecebb9b
d0993ead47cceaaee2e0ca2ac57df7964ddcb720
refs/heads/master
2016-09-05T16:54:09.776801
2012-08-19T15:17:50
2012-08-19T15:17:50
3,368,344
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,109
scm
doc.scm
;;; ;;; hpdf ;;; (define-module hpdf.doc (extend hpdf) (use gauche.interactive) (export-all) ) (select-module hpdf.doc) ;; Loads extension (dynamic-load "gauche--hpdf") ;; ;; Put your Scheme definitions here ;; (define-method version () (hpdf-get-version)) (define-method version! ((self <hpdf-doc>) ver) (hpdf-set-version self ver)) ;; TODO ;;(define-method new-ex () ;; ()) ;; TODO ;;(define-method error-handler! () ;; ()) (define-method free ((self <hpdf-doc>)) (hpdf-free self)) (define-method new-doc ((self <hpdf-doc>)) (hpdf-new-doc self)) (define-method free-doc ((self <hpdf-doc>)) (hpdf-free-doc self)) (define-method has-doc ((self <hpdf-doc>)) (hpdf-has-doc self)) (define-method free-doc-all ((self <hpdf-doc>)) (hpdf-free-doc-all self)) (define-method save-to-stream ((self <hpdf-doc>)) (hpdf-save-to-stream self)) ;; TODO ;; hpdf-get-contents (define-method stream-size ((self <hpdf-doc>)) (hpdf-get-stream-size self)) (define-method save-to-file ((self <hpdf-doc>) filename) (hpdf-save-to-file self filename)) ;; Epilogue (provide "hpdf/doc")
false
b90d2b370505bb4cd199d176ecd7ada0b79d03c6
6eaa87ed57fab28bb4b3b95a1aa721978947f3ec
/spec/lib/lambda-spec.scm
9a8a67497417dba5e56b595824876329327296a8
[ "MIT" ]
permissive
seven1m/scheme-vm
d8b28d79faf400e260c445c2e72aaf2a78182c92
00cdee125690429c16b1e5b71b180a6899ac6a58
refs/heads/master
2021-01-21T16:53:03.742073
2018-04-17T01:06:45
2018-04-17T01:06:45
27,324,674
9
0
null
null
null
null
UTF-8
Scheme
false
false
392
scm
lambda-spec.scm
(import (scheme base) (assert)) (define fixed-args (lambda (x y z) (list x y z))) (define variable-args (lambda args args)) (define rest-args (lambda (x y . rest) (list x y rest))) (assert (equal? (list 1 2 3) (fixed-args 1 2 3))) (assert (equal? (list 1 2 3) (variable-args 1 2 3))) (assert (equal? (list 1 2 (list 3 4)) (rest-args 1 2 3 4)))
false
1b017752332ef20514f9922cd7b8c60add4334b7
a938b2b8a309a4fb1cf97b18add5cd420e726f01
/test/runnertest.scm
289fc4728c363b559b165d12684fbfeed11dc7e7
[]
no_license
aj07mm/scmUnit
d5da096bccf26e1627e6a2bac6c408813c05f747
6b76cc02395570de17a372b03842cd9d9dcbd0d6
refs/heads/master
2020-07-29T16:12:11.865484
2013-02-09T14:19:20
2013-02-09T14:19:20
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,200
scm
runnertest.scm
;;;; -------------------------------------------------------------------------- ;;;; scmUnit ;;;; Nicholas Russell ;;;; -------------------------------------------------------------------------- ;;;; runnertest.scm ;;;; runner tests ;;;; -------------------------------------------------------------------------- (assert-true (scmunit:test-passed? scmunit:test-pass)) (assert-false (scmunit:test-passed? scmunit:test-fail)) (assert-false (scmunit:test-passed? scmunit:test-error)) (assert-true (scmunit:test-failed? scmunit:test-fail)) (assert-false (scmunit:test-failed? scmunit:test-pass)) (assert-false (scmunit:test-failed? scmunit:test-error)) (assert-true (scmunit:test-error? scmunit:test-error)) (assert-false (scmunit:test-error? scmunit:test-pass)) (assert-false (scmunit:test-error? scmunit:test-fail)) (let ((failure (call-capture-errors (lambda () (assertion-failure "failure msg")))) (err (call-capture-errors (lambda () (error "error msg"))))) (assert-eq 'fail (scmunit:evaluate-test-result failure)) (assert-eq 'error (scmunit:evaluate-test-result err)) (assert-eq 'pass (scmunit:evaluate-test-result #t)) (assert-eq 'pass (scmunit:evaluate-test-result '())) )
false
dde2a7e282b7959d1c63ca3ce58cdb3de2d910e9
81788f723d53fa098f2fce87d4d022dc78aaa68c
/chap-3/3-42.scm
45bb441049ed89b0e32ed81f699d62145121554b
[]
no_license
docmatrix/sicp
01ef2028b1fde0c035e4fa49106d2e07b4baf42d
c7f1214bdd6da23ef8edb0670b61cdb222147674
refs/heads/master
2020-12-24T06:44:10.783386
2017-11-28T17:03:09
2017-11-28T17:03:09
58,923,881
0
0
null
null
null
null
UTF-8
Scheme
false
false
207
scm
3-42.scm
; I'm guessing that it means that the withdraw calls could interleave as they ; are using the same serializer. Therefore not a safe change. ; INCORRECT. It's safe, just changes where serialization happens.
false
9ea0be64782c558471ea6953130f69af46f182b9
0011048749c119b688ec878ec47dad7cd8dd00ec
/src/spoilers/500/solution.scm
92da46a67ac21c07d3b76137076187a27a8a6d91
[ "0BSD" ]
permissive
turquoise-hexagon/euler
e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5
852ae494770d1c70cd2621d51d6f1b8bd249413c
refs/heads/master
2023-08-08T21:01:01.408876
2023-07-28T21:30:54
2023-07-28T21:30:54
240,263,031
8
0
null
null
null
null
UTF-8
Scheme
false
false
1,164
scm
solution.scm
(import (chicken fixnum) (euler) (srfi 69)) (define-constant limit #e1e7) (define (square-root n) (let loop ((i n)) (let ((_ (fx/ (fx+ i (fx/ n i)) 2))) (if (fx< _ i) (loop _) i)))) (define (make-prime? n) (let ((acc (make-vector (fx+ n 1) #f))) (for-each (lambda (p) (vector-set! acc p #t)) (primes n)) (define (prime? n) (vector-ref acc n)) prime?)) (define (make-valid? n) (let ((acc (make-vector (fx+ n 1))) (prime? (make-prime? n))) (define (valid? n) (let ((c (vector-ref acc n))) (if (boolean? c) c (let ((s (square-root n))) (let ((p (if (fx= (fx* s s) n) (valid? s) (prime? n)))) (vector-set! acc n p) p))))) valid?)) (define (solve n m) (let ((valid? (make-valid? limit))) (let loop ((i 2) (cnt 0) (acc 1)) (if (fx= cnt n) acc (if (valid? i) (loop (fx+ i 1) (fx+ cnt 1) (fxmod (fx* acc i) m)) (loop (fx+ i 1) cnt acc)))))) (let ((_ (solve 500500 500500507))) (print _) (assert (= _ 35407281)))
false
c00028d3b579013874ea066f772ecbb437c542df
97b9e4b5623c1e3d201fa0f0e624852c276e8cc6
/tests-constant.scm
4531c4c8d22ddbc1f6a769f533921645b466d115
[]
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
422
scm
tests-constant.scm
(add-tests-with-string-output "string" ;[(cons #\a #\b) => "(#\\a . #\\b)\n"] #|[(let ([s (string #\a #\b)]) (cons (string-ref s 0) (string-ref s 1))) => "(#\\a . #\\b)\n"]|# #|[(let ([s (make-string 2)]) [>(string-set! s 0 #\a) (string-set! s 1 #\b)<] (cons #\a #\b) ) => "(#\\a . #\\b)\n"]|# [(let ([s (make-string 1)]) (string-set! s 0 #\") s) => "\"\\\"\"\n"] )
false
abbb158e3e0e554ffd0c6622283cdfb540da9352
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/sicp/exercices/3.51.scm
80f9ae5ce041a9e1c4da203ddc5d7448911cc445
[]
no_license
Phantas0s/playground
a362653a8feb7acd68a7637334068cde0fe9d32e
c84ec0410a43c84a63dc5093e1c214a0f102edae
refs/heads/master
2022-05-09T06:33:25.625750
2022-04-19T14:57:28
2022-04-19T14:57:28
136,804,123
19
5
null
2021-03-04T14:21:07
2018-06-10T11:46:19
Racket
UTF-8
Scheme
false
false
1,149
scm
3.51.scm
; In order to take a closer look at delayed eval- ; uation, we will use the following procedure, which simply ; returns its argument after printing it: (define (show x) (display-line x) x) ; What does the interpreter print in response to evaluating ; each expression in the following sequence? (define (stream-enumerate-interval low high) (if (> low high) the-empty-stream (cons-stream low (stream-enumerate-interval (+ low 1) high)) ) ) (define x (stream-map show (stream-enumerate-interval 0 10))) (stream-ref x 5) (stream-ref x 7) ; We would have all the display just after defining x, then the other two stream reference would display 4 and 6. **WRONG** ; This is utterly wrong. The point of a stream is NOT to compute all its elements. Only the first is returned, so the call to define will call show on the first element of the stream, 0. (define x (stream-map show (stream-enumerate-interval 0 10))) ;0 ; When stream-ref are called, every values from 0 to the final one are computed. (stream-ref x 5) ; 0 ; 1 ; 2 ; 3 ; 4 ; 5 (stream-ref x 7) ;6 ;7 ; The last stream-ref only show 6 and 7 thanks to memoization.
false
fa584a5b51dacddbb61bf530f1b1b54bebacd359
0a0b1cdae21384ca702289c7b2b5a663ed2294f4
/pseudoscheme-features.scm
758cb8a6e520bbc77e7999d72c8929da420d04df
[ "BSD-2-Clause" ]
permissive
sharplispers/pseudoscheme
7cfbf63ce9e94d3f11ccc1c78e864800ed3fe233
239d9ee072a61c314af22a2678031472abe1e11a
refs/heads/master
2016-09-06T05:18:19.260992
2011-12-02T01:13:57
2011-12-02T01:13:57
2,895,386
18
5
null
null
null
null
UTF-8
Scheme
false
false
2,845
scm
pseudoscheme-features.scm
; -*- Mode: Scheme; Syntax: Scheme; Package: Scheme; -*- ; Copyright (c) 1993, 1994 by Richard Kelsey and Jonathan Rees. ; Copyright (c) 1996 by NEC Research Institute, Inc. See file COPYING. ; This is file pseudoscheme-features.scm. ; Synchronize any changes with all the other *-features.scm files. (define *load-file-type* #f) ;For fun ; SIGNALS (define error #'ps:scheme-error) (define warn #'ps:scheme-warn) (define (signal type . stuff) (apply warn "condition signalled" type stuff)) (define (syntax-error . rest) ; Must return a valid expression. (apply warn rest) ''syntax-error) (define (call-error message proc . args) (error message (cons proc args))) ; FEATURES (define force-output #'lisp:force-output) (define (string-hash s) (let ((n (string-length s))) (do ((i 0 (+ i 1)) (h 0 (+ h (lisp:char-code (string-ref s i))))) ((>= i n) h)))) (define (make-immutable! thing) thing) (define (immutable? thing) thing #f) (define (unspecific) (if #f #f)) ; BITWISE (define arithmetic-shift #'lisp:ash) (define bitwise-and #'lisp:logand) (define bitwise-ior #'lisp:logior) (define bitwise-not #'lisp:lognot) ; ASCII (define char->ascii #'lisp:char-code) (define ascii->char #'lisp:code-char) (define ascii-limit lisp:char-code-limit) (define ascii-whitespaces '(32 10 9 12 13)) ; CODE-VECTORS (define (make-code-vector len . fill-option) (lisp:make-array len :element-type '(lisp:unsigned-byte 8) :initial-element (if (null? fill-option) 0 (car fill-option)))) (define (code-vector? obj) (ps:true? (lisp:typep obj (lisp:quote (lisp:simple-array (lisp:unsigned-byte 8) (lisp:*)))))) (define (code-vector-ref bv k) (lisp:aref (lisp:the (lisp:simple-array (lisp:unsigned-byte 8) (lisp:*)) bv) k)) (define (code-vector-set! bv k val) (lisp:setf (lisp:aref (lisp:the (lisp:simple-array (lisp:unsigned-byte 8) (lisp:*)) bv) k) val)) (define (code-vector-length bv) (lisp:length (lisp:the (lisp:simple-array (lisp:unsigned-byte 8) (lisp:*)) bv))) ; The rest is unnecessary in Pseudoscheme versions 2.8d and after. ;(define eval #'schi:scheme-eval) ;(define (interaction-environment) schi:*current-rep-environment*) ;(define scheme-report-environment ; (let ((env (scheme-translator:make-program-env ; 'rscheme ; (list scheme-translator:revised^4-scheme-module)))) ; (lambda (n) ; n ;ignore ; env))) ; Dynamic-wind. ; ;(define (dynamic-wind in body out) ; (in) ; (lisp:unwind-protect (body) ; (out))) ; ;(define values #'lisp:values) ; ;(define (call-with-values thunk receiver) ; (lisp:multiple-value-call receiver (thunk)))
false
19d694b8f8f784ab4a093043991effc3d225dff9
0011048749c119b688ec878ec47dad7cd8dd00ec
/src/002/solution.scm
e760ebdee0f1cd8f711a7cf921c38f3155b9e389
[ "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
223
scm
solution.scm
(define (solve n) (let loop ((a 0) (b 1) (acc 0)) (if (> a n) acc (loop b (+ a b) (if (even? a) (+ acc a) acc))))) (let ((_ (solve #e4e6))) (print _) (assert (= _ 4613732)))
false
8dbb4616a8f869040b04ff584357409bf17299fc
f40f97c37847103138c82d3f1b3956d9c2592b76
/transformations/transformation-examples.scm
49282d399922006206624efae93c597aaef73bd0
[ "MIT" ]
permissive
k-tsushima/Shin-Barliman
34df6868aafcd2d36dbbc57ef56eab555da05a5c
abea8511d18273196ac806dcf14b88d4098e18f8
refs/heads/master
2021-06-25T13:47:22.721816
2020-01-24T04:11:24
2020-01-24T04:11:24
182,607,716
16
1
MIT
2020-12-02T00:12:39
2019-04-22T02:18:17
Scheme
UTF-8
Scheme
false
false
4,103
scm
transformation-examples.scm
(eval '((lambda (y) (y y)) (lambda (z) z)) (empty-env)) (define eval (lambda (expr env) (pmatch expr [,x (guard (symbol? x)) (apply-env env x)] [`(lambda (,x) ,body) (lambda (a) (eval body (extend-env x a env)))] [`(,e1 ,e2) ((eval e1 env) (eval e2 env))]))) (define eval (lambda (expr env) (pmatch expr [,x (guard (symbol? x)) (apply-env env x)] [`(lambda (,x) ,body) (lambda (a) (eval body (extend-env x a env)))] [`(,e1 ,e2) (let ((v1 (eval e1 env))) (v1 (eval e2 env)))]))) (define eval-anf (lambda (expr env) (pmatch expr [,x (guard (symbol? x)) (apply-env env x)] [`(lambda (,x) ,body) (lambda (a) (eval-anf body (extend-env x a env)))] [`(,e1 ,e2) (let ((v1 (eval-anf e1 env))) (let ((v2 (eval-anf e2 env))) (v1 v2)))]))) #!eof ;;; direct (define ! (lambda (n) (if (zero? n) 1 (* n (! (sub1 n)))))) ;; ANF (define ! (lambda (n) (if (zero? n) 1 (let ((v (! (sub1 n)))) (* n v))))) #!eof ;;; trampolined style (define trampoline (lambda (th) (trampoline (th)))) (define !-cps (lambda (n k) (lambda () (if (zero? n) (k 1) (!-cps (sub1 n) (lambda (v) (k (* n v)))))))) (call/cc (lambda (k) (trampoline (!-cps 5 k)))) #!eof (define trampoline (lambda (th) (if (procedure? th) (trampoline (th)) th))) (define !-cps (lambda (n k) (lambda () (if (zero? n) (k 1) (!-cps (sub1 n) (lambda (v) (k (* n v)))))))) (trampoline (!-cps 5 (lambda (v) v))) #!eof (define !-cps (lambda (n k) (if (zero? n) (k 1) (!-cps (sub1 n) (lambda (v) (k (* n v))))))) (!-cps 5 (lambda (v) v)) #!eof (define ! (lambda (n) (lambda () (if (zero? n) 1 (* n (! (sub1 n))))))) (trampoline (! 5)) #!eof ;; direct style (define ! (lambda (n) (if (zero? n) 1 (* n (! (sub1 n)))))) #!eof (eval '((lambda (y) (y y)) (lambda (z) z)) (lambda (x) (error 'lookup (format "unbound variable ~s" x)))) (define eval (lambda (expr env) (pmatch expr [,x (guard (symbol? x)) (env x)] [`(lambda (,x) ,body) (lambda (a) (eval body (lambda (y) (if (eq? x y) a (env y)))))] [`(,e1 ,e2) ((eval e1 env) (eval e2 env))]))) ;;; representation independence with respect environments (define apply-env (lambda (env x) (env x))) (define empty-env (lambda () (lambda (x) (error 'lookup (format "unbound variable ~s" x))))) (define extend-env (lambda (x a env) (lambda (y) (if (eq? x y) a (apply-env env y))))) ;;;; (eval '((lambda (y) (y y)) (lambda (z) z)) (empty-env)) (define eval (lambda (expr env) (pmatch expr [,x (guard (symbol? x)) (apply-env env x)] [`(lambda (,x) ,body) (lambda (a) (eval body (extend-env x a env)))] [`(,e1 ,e2) ((eval e1 env) (eval e2 env))]))) ;;; registerization (define *expr* 'whocares) (define *env* 'whocares) (define eval (lambda () (pmatch expr [,x (guard (symbol? x)) (apply-env *env* x)] [`(lambda (,x) ,body) (lambda (a) (eval body (extend-env! x a *env*)))] [`(,e1 ,e2) ((eval e1 env) (eval e2 env))]))) (define ! (lambda (n) (if (zero? n) 1 (* n (! (sub 1)))))) (define !-cps (lambda (n k) (if (zero? n) (k 1) (!-cps (sub 1) (lambda (v) (k (* n v))))))) (!-cps 5 (lambda (v) v)) (define tramp (lambda () (tramp))) (define !-cps (lambda (n k) (if (zero? n) (k 1) (!-cps (sub 1) (lambda (v) (k (* n v))))))) (!-cps 5 (lambda (v) v))
false
596f1b2aa05ce75bbc24cb57d11e11cdd63eb3b5
97c107938d7a7b80d319442337316604200fc0ae
/text-world/ncurses-unit.ss
e864b8b4a6d4beab40a5c23267e5d058edbbde49
[]
no_license
jeapostrophe/rl
ddb131563cb37da80905c5de2debd01ec6c371d6
865f2a68e075bb5cc91754839181a35b03e08cb9
refs/heads/master
2021-01-19T03:10:04.613667
2013-10-31T01:24:57
2013-10-31T01:24:57
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,998
ss
ncurses-unit.ss
#lang scheme (require (only-in htdp/image make-color)) (require (planet jaymccarthy/matrix) "../exp/ncurses/ncurses.ss" "../ui/ansi-colors.ss" "text-world-sig.ss") ; http://www.termsys.demon.co.uk/vtansi.htm ; http://www.connectrf.com/Documents/vt220.html ; http://ascii-table.com/ansi-escape-sequences.php (define (char->key-event c) (case c [(#\u0003) 'up] [(#\u0002) 'down] [(#\u0005) 'right] [(#\u0004) 'left] [else (if (not (char-iso-control? c)) c (error 'char->key-event "Can't translate ~S~n" c))])) (define-unit ncurses-text-world@ (import) (export text-world^) (define-struct scene (chars colors)) (define (empty-scene width height) (make-scene (build-matrix height width (lambda (ri ci) #\space)) (build-matrix height width (lambda (ri ci) ansi-reset)))) (define-struct image (str color)) (define (image-height img) 1) (define (image-width img) (string-length (image-str img))) (define (place-image img ci ri s) (define str (image-str img)) (define col (image-color img)) (for/fold ([s s]) ([char (in-string str)] [cd (in-naturals)]) (make-scene (matrix-set (scene-chars s) ri (+ ci cd) char) (matrix-set (scene-colors s) ri (+ ci cd) col)))) (define (text str color) (make-image str (ansi-ize color))) (define (update-display olds news do-not-update?) (define old (scene-chars olds)) (define new (scene-chars news)) (define new-cols (scene-colors news)) (for ([ri (in-range 0 (matrix-rows new))]) (for ([ci (in-range 0 (matrix-cols new))]) (let ([new-char (matrix-ref new ri ci)] [old-char (matrix-ref old ri ci)]) (unless (do-not-update? new-char old-char) (move! ri ci) ; XXX colors (add-char! new-char)))))) (define (big-bang init #:on-key on-key #:on-draw on-draw #:stop-when stop-when) (initialize-screen!) (with-handlers ([exn:fail? (lambda (x) (restore-screen!) (raise x))]) ; XXX use (has-colors?) (raw!) (no-newline-input!) (no-echo!) (set-keypad! stdscr #t) (set-interrupt-flush! stdscr #f) (set-meta! stdscr #t) (start-color!) (let ([disp (on-draw init)]) (erase!) (refresh!) (update-display disp disp (lambda (new old) #f)) (refresh!) (let loop ([old-disp disp] [w init]) (if (stop-when w) w (let ([new-disp (on-draw w)]) ; XXX Why doesn't the updating work? (update-display old-disp new-disp #;(lambda (new old) #f) char=?) (refresh!) (loop new-disp (on-key w (char->key-event (get-char!)))))))) (restore-screen!)))) (provide ncurses-text-world@)
false
f73ba4482969e63b854962fb9b66877aef3f7d65
688296a60e867bd61d72ce8c9e9fe18059fc4bfe
/benchmark/cases/kcfa-2.scm
91dd6bb2bd8feaf2fff250daad8ff984a0c91ed5
[]
no_license
JHU-PL-Lab/ddpa
4b3788e3f2bc193a9f4be4c0f05e43ceb0f83974
c793ee10258006548712eb54895f9e3653e15d90
refs/heads/master
2022-11-24T22:33:26.837760
2019-07-23T17:14:53
2019-07-23T17:14:53
281,700,524
3
0
null
null
null
null
UTF-8
Scheme
false
false
160
scm
kcfa-2.scm
; n = 2 ; # terms = 69 ((lambda (f1) (f1 #t) (f1 #f)) (lambda (x1) ((lambda (f2) (f2 #t) (f2 #f)) (lambda (x2) ((lambda (z) (z x1 x2)) (lambda (y1 y2) y1))))))
false
bbf07342cf0d0ba40728212c3934f9c6fe81e528
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/net/network-information/unicast-ipaddress-information.sls
5dc9e025c184f4db57605654f76101b98e32c8d5
[]
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,970
sls
unicast-ipaddress-information.sls
(library (system net network-information unicast-ipaddress-information) (export is? unicast-ipaddress-information? address-preferred-lifetime address-valid-lifetime dhcp-lease-lifetime duplicate-address-detection-state ipv4-mask prefix-origin suffix-origin) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Net.NetworkInformation.UnicastIPAddressInformation a)) (define (unicast-ipaddress-information? a) (clr-is System.Net.NetworkInformation.UnicastIPAddressInformation a)) (define-field-port address-preferred-lifetime #f #f (property:) System.Net.NetworkInformation.UnicastIPAddressInformation AddressPreferredLifetime System.Int64) (define-field-port address-valid-lifetime #f #f (property:) System.Net.NetworkInformation.UnicastIPAddressInformation AddressValidLifetime System.Int64) (define-field-port dhcp-lease-lifetime #f #f (property:) System.Net.NetworkInformation.UnicastIPAddressInformation DhcpLeaseLifetime System.Int64) (define-field-port duplicate-address-detection-state #f #f (property:) System.Net.NetworkInformation.UnicastIPAddressInformation DuplicateAddressDetectionState System.Net.NetworkInformation.DuplicateAddressDetectionState) (define-field-port ipv4-mask #f #f (property:) System.Net.NetworkInformation.UnicastIPAddressInformation IPv4Mask System.Net.IPAddress) (define-field-port prefix-origin #f #f (property:) System.Net.NetworkInformation.UnicastIPAddressInformation PrefixOrigin System.Net.NetworkInformation.PrefixOrigin) (define-field-port suffix-origin #f #f (property:) System.Net.NetworkInformation.UnicastIPAddressInformation SuffixOrigin System.Net.NetworkInformation.SuffixOrigin))
false
5193458e9aeae9afe13ded595cc4eba8e400ce4e
5add38e6841ff4ec253b32140178c425b319ef09
/%3a54.sls
bcdcc3acddfcd90c802c51445c5ab5755909397a
[ "X11-distribute-modifications-variant" ]
permissive
arcfide/chez-srfi
8ca82bfed96ee1b7f102a4dcac96719de56ff53b
e056421dcf75d30e8638c8ce9bc6b23a54679a93
refs/heads/master
2023-03-09T00:46:09.220953
2023-02-22T06:18:26
2023-02-22T06:18:26
3,235,886
106
42
NOASSERTION
2023-02-22T06:18:27
2012-01-21T20:21:20
Scheme
UTF-8
Scheme
false
false
62
sls
%3a54.sls
(library (srfi :54) (export cat) (import (srfi :54 cat)))
false
15c3796e87332f5c5c6b7ef8debde290bd9d1ed6
f4cf5bf3fb3c06b127dda5b5d479c74cecec9ce9
/Sources/LispKit/Resources/Libraries/srfi/135/kernel0.sld
95cba49a10be2624f345a133d99c85c52c866bc0
[ "Apache-2.0" ]
permissive
objecthub/swift-lispkit
62b907d35fe4f20ecbe022da70075b70a1d86881
90d78a4de3a20447db7fc33bdbeb544efea05dda
refs/heads/master
2023-08-16T21:09:24.735239
2023-08-12T21:37:39
2023-08-12T21:37:39
57,930,217
356
17
Apache-2.0
2023-06-04T12:11:51
2016-05-03T00:37:22
Scheme
UTF-8
Scheme
false
false
15,489
sld
kernel0.sld
;;; Copyright (C) William D Clinger (2016). ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, ;;; copy, modify, merge, publish, distribute, sublicense, and/or ;;; sell copies of the Software, and to permit persons to whom the ;;; Software is furnished to do so, subject to the following ;;; conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ;;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR ;;; OTHER DEALINGS IN THE SOFTWARE. (define-library (srfi 135 kernel0) (export ;; for internal use only complain ; for reporting illegal arguments text-rtd ; FIXME: for debugging only %new-text ; FIXME: for debugging only text.k text.chunks ; FIXME: for debugging only %text-length ; non-checking version %text-ref ; non-checking version %string->text ; 1-argument version N ; preferred text size for pieces of long texts the-empty-text ; there should be only one empty text ;; will be exported by (srfi 135) text? text-tabulate text-length text-ref subtext textual-concatenate) (import (lispkit base)) (begin (define (complain name . args) (apply error (string-append (symbol->string name) ": illegal arguments") args)) ;;; 1-argument version for internal use (define (%string->text s) (if (string? s) (text-tabulate (lambda (i) (string-ref s i)) (string-length s)) (complain 'string->text s))) ;;; A portable implementation can't rely on inlining, but it can rely on macros. (define N 128) (define (length&i0 len i0) (+ (* N len) i0)) (define-syntax length&i0.length (syntax-rules () ((_ k) (quotient k N)))) (define-syntax length&i0.i0 (syntax-rules () ((_ k) (remainder k N)))) (define-record-type text-rtd (new-text0 k chunks) text? (k text.k) (chunks text.chunks)) (define (%new-text len i0 chunks) (new-text0 (length&i0 len i0) chunks)) (define the-empty-text (%new-text 0 0 (vector (make-string 0)))) ;;; text? is defined by the record definition above. (define (text-length txt) (if (text? txt) (length&i0.length (text.k txt)) (error "text-length: not a text" txt))) (define (text-ref txt i) (if (and (text? txt) (exact-integer? i) (<= 0 i)) (let* ((k (text.k txt)) (chunks (text.chunks txt)) (len (length&i0.length k)) (i0 (length&i0.i0 k)) (i+i0 (+ i i0)) (j (quotient i+i0 N)) (ii (remainder i+i0 N))) (if (< i len) (let ((sj (vector-ref chunks j))) (string-ref sj ii)) (error "text-ref: index out of range" txt i))) (error "text-ref: illegal arguments" txt i))) ;;; Non-checking versions for internal use. (define (%text-length txt) (length&i0.length (text.k txt))) (define (%text-ref txt i) (let* ((k (text.k txt)) (chunks (text.chunks txt)) (len (length&i0.length k)) (i0 (length&i0.i0 k)) (i+i0 (+ i i0)) (j (quotient i+i0 N)) (ii (remainder i+i0 N))) (let ((sj (vector-ref chunks j))) (string-ref sj ii)))) ;;; text-tabulate avoids side effects (in case proc returns more than once) (define (text-tabulate proc len) (if (= 0 len) the-empty-text (let loop ((i len) ; highest index that's been tabulated (chunks '()) (chars '())) (cond ((= 0 i) (%new-text len 0 (list->vector (cons (list->string chars) chunks)))) ((and (= 0 (remainder i N)) (not (null? chars))) (loop i (cons (list->string chars) chunks) '())) (else (let* ((i-1 (- i 1)) (c (proc i-1))) (if (char? c) (loop i-1 chunks (cons c chars)) (error "text-tabulate: proc returned a non-character" proc len c)))))))) ;;; FIXME: should the fast case do something different ;;; if the length of the result is sufficiently small? ;;; Probably not: splitting a 100-character text into ;;; 100 1-character texts should be fast, and programmers ;;; can now use text-copy instead if they're worried about it. ;;; ;;; subtext is now defined only for texts; use subtextual ;;; if the first argument might be a string. (define (subtext txt start end) (cond ((and (text? txt) (exact-integer? start) (exact-integer? end) (<= 0 start end)) (%subtext txt start end)) (else (complain 'subtext txt start end)))) (define (%subtext txt start end) (let* ((k (text.k txt)) (chunks (text.chunks txt)) (len (length&i0.length k)) (i0 (length&i0.i0 k)) (i+i0 (+ start i0)) (end+i0 (+ end i0)) (len+i0 (+ len i0)) (jstart (quotient i+i0 N)) (jend (quotient end+i0 N)) (jlen (quotient len N))) (if (<= end len) (cond ((= start end) the-empty-text) ((and (= 0 jstart) (= jlen jend)) ;; the fast case (%new-text (- end start) i+i0 chunks)) (else (let* ((v (make-vector (+ 1 (- jend jstart))))) (do ((j jstart (+ j 1))) ((> j jend)) (vector-set! v (- j jstart) (vector-ref chunks j))) (%new-text (- end start) (remainder i+i0 N) v)))) (error "subtext: end out of range" txt start end)))) ;;; There are a lot of special cases that could be exploited here: ;;; share the characters of the longest text ;;; share the characters of the longest run of texts ;;; whose characters don't have to be copied ;;; if (text-length txt1) is a multiple of N, ;;; and txt2 starts at offset 0, ;;; then txt1 and txt2 can be concatenated ;;; without copying any of their characters ;;; ;;; That's a partial list. ;;; It would be easy to spend more time detecting special cases ;;; than would be saved on average. ;;; In the interest of simplicity and reliability, this code ;;; currently implements only two special cases: ;;; share the full chunks of the longest text ;;; provided ;;; it contains at least N characters ;;; it contains at least half the characters of the result ;;; its characters start at offset zero ;;; share the full chunks of the first text ;;; provided ;;; it contains at least N characters ;;; its characters start at offset zero (define (textual-concatenate texts) (cond ((not (list? texts)) (complain 'textual-concatenate texts)) ((null? texts) the-empty-text) ((null? (cdr texts)) (let ((txt (car texts))) (cond ((text? txt) txt) ((string? txt) (%string->text txt)) (else (complain 'textual-concatenate texts))))) (else (let loop ((items (reverse texts)) (real-texts '()) (n 0) (longest #f) (longest-length 0)) (cond ((null? items) (%text-concatenate-n real-texts n longest longest-length)) ((text? (car items)) (let* ((txt (car items)) (k (%text-length txt))) (loop (cdr items) (cons txt real-texts) (+ n k) (if (> k longest-length) txt longest) (max k longest-length)))) ((string? (car items)) (loop (cons (%string->text (car items)) (cdr items)) real-texts n longest longest-length)) (else (complain 'textual-concatenate texts))))))) ;;; All of the texts are really texts. No strings. ;;; n is the length of the result. ;;; longest is #f or the longest of the texts, and ;;; longest-length is its length (or zero). (define (%text-concatenate-n texts n longest longest-length) (if (and longest (> longest-length N) (< n (+ longest-length longest-length)) (= 0 (length&i0.i0 (text.k longest)))) (if (eq? longest (car texts)) (%%text-concatenate-n texts n) (let loop ((texts texts) (front '()) (front-length 0)) (cond ((eq? longest (car texts)) (%%text-concatenate-front (reverse front) (%%text-concatenate-n texts (- n front-length)) front-length n)) (else (let ((txt (car texts))) (loop (cdr texts) (cons txt front) (+ front-length (%text-length txt)))))))) (%%text-concatenate-n texts n))) ;;; texts is a non-empty list of texts, with no strings. ;;; n is the length of the result. ;;; ;;; The text returned has a start index of zero. ;;; ;;; Special case: ;;; If the first text has a start index of zero, ;;; then its full chunks don't have to be copied. (define (%%text-concatenate-n texts n) (if (= 0 n) the-empty-text (let* ((n/N (quotient n N)) (m (remainder n N)) (nchunks (+ n/N (if (= 0 m) 0 1))) (chunks (make-vector nchunks)) (txt (car texts)) (k (text.k txt)) (len (length&i0.length k)) (i0 (length&i0.i0 k))) (if (and (> len N) (= 0 i0)) (let* ((j (quotient len N)) (ti (* j N)) (chunks0 (text.chunks txt))) (do ((i 0 (+ i 1))) ((= i j)) (vector-set! chunks i (vector-ref chunks0 i))) (do ((i j (+ i 1))) ((= i n/N) (if (> m 0) (vector-set! chunks i (make-string m)))) (vector-set! chunks i (make-string N))) (%%text-concatenate-finish n 0 chunks j texts ti)) (let () (do ((i 0 (+ i 1))) ((= i n/N) (if (> m 0) (vector-set! chunks i (make-string m)))) (vector-set! chunks i (make-string N))) (%%text-concatenate-finish n 0 chunks 0 texts 0)))))) ;;; All of the texts are really texts. No strings. ;;; The second argument is a text that starts at offset zero. ;;; k is the total length of the texts passed as first argument. ;;; n is the length of the result. ;;; ;;; Returns the texts concatenated with the second argument, ;;; without copying any chunks of the second argument. (define (%%text-concatenate-front texts txt k n) (let* ((k/N (quotient k N)) (mk (remainder k N)) (i0 (if (= 0 mk) 0 (- N mk))) ; start offset for result (kchunks (+ k/N (if (= 0 mk) 0 1))) ; number of new chunks (n-k (- n k)) (n-k/N (quotient n-k N)) (m (remainder n-k N)) (nchunks (+ kchunks n-k/N (if (= 0 m) 0 1))) (chunks (make-vector nchunks)) (chunks2 (text.chunks txt))) ;; allocate new chunks and copy extant chunks (do ((i 0 (+ i 1))) ((= i kchunks)) (vector-set! chunks i (make-string N))) (do ((i kchunks (+ i 1))) ((= i nchunks)) (vector-set! chunks i (vector-ref chunks2 (- i kchunks)))) (%%text-concatenate-finish n i0 chunks 0 texts 0))) ;;; Given: ;;; ;;; n : the length of a text to be created ;;; i0 : start offset for the text to be created ;;; chunks : the vector of chunks for that new text ;;; j : vector index of first uninitialized chunk ;;; texts : a non-empty list of texts to be copied into the chunks ;;; ti : index of first uncopied character in the first text ;;; ;;; Copies the texts into the chunks and returns a new text. ;;; The given texts may not fill the chunks because the chunks ;;; of some shared text may already have been copied into some ;;; tail of the chunks vector. (define (%%text-concatenate-finish n i0 chunks j texts ti) (let loop ((texts (cdr texts)) (txt (car texts)) (j j) ; index into chunks (k i0) ; index into (vector-ref chunks j) (ti ti)) ; index into txt (cond ((= k N) (loop texts txt (+ j 1) 0 ti)) ((= ti (%text-length txt)) (if (null? texts) (%new-text n i0 chunks) (loop (cdr texts) (car texts) j k 0))) (else (string-set! (vector-ref chunks j) k (%text-ref txt ti)) (loop texts txt j (+ k 1) (+ ti 1)))))) ) )
true