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
38c54f44a63c5d2d9a6494d2d0f918541879284f
3c9983e012653583841b51ddfd82879fe82706fb
/r1/ui.scm
71ceb18f2158476fb5492231b724095ec152a5e3
[]
no_license
spdegabrielle/smalltalk-tng
3c3d4cffa09541b75524fb1f102c7c543a84a807
545343190f556edd659f6050b98036266a270763
refs/heads/master
2020-04-16T17:06:51.884611
2018-08-07T16:18:20
2018-08-07T16:18:20
165,763,183
1
0
null
null
null
null
UTF-8
Scheme
false
false
5,677
scm
ui.scm
(require 'srfi-1) (require 'sdl) (if (zero? (sdl-was-init SDL_INIT_VIDEO)) (error "Please initialise SDL (use sdl-csi).")) (ttf-init) (sdl-net-init) (define *system-font* (or (ttf-open-font "/sw/lib/X11/fonts/applettf/Monaco.ttf" 11) (ttf-open-font "/usr/share/fonts/truetype/ttf-bitstream-vera/VeraMono.ttf" 11))) (define *event-type-map* (make-hash-table eq?)) (define (traits-for-sdl-event-type t) (or (hash-table-ref *event-type-map* t #f) (error "No traits for event type" t))) (let-syntax ((def-sdl-event-type (syntax-rules () ((_ (global-var sdl-event-type) ...) (begin (define global-var '*) ...))))) (include "sdl-events.scm")) (define (update-sdl-event-type-map!) (let-syntax ((def-sdl-event-type (syntax-rules () ((_ (global-var sdl-event-type) ...) (begin (hash-table-set! *event-type-map* sdl-event-type global-var) ...))))) (include "sdl-events.scm"))) (push! global-load-hooks (lambda () (let-syntax ((def-sdl-event-type (syntax-rules () ((_ (global-var sdl-event-type) ...) (begin (set! global-var (hash-table-ref *image-root* 'global-var)) ... (update-sdl-event-type-map!)))))) (include "sdl-events.scm")))) (push! global-store-hooks (lambda () (let-syntax ((def-sdl-event-type (syntax-rules () ((_ (global-var sdl-event-type) ...) (begin (hash-table-set! *image-root* 'global-var global-var) ...))))) (include "sdl-events.scm")))) (push! bootstrap-hooks (lambda () (let-syntax ((def-sdl-event-type (syntax-rules () ((_ (global-var sdl-event-type) ...) (begin (set! global-var (make-traits (symbol->string 'sdl-event-type) `(#(sdlEvent ,*traits-sdl-event*) (sdlEventNumber ,sdl-event-type)))) ... (update-sdl-event-type-map!)))))) (include "sdl-events.scm")))) (let ((old-hook (primitive-traits-hook))) (primitive-traits-hook (lambda (o) (cond ((sdl-tcp-socket? o) *traits-socket*) ((sdl-surface? o) *traits-sdl-surface*) ((sdl-event? o) (traits-for-sdl-event-type (sdl-event-type o))) ((ttf-font? o) *traits-ttf-font*) (else (old-hook o)))))) (sdl-wm-set-caption "ThiNG" "ThiNG") (define (shutdown-sdl!) (let ((e (make-sdl-event))) (sdl-event-type-set! e SDL_QUIT) (sdl-push-event e))) (define *socket-set* (sdl-net-alloc-socket-set 100)) (define *active-sockets* '()) (define *the-eof-object* (read-char (open-input-string ""))) (define (activate-socket! sock suspension) (push! *active-sockets* (cons sock suspension)) (debug 1 "Adding "sock" to set "*socket-set*) (sdl-net-tcp-add-socket! *socket-set* sock)) (define (wait-for-socket-activity! sock) (metalevel-suspend-thread (lambda (suspension) (activate-socket! sock suspension)))) (define (read-from-socket sock) (wait-for-socket-activity! sock) (sdl-net-tcp-recv-string sock 4096)) (define (accept-from-socket sock) (wait-for-socket-activity! sock) (sdl-net-tcp-accept sock)) (define (make-char-provider-thunk-for-socket sock) (let ((state "") (len 0) (index 0)) (define (provider) (cond ((eof-object? state) state) ((>= index len) (let ((new-state (read-from-socket sock))) (if (string? new-state) (begin (set! state new-state) (set! len (string-length state)) (set! index 0) (provider)) (begin (set! state *the-eof-object*) (set! len 0) (set! index 0) (provider))))) (else (let ((result (string-ref state index))) (set! index (+ index 1)) result)))) provider)) (define (check-socket-set/delay delay-ms) (let ((next-event-time (+ (get-time-of-day) (/ delay-ms 1000.0))) (result (sdl-net-check-sockets *socket-set* 0))) (if (and result (positive? result)) (let-values (((ready unready) (partition (lambda (record) (sdl-net-socket-ready? (car record))) *active-sockets*))) (set! *active-sockets* unready) (for-each (lambda (record) (let ((sock (car record)) (suspension (cdr record))) (debug 1 "Removing "sock" from set "*socket-set*) (sdl-net-tcp-del-socket! *socket-set* sock) (metalevel-resume-thread! suspension sock))) ready))) (metalevel-run-runnable-suspensions next-event-time))) (define *video-surface* #f) (define (discover-best-resolution!) (let loop ((resolutions '( ;;(1600 1200) (1280 1024) (1024 768) (800 600) (640 480)))) (if (null? resolutions) (error "No resolution supported.") (let* ((res (car resolutions)) (maxx (car res)) (maxy (cadr res)) (s (sdl-set-video-mode maxx maxy 0 (+ SDL_HWSURFACE ;;SDL_FULLSCREEN SDL_HWPALETTE SDL_RESIZABLE SDL_DOUBLEBUF)))) (if (not (sdl-surface-pointer s)) (loop (cdr resolutions)) (set! *video-surface* s)))))) (define (ui-mainloop) (discover-best-resolution!) (sdl-fill-rect *video-surface* (make-sdl-rect 0 0 (sdl-surface-width *video-surface*) (sdl-surface-height *video-surface*)) (sdl-map-rgb (sdl-surface-pixel-format *video-surface*) 0 0 255)) (sdl-flip *video-surface*) (let ((start-time (get-time-of-day))) (let loop ((count 1)) (sdl-add-absolute-timer! (+ start-time (* count *invocation-count-update-interval*)) (lambda () (decay-invocation-counts!) (loop (+ count 1)))))) (do () ((metalevel-stopped?)) (let ((event (make-sdl-event))) (sdl-wait-event!* check-socket-set/delay event) (metalevel-spawn *nil* (lambda () (send handle event))))) (sdl-net-quit) (ttf-quit) (sdl-quit))
false
107fde3f33a9767ffa163af1dadb4cffeecc296d
2ac1fda367121cc75a6048afabc8543e8823f4d6
/graph.scm
fd57a5935fb3a1f5f406c8891a4d05c0eb977708
[ "MIT" ]
permissive
webyrd/tabling
9d8ce11040b4c1a9b6e6d74f1276e0a1a2b363d3
3ace7adfd272a99ca20a01c2b47cbfe14a830729
refs/heads/master
2020-05-31T12:08:12.573724
2015-04-06T02:16:12
2015-04-06T02:16:12
33,462,283
9
1
null
null
null
null
UTF-8
Scheme
false
false
2,569
scm
graph.scm
;; a -> b -> c -> a ;; d -> e -> f -> d (define edge (lambda (in-node out-node) (conde [(== 'a in-node) (== 'b out-node)] [(== 'b in-node) (== 'c out-node)] [(== 'c in-node) (== 'a out-node)] [(== 'd in-node) (== 'e out-node)] [(== 'e in-node) (== 'f out-node)] [(== 'f in-node) (== 'd out-node)]))) (define path (lambda (in out p) (conde [(== in out) (== '() p)] [(fresh (node p^) (== (cons (list in node) p^) p) (edge in node) (path node out p^))]))) (define curried-path (lambda (in out) (lambda (p) (conde [(== in out) (== '() p)] [(fresh (node p^) (== (cons (list in node) p^) p) (edge in node) ((curried-path node out) p^))])))) (define reachable (lambda (in out) (conde [(== in out)] [(fresh (node) (edge in node) (reachable node out))]))) ; (run 1 (q) (reachable 'd 'a)) (run* (q) (fresh (in out) (== (list in out) q) (edge in out))) (run 1 (p) (path 'a 'c p)) (run 3 (p) (path 'a 'c p)) (run 1 (p) ((curried-path 'a 'c) p)) (define tabled-path (tabled (in out p) (conde [(== in out) (== '() p)] [(fresh (node p^) (== (cons (list in node) p^) p) (edge in node) (tabled-path node out p^))]))) (define tabled-reachable (tabled (in out) (conde [(== in out)] [(fresh (node) (edge in node) (tabled-reachable node out))]))) (run 1 (q) (tabled-reachable 'd 'a)) #| (define tabled-inside-out-path (lambda (p) (tabled (in out) (conde [(== in out) (== '() p)] [(fresh (node p^) (== (cons (list in node) p^) p) (edge in node) ((tabled-inside-out-path p^) node out))])))) (run 10 (p) ((tabled-inside-out-path p) 'a 'c)) |# (define smart-path (lambda (in out p) (conde [(== in out) (== '() p) (tabled-reachable in out)] [(fresh (node p^) (== (cons (list in node) p^) p) (tabled-reachable in node) (tabled-reachable node out) (edge in node) (smart-path node out p^))]))) #| (define smart-path (lambda (in out p) (conde [(== in out) (== '() p) (tabled-reachable in out)] [(fresh (node p^) (== (cons (list in node) p^) p) (tabled-reachable in out) (edge in node) (smart-path node out p^))]))) |# #!eof (run 3 (p) (smart-path 'a 'c p))
false
5cf7e6674d0a6d5a9ad7509daf5df07b3be788f6
06d73af66d0c8450e2c9cb20757774c61c813ee6
/wrong-factorial.ss
e5025420ba6b7fb8f4df283f0a73bd0bb755916a
[]
no_license
logicshan/lc-with-redex
ce5dc164abc6550bb431b2a7fa20c98f5c024037
63aa4cbf1f0acf0553c545686ba00a1699f003f8
refs/heads/master
2020-12-29T01:42:06.026750
2014-04-29T05:23:37
2014-04-29T05:23:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
150
ss
wrong-factorial.ss
#lang scheme (((λ (m) ((λ (f) (m (f f))) (λ (f) (m (f f))))) (λ (!) 'this-is-never-evaluated)) 'this-is-evaluated-but-the-value-is-never-used)
false
7a172bfa09f719bd94467a8f1fad54fcc7450124
92b8d8f6274941543cf41c19bc40d0a41be44fe6
/testsuite/sva39940.scm
4bc6244090e4e15affe1aaba842d5d4f828e763a
[ "MIT" ]
permissive
spurious/kawa-mirror
02a869242ae6a4379a3298f10a7a8e610cf78529
6abc1995da0a01f724b823a64c846088059cd82a
refs/heads/master
2020-04-04T06:23:40.471010
2017-01-16T16:54:58
2017-01-16T16:54:58
51,633,398
6
0
null
null
null
null
UTF-8
Scheme
false
false
1,191
scm
sva39940.scm
;; Savannah bug #39940 ;; "Class member of type <procedure> compilation exception" (define-simple-class <Simple1> (<Object>) (callback type: <procedure>) ((*init*) (set! callback (lambda _ (format #t "Working1~%"))))) ((make <Simple1>):callback) ;; Output: Working1 ;; Same, but with a private field. (define-simple-class <Simple1p> (<Object>) (callback type: <procedure> access: 'private) ((*init*) (set! callback (lambda _ (format #t "Working1p~%")))) ((docallback) (callback))) ((make <Simple1p>):docallback) ;; Output: Working1p (define-simple-class <Simple2> (<Object>) (callback type: <procedure> init: (lambda _ (format #t "Working2~%"))) ((docallback) (callback))) ((make <Simple2>):docallback) ;; Output: Working2 ;; Same, but with a private field. (define-simple-class <Simple2p> (<Object>) (callback type: <procedure> access: 'private init: (lambda _ (format #t "Working2p~%"))) ((docallback) (callback))) ((make <Simple2p>):docallback) ;; Output: Working2p (define (foo) (let ((f (lambda _ (format #t "Working3~%")))) (list f f))) (format #t "~a~%" (car (foo)) ((cadr (foo)))) ;; Output: Working3 ;; Output: #<procedure f>
false
e4406e5c4348f0e41639331301d403f389173d76
5fa722a5991bfeacffb1d13458efe15082c1ee78
/src/eval/c4_8.scm
eee52bf848da93bd699dfc6883bfd3f05f3ccc61
[]
no_license
seckcoder/sicp
f1d9ccb032a4a12c7c51049d773c808c28851c28
ad804cfb828356256221180d15b59bcb2760900a
refs/heads/master
2023-07-10T06:29:59.310553
2013-10-14T08:06:01
2013-10-14T08:06:01
11,309,733
3
0
null
null
null
null
UTF-8
Scheme
false
false
14
scm
c4_8.scm
; in eval.scm
false
a473fa7610a2f4ff2e91945b284aface3b5a0a6a
db0567d04297eb710cd4ffb7af094d82b2f66662
/scheme/ikarus.not-yet-implemented.ss
2a4ee4ad9b5cbf2c51a06f7b44aa25bab47c70e6
[]
no_license
xieyuheng/ikarus-linux
3899e99991fd192de53c485cf429bfd208e7506a
941b627e64f30af60a25530a943323ed5c78fe1b
refs/heads/master
2021-01-10T01:19:05.250392
2016-02-13T22:21:24
2016-02-13T22:21:24
51,668,773
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,575
ss
ikarus.not-yet-implemented.ss
(library (ikarus not-yet-implemented) (export bitwise-reverse-bit-field bitwise-rotate-bit-field fxreverse-bit-field make-custom-binary-input/output-port make-custom-textual-input/output-port open-file-input/output-port equal-hash) (import (except (ikarus) bitwise-reverse-bit-field bitwise-rotate-bit-field fxreverse-bit-field make-custom-binary-input/output-port make-custom-textual-input/output-port open-file-input/output-port equal-hash)) (define-syntax not-yet (syntax-rules () [(_ x* ...) (begin (define (bug op) (define-condition-type &url &condition make-url-condition url-condition? (url condition-url)) (raise (condition (make-error) (make-who-condition 'ikarus) (make-message-condition "primitive not supported") (make-message-condition "Please visit the Ikarus FAQs page for more information") (make-url-condition "https://answers.launchpad.net/ikarus/+faqs") (make-irritants-condition (list op))))) (define (x* . args) (bug 'x*)) ...)])) (not-yet ;;; should be implemented bitwise-rotate-bit-field bitwise-reverse-bit-field fxreverse-bit-field ;;; not top priority at the moment equal-hash ;;; won't be implemented make-custom-binary-input/output-port make-custom-textual-input/output-port open-file-input/output-port ))
true
daf1966c994177a09b6b7fd01b357efe5d2fa1b8
a66514d577470329b9f0bf39e5c3a32a6d01a70d
/sdl2/joystick-functions.ss
7f1526a002a3ffbd233fa747d671fd710ee48746
[ "Apache-2.0" ]
permissive
ovenpasta/thunderchez
2557819a41114423a4e664ead7c521608e7b6b42
268d0d7da87fdeb5f25bdcd5e62217398d958d59
refs/heads/trunk
2022-08-31T15:01:37.734079
2021-07-25T14:59:53
2022-08-18T09:33:35
62,828,147
149
29
null
2022-08-18T09:33:37
2016-07-07T18:07:23
Common Lisp
UTF-8
Scheme
false
false
3,665
ss
joystick-functions.ss
(define-sdl-func void sdl-lock-joysticks () "SDL_LockJoysticks") (define-sdl-func void sdl-unlock-joysticks () "SDL_UnlockJoysticks") (define-sdl-func int sdl-num-joysticks () "SDL_NumJoysticks") (define-sdl-func string sdl-joystick-name-for-index ((device_index int)) "SDL_JoystickNameForIndex") ;;blacklisted probably because it uses a struct as value. (define sdl-joystick-get-device-guid #f) (define-sdl-func uint16 sdl-joystick-get-device-vendor ((device_index int)) "SDL_JoystickGetDeviceVendor") (define-sdl-func uint16 sdl-joystick-get-device-product ((device_index int)) "SDL_JoystickGetDeviceProduct") (define-sdl-func uint16 sdl-joystick-get-device-product-version ((device_index int)) "SDL_JoystickGetDeviceProductVersion") (define-sdl-func sdl-joystick-type-t sdl-joystick-get-device-type ((device_index int)) "SDL_JoystickGetDeviceType") (define-sdl-func sdl-joystick-id-t sdl-joystick-get-device-instance-id ((device_index int)) "SDL_JoystickGetDeviceInstanceID") (define-sdl-func (* sdl-joystick-t) sdl-joystick-open ((device_index int)) "SDL_JoystickOpen") (define-sdl-func (* sdl-joystick-t) sdl-joystick-from-instance-id ((joyid sdl-joystick-id-t)) "SDL_JoystickFromInstanceID") (define-sdl-func string sdl-joystick-name ((joystick (* sdl-joystick-t))) "SDL_JoystickName") ;;blacklisted probably because it uses a struct as value. (define sdl-joystick-get-guid #f) (define-sdl-func uint16 sdl-joystick-get-vendor ((joystick (* sdl-joystick-t))) "SDL_JoystickGetVendor") (define-sdl-func uint16 sdl-joystick-get-product ((joystick (* sdl-joystick-t))) "SDL_JoystickGetProduct") (define-sdl-func uint16 sdl-joystick-get-product-version ((joystick (* sdl-joystick-t))) "SDL_JoystickGetProductVersion") (define-sdl-func sdl-joystick-type-t sdl-joystick-get-type ((joystick (* sdl-joystick-t))) "SDL_JoystickGetType") ;;blacklisted probably because it uses a struct as value. (define sdl-joystick-get-guid-string #f) ;;blacklisted probably because it uses a struct as value. (define sdl-joystick-get-guid-from-string #f) (define-sdl-func sdl-bool-t sdl-joystick-get-attached ((joystick (* sdl-joystick-t))) "SDL_JoystickGetAttached") ;;blacklisted probably because it uses a struct as value. (define sdl-joystick-instance-id #f) (define-sdl-func int sdl-joystick-num-axes ((joystick (* sdl-joystick-t))) "SDL_JoystickNumAxes") (define-sdl-func int sdl-joystick-num-balls ((joystick (* sdl-joystick-t))) "SDL_JoystickNumBalls") (define-sdl-func int sdl-joystick-num-hats ((joystick (* sdl-joystick-t))) "SDL_JoystickNumHats") (define-sdl-func int sdl-joystick-num-buttons ((joystick (* sdl-joystick-t))) "SDL_JoystickNumButtons") (define-sdl-func void sdl-joystick-update () "SDL_JoystickUpdate") (define-sdl-func int sdl-joystick-event-state ((state int)) "SDL_JoystickEventState") (define-sdl-func sint16 sdl-joystick-get-axis ((joystick (* sdl-joystick-t)) (axis int)) "SDL_JoystickGetAxis") (define-sdl-func sdl-bool-t sdl-joystick-get-axis-initial-state ((joystick (* sdl-joystick-t)) (axis int) (state (* sint16))) "SDL_JoystickGetAxisInitialState") (define-sdl-func uint8 sdl-joystick-get-hat ((joystick (* sdl-joystick-t)) (hat int)) "SDL_JoystickGetHat") (define-sdl-func int sdl-joystick-get-ball ((joystick (* sdl-joystick-t)) (ball int) (dx (* int)) (dy (* int))) "SDL_JoystickGetBall") (define-sdl-func uint8 sdl-joystick-get-button ((joystick (* sdl-joystick-t)) (button int)) "SDL_JoystickGetButton") (define-sdl-func void sdl-joystick-close ((joystick (* sdl-joystick-t))) "SDL_JoystickClose") (define-sdl-func sdl-joystick-power-level-t sdl-joystick-current-power-level ((joystick (* sdl-joystick-t))) "SDL_JoystickCurrentPowerLevel")
false
7a8d86e6b10d2b60a34c7fb5fcce462a03df18f7
8198fe9ada6f569a9ad9932b22f8e0a743221407
/src/h2stub.scm
cbbb594bf7b50d82bde138b445600918fa95e057
[ "BSD-2-Clause" ]
permissive
shirok/Gauche-gtk2
56b17162d2a1a6cb814a6cfcfe48aed7293a857d
a90bdd15eafdfcff74eb1ca92b124aa9656a7079
refs/heads/master
2022-05-18T03:28:49.088852
2022-03-20T09:43:48
2022-03-20T09:43:48
684,933
8
2
NOASSERTION
2020-05-22T08:28:29
2010-05-25T10:29:50
C
UTF-8
Scheme
false
false
50,434
scm
h2stub.scm
;; ;; parse gtk headers to generate stub file ;; ;; OK. Defs file should be the way to go. However, gtk+ distribution ;; doesn't include defs file, and I couldn't find one for gtk-2.0 in ;; guile archive. For now, I hack this script. ;; ;; This script scans Gdk/Gtk headers and generate stub files. It doesn't ;; parse entire C syntax, though. It relies on gtk's coding convention. ;; Furthermore, it takes a manually created 'hints' file. (use srfi-1) (use srfi-2) (use srfi-11) (use srfi-13) (use file.util) (use text.tr) (use util.toposort) (use gauche.process) (use gauche.parameter) (use gauche.mop.instance-pool) ;;================================================================ ;; PARAMETERS (explicit global states) ;; ;; Keeps input file name during parsing (define input-file (make-parameter #f)) ;; Verbose flag (define verbose (make-parameter #t)) ;; Gtk and Pango version (major.minor) we're dealing with (define gtk-version (make-parameter "2.0")) (define pango-version (make-parameter "1.0")) ;; Directories to search input header files. ;; We first try pkg-config. If it fails, does ;; heuristic search. (define *header-search-paths* (delete-duplicates (append (call-with-input-process #`"pkg-config --variable=includedir gtk+-,(gtk-version)" (cut port->string-list <>) :on-abnormal-exit :ignore) (call-with-input-process #`"pkg-config --variable=includedir pango-,(pango-version)" (cut port->string-list <>) :on-abnormal-exit :ignore) '("/usr/include" "/usr/local/include")) string=?)) (define (find-header-dir target paths) (cond ((find-file-in-paths target :paths paths :pred file-is-readable?) => (lambda (p) (sys-dirname (sys-dirname p)))) (else (error #`",|target| couldn't find in ,*header-search-paths*")))) (define gtk-directory (make-parameter (find-header-dir #`"gtk-,(gtk-version)/gtk/gtk.h" *header-search-paths* ))) (define pango-directory (make-parameter (find-header-dir #`"pango-,(pango-version)/pango/pango.h" *header-search-paths*))) ;;================================================================ ;; CLASSES ;; (define-method for-each-instance (proc (class <instance-pool-meta>)) (for-each proc (instance-pool->list class))) (define-class <source-tracker-mixin> () ((source-file :accessor source-file-of) (files&definitions :allocation :class :initform '()) )) (define-method initialize ((self <source-tracker-mixin>) initargs) (next-method) (let1 file (sys-basename (input-file)) (set! (source-file-of self) file) (let1 p (assoc file (slot-ref self 'files&definitions)) (if p (push! (cdr p) self) (slot-push! self 'files&definitions (list file self)))))) ;; call proc with source file name and a list of objects defined in that file. (define (for-each-source-file proc) (for-each (lambda (def-list) (proc (car def-list) (reverse (cdr def-list)))) (reverse (class-slot-ref <source-tracker-mixin> 'files&definitions)))) (define (get-files&definitions) (reverse (class-slot-ref <source-tracker-mixin> 'files&definitions))) ;; <GTK-TYPE> - type (define-class <gtk-type> (<instance-pool-mixin>) ((c-name :init-keyword :c-name :accessor c-name-of) ;; symbol, such as 'GdkWindow* (body :init-keyword :body :init-value #f :accessor body-of) ;; has <gtk-struct>, <gtk-enum> or <gtk-array> if applicable. ;; symbol when this is a primitive type. )) (define-method write-object ((self <gtk-type>) port) (format port "<~a>" (c-name-of self))) (define (find-type name) (instance-pool-find <gtk-type> (lambda (item) (eq? (c-name-of item) name)))) (define (find-type-or-create name) (or (find-type name) (make <gtk-type> :c-name name))) ;; map <gtk-type> to stub type signature. (define-method scm-type-of ((self <gtk-type>)) (let1 body (body-of self) (cond ((symbol? body) body) ((is-a? body <gtk-enum>) '<int>) ((is-a? body <gtk-struct>) (scm-class-name-of body)) (else (cons 'UNKNOWN (c-name-of self)))))) ;; returns a fn that creates a C code fragment of unboxing/boxing slot value. ;; UGLY - this doesn't deal with array ref. (define-method get-slot-boxer ((self <gtk-type>)) (let1 body (body-of self) (cond ((is-a? body <gtk-struct>) (cut string-append (c-boxer-of body) "(" <> ")")) ((is-a? body <gtk-enum>) (cut string-append "Scm_MakeInteger(" <> ")")) ((symbol? body) ;; primitive type. There should be an interface to get this kind ;; of information; maybe lang.c.type module? For now, I hardcode them. (case body ((<char>) (cut string-append "SCM_MAKE_CHAR(" <> ")")) ((<boolean>) (cut (string-append "SCM_MAKE_BOOL(" <> ")"))) ((<int> <int8> <int16> <int32> <long>) (cut string-append "Scm_MakeInteger(" <> ")")) ((<uint> <uint8> <uint16> <uint32> <ulong>) (cut string-append "Scm_MakeIntegerFromUI(" <> ")")) ((<float> <double>) (cut string-append "Scm_MakeFlonum(" <> ")")) ((<const-char*> <const-gchar*> <gchar*>) (cut string-append "SCM_MAKE_STR_COPYING_SAFELY(" <> ")")) (else #f))) (;; check if it is an embedded structure. (and-let* ((ptrtype (find-type (string->symbol #`",(c-name-of self)*"))) (ptrbody (body-of ptrtype)) ((is-a? ptrbody <gtk-struct>))) (cut string-append (c-boxer-of ptrbody) "(&(" <> "))"))) (else #f)))) ;; define primitive types (for-each (lambda (entry) (make <gtk-type> :c-name (car entry) :body (cadr entry))) '((gint <int>) (gint8 <int8>) (gint16 <int16>) (gint32 <int32>) (glong <long>) (gshort <int16>) (guint <uint>) (guint8 <uint8>) (guint16 <uint16>) (guint32 <uint32>) (gulong <ulong>) (guchar <uint8>) (gushort <uint16>) (gboolean <boolean>) (gfloat <float>) (gdouble <double>) (long <long>) (int <int>) (short <int16>) (char <int8>) (void <void>) (float <float>) (double <double>) ;; C string business is tricky. We can only treat the case that ;; passing const char * or const gchar * - in those cases, gtk copies ;; the passed string immediately, so we can safely pass the string ;; from ScmGetStringConst*. (const-char* <const-char*>) (const-gchar* <const-gchar*>) ;; Generic GObject (GObject* <g-object>) ;; This is used to box the returned allocated gchar* (gchar* <gchar*>) ;; Opaque types (PangoContext* <pango-context>) (PangoLanguage* <pango-language>) (PangoAttrList* <pango-attr-list>) (PangoLayoutIter* <pango-layout-iter>) (GdkAtom <gdk-atom>) (GdkRegion* <gdk-region>) (GdkPixbufFormat* <gdk-pixbuf-format>) (GtkTreePath* <gtk-tree-path>) (GtkTreeRowReference* <gtk-tree-row-reference>) ;; GdkEvent is a union. (GdkEvent* <gdk-event>) ;; GtkAllocation is simply an alias of GdkRectangle (GtkAllocation* <gdk-rectangle>) ;; Interfaces (GtkEditable* <gtk-editable>) (GtkTreeModel* <gtk-tree-model>) (GtkTreeSortable* <gtk-tree-sortable>) )) ;; <GTK-VAR> - used in fields and arguments (define-class <gtk-var> () ((type :init-keyword :type :accessor type-of) (c-name :init-keyword :c-name :accessor c-name-of) (scm-name :allocation :virtual :accessor scm-name-of :slot-ref (lambda (o) (string->symbol (string-tr (x->string (c-name-of o)) "_" "-"))) :slot-set! (lambda (o v) #f)) ;; the following slots are used by field info (read-only? :initform #f :accessor read-only?) (accessible? :initform #t :accessor accessible?) (getter :init-keyword :getter :initform #f :accessor getter-of) (setter :init-keyword :setter :initform #f :accessor setter-of) )) (define-method write-object ((self <gtk-var>) port) (format port "<~a ~a>" (type-of self) (c-name-of self))) (define (grok-vardef type name) (let*-values (((ptrs var) (let1 brk (string-skip name #\*) (values (string-take name brk) (string-drop name brk)))) ((typesig) (if (pair? type) #`",(car type)-,(cdr type),|ptrs|" #`",|type|,|ptrs|"))) (make <gtk-var> :type (find-type-or-create (string->symbol typesig)) :c-name var))) (define (grok-arraydef type name dim) (receive (ptrs var) (let1 brk (string-skip name #\*) (values (string-take name brk) (string-drop name brk))) (let* ((elt-typesig (if (pair? type) #`",(car type)-,(cdr type),|ptrs|" #`",|type|,|ptrs|")) (typesig #`",elt-typesig[,dim]") (type (find-type-or-create (string->symbol typesig))) (elt-type (find-type-or-create (string->symbol elt-typesig)))) (set! (body-of type) (make <gtk-array> :size dim :element-type elt-type)) (make <gtk-var> :type type :c-name var)))) ;; <GTK-STRUCT> (define-class <gtk-struct> (<instance-pool-mixin> <source-tracker-mixin>) ((c-name :init-keyword :c-name :accessor c-name-of) (fields :init-keyword :fields :accessor fields-of) (internal? :init-value #f :accessor internal?) ;; - true if this struct is not exposed to Scheme. set by fixup (c-type :accessor c-type-of) ;; - for struct _GdkFoo, keeps #<gtk-type GdkFoo*> (superclass :accessor superclass-of) ;; - if inherited, this one keeps <gtk-type> of the parent class. (cpl :accessor cpl-of) ;; - class precedence list derived from superclass field. set by fixup. (allocation-type :accessor allocation-type-of :init-form 'simple) ;; - how the C structure should be allocated and freed ;; simple : ScmObj contains the entire structure. ;; gobject : ScmObj points to GObject* ;; indirect : ScmObj points to a mem that should be freed. ;; refcounted : ScmObj points to refcounted object. (scm-class-name :accessor scm-class-name-of) ;; - <gdk-foo> ; set by make-struct (c-caster :accessor c-caster-of) ;; - GDK_FOO ; set by make-struct (c-predicate :accessor c-predicate-of) ;; - SCM_GDK_FOO_P ; set by make-struct (c-predicate-nullable :accessor c-predicate-nullable-of) ;; - SCM_GDK_FOO_OR_NULL_P ; set by make-struct (c-unboxer :accessor c-unboxer-of) ;; - SCM_GDK_FOO ; set by make-struct (c-boxer :accessor c-boxer-of) ;; - SCM_MAKE_GDK_FOO ; set by make-struct (c-class-macro :accessor c-class-macro-of) ;; -SCM_CLASS_GDK_FOO ; set by make-struct (gtk-predicate :accessor gtk-predicate-of) ;; - GDK_IS_FOO ; set by make-struct (gtk-type-name :accessor gtk-type-name-of) ;; - GDK_TYPE_FOO ; set by make-struct (c-copy-proc :accessor c-copy-proc-of :init-value #f) ;; - Used by indirect struct, keeping C procedure name to copy ;; the data part. can be set in hints file. (c-free-proc :accessor c-free-proc-of :init-value #f) ;; - Used by indirect struct, keeping C procedure name to free ;; the data part. can be set in hints file. (allocator :init-form #f :accessor allocator-of) ;; - Special allocator setting that overrides the default. ;; May be set by hints file. This can be a string for ;; entire allocator body, or an assoc-list of required ;; initargs and the constructor to call. (qualifier :init-value :built-in :accessor qualifier-of) ;; - define-cclass qualifier. adjusted in fixup. (direct-supers :init-value () :accessor direct-supers-of) ;; - extra direct-supers if this class has a mixin. )) (define-method write-object ((self <gtk-struct>) port) (format port "#<gtk-struct ~s>" (c-name-of self))) (define-method gobject? ((self <gtk-struct>)) (eq? (allocation-type-of self) 'gobject)) (define-method indirect? ((self <gtk-struct>)) (eq? (allocation-type-of self) 'indirect)) (define-method refcounted? ((self <gtk-struct>)) (eq? (allocation-type-of self) 'refcounted)) (define (make-struct name fields) (let* ((c-name (string-drop name 1)) ;; drop preceding '_' (s (make <gtk-struct> :c-name (string->symbol c-name) :fields fields)) (tn (find-type-or-create (string->symbol #`",|c-name|*"))) (scmname (mixed-case-name->hyphenated-name c-name)) ) (set! (c-type-of s) tn) (set! (body-of tn) s) (set! (scm-class-name-of s) (string->symbol #`"<,|scmname|>")) (let1 base (string-tr scmname "a-z-" "A-Z_") (set! (c-caster-of s) base) (set! (c-predicate-of s) #`"SCM_,|base|_P") (set! (c-predicate-nullable-of s) #`"SCM_,|base|_OR_NULL_P") (set! (c-unboxer-of s) #`"SCM_,|base|") (set! (c-boxer-of s) #`"SCM_MAKE_,|base|") (set! (c-class-macro-of s) #`"SCM_CLASS_,|base|") ;; Anormality: GdkWindowObject uses GDK_IS_WINDOW macro (set!-values ((gtk-predicate-of s) (gtk-type-name-of s)) (cond ((equal? c-name "GdkWindowObject") (values "GDK_IS_WINDOW" "GDK_TYPE_WINDOW")) ((string-prefix? "PANGO" base) (values #`",(string-take base 6)IS_,(string-drop base 6)" #`",(string-take base 6)TYPE_,(string-drop base 6)")) (else ;; either GDK_ or GTK_ (values #`",(string-take base 4)IS_,(string-drop base 4)" #`",(string-take base 4)TYPE_,(string-drop base 4)")))) ) s)) (define (find-struct scm-name) (instance-pool-find <gtk-struct> (lambda (s) (eq? (scm-class-name-of s) scm-name)))) ;; <GTK-ARRAY> (define-class <gtk-array> () ((size :init-keyword :size :accessor size-of) (element-type :init-keyword :element-type :accessor element-type-of))) ;; <GTK-ENUM> (define-class <gtk-enum> (<instance-pool-mixin> <source-tracker-mixin>) ((c-name :init-keyword :c-name :accessor c-name-of) (values :init-keyword :values :accessor values-of) )) (define (make-enum name values) (let* ((n (string->symbol name)) (s (make <gtk-enum> :c-name n :values values))) (set! (body-of (find-type-or-create n)) s) s)) ;; <GTK-FUNCTION> (define-class <gtk-function> (<instance-pool-mixin> <source-tracker-mixin>) ((c-name :init-keyword :c-name :accessor c-name-of) (return-type :init-keyword :return-type :accessor return-type-of) (arguments :init-keyword :arguments :accessor arguments-of) (internal? :init-value #f :accessor internal?) ;; - true if this function is not exposed to Scheme. set by fixup-functions (scm-name :init-keyword :scm-name :accessor scm-name-of) ;; - scheme name, like gtk-foo for C-function gtk_foo. (body :init-value #f :accessor body-of) )) (define (make-function name ret args) (let1 scm-name (string->symbol (string-tr (x->string name) "_" "-")) (make <gtk-function> :c-name name :scm-name scm-name :return-type ret :arguments args))) (define (find-function scm-name) (instance-pool-find <gtk-function> (lambda (f) (eq? (scm-name-of f) scm-name)))) ;; <EXTRA-STUB> - literal stub added by hints file (define-class <extra-stub> (<source-tracker-mixin>) (;; s-expr to be placed in the stub file (body :init-keyword :body :accessor body-of) ;; true if this should go to .types file instead of .stub file (type? :init-keyword :type? :accessor type?))) (define-method print-body ((self <extra-stub>)) (write (body-of self)) (newline) (newline)) ;;================================================================ ;; UTILITIES ;; (define (report msg) (when (verbose) (display msg (current-error-port)) (newline (current-error-port)))) ;; FooBarBaz => foo-bar-baz ;; FooZBar => foo-zbar ;; FooZZBar => foo-zz-bar (define (mixed-case-name->hyphenated-name name) (define (loop current prev ncaps) (cond ((eof-object? current) (write-char (char-downcase prev))) ((char-upper-case? current) (if (char-lower-case? prev) (begin (write-char prev) (write-char #\-) (loop (read-char) current 1)) (begin (write-char (char-downcase prev)) (loop (read-char) current (+ ncaps 1))))) ((char-lower-case? current) (when (> ncaps 2) (write-char #\-)) (write-char (char-downcase prev)) (loop (read-char) current 0)) (else (write-char (char-downcase prev)) (loop (read-char) current 0)))) (with-output-to-string (lambda () (with-input-from-string name (lambda () (let1 c0 (read-char) (unless (eof-object? c0) (loop (read-char) c0 0))))))) ) ;;================================================================ ;; PASS 1 - PARSER ;; (define (parse-headers dir hlist) (for-each (lambda (hdr) (parse-header (build-path dir hdr))) hlist)) (define (parse-header filename) (parameterize ((input-file filename)) (report #`"parsing ,filename") (with-input-from-file filename parse-body))) (define (parse-body) (rxmatch-case (read-line) (test eof-object?) (#/^struct (_G[dt]k\w+)/ (#f name) (parse-struct name) (parse-body)) (#/^struct (_Pango\w+)/ (#f name) (parse-struct name) (parse-body)) (#/^typedef enum/ () (parse-enum) (parse-body)) (#/^([\w\*_]+)\s+((\*+)\s*)?((g[dt]k|pango)_[\w_]+)\s*\((.+)$/ (#f ret #f ptr fn #f rest) (parse-function (if ptr #`",|ret|,|ptr|" ret) fn rest) (parse-body)) (else (parse-body)))) (define (parse-struct name) (define (err-eof) (errorf "EOF while parsing struct ~s" name)) (define (parse-struct-body) (let loop ((line (read-line)) (fields '())) (rxmatch-case line (test eof-object? (err-eof)) (#/^\s*$/ () (loop (read-line) fields)) (#/^\{/ () (loop (read-line) fields)) (#/^\}/ () (make-struct name (reverse fields))) (test has-comment? (skip-comment line (cut loop <> fields) err-eof)) (#/^\s+([\w\*_]+)\s+([\w\*_]+)(\[([\w_]+)\])?\s*(:\s*\d+\s*)?\;/ (#f type var #f array) (if array (loop (read-line) (cons (grok-arraydef type var array) fields)) (loop (read-line) (cons (grok-vardef type var) fields)))) (#/^\s+[\w\*_]+\s+\**\([\w\*_]+\)(.*)/ (#f rest) ;; function pointer - ignore (let loop2 ((line rest)) (rxmatch-case line (test eof-object? (err-eof)) (#/\)\;/ () (loop (read-line) fields)) (else (loop2 (read-line)))))) (#/^\s+([\w\*_]+)\s+([\w\*_]+)\s*,(.*)$/ (#f type var rest) ;; something like int x,y; (let loop2 ((rest rest) (fields (cons (grok-vardef type var) fields))) (rxmatch-case rest (#/\s*([\w\*_]+)\s*\;/ (#f var) (loop (read-line) (cons (grok-vardef type var) fields))) (#/\s*([\w\*_]+)\s*,(.*)$/ (#f var rest) (loop2 rest (cons (grok-vardef type var) fields))) (else (warn "~s in ~a" line name) (loop (read-line) fields))))) (else (warn "~s in ~a" line name) (loop (read-line) fields)) ))) (define (skip-struct) (let loop ((line (read-line))) (rxmatch-case line (test eof-object? (err-eof)) (#/^\{/ () (loop (read-line))) (#/^\}/ () '()) (else (loop (read-line))) ))) (if (string-suffix? "Class" name) (skip-struct) (parse-struct-body)) ) (define (parse-enum) (define (err-eof) (error "EOF while parsing enum")) (let loop ((line (read-line)) (enums '())) (rxmatch-case line (test eof-object? (err-eof)) (#/^\{/ () (loop (read-line) enums)) (#/^\}\s*([\w_]+)/ (#f name) (make-enum name (reverse enums))) (#/^\s*$/ () (loop (read-line) enums)) (test has-comment? (skip-comment line (cut loop <> enums) err-eof)) (#/\s+([\w_]+),?/ (#f enum) (loop (read-line) (cons enum enums))) (#/\s+([\w_]+)\s+=/ (#f enum) (loop (read-line) (cons enum enums))) (else (warn "~s in enum" line) (loop (read-line) enums)) ))) (define (parse-function ret name rest) (define (err-eof) (errorf "EOF while parsing function ~s" name)) (define (grok-arg argstr) (rxmatch-case (string-trim-both argstr) (#/^const\s+(.+)$/ (#f rest) (let1 r (grok-arg rest) (acons 'const (car r) (cdr r)))) (#/^([\w\*_]+)\s+([\w\*_]+)$/ (#f type name) (cons type name)) (#/^([\w\*_]+)\s+\(([\w\*_]+)\)/ (#f type name) (acons 'fn type name)) (#/^void$/ () '()) (#/^...$/ () (cons "VARARG" "...")) (else (warn "can't grok arg ~a in ~a" argstr name) '("UNKNOWN" . "UNKNOWN")))) (define (finish-function ret name rargs) (make-function name (find-type-or-create (string->symbol ret)) (reverse (map (lambda (arg) (let1 a (grok-arg arg) (if (null? a) a (grok-vardef (car a) (cdr a))))) rargs)))) (let loop ((line rest) (args '())) (rxmatch-case line (test eof-object? (err-eof)) (#/^\s*$/ () (loop (read-line) args)) (test has-comment? (skip-comment line (cut loop <> args) err-eof)) (#/\s*([^,]+),(.*)/ (#f arg rest) (loop rest (cons arg args))) (#/\s*(.+)\).*\;/ (#f arg) (finish-function ret name (cons arg args))) (else (warn "~s in ~a" line name) (loop (read-line) args))))) (define (has-comment? line) (string-scan line "/*")) (define (skip-comment line cont error-eof) (receive (prev next) (string-scan line "/*" 'both) (cond ((string-scan next "*/" 'after) => (lambda (n) (cont #`",|prev| ,|n|"))) (else (let loop ((line (read-line))) (rxmatch-case line (test eof-object? (error-eof)) (#/\*\/(.*)/ (#f rest) (cont #`",|prev| ,|rest|")) (else (loop (read-line)))))))) ) ;;================================================================ ;; PASS 2 - FIXUPS ;; ;; Load "hints" files (define (load-hints) (parameterize ((input-file "hints.h")) ;;dummy (for-each (lambda (file) (when (file-exists? file) (report #`" loading ,file") (load file))) '("./pango-lib.hints" "./gdk-lib.hints" "./gtk-lib.hints" )))) ;; utilities that can be used inside hints file (define-macro (define-cproc-fix name . body) `(cproc-fix ',name (lambda (self) ,@body))) (define (cproc-fix name body) (let1 self (or (find-function name) (make <gtk-function> :scm-name name :c-name (string->symbol (string-tr (x->string name) "-" "_")) :return-type (find-type 'void) :arguments '())) (body self))) (define-macro (disable-cproc name) `(cond ((find-function ',name) => (lambda (f) (set! (internal? f) #t))))) (define-macro (fix-arguments! args) `(set! (arguments-of self) ,args)) (define-macro (fix-body! body) `(begin (set! (return-type-of self) #f) (set! (body-of self) ,body))) (define-macro (define-cclass-fix name . body) `(cclass-fix ',name (lambda (self) ,@body))) (define (cclass-fix name body) (let1 self (or (find-struct name) (error "cclass-fix: no such struct" name)) (body self))) (define-macro (disable-cclass name) `(cond ((find-struct ',name) => (lambda (s) (set! (internal? s) #t))))) (define-macro (fix-field! name . body) `((lambda (field) . ,body) (or (find (lambda (p) (eq? (scm-name-of p) ,name)) (fields-of self)) (error "no such field" ',name)))) (define-macro (add-field! c-name typesig . opts) `(set! (fields-of self) (append (fields-of self) (make <gtk-var> :c-name ,c-name :type (find-type-or-create ',typesig) ,@opts)))) ;; some field may be missing in certain gtk versions. ;; use this to ignore such fields. NB: there may be more than ;; one field registered, if such fields appears within union. (define-macro (ignore-field! name) `(for-each (lambda (f) (set! (accessible? f) #f)) (filter (lambda (p) (eq? (scm-name-of p) ,name)) (fields-of self)))) (define-macro (ignore-field-except! names) `(for-each (lambda (f) (set! (accessible? f) #f)) (remove (lambda (p) (memq (scm-name-of p) ,names)) (fields-of self)))) (define-macro (add-mixin! . c-mixin-names) `(begin (set! (direct-supers-of self) (list ,@c-mixin-names (car (cpl-of self)))) (set! (cpl-of self) (list* ,@c-mixin-names (cpl-of self))))) ;; adds opaque GObject. (define-macro (define-opaque c-name type) `(make-opaque ',c-name ,type)) (define (make-opaque c-name type) (let* ((struct (make-struct #`"_,|c-name|" '()))) (case type ((:gobject) (set! (allocation-type-of struct) 'gobject) (set! (superclass-of struct) (find-type 'GObject)) (set! (cpl-of struct) '("Scm_GObjectClass"))) ((:indirect) (set! (allocation-type-of struct) 'indirect) (set! (superclass-of struct) #f) (set! (cpl-of struct) '())) ((:refcounted) (set! (allocation-type-of struct) 'refcounted) (set! (superclass-of struct) #f) (set! (cpl-of struct) '())) (else (error "unknown opaque object type" type))))) ;; extra cproc and cclass defined in the fix file is copied to ;; the output stub file. (define-macro (define-cclass . args) `(make <extra-stub> :body '(define-cclass ,@args) :type? #f)) (define-macro (define-cproc . args) `(make <extra-stub> :body '(define-cproc ,@args) :type? #f)) (define-macro (define-enum . args) `(make <extra-stub> :body '(define-enum ,@args) :type? #f)) (define-macro (define-constant . args) `(make <extra-stub> :body '(define-constant ,@args) :type? #f)) (define-macro (define-type . args) `(make <extra-stub> :body '(define-type ,@args) :type? #t)) (define-macro (raw-code . args) `(make <extra-stub> :body (string-join ',args "\n" 'suffix) :type? #f)) ;; figure out what implemenation type each structure is, ;; by examining its first field. (define-method set-superclass ((self <gtk-struct>)) (if (slot-bound? self 'superclass) (superclass-of self) (receive (superclass gobject) (if (null? (fields-of self)) (values #f #f) (let ((first-slot-type (type-of (car (fields-of self))))) (cond ((eq? (c-name-of first-slot-type) 'GObject) (values first-slot-type #t)) ((and-let* ((ptrname (string->symbol #`",(c-name-of first-slot-type)*")) (ptrtype (find-type ptrname)) ((is-a? (body-of ptrtype) <gtk-struct>)) ((set-superclass (body-of ptrtype)))) (values ptrtype (gobject? (body-of ptrtype))))) (else (values #f #f))))) (when gobject (set! (allocation-type-of self) 'gobject)) (set! (superclass-of self) superclass) superclass))) (define-method set-cpl ((self <gtk-struct>)) ;; after setting up superclass field of all structs, sets up CPL. ;; the hints file may modify CPL afterwards. (set! (cpl-of self) (let loop ((super (superclass-of self)) (classes '())) (cond ((not super) (reverse classes)) ((eq? (c-name-of super) 'GObject) (reverse (cons "Scm_GObjectClass" classes))) ((eq? (c-name-of super) 'GdkEvent*) (reverse (cons "Scm_GdkEventClass" classes))) (else (loop (superclass-of (body-of super)) (cons #`"Scm_,(c-name-of (body-of super))Class" classes)))))) ) (define-method set-refcounted ((self <gtk-struct>)) ;; use heuristics to find out if self is a ref-counting object (and not an ;; GObject). (when (find (lambda (field) (equal? (c-name-of field) "ref_count")) (fields-of self)) (set! (allocation-type-of self) 'refcounted))) (define-method set-fields ((self <gtk-struct>)) ;; scan <gtk-var>'s in the fields and sets up it's default setter and getter (define (set-field-getter-n-setter field) (let ((stub-type (scm-type-of (type-of field)))) (cond ((eq? stub-type '<gchar*>) (set! (ref field 'getter) #`"return SCM_MAKE_STR_COPYING_SAFELY(obj->,(c-name-of field));") (set! (ref field 'setter) #f)) ((not (pair? stub-type)) ; has proper stub type, so no need of g&s. (set! (ref field 'getter) #t) (set! (ref field 'setter) #t)) (;; check if it is an embedded structure. (and-let* ((ptrtype (find-type (string->symbol #`",(c-name-of (type-of field))*"))) (ptrbody (body-of ptrtype)) ((is-a? ptrbody <gtk-struct>))) (set! (ref field 'getter) #`"return ,(c-boxer-of ptrbody)(&(obj->,(c-name-of field)));") (set! (ref field 'setter) #`"obj->,(c-name-of field) = *,(c-unboxer-of ptrbody)(value);") )) (;; check if it is an array reference. (and-let* ((arr (body-of (type-of field))) ((is-a? arr <gtk-array>)) (elttype (element-type-of arr)) (unboxer (get-slot-boxer elttype))) (set! (ref field 'getter) #`"ScmObj vec = Scm_MakeVector(,(size-of arr), SCM_FALSE); int i; for (i=0; i<,(size-of arr); i++) { SCM_VECTOR_ELEMENTS(vec)[i] = ,(unboxer #`\"(obj->,(c-name-of field)[i])\"); } return vec;") (set! (ref field 'setter) #f))) (else (set! (ref field 'accessible?) #f))))) (for-each set-field-getter-n-setter (fields-of self)) ) (define-method set-qualifier ((self <gtk-struct>)) ;; sets GtkObject subclasses :base class, so that Scheme subclass can ;; be defined. (when (eq? (allocation-type-of self) 'gobject) (set! (qualifier-of self) :base))) (define (fixup-structs) ;; Special treatment : GdkBitmap*, GdkPixmap* and GdkWindow* are really ;; synonyms of GdkDrawable*. (let ((gdkdrawable (find-type 'GdkDrawable*))) (for-each (lambda (n) (set! (body-of (find-type n)) (body-of gdkdrawable))) '(GdkBitmap* GdkPixmap* GdkWindow*))) ;; GtkAllocation is an alias of GdkRectangle. (let ((gtk-allocation-type (find-type-or-create 'GtkAllocation*)) (gdk-rectangle-struct (find-struct '<gdk-rectangle>))) (set! (body-of gtk-allocation-type) gdk-rectangle-struct)) (for-each-instance set-superclass <gtk-struct>) (for-each-instance set-cpl <gtk-struct>) (for-each-instance set-refcounted <gtk-struct>) (for-each-instance set-fields <gtk-struct>) ) (define (fixup-structs-after) ;; need to do this after loading hints, for the allocation type of ;; the struct may be modified in hints. (for-each-instance set-qualifier <gtk-struct>) ) ;; Some heuristics to remove irrelevant functions (define-method set-internal ((self <gtk-function>)) (let1 cnam (x->string (c-name-of self)) (when (or (string-suffix? "_ref" cnam) (string-suffix? "_unref" cnam) (string-suffix? "_get_type" cnam)) (set! (internal? self) #t)))) (define-method fix-arg ((self <gtk-function>)) ;; This is for (void) argument list (when (equal? (arguments-of self) '(())) (set! (arguments-of self) '())) ;; Ignore 'const' qualifier (except const-char*) (for-each (lambda (arg) (let* ((type (type-of arg)) (typename (c-name-of type))) (when (and (not (memq typename '(const-char* const-gchar*))) (string-prefix? "const-" (x->string typename))) (set! (type-of arg) (find-type-or-create (string->symbol (string-drop (x->string typename) 6))))))) (arguments-of self)) ) (define (fixup-functions) (for-each-instance set-internal <gtk-function>) (for-each-instance fix-arg <gtk-function>) ) (define (fixup) (fixup-structs) (fixup-functions) (load-hints) (fixup-structs-after) ) ;;================================================================ ;; PASS 3 - EMITTER ;; ;; emit.types - generate *.types file ;; emit.h - generate *.h file ;; emit.stub - generate *.stub file (define-method emit.types ((self <gtk-struct>) commenter) (print #`"(define-type ,(scm-class-name-of self) \",(c-name-of (c-type-of self))\" #f") (print #`" \",(c-predicate-of self)\" \",(c-unboxer-of self)\" \",(c-boxer-of self)\")") (print #`"(define-type ,(scm-class-name-of self)-or-null \",(c-name-of (c-type-of self))\" #f") (print #`" \",(c-predicate-nullable-of self)\" \",(c-unboxer-of self)\" \",(c-boxer-of self)\")") (print)) (define-method emit.types ((self <extra-stub>) commenter) (when (type? self) (print-body self))) (define-method emit.types ((self <top>) commenter) #f) (define-method emit.h ((self <gtk-struct>) commenter) (let1 atype (allocation-type-of self) ;; Structure definition. Note necessary for GObjects. (case atype ((refcounted indirect simple) (print #`"typedef struct Scm,(c-name-of self)Rec {") (print #`" SCM_HEADER;") (print #`" ,(c-name-of self) ,(if (eq? atype 'simple) \"\" \"*\")data;") (print #`"} Scm,(c-name-of self);") (print))) ;; Class declaration (print #`"SCM_CLASS_DECL(Scm_,(c-name-of self)Class);") (print #`"#define ,(c-class-macro-of self) (&Scm_,(c-name-of self)Class)") ;; Type predicate (case atype ((gobject) (print #`"#define ,(c-predicate-of self)(obj) (Scm_TypeP(obj, ,(c-class-macro-of self)))")) (else (print #`"#define ,(c-predicate-of self)(obj) SCM_XTYPEP(obj, ,(c-class-macro-of self))"))) ;; Boxer and unboxer (case atype ((gobject) (print #`"#define ,(c-unboxer-of self)(obj) SCM_GOBJECT_UNBOX(,(c-caster-of self), obj)") (print #`"#define ,(c-boxer-of self)(obj) SCM_GOBJECT_BOX(obj)")) ((refcounted indirect) (print #`"#define ,(c-unboxer-of self)(obj) (SCM_FALSEP(obj)?NULL:((Scm,(c-name-of self)*)(obj))->data)") (print #`"#define ,(c-boxer-of self)(obj) (Scm_Make,(c-name-of self)(obj))")) (else (print #`"#define ,(c-unboxer-of self)(obj) (SCM_FALSEP(obj)?NULL:&((Scm,(c-name-of self)*)(obj))->data)") (print #`"#define ,(c-boxer-of self)(obj) (Scm_Make,(c-name-of self)(obj))"))) (print #`"#define ,(c-predicate-nullable-of self)(obj) (SCM_FALSEP(obj)||,(c-predicate-of self)(obj))") (case atype ((refcounted indirect simple) (print #`"extern ScmObj Scm_Make,(c-name-of self)(,(c-name-of self) *data);"))) (print) )) (define-method emit.h ((self <top>) commenter) #f) (define-method emit.stub ((self <gtk-struct>) commenter) (print (commenter #`" struct ,(c-name-of self)")) (print) (unless (internal? self) (case (allocation-type-of self) ((gobject) (emit.stub-gobject self commenter)) ((indirect) (emit.stub-indirect self commenter)) ((refcounted) (emit.stub-refcounted self commenter)) (else (emit.stub-simple self commenter))))) (define (emit.stub-gobject self commenter) (print #`"(define-cclass ,(scm-class-name-of self) :,(qualifier-of self)") (print #`" \"ScmGObject*\" \"Scm_,(c-name-of self)Class\"") (emit.stub-class-hierarchy self) ;; Exclude the first slot which is an instance of superclass (let1 fields (fields-of self) (if (null? fields) (emit.stub-fields '()) (emit.stub-fields (cdr fields)))) ;; Allocator (print #`"(allocator (c \"Scm_GtkObjectAllocate\"))") ;; Direct supers, if it has mixin (when (not (null? (direct-supers-of self))) (write (cons 'direct-supers (direct-supers-of self))) (newline)) (print #`" )") (print) ;; Register initialization code (print #`"(initcode \"Scm_GtkRegisterClass(,(gtk-type-name-of self), ,(c-class-macro-of self));\n\")") (print) ) (define (emit.stub-refcounted self commenter) (let ((finalizer #`"scm_,(c-name-of self)_finalize") (cfn (string-tr (mixed-case-name->hyphenated-name (x->string (c-name-of self))) "-" "_"))) (print #`"\"static void ,|finalizer|(ScmObj obj, void* data)") (print #`" {") (print #`" Scm,(c-name-of self) *p = (Scm,(c-name-of self)*)obj;") (print #`" ,(c-name-of self) *d = ,(c-unboxer-of self)(obj);") (print #`" ,|cfn|_unref(d);") (print #`" p->data = NULL;") (print #`" }\"") (print) (print #`"\"ScmObj Scm_Make,(c-name-of self)(,(c-name-of self) *data)") (print #`" {") (print #`" Scm,(c-name-of self) *z = SCM_NEW(Scm,(c-name-of self));") (print #`" SCM_SET_CLASS(z, ,(c-class-macro-of self));") (print #`" z->data = data;") (print #`" Scm_RegisterFinalizer(SCM_OBJ(z), ,|finalizer|, NULL);") (print #`" ,|cfn|_ref(z->data);") (print #`" return SCM_OBJ(z);") (print #`" }\"") (print) (print #`"(define-cclass ,(scm-class-name-of self)") (print #`" \",(c-name-of self)*\" \"Scm_,(c-name-of self)Class\"") (emit.stub-class-hierarchy self) (emit.stub-fields (fields-of self)) (print #`" )") (print) )) (define (emit.stub-indirect self commenter) (let ((finalizer #`"scm_,(c-name-of self)_finalize")) (when (c-free-proc-of self) (print #`"\"static void ,|finalizer|(ScmObj obj, void* data)") (print #`" {") (print #`" Scm,(c-name-of self) *p = (Scm,(c-name-of self)*)obj;") (print #`" ,(c-name-of self) *d = ,(c-unboxer-of self)(obj);") (print #`" ,(c-free-proc-of self)(d);") (print #`" p->data = NULL;") (print #`" }\"") (print)) (print #`"\"ScmObj Scm_Make,(c-name-of self)(,(c-name-of self) *data)") (print #`" {") (print #`" Scm,(c-name-of self) *z = SCM_NEW(Scm,(c-name-of self));") (print #`" SCM_SET_CLASS(z, ,(c-class-macro-of self));") (if (c-copy-proc-of self) (print #`" z->data = ,(c-copy-proc-of self)(data);") (print #`" z->data = data;")) (when (c-free-proc-of self) (print #`" Scm_RegisterFinalizer(SCM_OBJ(z), ,|finalizer|, NULL);")) (print #`" return SCM_OBJ(z);") (print #`" }") (print #`"\"") (print) (print #`"(define-cclass ,(scm-class-name-of self)") (print #`" \",(c-name-of self)*\" \"Scm_,(c-name-of self)Class\"") (emit.stub-class-hierarchy self) (emit.stub-fields (fields-of self)) (print #`" )") (print) )) (define (emit.stub-simple self commenter) (print #`"\"ScmObj Scm_Make,(c-name-of self)(,(c-name-of self) *data)") (print #`" {") (cond ((allocator-of self) => print) (else (print #`" Scm,(c-name-of self) *z = SCM_NEW(Scm,(c-name-of self));") (print #`" SCM_SET_CLASS(z, ,(c-class-macro-of self));") (print #`" if (data) z->data = *data; /*copy*/") (print #`" return SCM_OBJ(z);"))) (print #`" }") (print #`"\"") (print) (print #`"(define-cclass ,(scm-class-name-of self)") (print #`" \",(c-name-of self)*\" \"Scm_,(c-name-of self)Class\"") (emit.stub-class-hierarchy self) (emit.stub-fields (fields-of self)) (print #`" (allocator \"return Scm_Make,(c-name-of self)(NULL);\")") (print #`" )") (print) ) (define (emit.stub-class-hierarchy self) (format #t " ~s\n" (cpl-of self))) (define (emit.stub-fields fields) (print " (") (for-each emit.stub-field fields) (print " )")) (define (emit.stub-field field) (let ((sname (scm-name-of field)) (type (scm-type-of (type-of field)))) (if (accessible? field) (format #t " ~s\n" `(,sname ,@(if (not (pair? type)) (list :type type) '()) ,@(if (not (eq? (getter-of field) #t)) (list :getter (getter-of field)) '()) ,@(if (not (eq? (setter-of field) #t)) (list :setter (setter-of field)) '()))) (print #`" ;; ,sname :type ,type")))) (define-method emit.stub ((self <gtk-enum>) commenter) (print (commenter #`" enum ,(c-name-of self)")) (for-each (lambda (v) (print #`"(define-enum ,v)")) (values-of self)) (print)) (define-method emit.stub ((self <gtk-function>) commenter) (print (commenter (c-name-of self))) (unless (internal? self) (let* ((unknown-arg? #f) (s-name (scm-name-of self)) (args (map (lambda (arg) (cond ((null? arg) (error "huh?" (c-name-of self))) ((symbol? arg) arg) (else (let ((name (c-name-of arg)) (s-type (scm-type-of (type-of arg)))) (when (pair? s-type) (set! unknown-arg? #t)) (string->symbol #`",|name|::,|s-type|"))))) (arguments-of self))) (ret (or (and-let* ((r (return-type-of self)) (t (scm-type-of r))) (when (pair? t) (set! unknown-arg? #t)) (list t)) '())) (sig `(define-cproc ,s-name ,args ,(or (body-of self) `(call ,@ret ,(x->string (c-name-of self)))))) ) (if unknown-arg? (print (commenter sig)) (begin (write sig) (newline)))) (print))) (define-method emit.stub ((self <extra-stub>) commenter) (unless (type? self) (print-body self))) (define (c-commenter content) #`"/* ,|content| */") (define (s-commenter content) #`";; ,content") (define (emitter method commenter) (print (commenter "Automatically generated - DO NOT EDIT")) (print) (for-each-source-file (lambda (file defined) (print (commenter (sys-basename file))) (print) (for-each (cut method <> commenter) defined) ))) ;; Emit gtk-lib.inits ;; The order of initialization is important, since the superclasses have ;; to be initialized before initializing subclass. Sort-files-for-inits ;; takes care of it. (define (emit.inits) (define (base file) (string-tr (string-drop-right (sys-basename file) 2) "-" "_")) (define files (sort-files-for-inits)) (print (c-commenter "Automatically generated - DO NOT EDIT")) (print) (for-each (lambda (file) (print #`"extern void Scm_Init_,(base file)(ScmModule*);")) files) (print) (print #`"void Scm_Init_gtk_lib(ScmModule *mod)") (print #`"{") (for-each (lambda (file) (print #`" Scm_Init_,(base file)(mod);")) files) (print #`"}")) ;; Sort files so that classes are initialized in the right order. (define (sort-files-for-inits) (let* ((files&defs (get-files&definitions)) ;; Quick mapper from <gtk-struct> to is defining file (struct->file (let ((table (make-hash-table))) (for-each (lambda (file&defs) (for-each (lambda (def) (when (is-a? def <gtk-struct>) (hash-table-put! table def (car file&defs)))) (cdr file&defs))) files&defs) (lambda (struct) (hash-table-get table struct #f)))) ;; returns a file that defines supertype of the given struct, or #f. (get-super-file (lambda (src-file struct) (and-let* ((super (superclass-of struct)) ((is-a? (body-of super) <gtk-struct>)) (file (struct->file (body-of super))) ((not (equal? src-file file)))) file))) (dependency-table (let ((table (make-hash-table 'string=?))) (for-each (lambda (file&defs) (hash-table-put! table (car file&defs) '())) files&defs) (for-each (lambda (file&defs) (receive (file defs) (car+cdr file&defs) (for-each (lambda (def) (and-let* (((is-a? def <gtk-struct>)) (super (get-super-file file def)) ((not (member super (hash-table-get table file))))) (hash-table-push! table file super))) defs))) files&defs) table)) ) (reverse (topological-sort (hash-table-map dependency-table cons))) )) ;; These types will be added to gtk-lib.types (define *predefined-types* '((define-type <const-char*> "const char *" #f "SCM_STRINGP" "CONST_CHAR_PTR") (define-type <const-gchar*> "const gchar *" #f "SCM_STRINGP" "CONST_GCHAR_PTR") (define-type <gchar*> "gchar *" #f "SCM_STRINGP" "CONST_GCHAR_PTR" "GCHAR_PTR_BOX") (define-type <const-gchar*>-or-null "const gchar *" #f "SCM_STRING_OR_NULL_P" "CONST_GCHAR_PTR_NULLABLE") (define-type <g-object> "GObject *" #f "SCM_GOBJECT_P" "SCM_GOBJECT_OBJECT" "SCM_GOBJECT_BOX") (define-type <g-timer> "GTimer *" #f "SCM_GTIMER_P" "SCM_GTIMER" "SCM_MAKE_GTIMER") (define-type <gdk-atom> "GdkAtom" #f #f #f "SCM_MAKE_GDK_ATOM") (define-type <gdk-event> "GdkEvent*" #f #f #f "SCM_MAKE_GDK_EVENT") (define-type <gdk-point-vector> "ScmGdkPointVector*") (define-type <gdk-segment-vector> "ScmGdkSegmentVector*") (define-type <gdk-rectangle-vector> "ScmGdkRectangleVector*") (define-type <gdk-color-vector> "ScmGdkColorVector*") (define-type <gtk-radio-group> "ScmGtkRadioGroup*") ;; we need a standard mechanism to incorporate these, really. (define-type <u8vector> "ScmU8Vector*") (define-type <s8vector> "ScmS8Vector*") (define-type <u16vector> "ScmU16Vector*") (define-type <s16vector> "ScmS16Vector*") (define-type <u32vector> "ScmU32Vector*") (define-type <s32vector> "ScmS32Vector*") (define-type <u64vector> "ScmU64Vector*") (define-type <s64vector> "ScmS64Vector*") (define-type <f32vector> "ScmF32Vector*") (define-type <f64vector> "ScmF64Vector*") )) ;; overwrite the original file iff it is changed; avoiding triggering ;; excessive make. (define (with-output-to-file-if-changed file thunk) (let1 tmpfile #`",|file|.tmp" (with-output-to-file tmpfile thunk) (if (and (file-exists? file) (file-equal? tmpfile file)) (begin (report #`" no change in ,file") (sys-unlink tmpfile)) (begin (report #`" writing ,file") (sys-rename tmpfile file))))) (define (emit-all) (with-output-to-file-if-changed "gtk-lib.types" (lambda () (emitter emit.types s-commenter) ;; some additional stuff (for-each (lambda (t) (write t) (newline)) *predefined-types*))) (with-output-to-file-if-changed "gtk-lib.h" (lambda () (emitter emit.h c-commenter))) (for-each-source-file (lambda (file defined) (receive (extra normal) (partition (cut is-a? <> <extra-stub>) defined) (with-output-to-file-if-changed #`",(string-drop-right (sys-basename file) 2).stub" (lambda () (print (s-commenter "Automatically generated - DO NOT EDIT")) (print) (write '(include "gtk-lib.types")) (print) (write "#include \"gauche-gtk.h\"") (print) (print) ;; need to emit <extra-stub> first, for they may define ;; static fns. (for-each (cut emit.stub <> s-commenter) extra) (for-each (cut emit.stub <> s-commenter) normal)))))) (with-output-to-file-if-changed "gtk-lib.inits" emit.inits) ) ;;================================================================ ;; DRIVER ;; (define (parse-gdk) (parse-headers #`",(gtk-directory)/gdk" (call-with-input-file "GDKFILES" port->string-list))) (define (parse-gdk-pixbuf) (parse-headers #`",(gtk-directory)/gdk-pixbuf" (call-with-input-file "GDKPIXBUFFILES" port->string-list))) (define (parse-gtk) (parse-headers #`",(gtk-directory)/gtk" (call-with-input-file "GTKFILES" port->string-list))) (define (parse-pango) (parse-headers #`",(pango-directory)/pango" (call-with-input-file "PANGOFILES" port->string-list))) (define (run-through) (report "Parsing ...") (parse-pango) (parse-gdk) (parse-gdk-pixbuf) (parse-gtk) (report "Fixing up ...") (fixup) (report "Generating ...") (emit-all)) (define (main args) (run-through) 0)
false
92611783d2dd55d84dafab07e19e11e065177f21
ae76253c0b7fadf8065777111d3aa6b57383d01b
/chap2/exec-2.71.ss
0fac42047069a0062a5bffbada0029abc3c2c772
[]
no_license
cacaegg/sicp-solution
176995237ad1feac39355f0684ee660f693b7989
5bc7df644c4634adc06355eefa1637c303cf6b9e
refs/heads/master
2021-01-23T12:25:25.380872
2014-04-06T09:35:15
2014-04-06T09:35:15
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,480
ss
exec-2.71.ss
(define (make-leaf symbol weight) (list 'leaf symbol weight)) (define (leaf? object) (eq? (car object) 'leaf)) (define (tree? object) (eq? (car object) 'tree)) (define (symbol-leaf x) (cadr x)) (define (weight-leaf x) (caddr x)) (define (make-code-tree left right) (list 'tree left right (append (symbols left) (symbols right)) (+ (weight left) (weight right)))) (define (left-branch tree) (cadr tree)) (define (right-branch tree) (caddr tree)) (define (symbols tree) (if (leaf? tree) (list (symbol-leaf tree)) (cadddr tree))) (define (weight tree) (if (leaf? tree) (weight-leaf tree) (car (cddddr tree)))) (define (adjoin-set x set) (cond ((null? set) (list x)) ((< (weight x) (weight (car set))) (cons x set)) (else (cons (car set) (adjoin-set x (cdr set)))))) (define (make-leaf-set pairs) (if (null? pairs) '() (let ((pair (car pairs))) (adjoin-set (if (or (leaf? pair) (tree? pair)) ; To sort it, we need to know if it's pair ; tree node or leaf (make-leaf (car pair) (cadr pair))) (make-leaf-set (cdr pairs)))))) (define (successive-merge o-pairs) (if (= 1 (length o-pairs)) (car o-pairs) (successive-merge ; Resort again for each merge (make-leaf-set (cons (make-code-tree (car o-pairs) (cadr o-pairs)) (cddr o-pairs)))))) (define (encode-symbol symbol tree) (cond ((eq? #f (memq symbol (symbols tree))) (error symbol "No such symbol")) ((leaf? tree) '()) (else (let ((left-symbols (symbols (left-branch tree))) (right-symbols (symbols (right-branch tree)))) (if (eq? #f (memq symbol left-symbols)) (cons 1 (encode-symbol symbol (right-branch tree))) (cons 0 (encode-symbol symbol (left-branch tree)))))))) (define (encode-symbols symbols tree) (if (null? symbols) '() (append (encode-symbol (car symbols) tree) (encode-symbols (cdr symbols) tree)))) (define n5 '((a 1) (b 2) (c 4) (d 8) (e 16))) (define n10 '((a 1) (b 2) (c 4) (d 8) (e 16) (f 32) (g 64) (h 128) (i 256) (j 512))) (define (generate-huffman-tree pairs) (successive-merge (make-leaf-set pairs))) (newline) (generate-huffman-tree n5) (generate-huffman-tree n10) ; Most Frequent > 1 bit ; Least Frequent > n - 1 bits
false
14e05bd35a136a2909ac224f2db597310f480067
c39b3eb88dbb1c159577149548d3d42a942fe344
/07-compilation/interpreter1.scm
89f68292df886e64b46a5079b7e92581657bf3af
[]
no_license
mbillingr/lisp-in-small-pieces
26694220205818a03efc4039e5a9e1ce7b67ff5c
dcb98bc847c803e65859e4a5c9801d752eb1f8fa
refs/heads/master
2022-06-17T20:46:30.461955
2022-06-08T17:50:46
2022-06-08T17:50:46
201,653,143
13
3
null
2022-06-08T17:50:47
2019-08-10T16:09:21
Scheme
UTF-8
Scheme
false
false
5,303
scm
interpreter1.scm
(import (builtin core) (libs utils) (libs book) (06-fast-interpreter common)) ; this is basically the same as interpreter 6-3 but the instructions modified ; to make them more linear and use more registers along with an explicit stack. (include "pretreatment.scm") (define (make-closure code closed-environment) (list 'closure code closed-environment)) (define (closure? obj) (eq? (car obj) 'closure)) (define (closure-code obj) (cadr obj)) (define (closure-closed-environment obj) (caddr obj)) (define (invoke f) (if (closure? f) ((closure-code f) (closure-closed-environment f)) (wrong "Not a function" f))) (define (CONSTANT value) (lambda () (println "CONSTANT" value)(set! *val* value))) (define (SHALLOW-ARGUMENT-REF j) (lambda () (set! *val* (activation-frame-argument *env* j)))) (define (PREDEFINED i) (lambda () (set! *val* (predefined-fetch i)))) (define (DEEP-ARGUMENT-REF i j) (lambda () (set! *val* (deep-fetch *env* i j)))) (define (GLOBAL-REF i) (lambda () (set! *val* (global-fetch i)))) (define (CHECKED-GLOBAL-REF i) (lambda () (let ((v (global-fetch i))) (if (eq? v undefined-value) (wrong "Uninitialized variable") (set! *val* v))))) (define (ALTERNATIVE m1 m2 m3) (lambda () (m1) (if *val* (m2) (m3)))) (define (SHALLOW-ARGUMENT-SET! j m) (lambda () (m) (set-activation-frame-argument! *env* j *val*))) (define (DEEP-ARGUMENT-SET! i j m) (lambda () (m) (deep-update! *env* i j *env*))) (define (GLOBAL-SET! i m) (lambda () (m) (global-update! i *val*))) (define (SEQUENCE m m+) (lambda () (m) (m+))) (define (FIX-CLOSURE m+ arity) (let ((arity+1 (+ arity 1))) (lambda () (define (the-function sr) (if (= (activation-frame-argument-length *val*) arity+1) (begin (set! *env* (sr-extend* sr *val*)) (m+)) (wrong "Incorrect arity"))) (set! *val* (make-closure the-function *env*))))) (define (NARY-CLOSURE m+ arity) (let ((arity+1 (+ arity 1))) (lambda () (define (the-function sr) (if (>= (activation-frame-argument-length *val*) arity+1) (begin (listify! *val* arity) (set! *env* (sr-extend* sr *val*)) (m+)) (wrong "Incorrect arity"))) (set! *val* (make-closure the-function *env*))))) (define (TR-REGULAR-CALL m m*) (lambda () (m) (stack-push *val*) (m*) (set! *fun* (stack-pop)) (invoke *fun*))) (define (REGULAR-CALL m m*) (lambda () (m) (stack-push *val*) (m*) (set! *fun* (stack-pop)) (stack-push *env*) (invoke *fun*) (set! *env* (stack-pop)))) (define (STORE-ARGUMENT m m* rank) (lambda () (m) (stack-push *val*) (m*) (let ((v (stack-pop))) (set-activation-frame-argument! *val* rank v)))) (define (ALLOCATE-FRAME size) (let ((size+1 (+ size 1))) (lambda () (set! *val* (allocate-activation-frame size+1))))) (define (FIX-LET m* m+) (lambda () (m*) (set! *env* (sr-extend* *env* *val*)) (m+) ;(set! *env* (activation-frame-next *env*)))) (set! *env* (environment-next *env*)))) ; I think this is correct (define (TR-FIX-LET m* m+) (lambda () (m*) (set! *env* (sr-extend* *env* *val*)) (m+))) (define (CONS-ARGUMENT m m* arity) (lambda () (m) (stack-push *val*) (m*) (let ((v (stack-pop))) (set-activation-frame-argument! *val* arity (cons v (activation-frame-argument *val* arity)))))) (define (ALLOCATE-DOTTED-FRAME arity) (let ((arity+1 (+ arity 1))) (lambda () (set! *val* (allocate-activation-frame arity+1)) (set-activation-frame-argument! *val* arity '())))) (define (CALL0 address) (lambda () (set! *val* (address)))) (define (CALL1 address m1) (lambda () (m1) (set! *val* (address *val*)))) (define (CALL2 address m1 m2) (lambda () (m1) (stack-push *val*) (m2) (set! *arg1* (stack-pop)) (set! *val* (address *arg1* *val*)))) (define (CALL3 address m1 m2 m3) (lambda () (m1) (stack-push *val*) (m2) (stack-push *val*) (m3) (set! *arg2* (stack-pop)) (set! *arg1* (stack-pop)) (set! *val* (address *arg1* *arg2* *val*)))) ; some dummy definitions (define *env* '()) (define *val* '()) (define *fun* '()) (define *arg1* '()) (define *arg2* '()) (define *stack* (make-vector 1000)) (define *stack-index* 0) (define (stack-push v) (println "push" v) (vector-set! *stack* *stack-index* v) (set! *stack-index* (+ *stack-index* 1))) (define (stack-pop) (println "pop") (set! *stack-index* (- *stack-index* 1)) (vector-ref *stack* *stack-index*)) (include "common-primitives.scm") (define (chapter7-interpreter1) (define (toplevel) (set! *env* sr.init) ((meaning (read) r.init #t)) (display *val*) (toplevel)) (toplevel)) (chapter7-interpreter1)
false
4f602f51bbd2bd16e184725d6a36ea0e4b71a521
174072a16ff2cb2cd60a91153376eec6fe98e9d2
/Chap-one/fixed-point-transform.scm
1aab6f6d77716860dd578c9dc2319bd1e542b836
[]
no_license
Wang-Yann/sicp
0026d506ec192ac240c94a871e28ace7570b5196
245e48fc3ac7bfc00e586f4e928dd0d0c6c982ed
refs/heads/master
2021-01-01T03:50:36.708313
2016-10-11T10:46:37
2016-10-11T10:46:37
57,060,897
1
0
null
null
null
null
UTF-8
Scheme
false
false
676
scm
fixed-point-transform.scm
(define (deriv g) (lambda (x) (/ (- (g (+ x dx)) (g x)) dx))) (define dx 0.0000001) (load "square.scm") (define (newton-transform g) (lambda (x) (- x (/ (g x) ((deriv g) x))))) (define (fixed-point f first-guess) (define (close-enough? a b) (< (abs ( - a b)) tolerance)) (define (try guess) (let ((next ( f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) (define tolerance 0.00001) (define (fixed-point-of-transform g transform guess) (fixed-point (transform g) guess)) (define (sqrt x) (fixed-point-of-transform (lambda (y) (- (square y) x)) newton-transform 1.0))
false
054207e04aced1913230ee0bee1901e2f85b7e34
354ae3428451a81e5a6e07d282edb9bd79ff0e3f
/private/variant.ss
44996544f497436eb8e8d1ae73a0d0d08570415a
[]
no_license
jeapostrophe/datalog
385a478dc18a904a35cbe36ebc7b1a7ec0a26478
a5d59e455b49d091f3c5348e4c1f0071a1bc0134
refs/heads/master
2021-01-18T13:42:51.827415
2013-10-31T01:32:07
2013-10-31T01:32:07
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,396
ss
variant.ss
#lang scheme (require "../ast.ss" "env.ss") ; Variants (define (variant-terms env1 env2 ts1 ts2) (if (empty? ts1) (empty? ts2) (and (not (empty? ts2)) (variant-term env1 env2 (first ts1) (first ts2) (rest ts1) (rest ts2))))) (define (variant-term env1 env2 t1 t2 ts1 ts2) (or (and (variable? t1) (variable? t2) (variant-var env1 env2 (variable-sym t1) (variable-sym t2) ts1 ts2)) (and (term-equal? t1 t2) (variant-terms env1 env2 ts1 ts2)))) (define (variant-var env1 env2 v1 v2 ts1 ts2) (match (cons (lookup env1 v1) (lookup env2 v2)) [(list-rest #f #f) (variant-terms (extend env1 v1 (make-variable #f v2)) (extend env2 v2 (make-variable #f v1)) ts1 ts2)] [(list (struct variable (_ v1-p)) (struct variable (_ v2-p))) (and (datum-equal? v1-p v2) (datum-equal? v2-p v1) (variant-terms env1 env2 ts1 ts2))] [_ #f])) (define (variant? l1 l2) (and (datum-equal? (literal-predicate l1) (literal-predicate l2)) (variant-terms (empty-env) (empty-env) (literal-terms l1) (literal-terms l2)))) (define (mem-literal lit ls) (ormap (lambda (l) (variant? lit l)) ls)) ; Literal Tables modulo variant? (define (term-hash t recur-hash) (cond [(variable? t) 101] [(constant? t) (recur-hash (constant-datum t))])) (define ((mk-literal-hash recur-hash) l) (let loop ([code (recur-hash (literal-predicate l))] [i 0] [terms (literal-terms l)]) (if (empty? terms) code (loop (+ code (term-hash (first terms) recur-hash) (* i -7)) (add1 i) (rest terms))))) (define literal-tbl/c (coerce-contract 'variant dict?)) (define (make-literal-tbl) (make-custom-hash variant? (mk-literal-hash equal-hash-code) (mk-literal-hash equal-secondary-hash-code))) (define (literal-tbl-find ltbl s) (dict-ref ltbl s #f)) (define (literal-tbl-replace! ltbl s x) (dict-set! ltbl s x)) (provide/contract [literal-tbl/c contract?] [make-literal-tbl (-> literal-tbl/c)] [literal-tbl-find (literal-tbl/c literal? . -> . (or/c false/c any/c))] [literal-tbl-replace! (literal-tbl/c literal? any/c . -> . void)] [mem-literal (literal? (listof literal?) . -> . boolean?)])
false
1542bd976f0645d19eb6729c447ddff0ecee57e7
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/ice-9/time.scm
0fad8dfca0adbafdb64fc78e392ae5f9cc70c2d5
[ "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
2,088
scm
time.scm
;;;; Copyright (C) 2001, 2004, 2006 Free Software Foundation, Inc. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public ;;;; License as published by the Free Software Foundation; either ;;;; version 3 of the License, or (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; Lesser General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU Lesser General Public ;;;; License along with this library; if not, write to the Free Software ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;;;; ;;; Commentary: ;; This module exports a single macro: `time'. ;; Usage: (time exp) ;; ;; Example: ;; guile> (time (sleep 3)) ;; clock utime stime cutime cstime gctime ;; 3.01 0.00 0.00 0.00 0.00 0.00 ;; 0 ;;; Code: (define-module (ice-9 time) :use-module (ice-9 format) :export (time)) (define (time-proc proc) (let* ((gc-start (gc-run-time)) (tms-start (times)) (result (proc)) (tms-end (times)) (gc-end (gc-run-time))) ;; FIXME: We would probably like format ~f to accept rationals, but ;; currently it doesn't so we force to a flonum with exact->inexact. (define (get proc start end) (exact->inexact (/ (- (proc end) (proc start)) internal-time-units-per-second))) (display "clock utime stime cutime cstime gctime\n") (format #t "~5,2F ~5,2F ~5,2F ~6,2F ~6,2F ~6,2F\n" (get tms:clock tms-start tms-end) (get tms:utime tms-start tms-end) (get tms:stime tms-start tms-end) (get tms:cutime tms-start tms-end) (get tms:cstime tms-start tms-end) (get identity gc-start gc-end)) result)) (define-macro (time exp) `((@@ (ice-9 time) time-proc) (lambda () ,exp))) ;;; time.scm ends here
false
398b5776b9f4a32a546bdbd6ecd545570b09459b
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/tests/genparse.ss
e669863b3a8ed9ea19af00c83543b9c94c63c398
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
446
ss
genparse.ss
(need parse/genparse) (define grammar1 '((a b c) (a x) (b comma c comma) (c l-paren a r-paren))) (define grammar '((exp foo) (foo bar) (foo foostart bar) (foostart foo comma))) (define s (grammar-start-production grammar)) (define i (production-initial-item s)) (define c (state-from-item-closure grammar i)) (define t (build-lr0-state-transition-graph grammar)) (print-state-transition-graph t)
false
77fc870853390bac8a156a28925e2647cdf86258
e1e2cd30484f96b2a24bb8592dcfb39a68255bb1
/util.scm
21779a9214c0a3fd0ecab7c82177e3679fce6d24
[]
no_license
lainproliant/toolbox-c-scheme
83e6ea79da4cd3fb7a3d791a9b0ffea08ddd158e
dce5e4e9c66ee585634ae170f282a29fe322c64b
refs/heads/master
2021-01-01T05:15:45.275880
2016-05-21T03:49:12
2016-05-21T03:49:12
58,909,717
1
0
null
null
null
null
UTF-8
Scheme
false
false
815
scm
util.scm
;-------------------------------------------------------------------- ; util.scm: Generic scheme utility functions. ; ; Author: Lain Supe (lainproliant) ; Date: Monday May 9 2016 ;-------------------------------------------------------------------- (module toolbox-util * (import chicken scheme) (use posix) ;; Determine if the given list is empty. (define (empty? lst) (and (list? lst) (equal? lst '()))) ;; A synonym for car (define first car) ;; Yields the first element of the list or #f if the list is empty. (define (first-or lst default) (if (empty? lst) default (car lst))) ;; Fetch an OS environment variable value, or #f if the variable ;; is not set. (define (getenv name) (assoc name (get-environment-variables))) )
false
ed7454ad66b14a247137dfbea79fb29ef5e4260a
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/tablegen/folds.scm
a1727b15113ab412e79c6215178879aaf1469d30
[ "Apache-2.0" ]
permissive
nvim-treesitter/nvim-treesitter
4c3c55cbe6ff73debcfaecb9b7a0d42d984be3e6
f8c2825220bff70919b527ee68fe44e7b1dae4b2
refs/heads/master
2023-08-31T20:04:23.790698
2023-08-31T09:28:16
2023-08-31T18:19:23
256,786,531
7,890
980
Apache-2.0
2023-09-14T18:07:03
2020-04-18T15:24:10
Scheme
UTF-8
Scheme
false
false
130
scm
folds.scm
[ (assert) (class) (multiclass) (def) (defm) (defset) (defvar) (foreach) (if) (let) (value_suffix) ] @fold
false
b6736160ae599bf93b15f72f65f0cf7beb1617b9
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/unity-serialization-holder.sls
a77564c6b893cbb388af2613e6aaccc36fad5387
[]
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,861
sls
unity-serialization-holder.sls
(library (system unity-serialization-holder) (export is? unity-serialization-holder? get-type-data get-module-data get-object-data get-assembly-data get-dbnull-data get-real-object) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.UnitySerializationHolder a)) (define (unity-serialization-holder? a) (clr-is System.UnitySerializationHolder a)) (define-method-port get-type-data System.UnitySerializationHolder GetTypeData (static: System.Void System.Type System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port get-module-data System.UnitySerializationHolder GetModuleData (static: System.Void System.Reflection.Module System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port get-object-data System.UnitySerializationHolder GetObjectData (System.Void System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port get-assembly-data System.UnitySerializationHolder GetAssemblyData (static: System.Void System.Reflection.Assembly System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port get-dbnull-data System.UnitySerializationHolder GetDBNullData (static: System.Void System.DBNull System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-method-port get-real-object System.UnitySerializationHolder GetRealObject (System.Object System.Runtime.Serialization.StreamingContext)))
false
7a34c2e81159b66f97724c6e2ccd9238826026a3
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/demo/fboyer.scm
8a1f5050fc26865443dd8b171ba387d5ae3c983e
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
5,580
scm
fboyer.scm
;;; ******** ;;; ;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt, ;;; Beranek and Newman Inc. ;;; ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice and this permission appear in all copies and in ;;; supporting documentation, and that the name Bolt, Beranek and Newman ;;; Inc. not be used in advertising or publicity pertaining to distribution ;;; of the software without specific, written prior permission. In ;;; addition, BBN makes no respresentation about the suitability of this ;;; software for any purposes. It is provided "AS IS" without express or ;;; implied warranties including (but not limited to) all implied warranties ;;; of merchantability and fitness. In no event shall BBN be liable for any ;;; special, indirect or consequential damages whatsoever resulting from ;;; loss of use, data or profits, whether in an action of contract, ;;; negligence or other tortuous action, arising out of or in connection ;;; with the use or performance of this software. ;;; ;;; ******** ;;; ;;;; Boyer-Moore Theorem prover - works by moby expansion (declare (usual-integrations)) ; Sample cases. (define modus-ponens '(implies (and (implies a b) a) b)) (define transitivity '(implies (and (implies (f x) (g x)) (implies (g x) (h x))) (implies (f x) (h x)))) (define three-deep '(implies (and (implies (f x) (g x)) (and (implies (g x) (h x)) (implies (h x) (i x)))) (implies (f x) (i x)))) ; Tautology detection checks forms (if predicate consequent alternate) ; If the predicate is known true then we just check the consequent ; If the predicate is known false then we just check the alternate ; Otherwise we see if the consequent is true assuming the predicate is true ; and that the alternate is true assuming the predicate is false (define (taut? form) (tautology? (rewrite form) () ())) (define (tautology? form true-list false-list) (cond ((known-true? form true-list) #!true) ((known-false? form false-list) #!false) ((eq? (car form) 'if) (cond ((known-true? (cadr form) true-list) (tautology? (caddr form) true-list false-list)) ((known-false? (cadr form) false-list) (tautology? (cadddr form) true-list false-list)) (else (and (future (tautology? (caddr form) (cons (cadr form) true-list) false-list)) (tautology? (cadddr form) true-list (cons (cadr form) false-list)))))) (else #!false))) (define (known-true? form true-list) (if (equal? form '(t)) #!true (member form true-list))) (define (known-false? form false-list) (if (equal? form '(f)) #!true (member form false-list))) ; Rewriting matches a form against the list of lemmas associated with the car ; of the form and first rewrites the remainder of the form before ; finding the first lemma which matches and expanding it accordingly. (define (rewrite form) (if (atom? form) form (future (rewrite-with-lemmas (cons (car form) (rewrite-args (cdr form))) (find-lemmas (car form)))))) (define (rewrite-args args) (if (null? args) () (cons (rewrite (car args)) (rewrite-args (cdr args))))) (define (rewrite-with-lemmas form lemmas) (if (null? lemmas) form (let ((subst-list (one-way-unify-util form (cadr (car lemmas)) ()))) (if (not (eq? subst-list 'failed)) (rewrite (apply-subst subst-list (caddr (car lemmas)))) (rewrite-with-lemmas form (cdr lemmas)))))) ; Weak unificiation works by a recursive pattern match. (define (one-way-unify-util form pattern frame) (cond ((eq? frame 'failed) 'failed) ((atom? pattern) (let ((already-matched (assq pattern frame))) (cond (already-matched ; if matched verify rematch (if (equal? form (cdr already-matched)) frame 'failed)) (else (cons (cons pattern form) frame))))) ((atom? form) 'failed) ((eq? (car form) (car pattern)) (one-way-unify-list (cdr form) (cdr pattern) frame)) (else 'failed))) (define (one-way-unify-list form pattern frame) (if (null? form) frame (one-way-unify-list (cdr form) (cdr pattern) (one-way-unify-util (car form) (car pattern) frame)))) ; Very simple substituter used by rewrite with the result of the unification. (define (apply-subst subst-list form) (if (atom? form) (let ((value (assq form subst-list))) (if value (cdr value) form)) (cons (car form) (apply-subst-list subst-list (cdr form))))) (define (apply-subst-list subst-list form) (if (null? form) () (cons (apply-subst subst-list (car form)) (apply-subst-list subst-list (cdr form))))) ; Since we don't have putprop we will associate lemmas with their keys by using ; assq on a lemma-list. We might make this faster some day. (define lemma-list ()) (define (add-lemma lemma) (cond ((and (not (atom? lemma)) (eq? (car lemma) 'equal) (not (atom? (cadr lemma)))) (let ((bucket (assq (car (cadr lemma)) lemma-list))) (if bucket (set-cdr! bucket (cons lemma (cdr bucket))) (set! lemma-list (cons (cons (car (cadr lemma)) (cons lemma ())) lemma-list)))) 'ADDED) (else (print `(Bad lemma form ,lemma))))) (define (find-lemmas key) (let ((the-list (assq key lemma-list))) (if the-list (cdr the-list) ()))) ; Useful functions that Scheme claims to have but doesn't. (define (atom? what) (not (pair? what)))
false
43f5c597b7a905061071e7f026dc556c500cfaec
b49e6c2edc0c5323f326e045c2a9fc769ba74778
/2.23.ss
793bb6d2c15d404b37473f5305b7edec05088825
[]
no_license
plotgeek/SICP
73d0109d37ca5f9ac2e98d847ecf633acb371021
e773a8071ae2fae768846a2b295b5ed96b019f8d
refs/heads/master
2023-03-09T18:50:54.195426
2012-08-14T10:18:59
2012-08-14T10:18:59
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
123
ss
2.23.ss
(define (for_each proc items) (if (null? items) nil ((proc (car items)) (for_each proc (cdr items)))))
false
d65cdb8be8a24089095123b6ca9fbcfdf3fe95c8
471a04fa9301455c51a890b8936cc60324a51f27
/srfi-lite-lib/srfi/29/bundles/es/srfi-19
8bfcc45b924ad90a8e9d93fdcab8eab905bb69d4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "MIT" ]
permissive
racket/srfi
e79e012fda6d6bba1a9445bcef461930bc27fde8
25eb1c0e1ab8a1fa227750aa7f0689a2c531f8c8
refs/heads/master
2023-08-16T11:10:38.100847
2023-02-16T01:18:44
2023-02-16T12:34:27
27,413,027
10
10
NOASSERTION
2023-09-14T14:40:51
2014-12-02T03:22:45
HTML
WINDOWS-1250
Scheme
false
false
946
srfi-19
;; -*- scheme -*- ( ;; weekday abbreviations (sun . "dom") (mon . "lun") (tue . "mar") (wed . "mié") (thu . "jue") (fri . "vie") (sat . "sáb") ;; long weekdays (sunday . "domingo") (monday . "lunes") (tuesday . "martes") (wednesday . "miércoles") (thursday . "jueves") (friday . "viernes") (saturday . "sábado") ;; month abbrevs (jan . "ene") (feb . "feb") (mar . "mar") (apr . "abr") (may . "may") (jun . "jun") (jul . "jul") (aug . "ago") (sep . "sep") (oct . "oct") (nov . "nov") (dec . "dic") ;; long month (january . "Enero") (february . "Febrero") (march . "Marzo") (april . "Abril") (may . "Mayo") (june . "Junio") (july . "Julio") (august . "Agosto") (septembre . "Septiembre") (octuber . "Octubre") (november . "Noviembre") (december . "Deciembre") (pm . "PM") (am . "AM") (date-time . "~a ~d ~b ~H:~M:~S~z ~Y") (date . "~d/~m/~y") (time . "~H:~M:~S") (iso8601 . "~Y-~m-~dT~H:~M:~S~z") (separator . ".") )
false
d1fedca956935bf7d325c003ef6f26c638d9ea0f
d3e9eecbf7fa7e015ab8b9c357882763bf6d6556
/solutions/book-example-code/section2.2.4.ss
771ee7a8f38a15ea9a0297f2fc28edc1bc38e4e3
[]
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
4,463
ss
section2.2.4.ss
#lang r5rs (require racket/include) (include "../lib/pic-lib.ss") (define wave2 (beside wave (flip-vert wave))) (paint wave2) (define wave4 (below wave2 wave2)) (paint wave4) ;; now abstract the painter (define (flipped-pairs painter) (let ((pair (beside painter (flip-vert painter)))) (below pair pair))) (paint (flipped-pairs wave)) ;; painter could be defined recursively (define (right-split painter n) (if (= n 0) painter (let ((smaller (right-split painter (- n 1)))) (beside painter (below smaller smaller))))) (paint (right-split wave 4)) (define (up-split painter n) (if (= n 0) painter (let ((smaller (up-split painter (- n 1)))) (below painter (beside smaller smaller))))) (paint (up-split wave 4)) (define (corner-split painter n) (if (= n 0) painter (let ((right (right-split painter (- n 1))) (up (up-split painter (- n 1))) ) (let ((top-left (beside up up)) (bottom-right (below right right)) (corner (corner-split painter (- n 1)))) (below (beside painter bottom-right) (beside top-left corner)))))) (paint (corner-split wave 4)) (define (square-limit painter n) (let ((quarter (corner-split painter n))) (let ((half (beside (flip-horiz quarter) quarter))) (below (flip-vert half) half)))) (paint (square-limit wave 3)) ;; we could abstract the painters which forms painters (define (square-of-four tl tr bl br) (lambda (painter) (let ((top (beside (tl painter) (tr painter))) (bottom (beside (bl painter) (br painter)))) (below bottom top)))) ;; redefine flipped-pairs and square-limit (define (identity x) x) (define flipped-pairs (square-of-four identity flip-vert identity flip-vert)) (paint (flipped-pairs wave)) (define (square-limit painter n) (let ((combine (square-of-four flip-horiz identity rotate180 flip-vert))) (combine (corner-split painter n)))) (paint (square-limit wave 3)) ;; frame-* and vector-* procedures are provided by the painter.ss (define (frame-coord-map frame) (lambda (v) (vector-add (frame-origin frame) (vector-add (vector-scale (vector-xcor v) (frame-edge1 frame)) (vector-scale (vector-ycor v) (frame-edge2 frame)))))) ;; a painter is just a procedure to display something to the frame ;; it includes ;; (define (segments->painter segment-list) ;; (lambda (frame) ;; (for-each ;; (lambda (segment) ;; (draw-line ;; this is a os-dependent procedure ;; ((frame-coord-map frame) ;; (start-segment segment)) ;; ((frame-coord-map frame) ;; (end-segment segment)))) ;; segment-list))) ;; a transformer performs operations on the frame passed in (define (transform-painter painter origin corner1 corner2) (lambda (frame) (let ((m (frame-coord-map frame))) (let ((new-origin (m origin))) (painter (make-frame new-origin (vector-sub (m corner1) new-origin) (vector-sub (m corner2) new-origin))))))) ;; flip over (paint (transform-painter wave (make-vect 0 1) (make-vect 1 1) (make-vect 0 0))) ;; shrink to the right corner (paint (transform-painter wave (make-vect .5 .5) (make-vect 1 .5) (make-vect .5 1))) ;; rotate 90 (paint (transform-painter wave (make-vect 0 1) (make-vect 0 0) (make-vect 1 1))) ;; squash inwards (paint (transform-painter wave (make-vect 0 0) (make-vect .65 .35) (make-vect .35 .65))) ;; compound painter is also defined by frame transformation (define (beside painter1 painter2) (let ((split-point (make-vect 0.5 0.0))) (let ((paint-left (transform-painter painter1 (make-vect 0 0) split-point (make-vect 0 1))) (paint-right (transform-painter painter2 split-point (make-vect 1 0) (make-vect 0.5 1)))) (superpose paint-left paint-right))))
false
89906675c13d6b2b9b9b8721bade7d0909c1930e
d17943098180a308ae17ad96208402e49364708f
/programs/gauss/gauss.sch
6c4719aa33ad8858a5d06c01113929f76aca7ba7
[]
no_license
dyoo/benchmark
b3f4f39714cc51e1f0bc176bc2fa973240cd09c0
5576fda204529e5754f6e1cc8ec8eee073e2952c
refs/heads/master
2020-12-24T14:54:11.354541
2012-03-02T19:40:48
2012-03-02T19:40:48
1,483,546
1
0
null
null
null
null
UTF-8
Scheme
false
false
211
sch
gauss.sch
(define (gauss n) (if (= n 0) 0 (+ n (gauss (- n 1))))) (letrec ([loop (lambda (n v) (if (zero? n) (begin (display v) (newline)) (loop (- n 1) (gauss 10000))))]) (loop 1500 0))
false
2836cce348fa7c08bd3e11785e18f7c353467862
00466b7744f0fa2fb42e76658d04387f3aa839d8
/sicp/chapter3/3.3/ex3.14.scm
be379cc0c6740d89980cdc5e11769033e328cc63
[ "WTFPL" ]
permissive
najeex/stolzen
961da2b408bcead7850c922f675888b480f2df9d
bb13d0a7deea53b65253bb4b61aaf2abe4467f0d
refs/heads/master
2020-09-11T11:00:28.072686
2015-10-22T21:35:29
2015-10-22T21:35:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
499
scm
ex3.14.scm
#lang scheme (require racket/mpair) (define cons mcons) (define car mcar) (define cdr mcdr) (define list mlist) (define set-cdr! set-mcdr!) (define set-car! set-mcar!) (define (mystery x) (define (loop x y) (if (null? x) y (let ((temp (cdr x))) (set-cdr! x y) (loop temp x) ) ) ) (loop x (list)) ) ; mystery reverses a list (mystery (list 'a 'b 'c 'd))
false
161d8f79746e27851d229000e868ceaac1b16a03
25a487e394b2c8369f295434cf862321c26cd29c
/lib/pikkukivi/commands/ylilauta.sls
620a99bc21ae550870b6db9686a46eedf1cfd53d
[]
no_license
mytoh/loitsu
b11e1ed9cda72c0a0b0f59070c9636c167d01a2c
d197cade05ae4acbf64c08d1a3dd9be6c42aac58
refs/heads/master
2020-06-08T02:00:50.563515
2013-12-17T10:23:04
2013-12-17T10:23:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,406
sls
ylilauta.sls
;;; ylilauta.sls --- ylilauta image get script ;;; Code: ;;; library declare (library (pikkukivi commands ylilauta) (export ylilauta) (import (silta base) (silta write) (silta file) (only (srfi :1 lists) delete-duplicates last) (srfi :26 cut) ;;(srfi :39 parameters) (only (mosh concurrent) sleep) (loitsu irregex) (loitsu match) (loitsu lamb) (loitsu file) (loitsu process) (loitsu control) (loitsu cli) (maali) (loitsu util) (surl)) (begin (define (extract-file-name uri) (last (irregex-split "/" uri))) (define (fetch uri) (let ((file (extract-file-name uri))) (unless (file-exists? file) (surl uri file)))) (define (save-html body thread) (let ((ofile (string-append thread ".html"))) (if (and (not (string=? "" body)) (file-exists? ofile)) (remove-file ofile)) (call-with-output-file ofile (lambda (out) (display body out))))) (define (thread-exists? board thread) (not (string=? "" (get-thread-html board thread)))) (define (make-url board thread) (string-append "http://ylilauta.org/" board "/" thread)) (define (get-image-url/thread board thread) (let ((image-regexp `(: "http://static.ylilauta.org/files/" (+ alphanumeric) "/orig/" (+ numeric) "." (or "jpg" "png" "gif" "bmp" "swf" "mp4" "flv" "mkv") "/" (+ (~ #\"))))) (delete-duplicates (map (cut irregex-match-substring <> 0) (irregex-fold image-regexp (lambda (i m s) (cons m s)) '() (get-thread-html board thread)))))) (define (get-thread-html board thread) (surl->utf8 (make-url board thread))) (define (setup-path thread) (unless (file-exists? thread) (make-directory* thread))) (define (valid-thread-number? num) (number? (string->number num))) (define (repeat f) (lambda args (let ((wait (* (* 60 (* 6 1000)) 1))) (let loop () (apply f args) ;; (sleep wait) (loop))))) (define (force-loop body) (guard (e (else (display "error, go back loop") (newline) (force-loop body))) (body))) (define *deleted-thread* (make-parameter '())) (define (update-deleted-thread thread) (if (not (memq thread (*deleted-thread*))) (*deleted-thread* (cons thread (*deleted-thread*))))) (define (thread-deleted? html) (string=? "" html)) ;;; get functions ;; get one thread (define (ylilauta-get-one-thread board thread) (cond ((and (not (member thread (*deleted-thread*))) (valid-thread-number? thread)) (setup-path thread) (cond ((thread-exists? board thread) (puts (paint thread 173)) (let ((res (get-thread-html board thread))) (unless (string=? "" res) (with-cwd thread (map fetch (get-image-url/thread board thread))) (with-cwd thread (save-html res thread))))) (else (update-deleted-thread thread)))))) ;;; all thread (define (ylilauta-get-all-thread board) (let ((threads (directory-list2 (current-directory)))) (for-each (cut ylilauta-get-one-thread board <>) threads) (puts (paint "-----------------------------" 29)))) (define-case ylilauta-get ((board) (force-loop ((repeat ylilauta-get-all-thread) board))) ((board thread) (ylilauta-get-one-thread board thread))) ;;; main (define (ylilauta args) (let ((args (cddr args))) (match args ((board) (ylilauta-get board)) ((board thread) (ylilauta-get board thread))))) ))
false
51e778d0a110d531257953b2a7780bcf766623cf
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Core/system/linq/expressions/member-member-binding.sls
5508160f396626e1243495f5e98524b0c4728f97
[]
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
618
sls
member-member-binding.sls
(library (system linq expressions member-member-binding) (export is? member-member-binding? bindings) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Linq.Expressions.MemberMemberBinding a)) (define (member-member-binding? a) (clr-is System.Linq.Expressions.MemberMemberBinding a)) (define-field-port bindings #f #f (property:) System.Linq.Expressions.MemberMemberBinding Bindings "System.Collections.ObjectModel.ReadOnlyCollection`1[[System.Linq.Expressions.MemberBinding, System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"))
false
d50ae9f7f8728b56753e7380abed16f7c32f85a5
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-02/ex2.28-obsidian.scm
d1e41afae1f2ceadb1eb67433af1846fc47ec56c
[]
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
1,064
scm
ex2.28-obsidian.scm
(load "../misc/scheme-test.scm") (define x (list (list 1 2) (list 3 4))) (define y (list 1 (list 1 2) (list 3 4))) (define z (list 1 2 3 4 (list 5 6 (list 7 8 9) 10 11 (list 12 13) 14))) (define (fringe items) (cond [(null? items) null] [(not (there-is-pair? items)) items] [else (append (if (pair? (car items)) (fringe (car items)) (list (car items))) (fringe (cdr items)))])) (define (there-is-pair? items) (cond [(null? items) false] [(pair? (car items)) true] [else (there-is-pair? (cdr items))])) (run (make-testcase '(assert-equal? (+ 1 1) 2) '(assert-equal? (append '(1 2 3 4) '(1 2 3 4)) '(1 2 3 4 1 2 3 4)) '(assert-true? (there-is-pair? '((1 2 3 4)))) '(assert-equal? (fringe x) '(1 2 3 4)) '(assert-equal? (fringe (list x x)) '(1 2 3 4 1 2 3 4)) '(assert-equal? (fringe y) '(1 1 2 3 4)) '(assert-equal? (fringe z) '(1 2 3 4 5 6 7 8 9 10 11 12 13 14)) ))
false
1190a4ee32568f30b3875b6c130a75c6b13dabf1
a6a1c8eb973242fd2345878e5a871a89468d4080
/3.75.scm
077fdd240386b8fa7b4fc0990d90517a5700e2dd
[]
no_license
takkyuuplayer/sicp
ec20b6942a44e48d559e272b07dc8202dbb1845a
37aa04ce141530e6c9803c3c7122016d432e924b
refs/heads/master
2021-01-17T07:43:14.026547
2017-02-22T03:40:07
2017-02-22T03:40:07
15,771,479
1
1
null
null
null
null
UTF-8
Scheme
false
false
1,199
scm
3.75.scm
(load "./lib/stream/base.scm") (load "./lib/stream/list.scm") (load "./lib/stream/calc.scm") (load "./lib/stream/display.scm") (define ones (cons-stream 1 ones)) (define integers (cons-stream 1 (add-streams ones integers))) (define (sign-change-detector after before) (cond ((and (>= before 0) (>= after 0)) 0) ((and (>= before 0) (< after 0)) -1) ((and (< before 0) (>= after 0) 1)) (else 0) ) ) (define sense-data (stream-map (lambda (x) (sin x)) integers)) ; 3.75 (define (make-zero-crossings input-stream last-value last-avpt) (let ((avpt (/ (+ (stream-car input-stream) last-value) 2))) (cons-stream (sign-change-detector avpt last-avpt) (make-zero-crossings (stream-cdr input-stream) (stream-car input-stream) avpt)))) (stream-head (make-zero-crossings sense-data 0 0) 10) ; last-value に avpt を渡してはいけない. 新しい信号の平均値は直前の"実測値"との平均を取らなければならない。 ; 最後の実測値 `last-value` と (sign-change-detector) に渡すようの直前の平均値を渡す必要がある。 
false
367e00a554443970ac5ee390d2c76813d53e62c4
378e5f5664461f1cc3031c54d243576300925b40
/rsauex/packages/the-dot.scm
addbd17992e8367e6187d34841d6eda14a2585ca
[]
no_license
rsauex/dotfiles
7a787f003a768699048ffd068f7d2b53ff673e39
77e405cda4277e282725108528874b6d9ebee968
refs/heads/master
2023-08-07T17:07:40.074456
2023-07-30T12:59:48
2023-07-30T12:59:48
97,400,340
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,517
scm
the-dot.scm
(define-module (rsauex packages the-dot) #:use-module ((guix build-system trivial) #:prefix trivial-build-system:) #:use-module ((guix download) #:prefix download:) #:use-module ((guix licenses) #:prefix licenses:) #:use-module ((guix packages)) #:use-module ((rsauex packages) #:prefix my-packages:) #:use-module ((web uri))) (define-public the-dot-cursor-theme (package (name "the-dot-cursor-theme") (version "0.6") (source (origin (method download:url-fetch/tarbomb) (uri (uri->string (build-uri 'file #:path (my-packages:search-rsauex-aux-file "thedot0.6.tar.gz")))) (sha256 (base32 "1iwvlv9qcrjyfbzab00vjqafmp3vdybz1hi02r6lwbgvwyfyrifg")))) (build-system trivial-build-system:trivial-build-system) (arguments (list #:modules '((guix build utils)) #:builder `(begin (use-modules (guix build utils)) (let ((source (string-append (assoc-ref %build-inputs "source") "/thedot0.6")) (output (string-append (assoc-ref %outputs "out") "/share/icons"))) (mkdir-p output) (copy-recursively source output))))) (synopsis "A Gtk theme based on Material Design Refresh.") (description "A Gtk theme based on Material Design Refresh.") (home-page "https://gitlab.com/tista500/plata-theme") (license licenses:gpl2)))
false
a0357d089102b9ac935a188f38322f99bf661759
c6ad21dc0e764de58f62b84ac52bb991f3a7e326
/lf2.scm
be2d81c8a199a90936a56aa908719f19f61c98bf
[]
no_license
tca/PANL
aaa0938b0f3218f0fac05fe4fdb1a7e49cf31699
5002b0b1fbb1b900f737032427cfc299dfe949d3
refs/heads/master
2021-01-10T02:47:48.402344
2016-03-14T16:08:48
2016-03-14T16:08:48
50,952,386
13
0
null
null
null
null
UTF-8
Scheme
false
false
1,644
scm
lf2.scm
(use-modules (minikanren language) (minikanren dcg)) ;;Program 4.1 ;; reduce(ArgˆExpr, Arg, Expr). (define (reduceo ae a e) (== ae `(lambda (,a) ,e))) ;; s(S) --> np(VPˆS), vp(VP). (--> (s s-) (fresh (np- vp-) (conde ((np `(lambda (,vp-) ,s-)) (vp vp-))))) (--> (n n-) (fresh (x-) (conde ('(program) ;; Xˆprogram(X) (== lf- `(lambda (,x-) (program ,x-))))))) ;; λp.λq.(∀x)p(x) ⇒ q(x) ;; `(lambda (,p) `(lambda (,q) (all ,x (=> (,p ,x) (,q ,x))))) ;; partially executed ;; det( (X^P)^(X^Q)^all(X,(P => Q)) ) --> [every]. (--> (det a) (fresh (x p q x^p x^q) (conde ((== x^p `(lambda (,x) ,p)) (== x^q `(lambda (,x) ,q)) (== a `(lambda (,x^p) (lambda (,x^q) (all ,x (=> ,p ,q))))) '(every))))) ;; vp(VP) --> tv(TV), np(NP), {reduce(TV, NP, VP)}. ;; vp(VP) --> iv(VP). (--> (vp vp-) (fresh (tv- np-) (conde ;;((tv tv-) (np np-) (escape (reduceo tv- np- vp-))) ;; partially executed ;; tv(NPˆVP), np(NP). ((tv `(lambda (,np-) ,vp-)) (np np-)) ((iv vp-))))) ;; iv(LF) --> [IV], {iv(IV, LF)}. ;; iv( halts, Xˆhalts(X) ). (--> (iv lf-) (fresh (x-) (conde ('(halts) (== lf- `(lambda (,x-) (halts ,x-))))))) (--> (tv lf-) (fresh (x-) (conde ('(wrote) (== lf- `(lambda (,x-) (wrote ,x-))))))) ;; np(NP) --> det(NˆNP), n(N). (--> (np np-) (fresh (n-) (conde ((det `(lambda (,n-) ,np-)) (n n-))))) (runi (lambda (lf) (s lf '(every program halts) '())))
false
f99fdab8653364056fe2d9c4d607028b6f07853a
6c40779f174bb777371a2edccfc8cee39692895f
/demos/heat.scm
6167bfe6796f4db2980b30fa4cf0e14e037018fd
[ "zlib-acknowledgement" ]
permissive
gramian/matrico
7231ed4f14fc33d22d4680354ba44e1580c81386
04ca69c08dcc8349daa70452c2c5a587027d82f5
refs/heads/main
2023-06-08T06:41:03.377110
2023-06-05T21:22:54
2023-06-05T21:22:54
16,047,652
2
0
null
null
null
null
UTF-8
Scheme
false
false
840
scm
heat.scm
;;;; demo-heat.scm ;;@project: matrico (numerical-schemer.xyz) ;;@version: 0.5 (2023-06-06) ;;@authors: Christian Himpe (0000-0003-2194-6754) ;;@license: zlib-acknowledgement (spdx.org/licenses/zlib-acknowledgement.html) ;;@summary: cooling demo code ;; This demo code computes a cooling process, by solving a semi-discrete ;; diffusion partial differential equation (linear heat equation) in one ;; dimension with a central box as initial state and zero Dirichlet boundaries. (load "matrico.scm") (import matrico) (define N 100) (define h (/ 10.0 (add1 N))) (define h^2 (* h h)) (define A^T (mx-tridiag N (/ 1.0 h^2) (/ -2.0 h^2) (/ 1.0 h^2))) (define x0 (mx-vercat (mx 43 1 0.0) (mx-vercat (mx 14 1 1.0) (mx 43 1 0.0)))) (define (f t x) (mx-dot* A^T x)) (define X (mx-ode2-ssp 5 f (cons 0.01 1.0) x0)) (mx-export "heat.csv" X)
false
85c3158718fff1e828e5a7851e467c60e6ed6f6f
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/collections/collection-base.sls
62de16bafbd410867c8e2d27b8d8cbed412178b2
[]
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,060
sls
collection-base.sls
(library (system collections collection-base) (export is? collection-base? remove-at get-enumerator clear count capacity-get capacity-set! capacity-update!) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Collections.CollectionBase a)) (define (collection-base? a) (clr-is System.Collections.CollectionBase a)) (define-method-port remove-at System.Collections.CollectionBase RemoveAt (System.Void System.Int32)) (define-method-port get-enumerator System.Collections.CollectionBase GetEnumerator (System.Collections.IEnumerator)) (define-method-port clear System.Collections.CollectionBase Clear (System.Void)) (define-field-port count #f #f (property:) System.Collections.CollectionBase Count System.Int32) (define-field-port capacity-get capacity-set! capacity-update! (property:) System.Collections.CollectionBase Capacity System.Int32))
false
85292e0c0e77a6914b28b30f878607a3e7adc9f6
5355071004ad420028a218457c14cb8f7aa52fe4
/1.3/e-1.46.scm
571d168c8d4884b8a2f88762fe83c8ec1ce12e73
[]
no_license
ivanjovanovic/sicp
edc8f114f9269a13298a76a544219d0188e3ad43
2694f5666c6a47300dadece631a9a21e6bc57496
refs/heads/master
2022-02-13T22:38:38.595205
2022-02-11T22:11:18
2022-02-11T22:11:18
2,471,121
376
90
null
2022-02-11T22:11:19
2011-09-27T22:11:25
Scheme
UTF-8
Scheme
false
false
1,905
scm
e-1.46.scm
; Exercise 1.46. ; ; Several of the numerical methods described in this chapter are instances of an ; extremely general computational strategy known as iterative improvement. Iterative ; improvement says that, to compute something, we start with an initial guess for the ; answer, test if the guess is good enough, and otherwise improve the guess and continue ; the process using the improved guess as the new guess. Write a procedure iterative-improve ; that takes two procedures as arguments: a method for telling whether a guess is good enough ; and a method for improving a guess. Iterative-improve should return as its value a procedure ; that takes a guess as argument and keeps improving the guess until it is good enough. ; Rewrite the sqrt procedure of section 1.1.7 and the fixed-point procedure of ; section 1.3.3 in terms of iterative-improve. ; (load "../common.scm") ; generic function of iterative improvement (define (iterative-improve good-enough? improve-guess) (lambda (guess) (define (iter guess) ; we use new-guess on more than one place so place it in variable (let ((new-guess (improve-guess guess))) (if (good-enough? new-guess) new-guess (iter new-guess)))) (iter guess))) ; sqrt implementation (define (sqrt-iter guess x) (define (improve guess) (average guess (/ x guess))) (define (good-enough? guess) (< (abs (- (square guess) x)) 0.001)) ((iterative-improve good-enough? improve) guess)) ; (display (sqrt-iter 1 64)) ; converges to 8 ; (newline) ; fixed point. Since applying f continuously is in fact improving guess ; then we don't need separate improve function (define (fixed-point-iter f guess) (define (close-enough? guess) (< (abs (- guess (f guess))) 0.001)) ((iterative-improve close-enough? f) guess)) ; (display (fixed-point-iter cos 1)) ; converges to 0.7395672022122561 ; (newline)
false
16d468016e527424765d05a5ca26df16cdf8a44a
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine/unity-engine/billboard-renderer.sls
b51359cd7d2e5da5487662e854631b18c66cba29
[]
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
661
sls
billboard-renderer.sls
(library (unity-engine billboard-renderer) (export new is? billboard-renderer? billboard-get billboard-set! billboard-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new UnityEngine.BillboardRenderer a ...))))) (define (is? a) (clr-is UnityEngine.BillboardRenderer a)) (define (billboard-renderer? a) (clr-is UnityEngine.BillboardRenderer a)) (define-field-port billboard-get billboard-set! billboard-update! (property:) UnityEngine.BillboardRenderer billboard UnityEngine.BillboardAsset))
true
c290a0fbb7a151a88fd08b67dd8b4e3f45365298
e1c580145992634f089af18940508f5c26d2e264
/umcu/packages/snpeff.scm
900e8fb714bb5fe7d376af63bf614d991ec4e185
[]
no_license
inijman/guix-additions
8542592972e644a4ccd7b36ad4dd9b5631008fb5
b8e0e3f3b9598aade3103e9f491307fa06ece03d
refs/heads/master
2021-07-13T21:35:25.731179
2020-05-28T14:01:04
2020-05-28T14:01:04
142,980,977
0
0
null
2018-07-31T07:49:53
2018-07-31T07:49:53
null
UTF-8
Scheme
false
false
10,176
scm
snpeff.scm
;;; GNU Guix --- Functional package management for GNU ;;; Copyright © 2016 Roel Janssen <[email protected]> ;;; ;;; This file is not officially part of GNU Guix. ;;; ;;; GNU Guix is free software; you can redistribute it and/or modify it ;;; under the terms of the GNU General Public License as published by ;;; the Free Software Foundation; either version 3 of the License, or (at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>. ;; WARNING: This is non-free software. It will NEVER and SHOULD NEVER be ;; mainlined in GNU Guix. You should avoid using this package, and if you ;; can, please write a free replacement for it. (define-module (umcu packages snpeff) #:use-module ((guix licenses) #:prefix license:) #:use-module (guix packages) #:use-module (guix utils) #:use-module (guix download) #:use-module (guix build-system gnu) #:use-module (gnu packages) #:use-module (gnu packages base) #:use-module (gnu packages bash) #:use-module (gnu packages compression) #:use-module (gnu packages java) #:use-module (gnu packages perl) #:use-module (gnu packages python) #:use-module (gnu packages statistics) #:use-module (umcu packages datasets)) (define-public snpeff-bin-4.1 (package (name "snpeff") (version "4.1") (source (origin (method url-fetch) (uri "mirror://sourceforge/snpeff/snpEff_v4_1_core.zip") (sha256 (base32 "1vjgj6aacjsw6iczy09h18q5kx8ppxrrcq8w38g159zq7y3732kb")))) (build-system gnu-build-system) (arguments `(#:tests? #f ; This is a binary package only, so no tests. #:phases (modify-phases %standard-phases (delete 'configure) ; Nothing to configure. (delete 'build) ; This is a binary package only. (replace 'install (lambda* (#:key inputs outputs #:allow-other-keys) (let* ((current-dir (getcwd)) (out (assoc-ref %outputs "out")) (bin (string-append out "/share/java/" ,name)) (share (string-append out "/share/snpeff")) (clinvar-file (string-append (assoc-ref inputs "clinvar") "/share/clinvar/GRCh37/clinvar.vcf.gz")) (snpeff-db-dir (string-append share "/data")) (snpeff-db (assoc-ref inputs "snpeff-database")) (dbsnp-file (string-append (assoc-ref inputs "dbsnp") "/share/dbsnp/dbSnp.vcf.gz")) (create-and-copy (lambda (dir) (mkdir (string-append bin "/" dir)) (copy-recursively dir (string-append bin "/" dir))))) (mkdir-p bin) (mkdir-p share) (substitute* "snpEff.config" (("data.dir = ./data/") (string-append "data.dir = " share "/data")) (("database.local.clinvar = ./db/GRCh38/clinvar/clinvar-latest.vcf.gz") (string-append "database.local.clinvar = " clinvar-file)) (("database.local.dbsnp = ./db/GRCh38/dbSnp/dbSnp.vcf.gz") (string-append "database.local.dbsnp = " dbsnp-file))) (chdir share) (system* (string-append (assoc-ref inputs "unzip") "/bin/unzip") snpeff-db) (chdir current-dir) (install-file "snpEff.config" bin) (install-file "snpEff.jar" bin) (install-file "SnpSift.jar" bin) (map create-and-copy '("scripts" "galaxy")))))))) (native-inputs `(("unzip" ,unzip) ("perl" ,perl) ("python" ,python-2) ("bash" ,bash) ("r" ,r))) (inputs `(("perl" ,perl) ("python" ,python) ("bash" ,bash) ("r" ,r) ("icedtea" ,icedtea-7) ("clinvar" ,clinvar-grch37) ("gwascatalog" ,gwascatalog) ("dbnsfp" ,dbnsfp) ("snpeff-database" ,(origin (method url-fetch) (uri (string-append "mirror://sourceforge/snpeff/databases/v4_1/" "snpEff_v4_1_GRCh37.74.zip")) (sha256 (base32 "1p02n1dd4b04vf425wm7c5b749rjxj6va78ibbfzdhggl38wg345")))) ("dbsnp" ,dbsnp))) (home-page "http://snpeff.sourceforge.net/") (synopsis "Genetic variant annotation and effect prediction toolbox.") (description "Genetic variant annotation and effect prediction toolbox. It annotates and predicts the effects of variants on genes (such as amino acid changes).") ;; No license specified. (license license:non-copyleft))) (define-public snpeff-bin-4.1h (package (inherit snpeff-bin-4.1) (name "snpeff") (version "4.1h") (source (origin (method url-fetch) (uri "mirror://sourceforge/snpeff/snpEff_v4_1h_core.zip") (sha256 (base32 "1j45jp4y8wj0q01clxsx46w1f4jm2wh85yl1mbrha7qbqs8c1qn3")))))) (define-public snpeff-bin-4.3t (package (inherit snpeff-bin-4.1) (name "snpeff") (version "4.3t") (source (origin (method url-fetch) (uri "mirror://sourceforge/snpeff/snpEff_v4_3t_core.zip") (sha256 (base32 "0i12mv93bfv8xjwc3rs2x73d6hkvi7kgbbbx3ry984l3ly4p6nnm")))) (arguments `(#:tests? #f ; This is a binary package only, so no tests. #:phases (modify-phases %standard-phases (delete 'configure) ; Nothing to configure. (delete 'build) ; This is a binary package only. (replace 'install (lambda* (#:key inputs outputs #:allow-other-keys) (chdir "../snpEff") (let* ((current-dir (getcwd)) (out (assoc-ref %outputs "out")) (bin (string-append out "/share/java/" ,name)) (patch-bin (string-append (assoc-ref %build-inputs "patch") "/bin/patch")) (share (string-append out "/share/snpeff")) (clinvar-file (string-append (assoc-ref inputs "clinvar") "/share/clinvar/GRCh37/clinvar.vcf.gz")) (snpeff-db-dir (string-append share "/data")) (snpeff-db (assoc-ref inputs "snpeff-database")) (dbsnp-dir (string-append (assoc-ref inputs "dbsnp") "/share/dbsnp/")) (gwascatalog-file (string-append (assoc-ref inputs "gwascatalog") "/share/gwascatalog/gwascatalog.txt")) (dbnsfp-file (string-append (assoc-ref inputs "dbnsfp") "/share/dbnsfp/dbNSFP2.9_gene.complete.gz")) (create-and-copy (lambda (dir) (mkdir (string-append bin "/" dir)) (copy-recursively dir (string-append bin "/" dir))))) (mkdir-p bin) (mkdir-p share) (substitute* "snpEff.config" (("data.dir = ./data/") (string-append "data.dir = " share "/data")) (("database.clinvar.GRCh37 = ./db/GRCh37/clinvar/clinvar-latest.vcf.gz") (string-append "database.clinvar.GRCh37 = " clinvar-file)) (("database.dbsnp.GRCh37 = ./db/GRCh37/dbSnp/") (string-append "database.dbsnp.GRCh37 = " dbsnp-dir)) (("database.gwascatalog.GRCh37 = ./db/GRCh37/gwasCatalog/gwascatalog.txt") (string-append "database.gwascatalog.GRCh37 = " gwascatalog-file)) (("database.dbnsfp.GRCh37 = ./db/GRCh37/dbNSFP/dbNSFP.txt.gz") (string-append "database.dbnsfp.GRCh37 = " dbnsfp-file))) (chdir share) (system* (string-append (assoc-ref inputs "unzip") "/bin/unzip") snpeff-db) (chdir current-dir) (install-file "snpEff.config" bin) (install-file "snpEff.jar" bin) (install-file "SnpSift.jar" bin) (for-each create-and-copy '("scripts" "galaxy")) ;; Backport settings from an older snpEff version by ;; applying the following patch. (with-directory-excursion bin (format #t "Applying patches... ") (let ((patch-file (assoc-ref %build-inputs "patch-file"))) (format #t (if (zero? (system (string-append patch-bin " < " patch-file))) " Succeeded.~%" " Failed.~%")))) #t)))))) (native-inputs `(("unzip" ,unzip) ("perl" ,perl) ("python" ,python-2) ("bash" ,bash) ("r" ,r) ("patch" ,patch) ("patch-file" ,(origin (method url-fetch) (uri (search-patch "snpeff-4.3t-backport-settings.patch")) (sha256 (base32 "1hw44vzcb6k8fq66740kd7kcdmb68bf5zbibc467bcxiiay8xpca")))))) (inputs `(("perl" ,perl) ("python" ,python) ("bash" ,bash) ("r" ,r) ("icedtea" ,icedtea-7) ("clinvar" ,clinvar-grch37) ("gwascatalog" ,gwascatalog) ("dbnsfp" ,dbnsfp) ("snpeff-database" ,(origin (method url-fetch) (uri (string-append "mirror://sourceforge/snpeff/databases/v4_3/" "snpEff_v4_3_hg19.zip")) (sha256 (base32 "0rnaa858shjgxx284m73ikf2a1k11n3gc7861svczm2f98wwhar2")))) ("dbsnp" ,dbsnp)))))
false
8f5c8fa97145ca54a6cef24d9df329c9c4a961ba
e358b0cf94ace3520adff8d078a37aef260bb130
/simple/1.37.scm
8da007788f38dcc00b0183d7e1b25ae60db88740
[]
no_license
dzhus/sicp
784766047402db3fad4884f7c2490b4f78ad09f8
090fa3228d58737d3558f2af5a8b5937862a1c75
refs/heads/master
2021-01-18T17:28:02.847772
2020-05-24T19:15:57
2020-05-24T20:56:00
22,468,805
0
0
null
null
null
null
UTF-8
Scheme
false
false
344
scm
1.37.scm
(define (cont-fract-recursive N D k) (define (frac i) (if (= i k) (/ (N i) (D i)) (/ (N i) (+ (D i) (frac (+ i 1)))) )) (frac 1)) (define (cont-fract-iterative N D k) (define (frac i result) (if (= i 0) result (frac (- i 1) (/ (N i) (+ (D i) result))))) (frac k 0))
false
46a5aef80bd7b89c253c2814ecf66a7f98d21d7f
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
/exercises/practice/word-count/test.scm
1003e8e527c5b5ea087c3c1c4a25902e27a638d6
[ "MIT", "CC-BY-SA-3.0" ]
permissive
exercism/scheme
a28bf9451b8c070d309be9be76f832110f2969a7
d22a0f187cd3719d071240b1d5a5471e739fed81
refs/heads/main
2023-07-20T13:35:56.639056
2023-07-18T08:38:59
2023-07-18T08:38:59
30,056,632
34
37
MIT
2023-09-04T21:08:27
2015-01-30T04:46:03
Scheme
UTF-8
Scheme
false
false
2,901
scm
test.scm
(load "test-util.ss") (define (matches? result expected) (let ([get-count (if (hashtable? result) (lambda (word) (hashtable-ref result word 0)) (lambda (word) (cond [(assoc word result) => cdr] [else 0])))]) (and (= (length expected) (if (hashtable? result) (hashtable-size result) (length result))) (fold-left (lambda (count-agrees w.c) (and count-agrees (= (cdr w.c) (get-count (car w.c))))) #t expected)))) (define test-cases `((test-success "count one word" matches? word-count '("word") '(("word" . 1))) (test-success "count one of each word" matches? word-count '("one of each") '(("one" . 1) ("of" . 1) ("each" . 1))) (test-success "multiple occurrences of a word" matches? word-count '("one fish two fish red fish blue fish") '(("one" . 1) ("fish" . 4) ("two" . 1) ("red" . 1) ("blue" . 1))) (test-success "handles cramped lists" matches? word-count '("one,two,three") '(("one" . 1) ("two" . 1) ("three" . 1))) (test-success "handles expanded lists" matches? word-count '("one,\ntwo,\nthree") '(("one" . 1) ("two" . 1) ("three" . 1))) (test-success "ignore punctuation" matches? word-count '("car: carpet as java: javascript!!&@$%^&") '(("car" . 1) ("carpet" . 1) ("as" . 1) ("java" . 1) ("javascript" . 1))) (test-success "include numbers" matches? word-count '("testing, 1, 2 testing") '(("testing" . 2) ("1" . 1) ("2" . 1))) (test-success "normalize case" matches? word-count '("go Go GO Stop stop") '(("go" . 3) ("stop" . 2))) (test-success "with apostrophes" matches? word-count '("First: don't laugh. Then: don't cry.") '(("first" . 1) ("don't" . 2) ("laugh" . 1) ("then" . 1) ("cry" . 1))) (test-success "with quotations" matches? word-count '("Joe can't tell between 'large' and large.") '(("joe" . 1) ("can't" . 1) ("tell" . 1) ("between" . 1) ("large" . 2) ("and" . 1))) (test-success "substrings from the beginning" matches? word-count '("Joe can't tell between app, apple and a.") '(("joe" . 1) ("can't" . 1) ("tell" . 1) ("between" . 1) ("app" . 1) ("apple" . 1) ("and" . 1) ("a" . 1))) (test-success "multiple spaces not detected as a word" matches? word-count '(" multiple whitespaces") '(("multiple" . 1) ("whitespaces" . 1))) (test-success "alternating word separators not detected as a word" matches? word-count '(",\n,one,\n ,two \n 'three'") '(("one" . 1) ("two" . 1) ("three" . 1))))) (run-with-cli "word-count.scm" (list test-cases))
false
cc9e671f5bcc89dfda31002204f4e9366cd2fe34
fae4190f90ada065bc9e5fe64aab0549d4d4638a
/660-typed-scheme/private/base-env.ss
772be8c93e770cfe84233ba37cdfa24d66bdaa27
[]
no_license
ilya-klyuchnikov/old-typed-racket
f161481661a2ed5cfc60e268f5fcede728d22488
fa7c1807231f447ff37497e89b25dcd7a9592f64
refs/heads/master
2021-12-08T04:19:59.894779
2008-04-13T10:54:34
2008-04-13T10:54:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
18,196
ss
base-env.ss
#lang scheme/base (require (for-template (only-in (lib "list.ss") foldl cons?) scheme/base CSU660/utils '#%paramz scheme/promise string-constants/string-constant #;'#%more-scheme #;'#%qq-and-or (only-in scheme/match/patterns match:error)) ) (require "extra-procs.ss" scheme/promise (except-in "type-rep.ss" make-arr) (only-in (lib "list.ss") foldl cons?) (only-in scheme sqr) (only-in CSU660/utils *cons *list? test-e test-1 test-2 test-postprocess string->sexpr) (only-in scheme/list first second third fourth fifth sixth rest) "type-effect-convenience.ss" (only-in "type-effect-convenience.ss" [make-arr* make-arr]) "union.ss" string-constants/string-constant (only-in scheme/match/patterns match:error) "tc-structs.ss") (require (for-syntax scheme/base "init-envs.ss" (except-in "type-rep.ss" make-arr) (only-in (lib "list.ss") foldl) "type-effect-convenience.ss" (only-in "type-effect-convenience.ss" [make-arr* make-arr]) "union.ss" string-constants/string-constant (only-in scheme/match/patterns match:error) "tc-structs.ss")) (define-for-syntax (initialize-others) (d-s date ([second : N] [minute : N] [hour : N] [day : N] [month : N] [year : N] [weekday : N] [year-day : N] [dst? : B] [time-zone-offset : N]) ()) (d-s exn ([message : -String] [continuation-marks : Univ]) ()) (d-s (exn:fail exn) () (-String Univ)) (d-s (exn:fail:read exn:fail) ([srclocs : (-lst Univ)]) (-String Univ))) (provide (for-syntax initial-env initialize-others)) (define-for-syntax initial-env (let ([make-lst make-Listof] [make-lst/elements -pair]) (make-env [raise (Univ . -> . (Un))] ;; 660 test code [test-e (-> Univ Univ Univ Univ)] [test-1 (-> Univ Univ Univ)] [test-2 (-> Univ Univ Univ Univ Univ)] [test-postprocess (-Param (-> Univ Univ) (-> Univ Univ))] ;; other 660 [string->sexpr (-> -String (-mu x (Un Sym -String N B (-lst x))))] (car (make-Poly (list 'a 'b) (cl-> [((-pair (-v a) (-v b))) (-v a)] [((make-lst (-v a))) (-v a)]))) [first (make-Poly (list 'a 'b) (cl-> [((-pair (-v a) (-v b))) (-v a)] [((make-lst (-v a))) (-v a)]))] [second (-poly (a b c) (cl-> [((-pair a (-pair b c))) b] [((-lst a)) a]))] [third (-poly (a b c d) (cl-> [((-pair a (-pair b (-pair c d)))) c] [((-lst a)) a]))] [fourth (-poly (a) ((-lst a) . -> . a))] [fifth (-poly (a) ((-lst a) . -> . a))] [sixth (-poly (a) ((-lst a) . -> . a))] [rest (-poly (a) ((-lst a) . -> . (-lst a)))] (cadr (-poly (a b c) (cl-> [((-pair a (-pair b c))) b] [((-lst a)) a]))) (caddr (-poly (a) (-> (-lst a) a))) (cadddr (-poly (a) (-> (-lst a) a))) (cdr (make-Poly (list 'a 'b) (cl-> [((-pair (-v a) (-v b))) (-v b)] [((make-lst (-v a))) (make-lst (-v a))]))) (cddr (make-Poly (list 'a) (-> (make-lst (-v a)) (make-lst (-v a))))) (cdddr (make-Poly (list 'a) (-> (make-lst (-v a)) (make-lst (-v a))))) (cons (-poly (a b) (cl-> [(a (-lst a)) (-lst a)] [(a b) (-pair a b)]))) [*cons (-poly (a b) (cl-> [(a b) (-pair a b)] [(a (-lst a)) (-lst a)]))] [*list? (make-pred-ty (-lst Univ))] (null? (make-pred-ty (-val null))) (eof-object? (make-pred-ty (-val eof))) [null (-val null)] (number? (make-pred-ty N)) (integer? (make-pred-ty -Integer)) (boolean? (make-pred-ty B)) (add1 (cl->* (-> -Integer -Integer) (-> N N))) (sub1 (cl->* (-> -Integer -Integer) (-> N N))) (eq? (-> Univ Univ B)) (eqv? (-> Univ Univ B)) (equal? (-> Univ Univ B)) (even? (-> N B)) [assert (-poly (a) (-> (*Un a (-val #f)) a))] [gensym (cl-> [(Sym) Sym] [() Sym])] [string-append (->* null -String -String)] [open-input-string (-> -String -Input-Port)] [open-output-file (cl-> [(-Pathlike) -Port] [(-Pathlike Sym) -Port])] [read (cl-> [(-Port) -Sexp] [() -Sexp])] [ormap (-poly (a b) ((-> a b) (-lst a) . -> . b))] [andmap (-poly (a b) ((-> a b) (-lst a) . -> . b))] [newline (cl-> [() -Void] [(-Port) -Void])] [not (-> Univ B)] [floor (-> N N)] [box (-poly (a) (a . -> . (make-Box a)))] [unbox (-poly (a) ((make-Box a) . -> . a))] [set-box! (-poly (a) ((make-Box a) a . -> . -Void))] [box? (make-pred-ty (make-Box Univ))] [cons? (make-pred-ty (-pair Univ Univ))] [pair? (make-pred-ty (-pair Univ Univ)) #;(-poly (a b) (make-pred-ty (-pair a b)))] [empty? (make-pred-ty (-val null))] [empty (-val null)] [string? (make-pred-ty -String)] [string (->* '() -Char -String)] [symbol? (make-pred-ty Sym)] [list? (make-pred-ty (-lst Univ))] [list (-poly (a) (->* '() a (-lst a)))] [procedure? (make-pred-ty (make-Function (list (make-top-arr))))] [map (-poly (a b c d) (cl-> [((-> a b) (-lst a)) (-lst b)] [((-> a b c) (-lst a) (-lst b)) (-lst c)] [((-> a b c d) (-lst a) (-lst b) (-lst c)) (-lst d)]))] [for-each (-poly (a b c) (cl-> [((-> a b) (-lst a)) -Void] [((-> a b c) (-lst a) (-lst b)) -Void]))] [foldl (-poly (a b) ((a b . -> . b) b (make-lst a) . -> . b))] [call-with-values (-poly (a b) (-> (-> a) (-> a b) b))] (error (make-Function (list (make-arr null (Un)) (make-arr (list Sym -String) (Un) Univ) (make-arr (list -String) (Un) Univ) (make-arr (list Sym) (Un))))) [namespace-variable-value (cl-> [(Sym) Univ] [(Sym B -Namespace (-> Univ)) Univ])] (match:error (Univ . -> . (Un))) (display (cl-> [(Univ) -Void] [(Univ -Port) -Void])) [void (->* '() Univ -Void)] [void? (make-pred-ty -Void)] [printf (->* (list -String) Univ -Void)] [fprintf (->* (list -Output-Port -String) Univ -Void)] [format (->* (list -String) Univ -String)] (fst (make-Poly (list 'a 'b) (-> (make-lst/elements (-v a) (-v b)) (-v a)))) (snd (make-Poly (list 'a 'b) (-> (make-lst/elements (-v a) (-v b)) (-v b)))) (= (->* (list N N) N B)) (>= (->* (list N N) N B)) (< (->* (list N N) N B)) (<= (->* (list N N) N B)) [> (->* (list N) N B)] (zero? (N . -> . B)) (* (cl->* (->* '() -Integer -Integer) (->* '() N N))) (/ (cl->* (->* (list N) N N))) (+ (cl->* (->* '() -Integer -Integer) (->* '() N N))) (- (cl->* (->* (list -Integer) -Integer -Integer) (->* (list N) N N))) (max (->* (list N) N N)) (min (->* (list N) N N)) [values (make-Poly '(a) (-> (-v a) (-v a)))] [vector-ref (make-Poly (list 'a) ((make-Vector (-v a)) N . -> . (-v a)))] [build-vector (-poly (a) (N (N . -> . a) . -> . (make-Vector a)))] [reverse (make-Poly '(a) (-> (make-lst (-v a)) (make-lst (-v a))))] [append (-poly (a) (->* (list) (-lst a) (-lst a)))] [length (make-Poly '(a) (-> (make-lst (-v a)) N))] [memq (make-Poly (list 'a) (-> (-v a) (make-lst (-v a)) (-opt (make-lst (-v a)))))] [memv (make-Poly (list 'a) (-> (-v a) (make-lst (-v a)) (-opt (make-lst (-v a)))))] [member (-poly (a) (a (-lst a) . -> . (-opt (-lst a))))] [string<? (->* (list -String -String) -String B)] [string>? (->* (list -String -String) -String B)] [string=? (->* (list -String -String) -String B)] [string<=? (->* (list -String -String) -String B)] [string>=? (->* (list -String -String) -String B)] [string-ci<? (->* (list -String -String) -String B)] [string-ci>? (->* (list -String -String) -String B)] [string-ci=? (->* (list -String -String) -String B)] [string-ci<=? (->* (list -String -String) -String B)] [string-ci>=? (->* (list -String -String) -String B)] [string-upcase (-> -String -String)] [string-downcase (-> -String -String)] [string-titlecase (-> -String -String)] [string-foldcase (-> -String -String)] [string-normalize-nfd (-> -String -String)] [string-normalize-nfkd (-> -String -String)] [string-normalize-nfc (-> -String -String)] [string-normalize-nfkc (-> -String -String)] [assq (-poly (a) (-> Univ (-lst (-pair Univ a)) a))] [build-path ((list -Pathlike*) -Pathlike* . ->* . -Path)] [string->number (-> -String (-opt N))] [with-input-from-file (-poly (a) (cl-> [(-Pathlike (-> a)) a] [(-Pathlike (-> a) Sym) a]))] [with-output-to-file (-poly (a) (cl-> [(-Pathlike (-> a)) a] [(-Pathlike (-> a) Sym) a]))] [random (cl-> [(N) N] [() N])] [assoc (-poly (a b) (a (-lst (-pair a b)) . -> . (-opt (-pair a b))))] [list-ref (-poly (a) ((-lst a) N . -> . a))] [positive? (-> N B)] [negative? (-> N B)] [odd? (-> N B)] [even? (-> N B)] [apply (-poly (a b) (((list) a . ->* . b) (-lst a) . -> . b))] [call/cc (-poly (a b) (((a . -> . (Un)) . -> . b) . -> . (*Un a b)))] [call/ec (-poly (a b) (((a . -> . (Un)) . -> . b) . -> . (*Un a b)))] [quotient (N N . -> . N)] [remainder (N N . -> . N)] [quotient/remainder (N N . -> . (-values (list N N)))] ;; parameter stuff [parameterization-key Sym] [extend-parameterization (-poly (a b) (-> Univ (-Param a b) a Univ))] [continuation-mark-set-first (-> (-opt -Cont-Mark-Set) Univ Univ)] [make-parameter (-poly (a b) (cl-> [(a) (-Param a a)] [(b (a . -> . b)) (-Param a b)]))] [current-directory (-Param -Pathlike -Path)] [current-namespace (-Param -Namespace -Namespace)] [print-struct (-Param B B)] [read-decimal-as-inexact (-Param B B)] [current-command-line-arguments (-Param (make-Vector -String) (make-Vector -String))] ;; regexp stuff [regexp-match (cl-> [((*Un -String -Regexp) -String) (-opt (-lst (-opt -String)))] [(-Pattern -String) (-opt (-lst (-opt (*Un -Bytes -String))))] [(-Pattern -String N) (-opt (-lst (-opt (*Un -Bytes -String))))] [(-Pattern -String N (-opt N)) (-opt (-lst (-opt (*Un -Bytes -String))))] [(-Pattern -String N (-opt N) (-opt -Output-Port)) (-lst (-opt (*Un -Bytes -String)))] [(-Pattern -String (-opt N) (-opt -Output-Port)) (-lst (-opt (*Un -Bytes -String)))] [(-Pattern -String (-opt -Output-Port)) (-lst (-opt (*Un -Bytes -String)))] [(-Pattern (*Un -Input-Port -Bytes)) (-opt (-lst (-opt -Bytes)))] [(-Pattern (*Un -Input-Port -Bytes) N) (-opt (-lst (-opt -Bytes)))] [(-Pattern (*Un -Input-Port -Bytes) N (-opt N)) (-opt (-lst (-opt -Bytes)))] [(-Pattern (*Un -Input-Port -Bytes) (-opt N)) (-opt (-lst (-opt -Bytes)))] [(-Pattern (*Un -Input-Port -Bytes) N (-opt N) (-opt -Output-Port)) (-lst (-opt -Bytes))])] [number->string (N . -> . -String)] [current-milliseconds (-> N)] [modulo (N N . -> . N)] ;; errors [raise-type-error (cl-> [(Sym -String Univ) (Un)] [(Sym -String N (-lst Univ)) (Un)])] ;; this is a hack [match:error ((list) Univ . ->* . (Un))] [vector-set! (-poly (a) (-> (make-Vector a) N a -Void))] [vector->list (-poly (a) (-> (make-Vector a) (-lst a)))] [list->vector (-poly (a) (-> (-lst a) (make-Vector a)))] [exact? (N . -> . B)] [inexact? (N . -> . B)] [expt (N N . -> . N)] [vector (-poly (a) (->* (list) a (make-Vector a)))] [real? (Univ . -> . B)] [real-part (N . -> . N)] [imag-part (N . -> . N)] [magnitude (N . -> . N)] [angle (N . -> . N)] [numerator (N . -> . N)] [denominator (N . -> . N)] [exact->inexact (N . -> . N)] [inexact->exact (N . -> . N)] [make-string (cl-> [(N) -String] [(N -Char) -String])] [arithmetic-shift (N N . -> . N)] [abs (N . -> . N)] [substring (cl-> [(-String N) -String] [(-String N N) -String])] [string-length (-String . -> . N)] [string-set! (-String N -Char . -> . -Void)] [make-vector (-poly (a) (cl-> [(N) (make-Vector N)] [(N a) (make-Vector a)]))] [file-exists? (-Pathlike . -> . B)] [string->symbol (-String . -> . Sym)] [symbol->string (Sym . -> . -String)] [vector-length (-poly (a) ((make-Vector a) . -> . N))] [call-with-input-file (-poly (a) (cl-> [(-String (-Port . -> . a)) a] [(-String (-Port . -> . a) Sym) a]))] [call-with-output-file (-poly (a) (cl-> [(-String (-Port . -> . a)) a] [(-String (-Port . -> . a) Sym) a]))] [current-output-port (-Param -Output-Port -Output-Port)] [current-error-port (-Param -Output-Port -Output-Port)] [current-input-port (-Param -Input-Port -Input-Port)] [round (N . -> . N)] [seconds->date (N . -> . (make-Struct 'date #f (list N N N N N N N N B N) #f))] [current-seconds (-> N)] [sqrt (-> N N)] [sqr (-> N N)] [path->string (-> -Path -String)] [link-exists? (-> -Pathlike B)] [directory-exists? (-> -Pathlike B)] [file-exists? (-> -Pathlike B)] [directory-list (cl-> [() (-lst -Path)] [(-Path) (-lst -Path)])] [make-hash (let ([ht-opt (*Un (-val 'weak) (-val 'equal))]) (-poly (a b) (cl-> [() (-HT a b)] [(ht-opt) (-HT a b)] [(ht-opt ht-opt) (-HT a b)])))] [hash-set! (-poly (a b) ((-HT a b) a b . -> . -Void))] [hash-map (-poly (a b c) ((-HT a b) (a b . -> . c) . -> . (-lst c)))] [hash-ref (-poly (a b c) (cl-> (((-HT a b) a) b) (((-HT a b) a (-> c)) (*Un b c)) (((-HT a b) a c) (*Un b c))))] #;[hash-index (-poly (a b) ((-HT a b) a b . -> . -Void))] [bytes (->* (list) N -Bytes)] [bytes-ref (-> -Bytes N N)] [bytes-append (->* (list -Bytes) -Bytes -Bytes)] [subbytes (cl-> [(-Bytes N) -Bytes] [(-Bytes N N) -Bytes])] [bytes-length (-> -Bytes N)] [open-input-file (-> -Pathlike -Input-Port)] [close-input-port (-> -Input-Port -Void)] [close-output-port (-> -Output-Port -Void)] [read-line (cl-> [() -String] [(-Input-Port) -String] [(-Input-Port Sym) -String])] [copy-file (-> -Pathlike -Pathlike -Void)] [bytes->string/utf-8 (-> -Bytes -String)] ;; language [(expand #'(this-language)) Sym string-constants/string-constant] ;; make-promise [(cadr (syntax->list (expand #'(delay 3)))) (-poly (a) (-> (-> a) (-Promise a))) scheme/promise] ;; qq-append [(cadr (syntax->list (expand #'`(,@'() 1)))) (-poly (a b) (cl->* (-> (-lst a) (-val '()) (-lst a)) (-> (-lst a) (-lst b) (-lst (*Un a b)))))] [force (-poly (a) (-> (-Promise a) a))] [bytes<? (->* (list -Bytes) -Bytes B)] [regexp-replace* (cl->* (-Pattern (*Un -Bytes -String) (*Un -Bytes -String) . -> . -Bytes) (-Pattern -String -String . -> . -String))] [peek-char (cl->* [-> -Char] [-Input-Port . -> . -Char] [-Input-Port N . -> . -Char] [N . -> . -Char])] [peek-byte (cl->* [-> -Byte] [-Input-Port . -> . -Byte] [-Input-Port N . -> . -Byte] [N . -> . -Byte])] [make-pipe (cl->* [-> (-values (list -Input-Port -Output-Port))] [N . -> . (-values (list -Input-Port -Output-Port))])] [open-output-bytes (cl->* [-> -Output-Port] [Univ . -> . -Output-Port])] [get-output-bytes (cl->* [-Output-Port . -> . -Bytes] [-Output-Port Univ . -> . -Bytes] [-Output-Port Univ N . -> . -Bytes] [-Output-Port Univ N N . -> . -Bytes] [-Output-Port N . -> . -Bytes] [-Output-Port N N . -> . -Bytes])] #;[exn:fail? (-> Univ B)] #;[exn:fail:read? (-> Univ B)] [write (-> -Sexp -Void)] [open-output-string (-> -Output-Port)] ;; FIXME - wrong [get-output-string (-> -Output-Port -String)] [make-directory (-> -Path -Void)] [hash-for-each (-poly (a b c) (-> (-HT a b) (-> a b c) -Void))] [delete-file (-> -Pathlike -Void)] [make-namespace (cl->* (-> -Namespace) (-> (*Un (-val 'empty) (-val 'initial)) -Namespace))] [eval (-> -Sexp Univ)] [exit (-> (Un))] ))) (begin-for-syntax (initialize-type-env initial-env) (initialize-others))
false
8038ac91ea8167670baff165254429f88dd8ddc9
f146a4cc8175d2b04ce9c38c020bc71dc9aa6acb
/util.scm
a9f48437e68b1b33f2998f686edd6377fa227802
[]
no_license
VoQn/Gauche-Color
27dca7f20a98048746cfa6f4d8dcba7eb8bc8262
7a4c78f1426d674f5f5107552c8da38068a6eb22
refs/heads/master
2016-09-06T19:17:45.133973
2011-12-06T21:03:17
2011-12-06T21:03:17
2,282,876
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,640
scm
util.scm
#!/usr/bin/env gosh ;; -*- mode: gauche; coding: utf-8; -*- (define-module util (export-all)) (select-module util) (define-macro (define-class* name supers slots . options) `(define-class ,name ,supers ,(map (^s (let ([has? (cut get-keyword <> <> #f)] [key (car s)] [accessor (^ (k a) (string->symbol #`",|k|-,|a|"))] [rest (cdr s)]) (let1 compl (^ (k i) (if (has? k rest) '() (list k i))) `(,key ,@(compl :init-value (make-init-value rest)) ,@(compl :init-keyword (make-keyword key)) ,@(compl :getter (accessor key 'of)) ,@(if (or (has? :setter rest) (has? :read-only rest)) '() (list :setter (accessor key 'set!))) ,@rest)))) slots) ,@options)) (define (make-init-value key-list) (let1 has? (cut get-keyword <> key-list #f) (if-let1 t (has? :is-a) (case t [(<number> <complex> <real> <integer>) 0] [(<string>) ""] [(<boolean>) #f] [(<list>) '()] [(<vector>) '#()] [else (make t)]) (undefined)))) (define-class <type-safe-meta> (<class>) (())) (define-method compute-get-n-set ((class <type-safe-meta>) slot) (let* ([has? (cut slot-definition-option slot <> #f)] [acc (compute-slot-accessor class slot (next-method))] [type-error (^ (value type) (error #`"Type Error : require type ,|type| but ,(class-of value)" value))] [validate-type (^v (if-let1 t (has? :is-a) (if (is-a? v t) v (type-error v t)) v))] [validate-value (^v (if-let1 validate (has? :validate) (validate v) v))] [filter-value (^v (if-let1 f (has? :filter) (f v) v))]) (if (or (has? :is-a) (has? :validate) (has? :filter)) (let1 filter/validate (.$ filter-value validate-value validate-type) (list (^ (o) (slot-ref-using-accessor o acc)) (^ (o v) (slot-set-using-accessor! o acc (filter/validate v))) (^ (o) (slot-bound-using-accessor? o acc)) #t)) (next-method)))) (define-syntax if$ (syntax-rules () [(_ pred true) (^ (x) (if (pred x) (true x)))] [(_ pred true false) (^ (x) (if (pred x) (true x) (false x)))])) (define (tolerance$ t) (.$ (pa$ > t) abs -)) (define (loop-mod$ max) (^x ((^v (if (= v (floor v)) (x->integer v) v)) (cond [(<= max x) (fmod x max)] [(> 0 x) (fmod (+ x max) max)] [else x])))) (define (inner$ min max) (cut clamp min <> max)) (define-method x->list ((str <string>)) (string->list str)) (define-method x->list ((vec <vector>)) (vector->list vec)) (define-method x->values ((obj <object>)) (apply values (x->list obj))) (provide "util") ;; EOF
true
b5c4efc0fac648e2daf6862e19432ad018fe043c
43612e5ed60c14068da312fd9d7081c1b2b7220d
/unit-tests/IFT3065/2/etape2-adder.scm
e70ce41fff3fa06be5a6125c81feb7e760d00deb
[ "BSD-3-Clause" ]
permissive
bsaleil/lc
b1794065183b8f5fca018d3ece2dffabda6dd9a8
ee7867fd2bdbbe88924300e10b14ea717ee6434b
refs/heads/master
2021-03-19T09:44:18.905063
2019-05-11T01:36:38
2019-05-11T01:36:38
41,703,251
27
1
BSD-3-Clause
2018-08-29T19:13:33
2015-08-31T22:13:05
Scheme
UTF-8
Scheme
false
false
141
scm
etape2-adder.scm
(define (adder y) (lambda (x) (+ x y))) (define inc (adder 1)) (define dec (adder -1)) (println (inc 100)) (println (dec 100)) ;101 ;99
false
2a3fd308ccbaf7d29c9330b922de92c11ee47344
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/sitelib/rfc/smtp/client.scm
16724b535a87bf893b5a6c709ed4f1ec975f63ce
[ "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
20,332
scm
client.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; rfc/smtp/client.scm - SMTP client ;;; ;;; Copyright (c) 2010-2015 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!read-macro=sagittarius/regex (library (rfc smtp client) (export make-smtp-connection smtp-connection? smtp-connection-options smtp-connection-authentication-methods smtp-authentication-required? make-smtp-mail smtp-mail? smtp-recipient? make-smtp-from smtp-from? make-smtp-to smtp-to? make-smtp-cc smtp-cc? make-smtp-bcc smtp-bcc? ;; basic procedures smtp-connect! smtp-authenticate! smtp-send! smtp-disconnect! ;; high level mail constructor smtp:mail ;; these are auxiliary syntax smtp:subject smtp:from smtp:to smtp:cc smtp:bcc smtp:attachment smtp:header smtp:alternative ;; re-export smtp-plain-authentication smtp-login-authentication ;; mail modification smtp-mail-add-recipent! smtp-mail-add-header! smtp-mail-add-attachment! make-smtp-attachment make-smtp-alternative-component make-smtp-alternative ;; low level smtp-mail->string smtp-address->string string->smtp-address ) (import (rnrs) (rnrs mutable-pairs) (rfc smtp commands) (rfc smtp extensions) (rfc smtp conditions) (rfc smtp authentications) (srfi :1) ;; for alist-delete (srfi :13) (srfi :14) (srfi :106) (srfi :112) (rfc tls) ;; need socket-port for TLS (rfc mime) ;; for attachments (rfc quoted-printable) (rfc :5322) (sagittarius regex) ) (define-record-type (<smtp-connection> make-smtp-connection smtp-connection?) (fields (immutable host smtp-connection-host) (immutable port smtp-connection-port) (immutable domain smtp-connection-domain) ;; computer name? (mutable socket smtp-connection-socket smtp-connection-socket-set!) (mutable in/out smtp-connection-in/out smtp-connection-in/out-set!) (mutable options smtp-connection-options smtp-connection-options-set!) (mutable authentication-methods smtp-connection-authentication-methods smtp-connection-authentication-methods-set!)) (protocol (lambda (p) (lambda (host port . maybe-domain) (let ((domain (if (null? maybe-domain) (machine-name) (car maybe-domain)))) ;; we don't connect it here (p host port domain #f #f '() '())))))) (define-record-type (<smtp-mail> make-smtp-mail smtp-mail?) (fields (immutable from smtp-mail-from) (mutable recipents smtp-mail-recipents smtp-mail-recipents-set!) (mutable headers smtp-mail-headers smtp-mail-headers-set!) (mutable subject smtp-mail-subject smtp-mail-subject-set!) (mutable contents smtp-mail-contents smtp-mail-contents-set!) (mutable attachments smtp-mail-attachments smtp-mail-attachments-set!)) (protocol (lambda (p) ;; TODO maybe use case-lambda? (lambda (from subject contents . recipients) (unless (smtp-from? from) (assertion-violation 'make-smtp-mail "<smtp-from> is required" from)) (unless (for-all smtp-recipient? recipients) (assertion-violation 'make-smtp-mail "<smtp-recipient>s are required" recipients)) (p from recipients '() subject contents '()))))) (define-record-type (<smtp-address> make-smtp-address smtp-address?) (fields (immutable type smtp-address-type) (immutable email smtp-address-email) (immutable name smtp-address-name)) (protocol (lambda (p) (lambda (type email name) (p type email name))))) (define-record-type (<smtp-recipipent> make-smtp-recipient smtp-recipient?) (parent <smtp-address>) (protocol (lambda (p) (lambda (t e m) ((p t e m)))))) (define-syntax define-recipient (lambda (x) (define (make-record-definitions k type) (let* ((s (symbol->string (syntax->datum type))) (r (string->symbol (string-append "<smtp-" s ">"))) (c (string->symbol (string-append "make-smtp-" s))) (p (string->symbol (string-append "smtp-" s "?")))) (datum->syntax k (list r c p)))) (define (make-header k type) (let* ((s (symbol->string (syntax->datum type))) (h (string-append (string-titlecase s) ": "))) (datum->syntax k h))) (syntax-case x () ((k type p) (with-syntax (((record ctr pred) (make-record-definitions #'k #'type)) (head (make-header #'k #'type))) #'(define-record-type (record ctr pred) (parent p) (protocol (lambda (p) (case-lambda ((address) ((p head address #f))) ((name address) ((p head address name)))))))))))) (define-recipient from <smtp-address>) (define-recipient to <smtp-recipipent>) (define-recipient cc <smtp-recipipent>) (define-recipient bcc <smtp-recipipent>) (define (smtp-mail-add-recipent! mail recipient) (unless (smtp-recipient? recipient) (assertion-violation 'smtp-mail-add-recipent "<smtp-recipient> is required" recipient)) (let ((old (smtp-mail-recipents mail))) (smtp-mail-recipents-set! mail (cons recipient old)) mail)) (define (smtp-mail-add-header! mail name value) (define reject-headers '("from" "to" "cc" "bcc" "subject")) (unless (and (string? name) (string? value)) (assertion-violation 'smtp-mail-add-header! "name and value must be strings" name value)) ;; reject some of headers (when (member name reject-headers string-ci=?) (assertion-violation 'smtp-mail-add-header! "specified header must be set by other procedures" name)) (let ((old (smtp-mail-headers mail)) (value (if (string-every char-set:ascii value) value (mime-encode-word value)))) (cond ((assoc name old string-ci=?) => ;; Should we raise an error? (lambda (slot) (set-cdr! slot (list value)))) (else (smtp-mail-headers-set! mail (cons (list name value) old)))) mail)) (define (smtp-mail-add-attachment! mail mime) (unless (mime-part? mime) (assertion-violation 'smtp-mail-add-header! "attachment must be mime-part" mime)) (let ((old (smtp-mail-attachments mail))) (smtp-mail-attachments-set! mail (cons mime old)) mail)) (define (raise-smtp-error smtp who msg . irr) (raise (condition (list smtp (make-who-condition who) (make-message-condition msg) (make-irritants-condition irr))))) (define tr (make-transcoder (utf-8-codec) (eol-style none))) (define (smtp-authentication-required? conn) (not (null? (smtp-connection-authentication-methods conn)))) (define (smtp-connect! conn) (define (auth-methods? line) (define (auth? s) (string-prefix? "AUTH" s)) (cond ((auth? line) (map string->symbol (cdr (string-tokenize line)))) (else #f))) (define (parse-options conn resp) (let ((in (open-string-input-port resp))) (let loop ((r '())) (let ((line (get-line in))) (cond ((eof-object? line) r) ((auth-methods? line) => (lambda (methods) (smtp-connection-authentication-methods-set! conn methods) (loop r))) (else (loop (cons line r)))))))) (define (send-hello conn port domain) (smtp-ehlo port domain) (let loop ((ehlo #t)) (let-values (((status resp) (smtp-recv port))) (cond ((= status 502) (smtp-helo port (smtp-connection-domain conn)) (loop #f)) ((= status 250) (if ehlo (parse-options conn resp) '())) (else (raise-smtp-error (make-smtp-error) 'smtp-connect! "HELO failed" status)))))) (let* ((socket (or (smtp-connection-socket conn) (make-client-socket (smtp-connection-host conn) (smtp-connection-port conn)))) (port (transcoded-port (socket-port socket #f) tr))) (let-values (((status resp) (smtp-recv port))) (unless (= status 220) (raise-smtp-error (make-smtp-error) 'smtp-connect! "Greeting failed" status))) (let* ((domain (smtp-connection-domain conn)) (options (send-hello conn port domain))) (if (member "STARTTLS" options string=?) (let* ((socket (smtp-starttls port socket)) (port (transcoded-port (socket-port socket #f) tr))) (smtp-connection-socket-set! conn socket) (smtp-connection-in/out-set! conn port) ;; ok do ehlo again (smtp-connection-options-set! conn (send-hello conn port domain))) (begin (smtp-connection-socket-set! conn socket) (smtp-connection-in/out-set! conn port) (smtp-connection-options-set! conn options))) conn))) (define (smtp-authenticate! conn gen-initial-response . maybe-next) (define (wrap-next next) (lambda (status content) (let-values (((command next-next) (next conn status content))) (if next-next (values command (wrap-next next-next)) (values command #f))))) (apply smtp-auth (smtp-connection-in/out conn) gen-initial-response (if (null? maybe-next) '() (list (wrap-next (car maybe-next)))))) (define (smtp-send! conn mail) (define (has-8bitmime? options) ;; some SMTP server return "8 BITMIME", don't know why (find (lambda (s) (or (string=? s "8BITMIME") (string=? s "8 BITMIME"))) options)) (define (address->postmaster a) (string-append "<" (smtp-address-email a) ">")) (define (check-status port status) (let-values (((rstatus resp) (smtp-recv port))) (unless (= rstatus status) (raise-smtp-error (make-smtp-error) 'smtp-send! resp rstatus)))) (let* ((data (smtp-mail->string mail)) ;; let it check here before we send (8bitmime? (has-8bitmime? (smtp-connection-options conn))) (port (smtp-connection-in/out conn)) (from (smtp-mail-from mail)) (recipents (smtp-mail-recipents mail))) ;; TODO PIPELINING (apply smtp-mail port (address->postmaster from) (if 8bitmime? '("BODY=8BITMIME") '())) (check-status port 250) (for-each (lambda (r) (smtp-rcpt port (address->postmaster r)) (check-status port 250)) recipents) (smtp-data port) (check-status port 354) (smtp-send-data port (open-string-input-port data)) (check-status port 250) conn)) ;; Disconnect SMTP connection ;; close socket (define (smtp-disconnect! conn) (let ((in/out (smtp-connection-in/out conn)) (socket (smtp-connection-socket conn))) (smtp-quit in/out) (smtp-recv in/out) (smtp-connection-socket-set! conn #f) (smtp-connection-in/out-set! conn #f) (socket-shutdown socket *shut-rdwr*) (socket-close socket) conn)) (define (smtp-send-command conn s) (let ((in/out (smtp-connection-in/out conn))) (put-string in/out s))) ;; wrapper for smtp-recv (define (smtp-recv-response conn) (let ((in/out (smtp-connection-in/out conn))) (smtp-recv in/out))) (define (smtp-address->string address) (let-values (((out extract) (open-string-output-port))) (put-string out (smtp-address-type address)) (let ((name (smtp-address-name address)) (email (smtp-address-email address))) (when name (put-string out name)) (put-char out #\<) (put-string out email) (put-char out #\>)) (extract))) (define (string->smtp-address ctr str) (cond ((#/([^<>]+)<(.+)>/ str) => (lambda (m) (ctr (m 1) (m 2)))) (else (ctr str)))) (define (smtp-mail->string mail) (define qpes quoted-printable-encode-string) (define (handle-multipart out headers content attachs) (let*-values (((type subtype) (cond ((assoc "content-type" headers string-ci=?) => (lambda (s) (let ((ctype (mime-parse-content-type (cdr s)))) (values (car ctype) (cadr ctype))))) (else (values "text" "plain")))) ((body boundary) (mime-compose-message-string (if (string? content) (cons (make-mime-part :type type :subtype subtype :content (qpes content) :transfer-encoding "quoted-printable") attachs) attachs)))) (put-string out "Mime-Version: 1.0\r\n") ;; To enable 'cid' reference defined in RFC 2387 ;; ref. https://tools.ietf.org/html/rfc2387 ;; we check existance of 'content-id' in the given attachments ;; if there is, then we put multpart/related with the generated ;; boundary ;; TODO this is too naive and how can we support alternative ;; with this? (if (exists (lambda (m) (assoc "content-id" (mime-part-headers m) string-ci=?)) attachs) (put-string out "Content-Type: multipart/related") (put-string out "Content-Type: multipart/mixed")) (put-string out (mime-compose-parameters `((boundary . ,boundary)) #f)) (put-string out "\r\n") (put-string out body))) (let ((from (smtp-mail-from mail)) (recipents (smtp-mail-recipents mail)) (headers (smtp-mail-headers mail)) (subject (smtp-mail-subject mail)) (content (smtp-mail-contents mail)) (attachs (smtp-mail-attachments mail))) (when (null? recipents) (assertion-violation 'smtp-mail->string "At least one recipient is required" mail)) (unless (for-all mime-part? attachs) (assertion-violation 'smtp-mail->string "Attachments must be mime-part" attachs)) (let-values (((out extract) (open-string-output-port))) (put-string out (smtp-address->string from)) (put-string out "\r\n") (for-each (lambda (r) (put-string out (smtp-address->string r)) (put-string out "\r\n")) recipents) (let ((headers (if (null? attachs) headers (alist-delete "content-type" headers string-ci=?)))) (rfc5322-write-headers headers :output out :continue #t)) ;; subject (put-string out "Subject: ") (if (string-every char-set:ascii subject) (put-string out subject) (put-string out (mime-encode-word subject))) (put-string out "\r\n") (cond ((null? attachs) (put-string out "\r\n") ;; check no content (when (string? content) (put-string out content))) (else (handle-multipart out headers content attachs))) (extract)))) (define (make-smtp-attachment type subtype content . maybe-filename) (define (merge-header generated user-defined) ;; user-defined is always stronger so if it has content-disposition ;; then use that one (cond ((assoc "content-disposition" user-defined string-ci=?) user-defined) (else (cons generated user-defined)))) (let* ((disposition-type (if (or (null? maybe-filename) (null? (cdr maybe-filename))) "attachment" (cadr maybe-filename))) (filename (if (null? maybe-filename) disposition-type (string-append disposition-type (mime-compose-parameters `((filename . ,(car maybe-filename))) #f)))) (headers (if (or (null? maybe-filename) (null? (cdr maybe-filename)) (null? (cddr maybe-filename))) '() (cddr maybe-filename)))) (make-mime-part :type type :subtype subtype :transfer-encoding "base64" :content content :headers (merge-header `("content-disposition" ,filename) headers)))) (define (make-smtp-alternative-component type subtype content . headers) (make-mime-part :type type :subtype subtype :transfer-encoding "base64" ; TODO printed-quotable? :content content :headers headers)) (define (make-smtp-alternative . alternatives) (make-mime-part :type "multipart" :subtype "alternative" :transfer-encoding #f :content alternatives)) ;; High level API (define-syntax smtp:subject (syntax-rules ())) (define-syntax smtp:to (syntax-rules ())) (define-syntax smtp:cc (syntax-rules ())) (define-syntax smtp:bcc (syntax-rules ())) (define-syntax smtp:from (syntax-rules ())) (define-syntax smtp:attachment (syntax-rules ())) (define-syntax smtp:header (syntax-rules ())) (define-syntax smtp:alternative (syntax-rules () ((_ (spec1 ...) (spec2 ...) (spec* ...) ...) (make-smtp-alternative (make-smtp-alternative-component spec1 ...) (make-smtp-alternative-component spec2 ...) (make-smtp-alternative-component spec* ...) ...)))) (define-syntax smtp:mail (syntax-rules (smtp:from smtp:subject smtp:to smtp:cc smtp:bcc smtp:attachment smtp:header smtp:alternative) ;; parse subject ((_ "parse" from "no subject" content (recp ...) (attach ...) (head ...) ((smtp:subject sub) elements ...)) (smtp:mail "parse" from sub content (recp ...) (attach ...) (head ...) (elements ...))) ;; TODO we want to generate these 3 somehow ;; parse to ((_ "parse" from subject content (recp ...) (attach ...) (head ...) ((smtp:to to ...) elements ...)) (smtp:mail "parse" from subject content (recp ... (make-smtp-to to ...)) (attach ...) (head ...) (elements ...))) ;; parse cc ((_ "parse" from subject content (recp ...) (attach ...) (head ...) ((smtp:cc to ...) elements ...)) (smtp:mail "parse" from subject content (recp ... (make-smtp-cc to ...)) (attach ...) (head ...) (elements ...))) ;; parse bcc ((_ "parse" from subject content (recp ...) (attach ...) (head ...) ((smtp:bcc to ...) elements ...)) (smtp:mail "parse" from subject content (recp ... (make-smtp-bcc to ...)) (attach ...) (head ...) (elements ...))) ;; parse attachment ((_ "parse" from subject content (recp ...) (attach ...) (head ...) ((smtp:attachment spec ...) elements ...)) (smtp:mail "parse" from subject content (recp ...) ((make-smtp-attachment spec ...) attach ...) (head ...) (elements ...))) ;; parse header ((_ "parse" from subject content (recp ...) (attach ...) (head ...) ((smtp:header n v) elements ...)) (smtp:mail "parse" from subject content (recp ...) (attach ...) (head ... (n v)) (elements ...))) ;; parse alternative (content must be #f) ;; NB alternative is mere attachment ((_ "parse" from subject #f (recp ...) (attach ...) (head ...) ((smtp:alternative (spec* ...) ...) elements ...)) ;; mark content #t so that alternative can only exist once (smtp:mail "parse" from subject #t (recp ...) ((smtp:alternative (spec* ...) ...) attach ...) (head ...) (elements ...))) ;; parse content ((_ "parse" from subject #f (recp ...) (attach ...) (head ...) (e elements ...)) (smtp:mail "parse" from subject e (recp ...) (attach ...) (head ...) (elements ...))) ((_ "parse" from subject content (recp ...) (attach ...) (head ...) (e elements ...)) (smtp:mail "parse" from subject (string-append content "\r\n" e) (recp ...) (attach ...) (head ...) (elements ...))) ;; finish ((_ "parse" from subject content (recp ...) (attach ...) ((hn hv) ...) ()) (let ((mail (make-smtp-mail from subject content recp ...))) (smtp-mail-add-attachment! mail attach) ... (smtp-mail-add-header! mail hn hv) ... mail)) ;; entry point ((_ (smtp:from from ...) elements ...) (smtp:mail "parse" (make-smtp-from from ...) "no subject" #f () () () (elements ...))))) )
true
7e1c7029b2d1429d0828b96622a45fbccf06595b
cb8cccd92c0832e056be608063bbec8fff4e4265
/chapter2/Exercises/2.17.scm
6a8153ccda881bc1eea349448136af11b706fc47
[]
no_license
JoseLGF/SICP
6814999c5fb15256401acb9a53bd8aac75054a14
43f7a8e6130095e732c6fc883501164a48ab2229
refs/heads/main
2023-07-21T03:56:35.984943
2021-09-08T05:19:38
2021-09-08T05:19:38
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
258
scm
2.17.scm
#lang scheme ; Ex 2.17 ; Assumes that the list is non-empty (define (last-pair lst) (if (null? (cdr lst)) (car lst) (last-pair (cdr lst)))) (last-pair (list 23 72 149 34)) (last-pair (list 23)) ; (last-pair (list )) ; Empty list throws error
false
f26c84ae68087174ebbf7350f2da93cdfa40b36f
f4aeaa0812ac15d5a8d2cb6da75ac335c3cf5cf4
/miruKanren/sorted-int-set.sld
6a250621c216789c0743deed10105ef2554daf09
[ "MIT" ]
permissive
orchid-hybrid/microKanren-sagittarius
13f7916f8ef7c946cefeb87e9e52d6d4a5dfe6c9
9e740bbf94ed2930f88bbcf32636d3480934cfbb
refs/heads/master
2021-01-13T01:54:20.589391
2015-06-13T12:40:14
2015-06-13T12:40:14
29,868,626
12
4
null
2015-02-12T07:11:25
2015-01-26T16:01:10
Scheme
UTF-8
Scheme
false
false
154
sld
sorted-int-set.sld
(define-library (miruKanren sorted-int-set) (import (scheme base)) (export intersects? intersection) (include "sorted-int-set.scm"))
false
aa8b341fa3729ccea482e3b46809f21e24429db8
0eabe12b2e378cdd8a6f8bc008a3607bdd4b6c70
/tests/opcode-tests.scm
11948ae29c6df5aa2ad780a08a6cdfa8b3b351db
[ "CC0-1.0" ]
permissive
Schol-R-LEA/Master-and
f92dda19874724d06f14f2869b17a75e45f8a8d6
8e0a0d68dfebd4e3e26626fd53b5b83e4ebb17cc
refs/heads/master
2020-12-15T07:06:17.035426
2020-10-31T19:40:24
2020-10-31T19:40:24
235,027,943
0
0
null
null
null
null
UTF-8
Scheme
false
false
848
scm
opcode-tests.scm
#!r6rs (import (rnrs (6)) (rnrs base (6)) (rnrs io simple (6)) (srfi srfi-64) (rnrs bytevectors (6)) (master-and opcodes)) (define runner (test-runner-simple)) (test-with-runner runner (test-group "Test nullaries" (test-group "Test make-nullary" (let ((zero-test (make-nullary 0))) (test-assert (list (make-bytevector 1 0)) (zero-test))))) (test-group "Test general opcodes" (test-group "Test make-opcode" (let ((foo (make-opcode #b11100000 (ind-zp-x zp imm abs ind-zp-y zp-x abs-y abs-x) "no-op"))) (test-equal (list (make-bytevector 1 #b11111100) (make-bytevector 1 3)) (foo 'abs-x 3))))))
false
c0538cfb0ecf6ddebe7bc016c7ef2e73fcdd038f
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/runtime/remoting/channels/aggregate-enumerator.sls
2caf81edfe28fc0ce916b420beb4fff868a6ddaf
[]
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,512
sls
aggregate-enumerator.sls
(library (system runtime remoting channels aggregate-enumerator) (export new is? aggregate-enumerator? reset move-next? entry key value current) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Runtime.Remoting.Channels.AggregateEnumerator a ...))))) (define (is? a) (clr-is System.Runtime.Remoting.Channels.AggregateEnumerator a)) (define (aggregate-enumerator? a) (clr-is System.Runtime.Remoting.Channels.AggregateEnumerator a)) (define-method-port reset System.Runtime.Remoting.Channels.AggregateEnumerator Reset (System.Void)) (define-method-port move-next? System.Runtime.Remoting.Channels.AggregateEnumerator MoveNext (System.Boolean)) (define-field-port entry #f #f (property:) System.Runtime.Remoting.Channels.AggregateEnumerator Entry System.Collections.DictionaryEntry) (define-field-port key #f #f (property:) System.Runtime.Remoting.Channels.AggregateEnumerator Key System.Object) (define-field-port value #f #f (property:) System.Runtime.Remoting.Channels.AggregateEnumerator Value System.Object) (define-field-port current #f #f (property:) System.Runtime.Remoting.Channels.AggregateEnumerator Current System.Object))
true
665acefe4ef601bca2cbcbac1e474e3d3109db1f
0bb7631745a274104b084f6684671c3ee9a7b804
/lib/srfi/2/syntax-utils.scm
aa6a9df728d884fa369fd57185bf4a36cfc551da
[ "Apache-2.0", "LGPL-2.1-only", "LicenseRef-scancode-free-unknown", "GPL-3.0-or-later", "LicenseRef-scancode-autoconf-simple-exception" ]
permissive
feeley/gambit
f87fd33034403713ad8f6a16d3ef0290c57a77d5
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
refs/heads/master
2023-03-17T06:19:15.652170
2022-09-05T14:31:53
2022-09-05T14:31:53
220,799,690
0
1
Apache-2.0
2019-11-10T15:09:28
2019-11-10T14:14:16
null
UTF-8
Scheme
false
false
359
scm
syntax-utils.scm
(##supply-module srfi/2/syntax-utils) (##namespace ("srfi/2/syntax-utils#")) (##import gambit) (##include "syntax-utils#.scm") (define (syntax-lift f) (lambda (src) (let ((r (f (##source-code src)))) (if (##source? r) r (datum->syntax src r))))) (define syntax-car (syntax-lift car)) (define syntax-cadr (syntax-lift cadr))
false
4aa7174604899f5628e50dfe71f92637616dcbe4
e358b0cf94ace3520adff8d078a37aef260bb130
/generic-ops/tests.ss
feaf620afdf44ddba6381f462d542654385da24a
[]
no_license
dzhus/sicp
784766047402db3fad4884f7c2490b4f78ad09f8
090fa3228d58737d3558f2af5a8b5937862a1c75
refs/heads/master
2021-01-18T17:28:02.847772
2020-05-24T19:15:57
2020-05-24T20:56:00
22,468,805
0
0
null
null
null
null
UTF-8
Scheme
false
false
15,575
ss
tests.ss
#lang scheme ;;; Tests for our generic arithmetics system (require srfi/1 srfi/27 (planet schematics/schemeunit:3) (planet schematics/schemeunit:3/text-ui)) (require "get-put.ss" "ddp-shared.ss" (prefix-in 2.78: "ex2.78.ss") "complex.ss" "packages.ss" "generic-arith.ss" "ex2.79.ss" "ex2.80.ss" "coercion-shared.ss" (prefix-in 2.81: "ex2.81.ss") (prefix-in 2.82: "ex2.82.ss") "ex2.83.ss" (prefix-in 2.84: "ex2.84.ss") (prefix-in 2.85: "ex2.85.ss") (prefix-in 2.86: "ex2.86.ss")) (define epsilon 1e-8) (define (all-true? list) (not (any false? list))) (define-simple-check (check-equ? x y) (check-true (equ? x y))) (define-test-suite get-put-test (test-case "Test put/get operations" (let ((op1 (lambda (x y) (* x y))) (op2 (lambda (x y) (+ x y)))) (put 'mul 'complex op1) (put 'add 'complex op2) ;; Make sure we get what we've put (let ((res1 (get 'mul 'complex)) (res2 (get 'add 'complex)) (res3 (get 'sub 'rational))) (check-equal? op1 res1) (check-equal? op2 res2) (check-false res3))))) (define-test-suite ddp-shared-test (test-case "Functions to attach tags to data" (let ((tags '(rational user-type type2)) (data-pieces (list "test1" (list "foo" '@ "bar") -1 5 (cons 2 2)))) (for-each (lambda (tag data) (let ((compound (attach-tag tag data))) (check-equal? tag (type-tag compound)) (check-equal? data (contents compound)))) tags data-pieces))) (test-case "Special version for Scheme numbers (ex. 2.78)" (let ((numbers '(1 -2.0 0 5/2))) (for-each (lambda (n) (check-equal? 'scheme-number (2.78:type-tag n)) (check-equal? n (2.78:contents n))) numbers)))) ;; Make sure generic operations do what's expected ;; Works only with unary constructors: ;; ;; (check-generic-operations ;; make-real ;; '(1 2 3) ;; (list (cons add +) ;; (cons mul *))) ;; ;; tests whether `(add (make-real 1) (make-real 2))` is the same as `(make-real (define-simple-check (check-generic-operations constructor numbers operations) (all-true? (map (lambda (op) (all-true? (map (lambda (n1 n2) (check-equ? ((car op) (constructor n1) (constructor n2)) (constructor ((cdr op) n1 n2)))) numbers numbers))) operations))) (define-test-suite arithmetics (test-case "Primitives for rectangular and polar representations of complex" (let* ((k (list (- (random-integer 100) 50) (random-integer 100) (random-integer 1234567890)))) (for-each (lambda (k1 k2) (let ((c1 (make-complex-from-real-imag k1 k2)) (c2 (make-complex-from-mag-ang k1 k2))) (check-equal? k1 (real-part c1)) (check-equal? k2 (imag-part c1)) (check-equal? k1 (magnitude c2)) (check-equal? k2 (angle c2)))) k k))) (test-case "=zero? predicate (excercise 2.80)" (let ((numbers (list (make-integer 0) (sub (make-integer 5) (make-integer 5)) (make-rational 0 10) (make-rational -0 1) (make-complex-from-real-imag 0.0 -0.0) (make-complex-from-real-imag -0.0 0e5) (make-complex-from-mag-ang -0.0 0) (make-complex-from-mag-ang 0.0 (/ pi -4))))) (for-each (lambda (n) (check-pred =zero? n)) numbers))) (test-case "equ? predicate (excercise 2.79)" (check-equ? (make-rational 3 9) (make-rational 21 63)) (check-equ? (make-rational 27 27) (make-rational 100000 100000)) (check-equ? (make-integer 0) (make-integer -0)) (check-false (equ? (make-integer 5) (make-integer -5))) (check-equ? (make-real 5) (make-real 5.0)) (check-false (equ? (make-real 1.7) (make-real 1.71))) (check-equ? (make-complex-from-real-imag 1 1) (make-complex-from-mag-ang (sqrt 2) (/ pi 4)))) (test-case "Integers" (check-generic-operations make-integer (list (random-integer 500) (- (random-integer 500) 250)) (list (cons add +) (cons sub -) (cons mul *)))) (test-case "Rationals" (check-equ? (sub (make-rational -1 5) (make-rational 21 6)) (make-rational -37 10)) (check-equ? (add (make-rational -1 5) (make-rational 21 6)) (make-rational 33 10)) (check-equ? (add (make-rational 1 3) (make-rational 1 4)) (make-rational 7 12)) (check-equ? (add (make-rational -100 1) (make-rational 201 99)) (make-rational -3233 33)) (check-equ? (add (make-rational -0 5) (make-rational 0 8)) (make-rational 0 101))) (test-case "Reals" (check-generic-operations make-real (list (* (random-real) 500) (- (* (random-real) 500)) (* (random-real) 123456)) (list (cons add +) (cons sub -) (cons mul *) (cons div /)))) (test-case "Complex representations interoperability test" (let ((c1 (make-complex-from-real-imag 1 1)) (c2 (make-complex-from-mag-ang (sqrt 2) (/ pi 4))) (c3 (make-complex-from-real-imag -1 0)) (c4 (make-complex-from-mag-ang 1 pi))) (check-equ? c1 c2) (check-equ? c3 c4) (check-false (equ? c1 c3)) (for-each (lambda (selector) (check-= (selector c1) (selector c2) epsilon)) (list real-part imag-part magnitude angle)))) (test-case "Complex numbers" (let ((c1 (make-complex-from-real-imag 1 -0)) (c2 (make-complex-from-real-imag (/ (sqrt 2) 2) (/ (sqrt 2) 2))) (c3 (make-complex-from-mag-ang 1 pi)) (c4 (make-complex-from-mag-ang 1 (* 7 (/ pi 4)))) (c5 (make-complex-from-mag-ang (sqrt 2) 0.0))) (check-equ? c1 (div c2 c2)) (check-equ? c3 (mul (mul c2 c2) (mul c2 c2))) (check-equ? c5 (add c2 c4)) (check-equ? c4 (sub c5 c2)) (check-equ? c1 (div c5 c5)) (check-equ? c1 (mul c2 c4))))) (define-test-suite coercion (test-case "Shared coercion functions" (let ((coer1 (lambda (x) (make-integer x))) (coer2 (lambda (x) (make-rational x 1)))) (put-coercion 'limbo 'integer coer1) (put-coercion 'integer 'rational coer2) ;; Make sure we get what we've put (let ((res1 (get-coercion 'limbo 'integer)) (res2 (get-coercion 'integer 'rational)) (res3 (get 'limbo 'complex))) (check-equal? coer1 res1) (check-equal? coer2 res2) (check-false res3)))) (test-case "Simple type coercion (excercise 2.81)" (put-coercion 'integer 'rational (lambda (x) (make-rational (contents x) 1))) (put-coercion 'integer 'real (lambda (x) (make-real (contents x)))) (put-coercion 'real 'complex (lambda (x) (make-complex-from-real-imag (contents x) 0))) (let ((c1 (make-integer 5)) (c2 (make-rational 1 8)) (c3 (make-real 10)) (c4 (make-complex-from-real-imag 0 -5))) (check-equ? (2.81:apply-generic 'add c1 c2) (make-rational 41 8)) (check-equ? (2.81:apply-generic 'mul c1 c3) (make-real 50)) (check-equ? (2.81:apply-generic 'sub c4 c3) (make-complex-from-real-imag -10 -5)))) (test-case "Advanced type coercion (excercise 2.82)" (let ((add-3-real (lambda (x y z) (make-real (+ x y z)))) (add-3-complex (lambda (x y z) (make-complex-from-real-imag (+ (real-part x) (real-part y) (real-part z)) 0)))) ;; Add generic operation which is implemented only for complex ;; numbers (put 'add '(real real real) add-3-real) (put 'add '(complex complex complex) add-3-complex) ;; Install coercion operations (integer->real and real->complex ;; have already been installed) (put-coercion 'rational 'real (lambda (x) (make-real (/ (numer x) (denom x))))) (put-coercion 'integer 'complex (lambda (x) (make-complex-from-real-imag (contents x) 0))) (let ((c1 (make-integer 1)) (c2 (make-real 757.13)) (c3 (make-rational 2 5)) (c4 (make-complex-from-mag-ang 13.37 0))) ;; Add real and rational (coercing to real) (check-equ? (2.82:apply-generic 'add c2 c3) (make-real 757.53)) ;; Add integer, real and rational (coercing to real) (check-equ? (2.82:apply-generic 'add c1 c2 c3) (make-real 758.53)) ;; Add integer, real and complex (coercing to latter) (check-equ? (2.82:apply-generic 'add c1 c2 c4) (make-complex-from-mag-ang 771.5 0)))))) (define-test-suite tower (test-case "Raising" (check-equ? (raise (make-integer 5)) (make-rational 10 2)) (check-equ? (raise (make-integer 0)) (make-rational 0 1)) (check-equ? (raise (make-rational 30 6)) (make-real 5.0)) (check-equ? (raise (make-real 13.37)) (make-complex-from-mag-ang 13.37 0))) (test-case "Coercion via raising" (let ((c1 (make-integer 5)) (c2 (make-rational 7 10)) (c3 (make-real 101.25)) (c4 (make-complex-from-real-imag 13.37 5))) ;; Add integer and rational (raising to rational) (check-equ? (2.84:apply-generic 'add c1 c2) (make-rational 57 10)) ;; Add integer, real and rational (raising to real) (relies on ;; add-3-real installed few tests ago) (check-equ? (2.84:apply-generic 'add c1 c2 c3) (make-real 106.95)) ;; Multiply integer and rational, resulting in rational (check-equ? (2.84:apply-generic 'mul c1 c2) (make-rational 35 10)) ;; Subtract rational and complex (raising to latter) (check-equ? (2.84:apply-generic 'sub c2 c4) (make-complex-from-real-imag -12.67 -5)) ;; Call operation defined only for reals and complex numbers with ;; integer and rational arguments (see `add-3-real` installed few ;; tests ago); gives a real number as apply-generic from 2.84 ;; does not drop result (check-equ? (2.84:apply-generic 'add c1 c1 c1) (make-real 15)) (check-equ? (2.84:apply-generic 'add c1 c2 c1) (make-real 10.7)))) (test-case "Dropping" (check-equ? (2.85:drop (make-complex-from-real-imag 5 0)) (make-integer 5)) (check-equ? (2.85:drop (make-complex-from-real-imag 1 1)) (make-complex-from-mag-ang (sqrt 2) (/ pi 4))) (check-equ? (2.85:drop (make-complex-from-mag-ang 5.2 0)) (make-rational 52 10)) (check-equ? (2.85:drop (make-real 20.0)) (make-integer 20)) (check-equ? (2.85:drop (make-real 0.6)) (make-rational 3 5)) (check-false (equ? (2.85:drop (make-real pi)) (make-rational 22 7))) (check-equ? (2.85:drop (make-rational 5 2)) (make-rational 10 4)) (check-equ? (2.85:drop (make-integer 9)) (make-integer 9))) (test-case "Simplification" (check-equ? (2.85:apply-generic 'add (make-complex-from-real-imag 5.0 0) (make-real 5.0)) (make-integer 10)) (check-equ? (2.85:apply-generic 'mul (make-real 17.5) (make-rational 2 5)) (make-integer 7)) (check-equ? (2.85:apply-generic 'add (make-rational 1 2) (make-real 1)) (make-rational 3 2)) (check-equ? (2.85:apply-generic 'sub (make-real 7.1) (make-real 5.1)) (make-integer 2)) (check-equ? (2.85:apply-generic 'add (make-complex-from-real-imag 5 1) (make-real 5)) (make-complex-from-real-imag 10 1)) ;; Ternary `add` is defined for real and complex numbers only, but ;; still works even with all integer and rational arguments thanks ;; to `apply-generic` in 2.84 (check-equ? (2.85:apply-generic 'add (make-integer 1) (make-rational 71 100) (make-rational 329 100)) (make-integer 5)) (check-equ? (2.85:apply-generic 'add (make-rational -10 10) (make-integer 1) (make-integer 329100)) (make-integer 329100)))) (define-test-suite adv-generics (test-case "Generic sine and cosine" (check-equ? (2.86:sin (make-integer 0)) (make-integer 0)) (check-equ? (2.86:sin (make-real (/ pi 2))) (make-integer 1)) (check-equ? (2.86:cos (make-integer 0)) (make-integer 1)) (check-equ? (2.86:cos (make-real pi)) (make-integer -1)) (check-equ? (2.86:cos (make-rational -0 4)) (make-integer 1))) (test-case "Generic sqrt" (check-equ? (2.86:sqrt (make-integer 0)) (make-integer 0)) (check-equ? (2.86:sqrt (make-rational 1 1)) (make-integer 1)) (check-equ? (2.86:sqrt (make-rational 4 1)) (make-integer 2)) (check-equ? (2.86:sqrt (make-real 100)) (make-integer 10)) (check-equ? (2.86:sqrt (make-rational 9 49)) (make-rational 3 7)) (check-equ? (2.86:sqrt (make-real 0.25)) (make-rational 1 2))) (test-case "atan" (check-equ? (2.86:atan (make-integer 0) (make-integer 1)) (make-integer 0)))) (define-test-suite adv-complex (test-case "Advanced complex numbers" (check-equ? (add (2.86:make-complex-from-real-imag (make-rational 1 4) (make-integer 10)) (2.86:make-complex-from-mag-ang (make-rational 3 4) (make-real 0))) (2.86:make-complex-from-real-imag (make-integer 1) (make-integer 10))) (check-equ? (2.86:make-complex-from-mag-ang (make-real (sqrt 2)) (make-integer 0)) (2.86:make-complex-from-real-imag (make-real (sqrt 2.0)) (make-rational -0 2))) (check-equ? (mul (2.86:make-complex-from-mag-ang (make-real 5) (make-integer 5)) (2.86:make-complex-from-mag-ang (make-real 7.0) (make-rational -4 2))) (2.86:make-complex-from-mag-ang (make-real 35.0) (make-integer 3))))) (exit (run-tests (test-suite "All tests" get-put-test ddp-shared-test arithmetics coercion adv-generics adv-complex tower)))
false
890bcf90c7e28c0b17cecb9dba4614cee57c29d2
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine.UI/unity-engine/ui/content-size-fitter.sls
c38d50202819b95f9c05ecf8babd7ee50c172672
[]
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,182
sls
content-size-fitter.sls
(library (unity-engine ui content-size-fitter) (export is? content-size-fitter? set-layout-vertical set-layout-horizontal horizontal-fit-get horizontal-fit-set! horizontal-fit-update! vertical-fit-get vertical-fit-set! vertical-fit-update!) (import (ironscheme-clr-port)) (define (is? a) (clr-is UnityEngine.UI.ContentSizeFitter a)) (define (content-size-fitter? a) (clr-is UnityEngine.UI.ContentSizeFitter a)) (define-method-port set-layout-vertical UnityEngine.UI.ContentSizeFitter SetLayoutVertical (System.Void)) (define-method-port set-layout-horizontal UnityEngine.UI.ContentSizeFitter SetLayoutHorizontal (System.Void)) (define-field-port horizontal-fit-get horizontal-fit-set! horizontal-fit-update! (property:) UnityEngine.UI.ContentSizeFitter horizontalFit UnityEngine.UI.ContentSizeFitter+FitMode) (define-field-port vertical-fit-get vertical-fit-set! vertical-fit-update! (property:) UnityEngine.UI.ContentSizeFitter verticalFit UnityEngine.UI.ContentSizeFitter+FitMode))
false
f87c0918329d5e2a2f4c4ad3a7d6be5a77d7e968
a2d8b4843847507b02085bb8adabd818f57dd09f
/scheme/scheme-programming-language/grades.ss
a4d23d2271439b4de939e7186b1c763787263132
[]
no_license
tcharding/self_learning
df911b018fc86bd5f918394b79d2456bf51f35a8
f6bb5c6f74092177aa1b71da2ce87ca1bfc5ef3c
refs/heads/master
2022-05-13T05:09:32.284093
2022-05-02T08:25:18
2022-05-02T08:25:18
41,029,057
13
2
null
null
null
null
UTF-8
Scheme
false
false
2,336
ss
grades.ss
;; Library example implementation ;; ;; spl page 86 (require rnrs) (library (grades) (export gpa->grade gpa distribution) (import (rnrs)) (define in-range? (lambda (x n y) (and (>= n x) (< n y)))) (define-syntax range-case (syntax-rules (- else) [(_ expr ((x - y) e1 e2 ...) ... [else ee1 ee2]) (let ([tmp expr]) (cond [(in-range? x tmp y) e1 e2 ...] ... [else ee1 ee2 ...]))] [(_ expr ((x - y e1 e2 ...) ...) (let ([tmp expr]) (cond [(in-range? x tmp y) e1 e2 ...] ...)))])) (define letter->number (lambda (x) (case x [(a) 4.0] [(b) 3.0] [(c) 2.0] [(d) 1.0] [(f) 0.0] [else (assertion-violation 'grade "invalid letter" x)]))) (define gpa->grade (lambda (x) (range-case x [(0.0 - 0.5) 'f] [(0.5 - 1.5) 'd] [(1.5 - 2.5) 'c] [(2.5 - 3.5) 'b] [else 'a]))) (define-syntax gpa (syntax-rules () [(_ g1 g2 ...) (let ([ls (map letter->number (rem* 'x '(g1 g2 ...)))]) (/ (apply + ls) (length ls)))])) (define rem* ; remove all occurences of atom from ls (lambda (atom ls) (cond ((null? ls) '()) ((eqv? atom (car ls)) (rem* atom (cdr ls))) (else (cons (car ls) (rem* atom (cdr ls))))))) (define-syntax distribution (syntax-rules () [(_ g1 g2 ...) (get-distribution (list g1 g2 ...))])) (define get-distribution (lambda (ls) (let f ([dist '((0 a) (0 b) (0 c) (0 d) (0 f))] [ls ls])) (cond ((null? ls) dist) (else (f (add-grade-to-dist (car ls) dist) (cdr ls)))))) (define add-grade-to-dist ; add grade to dist (list of pairs ((a 0) (b 2) ... (f 0)) (lambda (grade dist) (case grade [(a) (inc-grade (car dist))] [(b) (inc-grade (cadr dist))] [(c) (inc-grade (caddr dist))] [(d) (inc-grade (cadddr dist))] [(f) (inc-grade (cadddr (cdr dist)))] [else (assertion-violation 'grade "invalid letter" grade)]))) (define inc-grade (lambda (pair) (set-car! (cdr pair) (+ 1 (car (cdr pair)))))) (define grade-num (lambda (pair) (car (cdr pair)))) (define grade-let (lambda (pair) (car pair))) )
true
d4b8eac11b3f223385d6e033d5f69991277044ae
12c0e59d100e2eda39e5bef9b801ca65af93c82a
/exercise-2.02-2.03.scm
d1a5691e7d42edcb479a70563100c499ebf29120
[]
no_license
deiwin/sicp
f478039310ebccb8a786126250407d08128c5adb
83cc25f540fefc44273fc8d3bb0fd0d78f3708e5
refs/heads/master
2020-06-13T08:45:50.360224
2017-10-28T11:09:04
2017-10-28T11:22:11
75,431,135
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,680
scm
exercise-2.02-2.03.scm
(load "lib.scm") ; 2.2 (define (make-point x y) (cons x y)) (define (x-point p) (car p)) (define (y-point p) (cdr p)) (define (print-point p) (newline) (display "(") (display (x-point p)) (display ",") (display (y-point p)) (display ")")) (define (make-segment p1 p2) (cons p1 p2)) (define (start-segment s) (car s)) (define (end-segment s) (cdr s)) (define (midpoint-segment s) (let ((x (average (x-point (start-segment s)) (x-point (end-segment s)))) (y (average (y-point (start-segment s)) (y-point (end-segment s))))) (make-point x y))) ; 2.3 (define (length-segment s) (sqrt (+ (square (abs (- (x-point (start-segment s)) (x-point (end-segment s))))) (square (abs (- (y-point (start-segment s)) (y-point (end-segment s)))))))) (define (make-rect bottomm-side height) (cons bottomm-side height)) (define (height-rect r) (cdr r)) (define (width-rect r) (length-segment (car r))) (define (perimeter-rect r) (* 2 (+ (height-rect r) (width-rect r)))) (define (area-rect r) (* (height-rect r) (width-rect r))) (define (make-alt-rect left-side width) (cons left-side width)) ; Uncomment to make perimeter-rect and area-rect work with alt-rects ; (define (width-rect r) (cdr r)) ; (define (height-rect r) ; (length-segment (car r))) (define rect (make-rect (make-segment (make-point 0 0) (make-point 2 0)) 5)) (define alt-rect (make-alt-rect (make-segment (make-point 0 0) (make-point 0 5)) 2))
false
2e5450d33f9a9d6218f167c3704d1fad271c9aaf
495be054a7d58871a0a975ad90dcd3f9ad04ffe4
/ch3/racket-streams.scm
011330b92aac3a61212f8a4d7a33c2bc9623d463
[]
no_license
Galaxy21Yang/sicp
cd0b646aabc693f9bad46fac880ff2f50ac667ba
17990996ad4b8906ff3d27219d23033ca44753a0
refs/heads/master
2020-12-03T05:35:32.987780
2015-09-25T09:18:57
2015-09-25T09:18:57
43,195,037
13
5
null
2015-09-26T06:30:45
2015-09-26T06:30:45
null
UTF-8
Scheme
false
false
1,475
scm
racket-streams.scm
#lang racket #| - cons-stream : + stream-consが特殊形式のためマクロで再定義 - stream-car, stream-cdr, stream-null?, the-stream-empty : + SICPの名前に合わせて定義 - stream-map : + rakcet/stream版は引数に複数のストリームが取れないので ex 3.50から引用 - stream-ref, stream-filter, stream-append など : + racket/streamに含まれている手続きをそのまま流用 |# (require (prefix-in strm: racket/stream)) (define-syntax cons-stream (syntax-rules () ((_ a b) (strm:stream-cons a b)))) (define stream-car strm:stream-first) (define stream-cdr strm:stream-rest) (define stream-null? strm:stream-empty?) (define the-empty-stream strm:empty-stream) ;; form ex 3.50 (define (stream-map proc . argstreams) (if (stream-null? (car argstreams)) the-empty-stream (cons-stream (apply proc (map stream-car argstreams)) (apply stream-map (cons proc (map stream-cdr argstreams)))))) (define (list->stream sequence) (if (null? sequence) the-empty-stream (cons-stream (car sequence) (list->stream (cdr sequence))))) (define (scale-stream s factor) (stream-map (lambda (x) (* x factor)) s)) (define (add-streams s1 s2) (stream-map + s1 s2)) (define (mul-streams s1 s2) (stream-map * s1 s2)) (define (interleave s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) (provide (all-defined-out))
true
3d9d2ac2ac19b96702f16b8fbe80e3b20f5840bb
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/util/io.scm
05022f8712cf9c7933e6a1a9f1c34ec281372ebd
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
2,106
scm
io.scm
(define (read-fully port) (define (iter res) (let ((obj (read port))) (if (eof-object? obj) (reverse res) (iter (cons obj res))))) (iter '())) (define (read-file-fully filename) (call-with-input-file filename read-fully)) (define (println . args) (for-each display args) (newline)) (define (read-line port) (let loop ((s (make-string 4096)) (n 0) (char (read-char port))) (cond ((and (eof-object? char) (zero? n)) char) ((or (eof-object? char) (char=? char #\newline)) (substring s 0 n)) (else (if (>= n (string-length s)) (set! s (string-append s (make-string 4096)))) (if (char=? (integer->char #x0d) char) (loop s n (read-char port)) (begin (string-set! s n char) (loop s (+ n 1) (read-char port)))))))) (define (read-lines-fully port) (let loop ((top '()) (cur '()) (line (read-line port))) (if (eof-object? line) top (let ((cell (list line))) (if (null? cur) (loop cell cell (read-line port)) (begin (set-cdr! cur cell) (loop top cell (read-line port)))))))) (define (read-backslash-escaped-file-from-port port) (let loop ((l (list-builder)) (line (read-line port))) (cond ((eof-object? line) (list-finalize! l)) ((and (> (string-length line) 1) (char=? #\\ (string-ref line (- (string-length line) 1)))) (let ((next (read-line port)) (len (string-length line))) (if (eof-object? next) (begin (list-build! l (substring line 0 (- len 1))) (list-finalize! l)) (loop l (string-append (substring line 0 (- len 1)) next))))) (else (list-build! l line) (loop l (read-line port))))))
false
50020837f5d80894c0248f05a96145cf6b48ca80
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/system/data/odbc/odbc-parameter-converter.sls
84c943823b94417ecfb65c2f2623bb527a476ce9
[]
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
914
sls
odbc-parameter-converter.sls
(library (system data odbc odbc-parameter-converter) (export new is? odbc-parameter-converter? convert-to can-convert-to?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Data.Odbc.OdbcParameterConverter a ...))))) (define (is? a) (clr-is System.Data.Odbc.OdbcParameterConverter a)) (define (odbc-parameter-converter? a) (clr-is System.Data.Odbc.OdbcParameterConverter a)) (define-method-port convert-to System.Data.Odbc.OdbcParameterConverter ConvertTo (System.Object System.ComponentModel.ITypeDescriptorContext System.Globalization.CultureInfo System.Object System.Type)) (define-method-port can-convert-to? System.Data.Odbc.OdbcParameterConverter CanConvertTo (System.Boolean System.ComponentModel.ITypeDescriptorContext System.Type)))
true
875e35372f08fbdaeecaacf12bc1fc98e774b25f
b3f1b85ae1ce3bc09332b2a2c4f79b10aff2f82b
/C311GitTest/a10b.ss
69e67ae361376827da8aefd75f0f88b12e8c03a9
[]
no_license
KingLeper/PlayingWithGit
54a7d9a3abcc0c1fe51a07818f06ffec27213320
629f17bf4d9dba0b9ee707c22d54a47f02b2b324
refs/heads/master
2020-05-17T13:54:12.305323
2011-11-22T18:58:47
2011-11-22T18:58:47
2,829,761
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,992
ss
a10b.ss
;Alex Manus ;Assignment 10 Redux^4 (load "ParentheC.ss") (load "pc2c.ss") (define-union exp (const n) (var v) (if test conseq alt) (mult rand1 rand2) (sub1 rand) (zero rand) (letcc body) (throw rator rand) (lambda body) (app rator rand)) (define eval-expr (lambda (expr env k) (union-case expr exp [(const n) (k n)] [(var v) (apply-env env v k)] [(if test conseq alt) (eval-expr test env (lambda (x) (if x (eval-expr conseq env k) (eval-expr alt env k))))] [(mult rand1 rand2) (eval-expr rand1 env (lambda (x1) (eval-expr rand2 env (lambda (x2) (k (* x1 x2))))))] [(sub1 rand) (eval-expr rand env (lambda (x) (k (- x 1))))] [(zero rand) (eval-expr rand env (lambda (x) (k (zero? x))))] [(letcc body) (eval-expr body (envr_extend k env) k)] [(throw rator rand) (eval-expr rator env (lambda (v) (eval-expr rand env v)))] [(lambda body) (k (clos_closure body env))] [(app rator rand) (eval-expr rator env (lambda (v) (eval-expr rand env (lambda (w) (apply-proc v w k)))))]))) (define-union envr (empty) (extend arg env)) (define apply-env (lambda (env num k) (union-case env envr [(empty) (error 'pc "unbound variable")] [(extend arg env) (if (zero? num) (k arg) (apply-env env (sub1 num) k))]))) (define-union clos (closure code env)) (define apply-proc (lambda (c a k) (union-case c clos [(closure code env) (eval-expr code (envr_extend a env) k)]))) (define apply-k (lambda (k a) (k a))) (define empty-k (lambda () (lambda (v) v))) ; Factorial of 5...should be 120. (pretty-print (eval-expr (exp_app (exp_lambda (exp_app (exp_app (exp_var 0) (exp_var 0)) (exp_const 5))) (exp_lambda (exp_lambda (exp_if (exp_zero (exp_var 0)) (exp_const 1) (exp_mult (exp_var 0) (exp_app (exp_app (exp_var 1) (exp_var 1)) (exp_sub1 (exp_var 0)))))))) (envr_empty) (empty-k))) ; Test of letcc/throw...should evaluate to 12. (pretty-print (eval-expr (exp_letcc (exp_mult (exp_const 5) (exp_throw (exp_var 0) (exp_mult (exp_const 2) (exp_const 6))))) (envr_empty) (empty-k)))
false
e5b4dc5a188686c58ec0f664afba40818b11668b
26aaec3506b19559a353c3d316eb68f32f29458e
/modules/graph/examples/ex-loglog.scm
ee4acf7fbaaa6abdced74a9164db6462c1eb22f6
[ "BSD-3-Clause" ]
permissive
mdtsandman/lambdanative
f5dc42372bc8a37e4229556b55c9b605287270cd
584739cb50e7f1c944cb5253966c6d02cd718736
refs/heads/master
2022-12-18T06:24:29.877728
2020-09-20T18:47:22
2020-09-20T18:47:22
295,607,831
1
0
NOASSERTION
2020-09-15T03:48:04
2020-09-15T03:48:03
null
UTF-8
Scheme
false
false
2,272
scm
ex-loglog.scm
;; graph example (from cgraph) ;; the data to plot (define data '((1.95 2.39) (0.99 0.82) (1.21 1.39) (1.97 2.23) (2.25 2.23) (3.65 4.17) (2.84 2.85) (2.42 2.79) (1.34 0.78) (3.26 3.91) (1.67 2.49) (3.59 2.84) (2.65 2.85) (1.56 2.55) (1.58 0.95) (2.33 2.07) (1.02 1.63) (1.93 1.04) (1.32 2.75) (1.82 2.54) (1.2 1.68) (1.78 1.91) (1.4 1.55) (2.37 1.89) (3.91 3.26) (2.91 2.6) (1.32 1.25) (3.65 3.12) (4.19 3.71) (2.57 1.74) (3.35 1.99) (4.02 3.96) (4.32 5.13) (1.27 0.9) (2.5 2.59) (4.21 4.81) (3.12 3.12) (4.17 4.69) (2.6 2.67) (1.56 2.08) (2.6 2.22) (2.71 2.44) (1.8 1.56) (2.61 0.78) (1.39 1.11) (1.94 2.25) (1.85 1.75) (0.56 0.99) (1.04 1.56) (2.08 3.12) (2.11 3.16) (3.12 3.04) (2.6 1.56) (2.35 2.48) (3.11 2.74) (1.56 1.56) (2 2.13) (1.9 1.92) (4.56 4.56) (2.36 2.81) (2.84 2.84) (3.55 4.26) (1.11 1.56) (6.61 6.61) (2.14 2.94))) (define g (graph-new 330 290)) ;; set the font (graph-font g "Helvetica" 12) ;; set the origin (graph-aorigin g 1.1 0.75) ;; set the style of the log axis (graph-logstyle g #xb #x7ff 4 3 4 8) ;; initialize the log axis (graph-xlog g 3.0 0.5 10. 0.0) (graph-ylog g 3. 0.5 10. 0.0) ;; draw a domain mesh (graph-color g Grey) (graph-mesh g) ;; draw some lines (graph-color g Red) (graph-linewidth g 0.6) ;; a solid diagonal line (graph-moveto g 0.5 0.5) (graph-lineto g 10. 10.) (graph-stroke g) ;; dashed lines (graph-dash g 6 0.1364) (define vLmin 0.5) (define vLmax 10.0) (define vRmin 0.5) (define vRmax 10.0) (define ratio 1.5) (graph-moveto g (* vLmin ratio) vRmin) (graph-lineto g vLmax (/ vRmax ratio)) (graph-moveto g vLmin (* vRmin ratio)) (graph-lineto g (/ vLmax ratio) vRmax) (graph-stroke g) (graph-dash g 0 1.0) (graph-linewidth g 1.0) ;; plot markers here (let loop ((d data)) (if (> (length d) 0) (begin (graph-color g White) (graph-marker g (car (car d)) (cadr (car d)) GRAPH_SOLIDTRIANGLE 10) (graph-color g Black) (graph-marker g (car (car d)) (cadr (car d)) GRAPH_OPENTRIANGLE 10) (loop (cdr d))))) ;; draw an axis frame (graph-frame g) ;; draw the x and y axis (graph-xaxis g) (graph-yaxis g) ;; draw the axis labels (graph-xlabel g "The X axis label") (graph-ylabel g "The Y axis label") (graph-output g 'GRAPH_PDF "ex-loglog.pdf") (graph-output g 'GRAPH_SVG "ex-loglog.svg")
false
313a69dc37c94837101c6cb8e4b1c62838c18050
943e73b33b7bc61fee44808cbd18f91c7ed1db7a
/csi.import.scm
7f18730014e7d52b53641611fbb5989f3fa8f476
[ "BSD-3-Clause" ]
permissive
opt9/chicken-scheme
a631d3fb455c61312e0c9d30d791c78a6d99a7f6
1eb14684c26b7c2250ca9b944c6b671cb62cafbc
refs/heads/master
2020-03-09T15:41:06.499607
2009-07-25T23:49:53
2009-07-25T23:49:53
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,668
scm
csi.import.scm
;;;; csi.import.scm - import library for "csi" module ; ; Copyright (c) 2008-2009, The Chicken Team ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following ; conditions are met: ; ; Redistributions of source code must retain the above copyright notice, this list of conditions and the following ; disclaimer. ; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following ; disclaimer in the documentation and/or other materials provided with the distribution. ; Neither the name of the author nor the names of its contributors may be used to endorse or promote ; products derived from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS ; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY ; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR ; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ; POSSIBILITY OF SUCH DAMAGE. (##sys#register-primitive-module 'csi '(toplevel-command set-describer!))
false
7844ecb0bf68ceffd7a17c369d90e2a8b0c28d7b
19292e8363b55af987be106ea2d85752f8516ffc
/contrib/s9e.scm
6690cb795ef8c5c683294773eb19e8050033a4b1
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
ktp-forked-repos/S9fES
df3bd76be1869cabb259c2a843fc93a8fd3bc553
0ade11593cf35f112e197026886fc819042058dd
refs/heads/master
2021-12-09T06:05:54.381647
2014-01-11T11:31:37
2014-01-11T11:31:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
85,272
scm
s9e.scm
; S9E is the Scheme 9 Editor ; by Nils M Holm, 2012 ; Placed in the Public Domain ; ; (s9e string <option> ...) ==> unspecific ; (s9e) ==> unspecific ; ; The S9E procedure implements a Scheme-centric full screen text editor. ; If specified, it loads the file STRING into an editing buffer. ; ; When the 'READ-ONLY option is passed to S9E, the initial buffer will ; be read-only. ; ; (Example): (s9e "foo.scm") ; ; Todo: ; warn about expanded tabs ; CR/LF mode (require-extension sys-unix curses) (load-from-library "syntax-rules.scm") (load-from-library "define-structure.scm") (load-from-library "pretty-print.scm") (load-from-library "read-line.scm") (load-from-library "read-file.scm") (load-from-library "get-line.scm") (load-from-library "hof.scm") (load-from-library "setters.scm") (load-from-library "letcc.scm") (load-from-library "and-letstar.scm") (load-from-library "format.scm") (load-from-library "adjoin.scm") (load-from-library "remove.scm") (load-from-library "mergesort.scm") (load-from-library "string-expand.scm") (load-from-library "string-split.scm") (load-from-library "string-unsplit.scm") (load-from-library "string-position.scm") (load-from-library "string-last-position.scm") (load-from-library "string-prefixeqp.scm") (load-from-library "string-parse.scm") (load-from-library "get-prop.scm") (load-from-library "search-path.scm") (load-from-library "spawn-command.scm") (load-from-library "spawn-shell-command.scm") (load-from-library "flush-output-port.scm") ; ----- curses abstraction layer ----- (define addch curs:addch) (define addstr curs:addstr) (define attrset curs:attrset) (define beep curs:beep) (define cbreak curs:cbreak) (define clear curs:clear) (define clrtoeol curs:clrtoeol) (define cols curs:cols) (define deleteln curs:deleteln) (define echo curs:echo) (define endwin curs:endwin) (define flash curs:flash) (define getch curs:getch) (define color? curs:has-colors) (define idlok curs:idlok) (define initscr curs:initscr) (define insertln curs:insertln) (define keypad curs:keypad) (define lines curs:lines) (define move curs:move) (define mvaddstr curs:mvaddstr) (define nl curs:nl) (define noecho curs:noecho) (define nodelay curs:nodelay) (define nonl curs:nonl) (define noraw curs:noraw) (define raw curs:raw) (define refresh curs:refresh) (define scrollok curs:scrollok) (define setcolor curs:color-set) (define standend curs:standend) (define standout curs:standout) (define unctrl curs:unctrl) (define ungetch curs:ungetch) (define *black* curs:color-black) (define *blue* curs:color-blue) (define *green* curs:color-green) (define *cyan* curs:color-cyan) (define *red* curs:color-red) (define *magenta* curs:color-magenta) (define *yellow* curs:color-yellow) (define *gray* curs:color-gray) (define *attr-standout* curs:attr-standout) (define *attr-bold* curs:attr-bold) (define *attr-normal* curs:attr-normal) (define *key-up* curs:key-up) (define *key-down* curs:key-down) (define *key-left* curs:key-left) (define *key-right* curs:key-right) (define *key-ppage* curs:key-ppage) (define *key-npage* curs:key-npage) (define *key-home* curs:key-home) (define *key-end* curs:key-end) (define *key-backspace* curs:key-backspace) (define *key-delete* curs:key-dc) (define *key-insert* curs:key-ic) (define (key-pressed?) (nodelay #t) (let ((k (getch))) (nodelay #f) (if k (ungetch k)) (number? k))) ; ----- system abstraction layer ----- (define catch-errors sys:catch-errors) (define chmod sys:chmod) (define directory? sys:stat-directory?) (define make-output-port sys:make-output-port) (define fd-close sys:close) (define fd-creat sys:creat) (define fd-read sys:read) (define fd-select sys:select) (define errno sys:errno) (define errno->string sys:strerror) (define exit sys:exit) (define getcwd sys:getcwd) (define getenv sys:getenv) (define getpid sys:getpid) (define read-directory sys:readdir) (define remove-file sys:unlink) (define rename-file sys:rename) (define run-shell-command sys:system) (define send-signal sys:notify) (define stat-file sys:stat) (define stat-get-mode (compose cdr (curry assq 'mode))) (define unix-time sys:time) (define wait-for-process sys:wait) (define (file-exists? path) (sys:access path sys:access-f-ok)) (define (file-readable? path) (sys:access path sys:access-r-ok)) (define (file-writable? path) (sys:access path sys:access-w-ok)) ; ----- globals ----- (define *buffers* (list)) (define *yanked* #f) (define *switch-to* #f) (define *chunk-size* 1000) (define *offset-jump* 8) (define *spaces* "") (define *dashes* "") (define *message* #f) (define *repl* #f) (define *symbols* '()) (define *undo-mark* #f) (define (^ c) (integer->char (- (char->integer c) (char->integer #\@)))) (define ^A (^ #\A)) (define ^B (^ #\B)) (define ^C (^ #\C)) (define ^D (^ #\D)) (define ^E (^ #\E)) (define ^F (^ #\F)) (define ^G (^ #\G)) (define ^H (^ #\H)) (define ^I (^ #\I)) (define ^J (^ #\J)) (define ^K (^ #\K)) (define ^L (^ #\L)) (define ^M (^ #\M)) (define ^N (^ #\N)) (define ^O (^ #\O)) (define ^P (^ #\P)) (define ^Q (^ #\Q)) (define ^R (^ #\R)) (define ^S (^ #\S)) (define ^T (^ #\T)) (define ^U (^ #\U)) (define ^V (^ #\V)) (define ^W (^ #\W)) (define ^X (^ #\X)) (define ^Y (^ #\Y)) (define ^Z (^ #\Z)) (define LP #\() (define RP #\)) (define LB #\[) (define RB #\]) (define *properties* '(("ai" auto-indent global #t) ("al" auto-load local #F) ("ct" color-text global "gray/blue") ("cr" color-region global "gray/red") ("cs" color-status global "blue/cyan") ("ci" color-info global "gray/green") ("ce" color-error global "black/yellow") ("cp" color-paren global "blue/yellow") ("eb" error-bell global #t) ("hr" help-reminder global #t) ("lt" load-timeout global 10) ("ro" read-only local #F) ("rc" repl-command global "s9 -q") ("ri" repl-init global "") ("rt" repl-timeout global 5) ("sc" sense-case global #F) ("sm" show-match global #t) ("" scheme-repl internal #F) ("" transient internal #F))) (define prop-abbr car) (define prop-prop cadr) (define prop-scope caddr) (define prop-default cadddr) (define *globals* (list)) (define (property x) (get-prop *globals* x)) ; ----- editing buffer structure ----- (define-structure buffer (name #f) (properties (list)) (length 1) (y 0) (x 0) (col 0) (top 0) (off 0) (mark #f) (reg0 #f) (regn #f) (searchstr "") (undo '()) (redo '()) (last-char #f) (buf (make-vector *chunk-size* ""))) (define (reset-undo! buf) (buffer-set-undo! buf '()) (buffer-set-redo! buf '())) (define (buf-line buf pos) (if (>= pos (buffer-length buf)) "" (vector-ref (buffer-buf buf) pos))) (define (buf-cur-line buf) (buf-line buf (buffer-y buf))) (define (buf-cur-length buf) (string-length (buf-cur-line buf))) (define (buf-cur-char buf) (if (>= (buffer-x buf) (buf-cur-length buf)) #f (string-ref (buf-cur-line buf) (buffer-x buf)))) (define (buf-prop? buf p) (get-prop (buffer-properties buf) p)) (define (buf-set-prop! buf p) (buffer-set-properties! buf (put-prop (buffer-properties buf) p #t))) (define (buf-rem-prop! buf p) (buffer-set-properties! buf (rem-prop (buffer-properties buf) p))) (define (modified! buf) (buf-set-prop! buf 'modified)) (define (modified? buf) (and (buf-prop? buf 'modified) (not (buf-prop? buf 'scheme-repl)))) (define (read-only? buf) (buf-prop? buf 'read-only)) (define (end-of-buf? buf) (and (>= (buffer-y buf) (- (buffer-length buf) 1)) (not (buf-cur-char buf)))) (define (top-of-buf? buf) (and (zero? (buffer-y buf)) (zero? (buffer-x buf)))) (define (sync-mark buf) (if (not (buffer-mark buf)) (buffer-set-regn! buf (list (buffer-x buf) (buffer-y buf))))) ; ----- buffer management ----- (define (fresh-buffer props) (let ((b (make-buffer #f '()))) (for-each (curry buf-set-prop! b) props) (set! *buffers* (append *buffers* (list b))) b)) (define (delete-buffer buf) (set! *buffers* (remq buf *buffers*))) (define (nth-buffer n) (do ((n n (- n 1)) (b *buffers* (cdr b))) ((zero? n) (car b)))) (define (this-buffer buf) (let find ((b *buffers*)) (cond ((null? b) #f) ((eq? buf (car b)) b) (else (find (cdr b)))))) (define (find-buffer tag . create) (let find ((b *buffers*)) (cond ((null? b) (if (null? create) #f (fresh-buffer (list tag)))) ((buf-prop? (car b) tag) (car b)) (else (find (cdr b)))))) (define (modified-buffers) (do ((n 0 (if (modified? (car b)) (+ 1 n) n)) (b *buffers* (cdr b))) ((null? b) n))) ; ----- buffer I/O ----- (define (change-line! buf pos line) (if (>= pos (vector-length (buffer-buf buf))) (let ((newsize (* *chunk-size* (+ 1 (quotient pos *chunk-size*))))) (let ((new (make-vector newsize "")) (old (buffer-buf buf)) (len (vector-length (buffer-buf buf)))) (do ((i 0 (+ 1 i))) ((>= i len)) (vector-set! new i (vector-ref old i))) (buffer-set-buf! buf new)))) (if (>= pos (buffer-length buf)) (buffer-set-length! buf (+ 1 pos))) (vector-set! (buffer-buf buf) pos line)) (define (clear-buffer buf) (change-line! buf 0 "") (buffer-set-length! buf 1) (let ((al (buf-prop? buf 'auto-load))) (buffer-set-properties! buf '()) (if al (buf-set-prop! buf 'auto-load))) (move-to buf 0 0 0)) (define (load-buffer buf path . silent) (buffer-set-name! buf path) (if (not (file-readable? path)) (err "new file: ~A" path) (with-input-from-file path (lambda () (reset-undo! buf) (let load ((line (read-line)) (pos 0)) (cond ((eof-object? line) (go-to buf 0 0 0) (set! *message* #f) (if (null? silent) (begin (if (not (file-writable? path)) (begin (buf-set-prop! buf 'read-only) (err "file is read-only")) (status-line buf)) (show-buffer buf)))) (else (let ((line (string-expand line))) (if (zero? (remainder pos 100)) (info "~D lines loaded" pos)) (change-line! buf pos line) (load (read-line) (+ 1 pos)))))))))) (define (save-buffer buf path . range) (catch-errors #t) (let* ((tmpname (string-append path "." (number->string (getpid)) ".tmp"))) (if (file-exists? tmpname) (remove-file tmpname)) (if (not (let ((fd (fd-creat tmpname))) (if fd (fd-close fd)) fd)) (begin (err (format #f "could not create file: ~A" (errno->string (errno)))) (catch-errors #f) #f) (let* ((reg0 (if (null? range) (list 0 0) (car range))) (regn (if (null? range) (list 0 (buffer-length buf)) (cadr range))) (pos0 (car reg0)) (posn (car regn)) (from (cadr reg0)) (to (cadr regn))) (remove-file tmpname) (with-output-to-file tmpname (lambda () (do ((i from (+ 1 i))) ((> i to)) (if (zero? (remainder i 100)) (info (format #f "~D lines written" i))) (cond ((= i from) (let* ((s (buf-line buf i)) (k (string-length s))) (display (substring s pos0 k)))) ((= i to) (display (substring (buf-line buf i) 0 posn))) (else (display (buf-line buf i)))) (if (not (= i to)) (newline))))) (let ((mode (cond ((stat-file path) => stat-get-mode) (else (errno) #f)))) (if (file-exists? path) (remove-file path)) (rename-file tmpname path) (if mode (chmod path mode)) (catch-errors #f) (let ((e (errno))) (cond ((not (zero? e)) (err (format #f "error writing file: ~A" (errno->string e))) #f) (else (info (format #f "~D lines written" (if (zero? posn) (- to from) (+ 1 (- to from))))) #t)))))))) ; ----- utilities ----- (define (string-cut s k) (if (> k (string-length s)) s (substring s 0 k))) (define (string-trim s k) (let ((n (string-length s))) (if (> k n) s (substring s (- n k) n)))) (define (string-skip-white s) (let ((k (string-length s))) (do ((i 0 (+ 1 i))) ((or (>= i k) (not (char=? #\space (string-ref s i)))) (substring s i k))))) (define (last x) (car (reverse x))) (define (indentation s) (let ((k (string-length s))) (do ((i 0 (+ 1 i))) ((or (>= i k) (not (char=? #\space (string-ref s i)))) i)))) ; ----- buffer display ----- (define (uncontrol k) (integer->char (+ (char->integer k) (char->integer #\@)))) (define (visual-char k) (let ((n (char->integer k))) (cond ((< n 32) (format #f "^~C" (uncontrol k))) ((= n 127) "^?") (else (string k))))) (define (screen-top) 0) (define (screen-bottom) (if (color?) (- (lines) 1) (- (lines) 2))) (define (statline-pos) (if (color?) (screen-bottom) (+ (screen-bottom) 1))) (define (screen-lines) (- (screen-bottom) (screen-top))) (define (on-screen? buf x y) (and (<= (buffer-off buf) x (+ (buffer-off buf) (cols) -1)) (<= (buffer-top buf) y (+ (buffer-top buf) (screen-lines) -1)))) (define (set-color fg/bg alt) (if (color?) (apply setcolor fg/bg) (attrset alt))) (define *color-text* (list *gray* *blue*)) (define *color-region* (list *gray* *red*)) (define *color-status* (list *blue* *cyan*)) (define *color-info* (list *gray* *green*)) (define *color-error* (list *black* *yellow*)) (define *color-paren* (list *blue* *yellow*)) (define (color-text) (set-color *color-text* *attr-normal*)) (define (color-region) (set-color *color-region* *attr-standout*)) (define (color-status) (set-color *color-status* *attr-normal*)) (define (color-info) (set-color *color-info* *attr-normal*)) (define (color-error) (set-color *color-error* *attr-bold*)) (define (color-paren) (set-color *color-paren* *attr-bold*)) (define-syntax update-color! (syntax-rules () ((_ cvar prop) (set! cvar (parse-color cvar (property 'prop)))))) (define (update-colors) (update-color! *color-text* color-text) (update-color! *color-region* color-region) (update-color! *color-status* color-status) (update-color! *color-info* color-info) (update-color! *color-error* color-error) (update-color! *color-paren* color-paren)) (define (before x y dx dy) (or (< y dy) (and (= y dy) (< x dx)))) (define (region buf) (and-let* ((r0 (buffer-reg0 buf)) (rn (buffer-regn buf)) (x0 (car r0)) (y0 (cadr r0)) (xn (car rn)) (yn (cadr rn))) (if (before x0 y0 xn yn) `((,x0 ,y0) (,xn ,yn)) `((,xn ,yn) (,x0 ,y0))))) (define (region? buf) (and (region buf) #t)) (define (region-start buf) (and-let* ((r (region buf))) (car r))) (define (region-end buf) (and-let* ((r (region buf))) (cadr r))) (define (in-region? buf x y) (and-let* ((r (region buf)) (r0 (car r)) (rn (cadr r)) (x0 (car r0)) (y0 (cadr r0)) (xn (car rn)) (yn (cadr rn))) (and (not (before x y x0 y0)) (not (before xn yn x y))))) (define (region-break? buf y) (and-let* ((r0 (buffer-reg0 buf)) (rn (buffer-regn buf))) (or (= y (cadr r0)) (= y (cadr rn))))) (define (show-region-break buf line pos len) (let* ((rs (region-start buf)) (re (region-end buf)) (b0 (if (= pos (cadr rs)) (if (< (car rs) (buffer-off buf)) (buffer-off buf) (car rs)) 0)) (bn (if (= pos (cadr re)) (car re) (+ 1 len)))) (let loop ((chars (string->list line)) (i (buffer-off buf))) (if (= i b0) (color-region)) (if (= i bn) (color-text)) (if (null? chars) (begin (addstr (substring *spaces* (string-length line) (cols))) (color-text)) (begin (addch (car chars)) (loop (cdr chars) (+ 1 i))))))) (define (show-line buf pos y) (let* ((line (buf-line buf pos)) (k (string-length line)) (line (if (< k (buffer-off buf)) "" (substring line (buffer-off buf) k))) (line (string-cut line (cols)))) (cond ((region-break? buf pos) (move y 0) (show-region-break buf line pos k)) (else (if (in-region? buf 0 pos) (color-region)) (mvaddstr y 0 line) (addstr (substring *spaces* (string-length line) (cols))) (color-text))))) (define (show-cur-line buf) (color-text) (show-line buf (buffer-y buf) (+ (- (buffer-y buf) (buffer-top buf)) (screen-top)))) (define (show-buffer buf) (color-text) (let show ((pos (buffer-top buf)) (y (screen-top))) (if (< y (screen-bottom)) (begin (show-line buf pos y) (show (+ 1 pos) (+ 1 y)))))) (define (go-to buf x y . offset) (let ((offset (if (null? offset) (quotient (screen-lines) 3) (car offset)))) (if (not (on-screen? buf x y)) (let ((top (max 0 (- y offset))) (off (max 0 (if (< x (cols)) 0 (- x *offset-jump*))))) (buffer-set-top! buf top) (buffer-set-off! buf off))) (buffer-set-x! buf x) (buffer-set-y! buf y))) (define (move-to buf x y . offset) (apply go-to buf x y offset) (update-col buf) (show-buffer buf)) (define (menu-dashes) (if (not (color?)) (mvaddstr (screen-bottom) 0 *dashes*))) (define (status-line buf) (color-status) (menu-dashes) (let* ((p (buffer-name buf)) (p (if p p "")) (k (- (cols) 30)) (s (format #f " ~C~C~C~C L:~D/~D C:~D [~A~A]~A" (if (buf-prop? buf 'auto-load) #\a #\.) (if (region? buf) #\R #\.) (if (modified? buf) #\m #\.) (if (read-only? buf) #\r #\.) (+ 1 (buffer-y buf)) (buffer-length buf) (+ 1 (buffer-x buf)) (if (> (string-length p) k) "<" "") (string-trim p k) (if (or (not (property 'help-reminder)) (buf-prop? buf 'transient)) "" " ^L = command")))) (mvaddstr (statline-pos) 0 *spaces*) (mvaddstr (statline-pos) 0 s) (set! *message* #f))) (define (message . args) (let* ((msg (apply format #f args)) (msg (string-cut msg (- (cols) 1)))) (mvaddstr (statline-pos) 0 *spaces*) (mvaddstr (statline-pos) 0 msg) (set! *message* msg) (refresh))) (define (bell) (if (property 'error-bell) (beep))) (define (err . args) (color-error) (if *message* (begin (mvaddstr (statline-pos) (+ 1 (string-length *message*)) "-- more") (getch))) (apply message args) (bell)) (define (info . args) (color-info) (apply message args)) ; ----- keyboard input ----- (define (sync-pos buf) (move (- (buffer-y buf) (buffer-top buf)) (- (buffer-x buf) (buffer-off buf)))) (define (get-key buf) (sync-pos buf) (let ((k (getch))) (if *message* (status-line buf)) (set! *message* #f) (cond ((= k *key-home*) ^A) ((= k *key-end*) ^E) ((= k *key-left*) ^B) ((= k *key-right*) ^F) ((= k *key-up*) ^P) ((= k *key-down*) ^N) ((= k *key-ppage*) ^T) ((= k *key-npage*) ^V) ((= k *key-delete*) ^D) ((= k *key-backspace*) ^H) ((= k *key-insert*) ^Y) ((<= 0 k 127) (integer->char k)) (else (err "unknown key code: <~D>" k) #f)))) ; ----- motion commands ----- (define (update-col buf) (buffer-set-col! buf (buffer-x buf))) (define (reset-col buf) (if (<= (buffer-col buf) (buf-cur-length buf)) (buffer-set-x! buf (buffer-col buf)) (buffer-set-x! buf (buf-cur-length buf)))) (define (move-to-pos0 buf) (buffer-set-x! buf 0) (update-col buf)) (define (move-to-eol buf) (buffer-set-x! buf (buf-cur-length buf)) (update-col buf)) (define (move-forward buf) (let ((max (buf-cur-length buf))) (if (< (buffer-x buf) max) (buffer-set-x! buf (+ 1 (buffer-x buf))) (if (< (buffer-y buf) (- (buffer-length buf) 1)) (begin (buffer-set-x! buf 0) (buffer-set-y! buf (+ 1 (buffer-y buf)))) (bell))) (update-col buf))) (define (move-backward buf) (if (positive? (buffer-x buf)) (buffer-set-x! buf (- (buffer-x buf) 1)) (if (positive? (buffer-y buf)) (begin (buffer-set-y! buf (- (buffer-y buf) 1)) (move-to-eol buf)) (bell))) (update-col buf)) (define (move-down buf) (if (< (buffer-y buf) (- (buffer-length buf) 1)) (buffer-set-y! buf (+ 1 (buffer-y buf)))) (reset-col buf)) (define (move-up buf) (if (positive? (buffer-y buf)) (buffer-set-y! buf (- (buffer-y buf) 1))) (reset-col buf)) (define (move-next-word buf) (let* ((word? (compose not char-whitespace?)) (ch (if (buf-cur-char buf) (buf-cur-char buf) #\space)) (skip? (cond ((word? ch) word?) ((char-whitespace? ch) (const #f)) (else (compose not word?))))) (if (end-of-buf? buf) (bell) (let loop ((ch (buf-cur-char buf))) (cond ((not ch) (if (not (end-of-buf? buf)) (begin (move-forward buf) (loop #\space)))) ((skip? ch) (move-forward buf) (loop (buf-cur-char buf))) (else (let loop ((ch (buf-cur-char buf))) (cond ((not ch) (if (not (end-of-buf? buf)) (begin (move-forward buf) (loop (buf-cur-char buf))))) ((char-whitespace? ch) (move-forward buf) (loop (buf-cur-char buf))))))))) (update-col buf))) (define (move-prev-word buf) (let ((word? (compose not char-whitespace?))) (move-backward buf) (let loop ((ch (buf-cur-char buf))) (cond ((not ch) (if (top-of-buf? buf) (bell) (begin (move-backward buf) (loop #\space)))) ((char-whitespace? ch) (move-backward buf) (loop (buf-cur-char buf))) (else (let ((skip? (if (word? ch) word? (compose not char-whitespace?)))) (let loop ((ch (buf-cur-char buf))) (cond ((and ch (not (top-of-buf? buf)) (skip? ch)) (move-backward buf) (loop (buf-cur-char buf))) (else (if (not (top-of-buf? buf)) (move-forward buf)))))))))) (update-col buf)) (define (move-next-page buf) (if (>= (+ (buffer-y buf) (screen-lines) -1) (buffer-length buf)) (buffer-set-y! buf (- (buffer-length buf) 1)) (buffer-set-y! buf (+ (buffer-y buf) (screen-lines) -1))) (if (not (negative? (- (buffer-y buf) (- (screen-lines) 1)))) (buffer-set-top! buf (- (buffer-y buf) (- (screen-lines) 1))) (buffer-set-top! buf 0)) (reset-col buf) (show-buffer buf)) (define (move-prev-page buf) (if (negative? (- (buffer-y buf) (screen-lines) -1)) (buffer-set-y! buf 0) (buffer-set-y! buf (- (buffer-y buf) (screen-lines) -1))) (buffer-set-top! buf (buffer-y buf)) (reset-col buf) (show-buffer buf)) (define (move-to-eof buf) (move-to buf 0 (- (buffer-length buf) 1) (screen-lines))) (define (move-to-line buf) (color-info) (let* ((ln (get-line (statline-pos) 0 "" "line: ")) (ln (if ln (string->number ln) #f))) (cond ((not ln)) ((not (<= 1 ln (buffer-length buf))) (err "no such line: ~D" ln)) (else (move-to buf 0 (- ln 1))))) (if (not *message*) (status-line buf))) (define (simple-motion-command buf k) (cond ((char=? k ^A) (move-to-pos0 buf) #t) ((char=? k ^B) (move-backward buf) #t) ((char=? k ^E) (move-to-eol buf) #t) ((char=? k ^F) (move-forward buf) #t) ((char=? k ^N) (move-down buf) #t) ((char=? k ^P) (move-up buf) #t) ((char=? k ^T) (move-prev-page buf) #t) ((char=? k ^V) (move-next-page buf) #t) ((char=? k ^W) (move-next-word buf) #t) ((char=? k ^X) (move-prev-word buf) #t) (else #f))) (define (motion-command buf k) (if (char=? k ^L) (begin (info " ^L Top Bottom Goto Locate Next") (l-motion-command buf (get-key buf))) (simple-motion-command buf k))) (define (save-pos buf) (list (buffer-x buf) (buffer-y buf) (buffer-top buf))) (define (reset-pos buf pos) (buffer-set-x! buf (car pos)) (buffer-set-y! buf (cadr pos)) (buffer-set-top! buf (caddr pos))) (define (restore-pos buf pos) (reset-pos buf pos) (update-col buf) (show-buffer buf)) ; ----- mark commands ----- (define (raise-mark buf) (buffer-set-mark! buf #f) (buffer-set-reg0! buf (list (buffer-x buf) (buffer-y buf)))) (define (finish-mark buf) (buffer-set-mark! buf #t)) (define (drop-mark buf) (let ((redraw (buffer-reg0 buf))) (buffer-set-mark! buf #f) (buffer-set-reg0! buf #f) (if redraw (show-buffer buf)))) (define (toggle-mark buf) (cond ((not (buffer-reg0 buf)) (raise-mark buf)) ((not (buffer-mark buf)) (finish-mark buf)) (else (drop-mark buf) (show-buffer buf)))) (define (match-left buf on-scr intr) (let match-left ((k (buf-cur-char buf)) (n 0)) (cond ((and intr (key-pressed?)) #f) ((and on-scr (not (on-screen? buf (buffer-x buf) (buffer-y buf)))) #f) ((not k) (if (top-of-buf? buf) #f (begin (move-backward buf) (match-left (buf-cur-char buf) n)))) ((or (char=? k RP) (char=? k RB)) (move-backward buf) (match-left (buf-cur-char buf) (+ 1 n))) ((or (char=? k LP) (char=? k LB)) (cond ((zero? n) (list (buffer-x buf) (buffer-y buf))) (else (move-backward buf) (match-left (buf-cur-char buf) (- n 1))))) ((top-of-buf? buf) #f) (else (move-backward buf) (match-left (buf-cur-char buf) n))))) (define (match-right buf on-scr intr) (move-forward buf) (let match-right ((k (buf-cur-char buf)) (n 0)) (cond ((and intr (key-pressed?)) #f) ((and on-scr (not (on-screen? buf (buffer-x buf) (buffer-y buf)))) #f) ((end-of-buf? buf) #f) ((not k) (move-forward buf) (match-right (buf-cur-char buf) n)) ((or (char=? k LP) (char=? k LB)) (move-forward buf) (match-right (buf-cur-char buf) (+ 1 n))) ((or (char=? k RP) (char=? k RB)) (cond ((zero? n) (if (not on-scr) (move-forward buf)) (list (buffer-x buf) (buffer-y buf))) (else (move-forward buf) (match-right (buf-cur-char buf) (- n 1))))) (else (move-forward buf) (match-right (buf-cur-char buf) n))))) (define (mark-expr buf) (let* ((here (save-pos buf)) (k (buf-cur-char buf)) (left (begin (if (and k (or (char=? k RP) (char=? k RB))) (move-backward buf)) (match-left buf #f #f))) (right (if left (match-right buf #f #f) #f))) (restore-pos buf here) (if right (begin (buffer-set-reg0! buf left) (buffer-set-regn! buf right) (buffer-set-mark! buf #t) (show-buffer buf))))) ; ----- undo/redo stack ----- (define (log-undo buf what args) (if (and (not (null? (buffer-undo buf))) (eq? (buffer-last-char buf) (buffer-undo buf))) (buffer-set-last-char buf #f)) (buffer-set-redo! buf '()) (buffer-set-undo! buf (cons (list what args) (buffer-undo buf)))) (define (uncut buf r0 rn lines) (apply move-to buf r0) (splice-region #f buf (car r0) (cadr r0) lines)) (define (unsplice buf x y lines) (move-to buf x y) (let ((r0 (list x y)) (rn (list (if (null? (cdr lines)) (+ x (string-length (car lines))) (string-length (last lines))) (+ y (- (length lines) 1))))) (cut-region #f buf r0 rn))) (define (recut buf r0 rn lines) (apply move-to buf r0) (cut-region #f buf r0 rn)) (define (resplice buf x y lines) (move-to buf x y) (splice-region #f buf x y lines)) (define (shift-to-redo buf) (buffer-set-redo! buf (cons (car (buffer-undo buf)) (buffer-redo buf))) (buffer-set-undo! buf (cdr (buffer-undo buf)))) (define (shift-to-undo buf) (buffer-set-undo! buf (cons (car (buffer-redo buf)) (buffer-undo buf))) (buffer-set-redo! buf (cdr (buffer-redo buf)))) (define (undo buf u) (cond ((eq? 'cut (car u)) (apply uncut buf (cadr u))) ((eq? 'splice (car u)) (apply unsplice buf (cadr u))) ((eq? 'group (car u)) (for-each (curry undo buf) (cadr u))))) (define (undo-cmd buf) (let ((u (buffer-undo buf))) (if (null? u) (err "nothing to undo") (begin (undo buf (car u)) (modified! buf) (shift-to-redo buf) (update-col buf) (show-buffer buf))))) (define (redo buf r) (cond ((null? r) (err "nothing to redo")) ((eq? 'cut (car r)) (apply recut buf (cadr r))) ((eq? 'splice (car r)) (apply resplice buf (cadr r))) ((eq? 'group (car r)) (for-each (curry redo buf) (reverse (cadr r)))))) (define (redo-cmd buf) (let ((r (buffer-redo buf))) (if (null? r) (err "nothing to redo") (begin (redo buf (car r)) (modified! buf) (shift-to-undo buf) (update-col buf) (show-buffer buf))))) (define (begin-undo-group buf) (set! *undo-mark* (buffer-undo buf))) (define (end-undo-group buf) (let loop ((b (buffer-undo buf)) (g '())) (cond ((eq? b *undo-mark*) (buffer-set-undo! buf *undo-mark*) (log-undo buf 'group (reverse! g))) (else (loop (cdr b) (cons (car b) g)))))) ; ----- yank/delete/insert commands ----- (define (writable? buf) (if (read-only? buf) (begin (err "buffer is read-only") #f) #t)) (define-syntax if-writable (syntax-rules () ((_ buf body ...) (if (writable? buf) (begin body ...))))) (define (copy-region buf r0 rn) (let ((res '())) (let yank-line ((y (cadr r0)) (r '())) (let* ((line (buf-line buf y)) (k (string-length line))) (cond ((= y (cadr r0) (cadr rn)) (set! res (cons (substring line (car r0) (car rn)) r))) ((= y (cadr r0)) (yank-line (+ 1 y) (cons (substring line (car r0) k) r))) ((= y (cadr rn)) (set! res (cons (substring line 0 (car rn)) r))) (else (yank-line (+ 1 y) (cons line r)))))) (reverse! res))) (define (yank-region buf) (set! *yanked* (apply copy-region buf (region buf))) (buffer-set-mark! buf #t)) ; slow version without VECTOR-COPY and VECTOR-APPEND (define (delete-lines buf y0 yn) (let* ((range (- yn y0)) (max (- (buffer-length buf) range))) (if (> max 100) (info "deleting...")) (let loop ((i y0)) (if (< i max) (begin (change-line! buf i (buf-line buf (+ i range))) (loop (+ 1 i))))) (buffer-set-length! buf (- (buffer-length buf) range)) (status-line buf))) (define (delete-lines buf y0 yn) (let* ((range (- yn y0)) (len (buffer-length buf)) (max (- (buffer-length buf) range)) (top (vector-copy (buffer-buf buf) 0 y0)) (bot (vector-copy (buffer-buf buf) yn len))) (buffer-set-buf! buf (vector-append top bot)) (buffer-set-length! buf (- (buffer-length buf) range)) (status-line buf))) (define (cut-region log buf r0 rn) (if log (log-undo buf 'cut (list r0 rn (copy-region buf r0 rn)))) (cond ((= (cadr r0) (cadr rn)) (let ((line (buf-line buf (cadr r0)))) (change-line! buf (cadr r0) (string-append (substring line 0 (car r0)) (substring line (car rn) (string-length line)))))) ((and (zero? (car r0)) (zero? (car rn))) (delete-lines buf (cadr r0) (cadr rn))) (else (let* ((lin0 (buf-line buf (cadr r0))) (linn (buf-line buf (cadr rn))) (k (string-length linn)) (new (string-append (substring lin0 0 (car r0)) (substring linn (car rn) k)))) (change-line! buf (cadr r0) new) (delete-lines buf (+ 1 (cadr r0)) (+ 1 (cadr rn)))))) (buffer-set-mark! buf #f) (buffer-set-reg0! buf #f)) (define (delete-region buf yank) (if-writable buf (modified! buf) (cond ((region? buf) (if yank (yank-region buf)) (apply move-to buf (region-start buf)) (apply cut-region #t buf (region buf))) (else (raise-mark buf) (move-forward buf) (sync-mark buf) (move-backward buf) (apply cut-region #t buf (region buf)))) (show-buffer buf))) (define (backspace buf) (if-writable buf (cond ((region? buf) (delete-region buf #t)) ((top-of-buf? buf) (bell)) (else (move-backward buf) (drop-mark buf) (delete-region buf #f))))) (define (kill-line buf) (if-writable buf (cond ((= (buffer-x buf) (buf-cur-length buf)) (buffer-set-x! buf 0) (update-col buf) (raise-mark buf) (move-down buf) (sync-mark buf)) (else (raise-mark buf) (move-to-eol buf) (sync-mark buf))) (delete-region buf #t) (update-col buf))) ; slow version without VECTOR-COPY and VECTOR-APPEND (define (insert-lines buf y range) (let* ((max (- (buffer-length buf) 1))) (if (> max 100) (info "inserting...")) (let move ((i max)) (if (>= i y) (begin (change-line! buf (+ i range) (buf-line buf i)) (move (- i 1))))) (let fill ((i (+ y range -1))) (if (>= i y) (begin (change-line! buf i "") (fill (- i 1))))) (status-line buf))) (define (insert-lines buf y range) (let* ((max (- (buffer-length buf) 1)) (len (buffer-length buf)) (top (vector-copy (buffer-buf buf) 0 y)) (bot (vector-copy (buffer-buf buf) y len)) (mid (make-vector range ""))) (buffer-set-buf! buf (vector-append top mid bot)) (buffer-set-length! buf (+ len range)) (status-line buf))) (define (splice-region log buf x y lines) (let* ((old (buf-line buf y)) (left (substring old 0 x)) (right (substring old x (string-length old)))) (if log (log-undo buf 'splice (list x y lines))) (if (null? (cdr lines)) (begin (change-line! buf y (string-append left (car lines) right)) (list (+ x (string-length (car lines))) y)) (begin (change-line! buf y (string-append left (car lines))) (insert-lines buf (+ 1 y) 1) (change-line! buf (+ 1 y) (string-append (last lines) right)) (insert-lines buf (+ 1 y) (- (length lines) 2)) (let copy ((i (+ 1 y)) (lines (cdr lines))) (if (not (null? (cdr lines))) (begin (change-line! buf i (car lines)) (copy (+ 1 i) (cdr lines))))) (list (string-length (last lines)) (+ y (length lines) -1)))))) (define (splice-region-here buf lines char-hint) (define (insert-subsequent? buf hint last args) (and (eq? hint last) (= (buffer-y buf) (cadr args)) (= (buffer-x buf) (+ (car args) (string-length (caaddr args)))))) (let* ((hint (buffer-last-char buf)) (ubuf (buffer-undo buf)) (last (if (null? ubuf) '() (car ubuf))) (args (if (null? ubuf) '() (cadr last)))) (cond ((and char-hint (insert-subsequent? buf hint last args)) (set-car! (caddr args) (string-append (caaddr args) (car lines))) (splice-region #f buf (buffer-x buf) (buffer-y buf) lines)) (else (let ((r (splice-region #t buf (buffer-x buf) (buffer-y buf) lines))) (if char-hint (buffer-set-last-char! buf (car (buffer-undo buf)))) r))))) (define (set-region-here buf regn) (raise-mark buf) (buffer-set-regn! buf regn) (buffer-set-mark! buf #t)) (define (insert-region buf) (if-writable buf (if (not *yanked*) (err "nothing to insert") (let ((regn (splice-region-here buf *yanked* #f))) (set-region-here buf regn) (modified! buf) (show-buffer buf))))) (define (insert-char buf k) (if-writable buf (drop-mark buf) (splice-region-here buf (list (string k)) #t) (move-forward buf) (modified! buf) (show-cur-line buf))) (define (split-line buf) (if-writable buf (let* ((n (if (property 'auto-indent) (min (indentation (buf-cur-line buf)) (buffer-x buf)) 0)) (ind (make-string n #\space))) (drop-mark buf) (splice-region-here buf (list "" ind) #f) (move-down buf) (buffer-set-x! buf n) (update-col buf) (modified! buf) (show-buffer buf)))) (define symbolic? (let ((special (string->list "+-.*/<=>!?:$%_&~^"))) (lambda (c) (or (char-alphabetic? c) (char-numeric? c) (and (memv c special) #t))))) (define (find-prefix s words) (let ((k (string-length s))) (let loop ((w words) (r '())) (cond ((null? w) (let ((lim (if (null? r) 0 (apply min (map string-length r))))) (let loop ((i k)) (cond ((>= i lim) (if (zero? lim) "" (substring (car r) 0 i))) ((let ((c* (map (lambda (x) (string-ref x i)) r))) (and (> (length c*) 1) (not (apply char-ci=? c*)))) (substring (car r) 0 i)) (else (loop (+ 1 i))))))) ((and (<= k (string-length (car w))) (string-ci=? (substring (car w) 0 k) s)) (loop (cdr w) (cons (car w) r))) (else (loop (cdr w) r)))))) (define (expand-tabs buf) (let* ((k (- 8 (remainder (buffer-x buf) 8))) (s (make-string k #\space))) (splice-region-here buf (list s) #f) (buffer-set-x! buf (+ k (buffer-x buf))) (update-col buf) (show-cur-line buf))) (define (auto-complete buf) (if-writable buf (drop-mark buf) (let ((line (buf-cur-line buf))) (if (or (zero? (buffer-x buf)) (char=? #\space (string-ref line (- (buffer-x buf) 1)))) (expand-tabs buf) (let find ((x (- (buffer-x buf) 1))) (let ((c (string-ref line x))) (cond ((or (zero? x) (not (symbolic? c))) (let* ((x0 (if (symbolic? c) x (+ 1 x))) (s (substring line x0 (buffer-x buf))) (cs (find-prefix s *symbols*)) (y (buffer-y buf))) (if (not (string=? "" cs)) (begin (begin-undo-group buf) (cut-region #t buf (list x0 y) (list (buffer-x buf) y)) (splice-region #t buf x0 y (list cs)) (end-undo-group buf) (buffer-set-x! buf (+ x0 (string-length cs))) (show-cur-line buf))))) (else (find (- x 1)))))))))) ; ----- long commands ----- (define (adjust-display buf) (let ((show #f)) (cond ((buffer-reg0 buf) (sync-mark buf) (set! show #t))) (cond ((< (buffer-x buf) (buffer-off buf)) (buffer-set-off! buf (max 0 (- (buffer-x buf ) (- *offset-jump* 1)))) (set! show #t)) ((>= (buffer-x buf) (+ (buffer-off buf) (cols))) (buffer-set-off! buf (- (buffer-x buf) (- (cols) *offset-jump*))) (set! show #t)) ((< (buffer-y buf) (buffer-top buf)) (buffer-set-top! buf (buffer-y buf)) (set! show #t)) ((>= (buffer-y buf) (+ (buffer-top buf) (- (screen-lines) 1))) (buffer-set-top! buf (- (buffer-y buf) (- (screen-lines) 1))) (set! show #t))) (if show (show-buffer buf)))) (define (yesno buf) (let ((k (get-key buf))) (case k ((#\y #\Y) #t) (else #f)))) (define (cmd-quit buf) (if (buf-prop? buf 'scheme-repl) (auto-save-repl)) (cond ((and (modified? buf) (begin (err "buffer is modified, discard changes? (y/n)") (not (yesno buf))))) ((null? (cdr *buffers*)) 'quit) (else (cmd-rotate buf) (delete-buffer buf)))) (define (cmd-kill-session buf) (let ((n (modified-buffers))) (cond ((> n 1) (err "there are ~D modified buffers, really quit? (y/n)" n) (if (yesno buf) 'quit)) ((modified? buf) (err "buffer is modified, really quit? (y/n)") (if (yesno buf) 'quit)) ((positive? n) (err "there is a modified buffer, really quit? (y/n)") (if (yesno buf) 'quit)) (else 'quit)))) (define (cmd-exit buf) (cmd-save buf) (cmd-quit buf)) (define (cmd-redraw buf) (clear) (show-buffer buf) (status-line buf)) (define (fill-dir-buffer dir path) (move-to dir 0 0 0) (buffer-set-length! dir 0) (buffer-set-name! dir path) (let fill ((files (cons ".." (mergesort string<? (read-directory path)))) (pos 0)) (if (not (null? files)) (begin (change-line! dir pos (car files)) (fill (cdr files) (+ 1 pos)))))) (define (adjust-path path file) (if (string=? ".." file) (let* ((s* (string-split #\/ path)) (s (string-unsplit #\/ (reverse! (cdr (reverse s*)))))) (if (string=? "" s) "/" s)) (string-append path "/" file))) (define (mark-line buf) (buffer-set-x! buf 0) (raise-mark buf) (move-to-eol buf) (sync-mark buf) (buffer-set-mark! buf #t) (buffer-set-x! buf 0) (adjust-display buf)) (define (select-file buf path) (let ((dir (fresh-buffer '(read-only))) (path (if (string=? "." path) (getcwd) (string-append (getcwd) "/" path)))) (fill-dir-buffer dir path) (show-buffer dir) (status-line dir) (let select () (mark-line dir) (let ((k (get-key dir))) (cond ((motion-command dir k) (select)) ((or (char=? k ^C) (char=? k ^G) (char=? k #\q)) (delete-buffer dir) (show-buffer buf) #f) ((char=? k ^M) (let* ((file (buf-cur-line dir)) (new (string-append path "/" file))) (if (directory? new) (if (file-readable? new) (begin (set! path (adjust-path path file)) (fill-dir-buffer dir path) (select)) (begin (err "directory not readable") (select))) (begin (show-buffer buf) (delete-buffer dir) new)))) (else (info " ^LE q = quit ENTER = open") (select))))))) (define (cmd-edit buf) (cond ((or (not (modified? buf)) (begin (err "buffer is modified, discard changes? (y/n)") (yesno buf))) (color-info) (let* ((file (get-line (statline-pos) 0 "" "edit: ")) (file (if (and file (string=? "" file)) "." file))) (cond ((not file)) ((directory? file) (let ((file (select-file buf file))) (if file (begin (clear-buffer buf) (buf-rem-prop! buf 'read-only) (load-buffer buf file)) (info "never mind")))) (else (clear-buffer buf) (buf-rem-prop! buf 'read-only) (load-buffer buf file))))))) (define (get-name buf prompt) (let loop ((name "")) (color-info) (let ((name (get-line (statline-pos) 0 name prompt #t))) (cond ((or (not name) (string=? "" name)) #f) ((or (not (file-exists? name)) (begin (err "file already exists; overwrite? (y/n)") (yesno buf))) name) (else (loop name)))))) (define (cmd-save buf) (if-writable buf (let ((name (if (buffer-name buf) (buffer-name buf) (get-name buf "save: ")))) (if name (buffer-set-name! buf name)) (cond ((not name) (info "never mind") #f) ((and (file-exists? name) (not (file-writable? name))) (err "file not writable") #f) ((save-buffer buf (buffer-name buf)) (buf-rem-prop! buf 'modified) #t) (else #f))))) (define (cmd-sync buf) (let save ((b *buffers*) (n 0)) (cond ((null? b) (show-buffer buf) (info "~D buffer(s) saved" n)) ((or (buf-prop? (car b) 'read-only) (buf-prop? (car b) 'transient) (buf-prop? (car b) 'scheme-repl)) (save (cdr b) n)) ((modified? (car b)) (if (not (buffer-name (car b))) (show-buffer (car b))) (if (cmd-save (car b)) (save (cdr b) (+ 1 n)) (save (cdr b) n))) (else (save (cdr b) n))))) (define (cmd-save-as buf) (let ((name (get-name buf "save as: "))) (cond ((not name) (info "never mind")) ((and (file-exists? name)) (not (file-writable? name)) (err "file exists and is not writable")) ((or (not (file-exists? name)) (begin (err "file exists; overwrite? (y/n)") (yesno buf))) (save-buffer buf name))))) (define (cmd-write buf) (if (not (region? buf)) (err "no region marked for writing") (let ((name (get-name buf "write region: "))) (cond ((not name) (info "never mind")) ((and (file-exists? name) (not (file-writable? name))) (err "file not writable")) (else (save-buffer buf name (region-start buf) (region-end buf))))))) (define (cmd-read buf) (color-info) (let ((name (get-line (statline-pos) 0 "" "read file: "))) (cond ((or (not name) (string=? "" name)) (info "never mind")) ((not (file-exists? name)) (err "no such file")) ((not (file-readable? name)) (err "file not readable")) (else (let* ((lines (append (with-input-from-file name read-file) '(""))) (regn (splice-region-here buf lines #f))) (set-region-here buf regn) (modified! buf) (show-buffer buf)))))) (define (string-pos s1 s2) ((if (property 'sense-case) string-position string-ci-position) s1 s2)) (define (string-last-pos s1 s2) ((if (property 'sense-case) string-last-position string-ci-last-position) s1 s2)) (define (find-next buf text . options) (let ((offset (if (memq 'first options) 0 1))) (cond ((and (> (buf-cur-length buf) (buffer-x buf)) (string-pos text (substring (buf-cur-line buf) (+ offset (buffer-x buf)) (buf-cur-length buf)))) => (lambda (col) (buffer-set-x! buf (+ offset (buffer-x buf) col)) #t)) (else (info "searching...") (let loop ((y (+ 1 (buffer-y buf)))) (cond ((>= y (buffer-length buf)) (set! *message* #f) (err "string not found") #f) ((string-pos text (buf-line buf y)) => (lambda (col) (if (memq 'silent options) (go-to buf col y) (move-to buf col y)) #t)) (else (loop (+ 1 y))))))))) (define (find-previous buf text) (cond ((string-last-pos text (substring (buf-cur-line buf) 0 (buffer-x buf))) => (lambda (col) (buffer-set-x! buf col) #t)) (else (info "searching...") (let loop ((y (- (buffer-y buf) 1))) (cond ((negative? y) (set! *message* #f) (err "string not found") #f) ((string-last-pos text (buf-line buf y)) => (lambda (col) (move-to buf col y) #t)) (else (loop (- y 1)))))))) (define (cmd-locate buf) (color-info) (let ((text (get-line (statline-pos) 0 (buffer-searchstr buf) "locate: " #t))) (cond ((or (not text) (string=? "" text)) (info "never mind")) (else (buffer-set-searchstr! buf text) (let loop ((found (find-next buf text))) (if found (info " ^LL ^N = next ^P = previous other = exit")) (let ((k (get-key buf))) (cond ((char=? k ^N) (loop (find-next buf text))) ((char=? k ^P) (loop (find-previous buf text)))))))))) (define (cmd-next buf) (let ((sstr (buffer-searchstr buf))) (if (string=? "" sstr) (err "nothing to locate") (find-next buf sstr)))) (define (mark-cols buf cols) (raise-mark buf) (buffer-set-regn! buf (list (+ (buffer-x buf) cols) (buffer-y buf))) (buffer-set-mark! buf #t)) (define (exchange buf old new) (define (change new) (apply cut-region #t buf (region buf)) (splice-region-here buf (list new) #f) (modified! buf)) (move-to buf 0 0) (let ((cols (string-length old)) (auto #f) (first #t) (msg " ^LX CR = replace space = skip Q = quit A = all L = last") (n 0)) (begin-undo-group buf) (let loop () (if (not (find-next buf old (if auto 'silent '()) (if first 'first '()))) (end-undo-group buf) (begin (set! first #f) (mark-cols buf cols) (if (not auto) (begin (show-buffer buf) (info msg))) (let ((k (if auto ^M (get-key buf)))) (cond ((char=? k ^M) (change new) (inc! n) (loop)) ((char=? k #\space) (loop)) ((memv k '(#\Q #\q)) (end-undo-group buf)) ((memv k '(#\A #\a)) (change new) (inc! n) (set! auto #t) (loop)) ((memv k '(#\L #\l)) (change new) (inc! n) (end-undo-group buf))))))) (if auto (info "~D strings replaced" n)))) (define (auto-exchange buf old new reg0 regn) (define (change new) (let ((reg0 (buffer-reg0 buf)) (regn (buffer-regn buf))) (mark-cols buf (string-length old)) (apply cut-region #t buf (region buf)) (splice-region-here buf (list new) #f) (buffer-set-reg0! buf reg0) (buffer-set-regn! buf regn) (buffer-set-mark! buf #t) (modified! buf))) (buffer-set-mark! buf #t) (apply move-to buf reg0) (let ((here (save-pos buf)) (ocol (string-length old)) (ncol (string-length new)) (first #t) (n 0)) (begin-undo-group buf) (let loop () (if (and (find-next buf old 'silent (if first 'first '())) (apply before (buffer-x buf) (buffer-y buf) regn)) (begin (set! first #f) (change new) (set! here (save-pos buf)) (inc! n) (loop)))) (end-undo-group buf) (restore-pos buf here) (if (not (zero? n)) (info "~D strings replaced" n)))) (define (cmd-exchange buf) (if-writable buf (color-info) (let* ((sstr (buffer-searchstr buf)) (old (get-line (statline-pos) 0 sstr "old: " #t)) (new (if old (get-line (statline-pos) 0 "" "new: ") #f))) (cond ((or (not old) (not new) (string=? "" old)) (info "never mind")) ((region? buf) (apply auto-exchange buf old new (region buf))) (else (exchange buf old new))) (show-buffer buf)))) (define (region-of-lines! buf) (let* ((r (region buf)) (reg0 (car r)) (regn (cadr r))) (buffer-set-reg0! buf (list 0 (cadr reg0))) (if (positive? (car regn)) (buffer-set-regn! buf (list 0 (+ 1 (cadr regn))))) (show-buffer buf))) (define (in/out-dent-region buf action) (let* ((reg (region buf)) (text (apply copy-region buf reg))) (move-to buf 0 (cadr (region-start buf))) (apply cut-region #t buf reg) (let ((text (map action text))) (let ((r (splice-region-here buf text #f))) (set-region-here buf r) (show-buffer buf))))) (define (indent buf) (in/out-dent-region buf (lambda (s) (if (string=? "" s) s (string-append " " s))))) (define (outdentable? buf) (let outdent ((y (cadr (region-start buf)))) (if (>= y (cadr (region-end buf))) #t (let ((s (buf-line buf y))) (if (and (not (string=? "" s)) (not (char=? #\space (string-ref s 0)))) #f (outdent (+ 1 y))))))) (define (outdent buf) (if (not (outdentable? buf)) (begin (set! *message* #f) (err "insufficient leading space")) (in/out-dent-region buf (lambda (s) (if (string=? "" s) s (substring s 1 (string-length s))))))) (define (cmd-indent buf) (if-writable buf (let ((msg " ^LI ^B = outdent ^F = indent other = quit")) (cond ((not (region? buf)) (err "no region to indent")) (else (region-of-lines! buf) (buffer-set-mark! buf #t) (info msg) (begin-undo-group buf) (let loop () (info msg) (let ((k (get-key buf))) (cond ((char=? k ^F) (indent buf) (loop)) ((char=? k ^B) (outdent buf) (loop)) (else (if (not (eq? *undo-mark* (buffer-undo buf))) (begin (end-undo-group buf) (let* ((g (cadar (buffer-undo buf))) (u0 (car g)) (ul (last g))) (set-car! (buffer-undo buf) `(group (,u0 ,ul)))))) (status-line buf)))))))))) (define (run-filter buf cmd) (region-of-lines! buf) (let* ((filter (spawn-shell-command cmd)) (reg (region buf)) (text (apply copy-region buf reg))) (move-to buf 0 (cadr (region-start buf))) (info "filtering...") (begin-undo-group buf) (apply cut-region #t buf reg) (for-each (lambda (x) (display x (cadr filter)) (newline (cadr filter))) text) (close-output-port (cadr filter)) (let ((text (map string-expand (read-file (car filter))))) (let ((r (splice-region-here buf text #f))) (end-undo-group buf) (set-region-here buf r) (show-buffer buf))))) (define (cmd-filter buf) (if-writable buf (cond ((not (region? buf)) (err "no region to filter")) (else (color-info) (let ((cmd (get-line (statline-pos) 0 "" "filter: "))) (cond ((or (not cmd) (string=? "" cmd)) (info "never mind")) (else (run-filter buf cmd)))))))) (define (help-buffer) (find-buffer 'help-buffer #t)) (define (cmd-help buf) (let* ((hb (help-buffer)) (id (buffer-name hb))) (if (< (buffer-length hb) 2) (let ((helpfile (locate-file "s9e.help"))) (if (not helpfile) (err "oops - help file (s9e.help) not found!") (begin (load-buffer hb helpfile) (buffer-set-name! hb id) (buf-set-prop! hb 'read-only))))) (set! *switch-to* hb))) (define (cmd-buf-list buf) (let ((blist (fresh-buffer (list 'read-only 'transient)))) (buffer-set-name! blist "*buffer-list*") (do ((i 0 (+ 1 i)) (b *buffers* (cdr b))) ((null? b)) (let ((line (format #f "~C~C~C ~7:D ~A" (if (buf-prop? (car b) 'auto-load) #\a #\.) (if (modified? (car b)) #\m #\.) (if (read-only? (car b)) #\r #\.) (buffer-length (car b)) (if (buffer-name (car b)) (buffer-name (car b)) "*anonymous*")))) (change-line! blist i line))) (show-buffer blist) (status-line blist) (let loop () (mark-line blist) (let ((k (get-key blist))) (cond ((motion-command blist k) (loop)) ((or (char=? k ^C) (char=? k ^G) (char=? k #\q)) (delete-buffer blist) (show-buffer buf) #f) ((char=? k ^M) (let ((b (nth-buffer (buffer-y blist)))) (if (buf-prop? b 'transient) (err "buffer is transient") (set! *switch-to* (nth-buffer (buffer-y blist))))) (delete-buffer blist) (show-buffer buf)) (else (info " ^LV q = quit ENTER = select") (loop))))))) (define (cmd-buf-open buf) (set! *switch-to* (fresh-buffer '())) (status-line *switch-to*)) (define (cmd-rotate buf) (let ((this (this-buffer buf))) (if (null? (cdr this)) (set! *switch-to* (car *buffers*)) (set! *switch-to* (cadr this))) (status-line *switch-to*))) (define (parse-color dflt name) (let ((colors `((black . ,*black*) (blue . ,*blue*) (green . ,*green*) (cyan . ,*cyan*) (red . ,*red*) (magenta . ,*magenta*) (yellow . ,*yellow*) (gray . ,*gray*) (white . ,*gray*)))) (let* ((fg/bg (string-split #\/ name)) (fg (car fg/bg)) (bg (if (null? (cdr fg/bg)) "" (cadr fg/bg))) (fg (assq (string->symbol fg) colors)) (bg (assq (string->symbol bg) colors))) (if (and fg bg) (list (cdr fg) (cdr bg)) dflt)))) (define (parse-setprop-cmd buf s err-fn) (define (find-prop s) (let find ((p *properties*)) (cond ((null? p) #f) ((string=? s (prop-abbr (car p))) (car p)) ((string=? s (symbol->string (prop-prop (car p)))) (car p)) (else (find (cdr p)))))) (define (set-prop-value buf p v) (let ((v (if (number? (prop-default p)) (let ((n (string->number v))) (if n n (begin (err-fn "~A: numeric value expected" (prop-prop p)) (prop-default p)))) v))) (if (eq? 'global (prop-scope p)) (put-prop! *globals* (prop-prop p) v) (buffer-set-properties! buf (put-prop (buffer-properties buf) (prop-prop p) v))) (update-colors))) (let* ((s (string-skip-white s)) (k (string-length s)) (v (string-position "=" s))) (cond ((or (string-prefix=? "no-" s) (string-prefix=? "no" s)) (let* ((s (if (string-prefix=? "no-" s) (substring s 3 k) (substring s 2 k))) (p (find-prop s))) (if p (set-prop-value buf p #f) (err-fn "no such property: ~A" s)))) (v (let ((s (substring s 0 v)) (v (substring s (+ 1 v) k))) (let ((p (find-prop s))) (if p (set-prop-value buf p v) (err-fn "no such property: ~A" s))))) (else (let ((p (find-prop s))) (if p (set-prop-value buf p #t) (err-fn "no such property: ~A" s))))))) (define (edit-setprop-cmd buf s) (color-info) (let ((s (get-line (statline-pos) 0 s "property: " #t))) (cond ((or (not s) (string=? "" s)) (info "never mind")) (else (parse-setprop-cmd buf s err))))) (define (list-properties buf) (define (prop-value p) (if (eq? 'global (prop-scope p)) (get-prop *globals* (prop-prop p)) (get-prop (buffer-properties buf) (prop-prop p)))) (define (prop->string p) (let* ((name (format #f "~15A" (prop-prop p))) (val (prop-value p)) (val (cond ((boolean? val) (if val "on" "off")) ((number? val) (number->string val)) (else (string-append "\"" val "\"")))) (line (string-append (prop-abbr p) " " name val))) (if (eq? 'local (prop-scope p)) (string-append line " (local)") line))) (define (make-config-cmd p) (let ((v (prop-value p))) (cond ((eq? v #t) (prop-abbr p)) ((eq? v #f) (string-append "no" (prop-abbr p))) ((number? v) (string-append (prop-abbr p) "=" (number->string v))) (else (string-append (prop-abbr p) "=" v))))) (let ((plist (fresh-buffer (list 'read-only 'transient)))) (buffer-set-name! plist "*property-list*") (let reload () (buffer-set-length! plist 1) (do ((i 0 (+ 1 i)) (p *properties* (cdr p))) ((null? p)) (if (not (eq? 'internal (prop-scope (car p)))) (change-line! plist i (prop->string (car p))))) (show-buffer plist) (if (not *message*) (status-line plist)) (let loop () (mark-line plist) (let ((k (get-key plist))) (cond ((motion-command plist k) (loop)) ((or (char=? k ^C) (char=? k ^G) (char=? k #\q)) (delete-buffer plist) (show-buffer buf)) ((char=? k ^M) (edit-setprop-cmd buf (make-config-cmd (list-ref *properties* (buffer-y plist)))) (reload)) (else (info " ^LP q = quit ENTER = change") (loop)))))))) (define (cmd-set-props buf) (color-info) (let ((prop (get-line (statline-pos) 0 "" "property: "))) (cond ((not prop) (info "never mind")) ((string=? "" prop) (list-properties buf)) (else (parse-setprop-cmd buf prop err))))) (define (l-motion-command buf k) (cond ((char=? k ^V) (move-to-eof buf) #t) ((char=? k ^L) (cmd-redraw buf) #t) ((char=? k ^T) (move-to buf 0 0 0) #t) ((char=? k #\b) (move-to-eof buf) #t) ((char=? k #\g) (move-to-line buf) #t) ((char=? k #\l) (cmd-locate buf) #t) ((char=? k #\n) (cmd-next buf) #t) ((char=? k #\t) (move-to buf 0 0 0) #t) (else #f))) (define (l-command buf) (let* ((msgs #(" ^L Top Bottom Locate Next eXchange Goto Help Quit" " ^L Edit Read Save saveAs Write sYnc Indent Filter " " ^L Kill-buffers Open-buffer View-buffers ")) (nmsg (vector-length msgs))) (let loop ((n 0)) (info (string-append (vector-ref msgs n) " space=more")) (let ((k (get-key buf))) (cond ((not k)) ((l-motion-command buf k)) ((char=? k #\a) (cmd-save-as buf)) ((char=? k #\e) (cmd-edit buf)) ((char=? k #\f) (cmd-filter buf)) ((char=? k #\h) (cmd-help buf)) ((char=? k #\i) (cmd-indent buf)) ((char=? k #\k) (cmd-kill-session buf)) ((char=? k #\o) (cmd-buf-open buf)) ((char=? k #\p) (cmd-set-props buf)) ((char=? k #\q) (cmd-quit buf)) ((char=? k #\r) (cmd-read buf)) ((char=? k #\s) (cmd-save buf)) ((char=? k #\v) (cmd-buf-list buf)) ((char=? k #\w) (cmd-write buf)) ((char=? k #\x) (cmd-exchange buf)) ((char=? k #\y) (cmd-sync buf)) ((char=? k #\z) (cmd-exit buf)) ((char=? k #\space) (loop (if (= n (- nmsg 1)) 0 (+ 1 n)))) (else)))))) ; ----- Scheme commands ----- (define (run-scheme) (let* ((scm (string-parse (string #\space) (property 'repl-command))) (path (getenv "PATH")) (cmd (if (char=? #\. (string-ref (car scm) 0)) (car scm) (search-path (car scm) (if path path "")))) (cmd (if cmd cmd (car scm))) (args (cdr scm))) (let ((conn (spawn-command/fd cmd args))) (set! *repl* (list (car conn) (make-output-port (cadr conn)) (caddr conn)))))) (define (send-to-repl s*) (catch-errors #t) (for-each (lambda (s) (display s (cadr *repl*)) (newline (cadr *repl*))) s*) (catch-errors #f)) (define (flush-repl) (let ((done-magic (string-append "(done " (number->string (unix-time)) ")"))) (send-to-repl (list (string-append (string #\newline) "(newline)" (string #\newline) "'" done-magic))) (catch-errors #t) (flush-output-port (cadr *repl*)) (catch-errors #f) done-magic)) (define (make-reader input-fd) (let ((buffer #f) (limit 0) (next 0)) (lambda chars-left? (cond ((not (null? chars-left?)) (< next limit)) ((>= next limit) (let* ((next-buffer (fd-read input-fd 10240)) (k (string-length next-buffer))) (if (zero? k) #f (begin (set! buffer next-buffer) (set! limit k) (set! next 1) (string-ref buffer 0))))) (else (let ((c (string-ref buffer next))) (set! next (+ 1 next)) c)))))) (define (read-line-from-repl reader) (letrec ((collect-chars (lambda (c s) (cond ((not c) (if (null? s) c (string-expand (list->string (reverse! s))))) ((char=? c #\newline) (string-expand (list->string (reverse! s)))) (else (collect-chars (reader) (cons c s))))))) (collect-chars (reader) '()))) (define (user-interrupt?) (nodelay #t) (let ((k (getch))) (nodelay #f) (eqv? 3 k))) (define (disconnect!) (close-output-port (cadr *repl*)) (catch-errors #t) (send-signal (caddr *repl*)) (wait-for-process) (catch-errors #f) (set! *repl* #f)) (define (hello-scheme?) (let* ((magic (flush-repl)) (k (string-length magic)) (reader (make-reader (car *repl*)))) (let ((s (begin (read-line-from-repl reader) (read-line-from-repl reader)))) (and (string? s) (>= (string-length s) k) (string=? magic (substring s 0 k)))))) (define (start-scheme-repl) (if (not *repl*) (begin (catch-errors #t) (run-scheme) (let ((e (errno))) (catch-errors #f) (cond ((not *repl*) (disconnect!) (err "failed to run scheme: ~A" (errno->string e))) ((hello-scheme?) (send-to-repl (list (property 'repl-init))) (get-repl-output #f (property 'repl-timeout) #f #t)) (else (disconnect!) (err "failed to run scheme (no response)"))))))) (define (append-to-buffer dest lines) (modified! dest) (if (not (string=? "" (buf-line dest (- (buffer-length dest) 1)))) (change-line! dest (buffer-length dest) "")) (go-to dest 0 (- (buffer-length dest) 1) (screen-lines)) (let ((regn (splice-region-here dest (append lines '("")) #f))) (raise-mark dest) (buffer-set-mark! dest #t) (buffer-set-regn! dest regn))) (define (get-repl-output dest timeout skip-comments silent) (let ((done-magic (flush-repl)) (reader (make-reader (car *repl*)))) (info "running...") (set! *message* #f) (let loop ((output '())) (cond ((and (not (reader 'check)) (not (fd-select (list timeout 0) (list (car *repl*)) '()))) (disconnect!) (err "run time limit exceeded")) ((user-interrupt?) (disconnect!) (err "interrupted")) (else (let ((s (read-line-from-repl reader))) (cond ((not s) (if dest (append-to-buffer dest (reverse! output))) (disconnect!) (err "error(s) found")) ((string=? done-magic s) (let ((output (if (and (not (null? output)) (string=? "" (car output))) (reverse! (cdr output)) (reverse! output)))) (if dest (append-to-buffer dest output)) (if (and (not silent) (positive? (length output))) (info "output received")))) ((and skip-comments (> (string-length s) 1) (char=? #\; (string-ref s 0))) (loop output)) (else (loop (cons s output)))))))))) (define (load-repl-buffer sb) (and-let* ((home (getenv "HOME")) (path (string-append home "/.s9fes/s9e-repl-buffer")) (_ (file-readable? path))) (load-buffer sb path 'silent) (go-to sb 0 (- (buffer-length sb) 1) (screen-lines)))) (define (scheme-buffer) (let ((sb (find-buffer 'scheme-repl))) (if (not sb) (let ((sb (find-buffer 'scheme-repl #t))) (load-repl-buffer sb) sb) sb))) (define (scheme-repl buf) (start-scheme-repl) (set! *switch-to* (scheme-buffer))) (define (compile-buffer buf) (start-scheme-repl) (let ((k (buffer-length buf))) (do ((i 0 (+ 1 i))) ((>= i k)) (display (buf-line buf i) (cadr *repl*)) (newline (cadr *repl*)))) (get-repl-output (scheme-buffer) (property 'load-timeout) #t #t)) (define (scheme-compile buf) (compile-buffer buf) (if (not *message*) (info "buffer compiled"))) (define (auto-load buf) (do ((b *buffers* (cdr b))) ((or (null? b) *message*)) (if (buf-prop? (car b) 'auto-load) (compile-buffer (car b))))) (define (scheme-eval buf) (let ((here (save-pos buf))) (start-scheme-repl) (auto-load buf) (if (not *message*) (begin (restore-pos buf here) (mark-expr buf) (if (not (region? buf)) (err "nothing to evaluate") (let ((prog (apply copy-region buf (region buf)))) (send-to-repl prog) (get-repl-output (scheme-buffer) (property 'repl-timeout) #f #f))))))) (define (scheme-pretty-print buf . options) (if-writable buf (if (not (region? buf)) (err "nothing to pretty-print") (let* ((reg (region buf)) (text (apply copy-region buf reg))) (modified! buf) (apply move-to buf (buffer-reg0 buf)) (begin-undo-group buf) (apply cut-region #t buf reg) (let* ((text (apply pp-string text 'indent: (buffer-x buf) options)) (r (splice-region-here buf text #f))) (end-undo-group buf) (set-region-here buf r) (show-buffer buf)))))) (define (z-command buf) (info " ^Z Compile Eval Format Pretty-print Scheme ^Z = mark expr") (let ((k (get-key buf))) (cond ((char=? k ^Z) (mark-expr buf)) ((char=? k #\c) (scheme-compile buf)) ((char=? k #\e) (scheme-eval buf)) ((char=? k #\f) (scheme-pretty-print buf 'data)) ((char=? k #\p) (scheme-pretty-print buf 'code)) ((char=? k #\s) (scheme-repl buf)) (else #f)))) ; ----- command loop ----- (define (paren-match buf on) (let ((c (buf-cur-char buf)) (x (buffer-col buf)) (h (save-pos buf)) (d #f)) (cond ((not c)) ((and (char=? c LP) (match-right buf #t on)) (sync-pos buf) (if on (color-paren) (color-text)) (addch RP) (set! d #t)) ((and (char=? c RP) (begin (move-backward buf) (match-left buf #t on))) (sync-pos buf) (if on (color-paren) (color-text)) (addch LP) (set! d #t)) ((and (char=? c LB) (match-right buf #t on)) (sync-pos buf) (if on (color-paren) (color-text)) (addch RB) (set! d #t)) ((and (char=? c RB) (begin (move-backward buf) (match-left buf #t on))) (sync-pos buf) (if on (color-paren) (color-text)) (addch LB) (set! d #t))) (reset-pos buf h) (buffer-set-col! buf x) d)) (define (command-loop buf) (let/cc exit (let ((pmatch #f)) (let loop () (if *switch-to* (begin (set! buf *switch-to*) (set! *switch-to* #f) (show-buffer buf))) (if (not *message*) (status-line buf)) (adjust-display buf) (if (property 'show-match) (set! pmatch (paren-match buf #t)) (set! pmatch #f)) (let ((k (get-key buf))) (if pmatch (paren-match buf #f)) (cond ((not k)) ((simple-motion-command buf k)) ((char=? k ^D) (delete-region buf #t)) ((char=? k ^H) (backspace buf)) ((char=? k ^I) (auto-complete buf)) ((char=? k ^J) (scheme-eval buf)) ((char=? k ^K) (kill-line buf)) ((char=? k ^L) (if (eq? 'quit (l-command buf)) (exit #t))) ((char=? k ^M) (split-line buf)) ((char=? k ^O) (yank-region buf)) ((char=? k ^Q) (cmd-rotate buf)) ((char=? k ^R) (redo-cmd buf)) ((char=? k ^S) (toggle-mark buf)) ((char=? k ^U) (undo-cmd buf)) ((char=? k ^Y) (insert-region buf)) ((char=? k ^Z) (z-command buf)) ((<= 32 (char->integer k) 126) (insert-char buf k)) (else (err "unknown command: ~A; press ^L-h for help" (visual-char k)))) (loop)))))) ; ----- init and shutdown ----- (define (init) (initscr) (raw) (noecho) (nonl) (idlok #t) (scrollok #f) (keypad #t) (set! *spaces* (make-string (cols) #\space)) (set! *dashes* (make-string (cols) #\-))) (define (quit) (color-text) (mvaddstr (statline-pos) 0 *spaces*) (refresh) (move (statline-pos) 0) (endwin)) (define (auto-save-repl) (let ((sb (scheme-buffer))) (cond ((buf-prop? sb 'modified) (if (not (save-buffer sb (buffer-name sb))) (begin (err "Could not save REPL buffer! (This is a bug!)") (getch))))))) (define (set-up-defaults) (for-each (lambda (p) (if (eq? 'global (prop-scope p)) (put-prop! *globals* (prop-prop p) (prop-default p)))) *properties*)) (define (load-config buf) (and-let* ((home (getenv "HOME")) (path (string-append home "/.s9fes/s9e-config")) (_ (file-readable? path))) (with-input-from-file path (lambda () (let ((errors #f)) (let read ((line (read-line))) (if (not (eof-object? line)) (cond ((or (zero? (string-length line)) (char=? #\# (string-ref line 0)))) (else (parse-setprop-cmd buf line (lambda x (display (apply format #f x)) (newline) (set! errors #t))) (read (read-line)))))) (if errors (exit 1))))))) (define (load-symbols) (and-let* ((home (getenv "HOME")) (path (string-append home "/.s9fes/symbols")) (_ (file-readable? path))) (set! *symbols* (with-input-from-file path read-file)))) (define (configure buf) (set-up-defaults) (load-config buf) (load-symbols)) (define (s9e . args) (let* ((file (if (null? args) #f (car args))) (options (if (null? args) '() (cdr args)))) (let ((buf (fresh-buffer (append options '(auto-load))))) (configure buf) (init) (show-buffer buf) (if file (load-buffer buf file) (info "Welcome to S9E beta! Press ^L-h for help.")) (menu-dashes) (show-buffer buf) (command-loop buf) (auto-save-repl) (quit))))
true
63a77b515de6f02ff10d9bfdac6f56eda76a4ee9
f08220a13ec5095557a3132d563a152e718c412f
/logrotate/skel/usr/share/guile/2.0/sxml/ssax.scm
f750c934a94e04413f44f57af81af7c85d824ffb
[ "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
11,011
scm
ssax.scm
;;;; (sxml ssax) -- the SSAX parser ;;;; ;;;; Copyright (C) 2009, 2010,2012,2013 Free Software Foundation, Inc. ;;;; Modified 2004 by Andy Wingo <wingo at pobox dot com>. ;;;; Written 2001,2002,2003,2004 by Oleg Kiselyov <oleg at pobox dot com> as SSAX.scm. ;;;; ;;;; 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 ;;;; ;;; Commentary: ;; ;@subheading Functional XML parsing framework ;@subsubheading SAX/DOM and SXML parsers with support for XML Namespaces and validation ; ; This is a package of low-to-high level lexing and parsing procedures ; that can be combined to yield a SAX, a DOM, a validating parser, or ; a parser intended for a particular document type. The procedures in ; the package can be used separately to tokenize or parse various ; pieces of XML documents. The package supports XML Namespaces, ; internal and external parsed entities, user-controlled handling of ; whitespace, and validation. This module therefore is intended to be ; a framework, a set of "Lego blocks" you can use to build a parser ; following any discipline and performing validation to any degree. As ; an example of the parser construction, this file includes a ; semi-validating SXML parser. ; The present XML framework has a "sequential" feel of SAX yet a ; "functional style" of DOM. Like a SAX parser, the framework scans the ; document only once and permits incremental processing. An application ; that handles document elements in order can run as efficiently as ; possible. @emph{Unlike} a SAX parser, the framework does not require ; an application register stateful callbacks and surrender control to ; the parser. Rather, it is the application that can drive the framework ; -- calling its functions to get the current lexical or syntax element. ; These functions do not maintain or mutate any state save the input ; port. Therefore, the framework permits parsing of XML in a pure ; functional style, with the input port being a monad (or a linear, ; read-once parameter). ; Besides the @var{port}, there is another monad -- @var{seed}. Most of ; the middle- and high-level parsers are single-threaded through the ; @var{seed}. The functions of this framework do not process or affect ; the @var{seed} in any way: they simply pass it around as an instance ; of an opaque datatype. User functions, on the other hand, can use the ; seed to maintain user's state, to accumulate parsing results, etc. A ; user can freely mix his own functions with those of the framework. On ; the other hand, the user may wish to instantiate a high-level parser: ; @code{SSAX:make-elem-parser} or @code{SSAX:make-parser}. In the latter ; case, the user must provide functions of specific signatures, which ; are called at predictable moments during the parsing: to handle ; character data, element data, or processing instructions (PI). The ; functions are always given the @var{seed}, among other parameters, and ; must return the new @var{seed}. ; From a functional point of view, XML parsing is a combined ; pre-post-order traversal of a "tree" that is the XML document ; itself. This down-and-up traversal tells the user about an element ; when its start tag is encountered. The user is notified about the ; element once more, after all element's children have been ; handled. The process of XML parsing therefore is a fold over the ; raw XML document. Unlike a fold over trees defined in [1], the ; parser is necessarily single-threaded -- obviously as elements ; in a text XML document are laid down sequentially. The parser ; therefore is a tree fold that has been transformed to accept an ; accumulating parameter [1,2]. ; Formally, the denotational semantics of the parser can be expressed ; as ;@smallexample ; parser:: (Start-tag -> Seed -> Seed) -> ; (Start-tag -> Seed -> Seed -> Seed) -> ; (Char-Data -> Seed -> Seed) -> ; XML-text-fragment -> Seed -> Seed ; parser fdown fup fchar "<elem attrs> content </elem>" seed ; = fup "<elem attrs>" seed ; (parser fdown fup fchar "content" (fdown "<elem attrs>" seed)) ; ; parser fdown fup fchar "char-data content" seed ; = parser fdown fup fchar "content" (fchar "char-data" seed) ; ; parser fdown fup fchar "elem-content content" seed ; = parser fdown fup fchar "content" ( ; parser fdown fup fchar "elem-content" seed) ;@end smallexample ; Compare the last two equations with the left fold ;@smallexample ; fold-left kons elem:list seed = fold-left kons list (kons elem seed) ;@end smallexample ; The real parser created by @code{SSAX:make-parser} is slightly more ; complicated, to account for processing instructions, entity ; references, namespaces, processing of document type declaration, etc. ; The XML standard document referred to in this module is ; @uref{http://www.w3.org/TR/1998/REC-xml-19980210.html} ; ; The present file also defines a procedure that parses the text of an ; XML document or of a separate element into SXML, an S-expression-based ; model of an XML Information Set. SXML is also an Abstract Syntax Tree ; of an XML document. SXML is similar but not identical to DOM; SXML is ; particularly suitable for Scheme-based XML/HTML authoring, SXPath ; queries, and tree transformations. See SXML.html for more details. ; SXML is a term implementation of evaluation of the XML document [3]. ; The other implementation is context-passing. ; The present frameworks fully supports the XML Namespaces Recommendation: ; @uref{http://www.w3.org/TR/REC-xml-names/} ; Other links: ;@table @asis ;@item [1] ; Jeremy Gibbons, Geraint Jones, "The Under-appreciated Unfold," ; Proc. ICFP'98, 1998, pp. 273-279. ;@item [2] ; Richard S. Bird, The promotion and accumulation strategies in ; transformational programming, ACM Trans. Progr. Lang. Systems, ; 6(4):487-504, October 1984. ;@item [3] ; Ralf Hinze, "Deriving Backtracking Monad Transformers," ; Functional Pearl. Proc ICFP'00, pp. 186-197. ;@end table ;; ;;; Code: (define-module (sxml ssax) #:use-module (sxml ssax input-parse) #:use-module (srfi srfi-1) #:use-module (srfi srfi-13) #:export (current-ssax-error-port with-ssax-error-to-port xml-token? xml-token-kind xml-token-head make-empty-attlist attlist-add attlist-null? attlist-remove-top attlist->alist attlist-fold define-parsed-entity! reset-parsed-entity-definitions! ssax:uri-string->symbol ssax:skip-internal-dtd ssax:read-pi-body-as-string ssax:reverse-collect-str-drop-ws ssax:read-markup-token ssax:read-cdata-body ssax:read-char-ref ssax:read-attributes ssax:complete-start-tag ssax:read-external-id ssax:read-char-data ssax:xml->sxml ssax:make-parser ssax:make-pi-parser ssax:make-elem-parser)) (define (parser-error port message . rest) (apply throw 'parser-error port message rest)) (define ascii->char integer->char) (define char->ascii char->integer) (define current-ssax-error-port (make-parameter (current-error-port))) (define *current-ssax-error-port* (parameter-fluid current-ssax-error-port)) (define (with-ssax-error-to-port port thunk) (parameterize ((current-ssax-error-port port)) (thunk))) (define (ssax:warn port . args) (with-output-to-port (current-ssax-error-port) (lambda () (display ";;; SSAX warning: ") (for-each display args) (newline)))) (define (ucscode->string codepoint) (string (integer->char codepoint))) (define char-newline #\newline) (define char-return #\return) (define char-tab #\tab) (define nl "\n") ;; This isn't a great API, but a more proper fix will involve hacking ;; SSAX. (define (reset-parsed-entity-definitions!) "Restore the set of parsed entity definitions to its initial state." (set! ssax:predefined-parsed-entities '((amp . "&") (lt . "<") (gt . ">") (apos . "'") (quot . "\"")))) (define (define-parsed-entity! entity str) "Define a new parsed entity. @var{entity} should be a symbol. Instances of &@var{entity}; in XML text will be replaced with the string @var{str}, which will then be parsed." (set! ssax:predefined-parsed-entities (acons entity str ssax:predefined-parsed-entities))) ;; Execute a sequence of forms and return the result of the _first_ one. ;; Like PROG1 in Lisp. Typically used to evaluate one or more forms with ;; side effects and return a value that must be computed before some or ;; all of the side effects happen. (define-syntax begin0 (syntax-rules () ((begin0 form form1 ... ) (let ((val form)) form1 ... val)))) ; Like let* but allowing for multiple-value bindings (define-syntax let*-values (syntax-rules () ((let*-values () . bodies) (begin . bodies)) ((let*-values (((var) initializer) . rest) . bodies) (let ((var initializer)) ; a single var optimization (let*-values rest . bodies))) ((let*-values ((vars initializer) . rest) . bodies) (call-with-values (lambda () initializer) ; the most generic case (lambda vars (let*-values rest . bodies)))))) ;; needed for some dumb reason (define inc 1+) (define dec 1-) (define-syntax include-from-path/filtered (lambda (x) (define (read-filtered accept-list file) (with-input-from-file (%search-load-path file) (lambda () (let loop ((sexp (read)) (out '())) (cond ((eof-object? sexp) (reverse out)) ((and (pair? sexp) (memq (car sexp) accept-list)) (loop (read) (cons sexp out))) (else (loop (read) out))))))) (syntax-case x () ((_ accept-list file) (with-syntax (((exp ...) (datum->syntax x (read-filtered (syntax->datum #'accept-list) (syntax->datum #'file))))) #'(begin exp ...)))))) (include-from-path "sxml/upstream/assert.scm") (include-from-path/filtered (define define-syntax ssax:define-labeled-arg-macro) "sxml/upstream/SSAX.scm")
true
411e949767ff8306d19e7c8e4606465ad2c21da3
1d7b2253c41c7ef52161b49d0aef76da35229589
/LETREC/scanner.ss
c7be48ca00d1853c414394355ee592064b7c95b9
[]
no_license
DavidOHafner/unstructured-transfer
9b51b350a8b6bfd98ef9dac80add8d259ac873d9
71e41a143b551e6e480cf4f185ca22a771d63cef
refs/heads/master
2020-07-19T11:36:58.215308
2019-10-15T17:06:27
2019-10-15T17:06:27
206,441,670
0
0
null
null
null
null
UTF-8
Scheme
false
false
11,304
ss
scanner.ss
#!r7rs ;;; A scanner for the LETREC language ;;; John David Stone ;;; Department of Computer Science ;;; Grinnell College ;;; Edited by Samantha Hafner ;;; created February 8, 2009 ;;; last revised October 4, 2019 ;;; This file provides a scanner ;;; for the LETREC language ;;; developed by Daniel P. Friedman and Mitchell Wand ;;; in section 3.4 of their book ;;; _Essentials of programming languages_ (third edition). ;;; Extention to add lists as an expressed value are by ;;; Samantha Orion Hafner according to specifications by ;;; John David Stone. All code changes noted. (define-library (LETREC scanner) (export scanner) (import (scheme base) (scheme char) (utilities eopl) (utilities character-sources) (LETREC tokens)) (begin ;; The scanner is implemented as a procedure ;; that takes a character source as its argument ;; and returns a "token source" object, ;; which responds to the same three messages ;; as a character source, ;; (namely at-end?, peek, and get) ;; but returns a token rather than a character ;; in response to peek and get messages. ;; scanner : Character-source -> Token-source (define scanner (lambda (character-source) ;; When we first peek at a token, ;; we'll have to get all of the characters that make it up ;; from the character source. ;; Since we can get those characters only once, however, ;; we'll have to store the token ;; so that we can still return it ;; when the next peek or get message is received. ;; The local variable named buffer ;; holds the next available token, ;; if we have peeked at it, ;; or the symbol empty if we have not. (let ((buffer 'empty)) (lambda (message) ;; When the token source that scanner returns ;; receives any message, ;; it first discards any whitespace ;; and any comments ;; that it finds in the given character source. ;; This ensures that the character source ;; is either "at end" ;; or positioned to yield a non-whitespace, ;; non-comment character. (skip-whitespace character-source) (case message ;; Then, if the message is at-end?, ;; the token source returns #t ;; if the buffer is empty ;; and the character source can supply ;; no more input. ;; Otherwise, another token may and should be available, ;; so the token source returns #f. ((at-end?) (and (eqv? buffer 'empty) (character-source 'at-end?))) ;; If the message is peek, ;; the token source returns the token from the buffer, ;; filling it first if it starts out empty. ((peek) (when (eqv? buffer 'empty) (set! buffer (get-token character-source))) buffer) ;; If the message is get, ;; the token source returns the token from the buffer ;; if there is one ;; (emptying out the buffer along the way) ;; or the next token from the character source ;; if there is no token in the buffer. ((get) (if (eqv? buffer 'empty) (get-token character-source) (let ((result buffer)) (set! buffer 'empty) result))) (else (report-bad-message-error message))))))) ;; report-bad-message-error : Symbol -> (aborts the computation) (define report-bad-message-error (lambda (non-message) (eopl:error 'token-source "The message ~a was not recognized.~%" non-message))) ;; Comments in the LETREC language ;; begin with a percentage sign and ;; end at the next following newline. ;; comment-starter : Char (define comment-starter #\%) ;; comment-ender : Char (define comment-ender #\newline) ;; The discard-comment procedure is invoked ;; when the beginning of a comment has been detected (and consumed). ;; It consumes characters from the source ;; up to and including a newline character ;; (unless it reaches the end of the source first, ;; in which case it consumes all of the remaining ;; characters from the source). ;; discard-comment : Character-source -> () (define discard-comment (lambda (source) (let loop () (unless (or (source 'at-end?) (char=? (source 'get) comment-ender)) (loop))))) ;; The skip-whitespace procedure discards whitespace ;; and comments from the character source. ;; Its postcondition is that ;; either the character source ;; has no more available characters, ;; or the next available character ;; is a non-whitespace character ;; that is not part of a comment. ;; skip-whitespace : Character-source -> () (define skip-whitespace (lambda (source) (let loop () (unless (source 'at-end?) (let ((next (source 'peek))) (cond ((char-whitespace? next) (source 'get) (loop)) ((char=? next comment-starter) (source 'get) (discard-comment source) (loop)))))))) ;; The get-token procedure consumes the text of one token ;; from the character source ;; and constructs and returns the appropriate token. ;; It is a precondition of this procedure ;; that the next available character can begin a token. ;; get-token : Character-source -> Token (define get-token (lambda (source) (let ((next (source 'peek))) (cond ((char-numeric? next) (numeral-token (get-numeral-value source))) ((char-alphabetic? next) (let ((id (get-identifier source))) (case id ((zero?) (zero?-token)) ((if) (if-token)) ((then) (then-token)) ((else) (else-token)) ((let) (let-token)) ((in) (in-token)) ((proc) (proc-token)) ((letrec) (letrec-token)) ((emptylist) (emptylist-token));CHANGE to recongnize five new tokens ((cons) (cons-token)) ((null?) (null?-token)) ((car) (car-token)) ((cdr) (cdr-token));end CHANGE (else (identifier-token id))))) (else (source 'get) (case next ((#\-) (scan-after-minus source)) ((#\() (open-parenthesis)) ((#\,) (comma)) ((#\)) (close-parenthesis)) ((#\=) (equals-sign)) (else (report-mislexical-error next)))))))) ;; report-mislexical-error : Char -> (aborts the computation) (define report-mislexical-error (lambda (bad-character) (eopl:error 'scanner "A token may not begin with the ~a character.~%" bad-character))) ;; As we collect the characters that make up a numeral, ;; we'll need to compute its value. ;; The digit-value procedure assists this process. ;; It returns the natural number denoted by any given digit character ;; (in ASCII; to make this work for Unicode would be much trickier). ;; digit-value : Char -> Int (define digit-value (let ((zero-slot (char->integer #\0))) (lambda (digit) (- (char->integer digit) zero-slot)))) ;; The get-numeral-value procedure ;; consumes an uninterrupted sequence of digit characters ;; from the character source ;; and computes and returns the value of the numeral ;; that they compose. ;; It is a precondition of this procedure ;; that the next available character is a digit character. ;; get-numeral-value : Character-source -> Natural-number (define get-numeral-value (lambda (source) (let loop ((value (digit-value (source 'get)))) (if (or (source 'at-end?) (not (char-numeric? (source 'peek)))) value (loop (+ (* value 10) (digit-value (source 'get)))))))) ;; As we collect the characters that make up a keyword or an identifier, ;; we'll need to know where to stop. ;; The successor? predicate tests whether a given character ;; can appear in a keyword or identifier ;; (after the initial position, which must be a letter). ;; The characters permitted here ;; are letters, digits, hyphens, and question marks. ;; successor? : Char -> Bool (define successor? (lambda (ch) (or (char-alphabetic? ch) (char-numeric? ch) (char=? ch #\-) (char=? ch #\?)))) ;; The get-identifier procedure consumes an uninterrupted sequence ;; of letters, digits, and question marks ;; from the character source, ;; assembles them into a string, ;; and constructs and returns the symbol ;; named by that string. ;; It is a precondition of this procedure ;; that the next available character is a letter. ;; get-identifier : Character-source -> Sym (define get-identifier (lambda (source) (let loop ((reversed-name (list (source 'get)))) (if (or (source 'at-end?) (not (successor? (source 'peek)))) (string->symbol (list->string (reverse reversed-name))) (loop (cons (source 'get) reversed-name)))))) ;; The scan-after-minus procedure determines whether ;; a minus sign that has just been discovered (and consumed) ;; is a subtraction operator ;; or the beginning of a numeral, ;; then consumes the rest of the token's text (if any) ;; from the character source and returns the token. ;; scan-after-minus : Character-source -> Token (define scan-after-minus (lambda (source) (if (source 'at-end?) (minus-sign) (let ((next (source 'peek))) (if (char-numeric? next) (numeral-token (- (get-numeral-value source))) (minus-sign)))))))) ;;; Copyright (C) 2009, 2015, 2019 John David Stone ;;; This program is free software. ;;; You may redistribute it and/or modify it ;;; under the terms of the GNU General Public License ;;; as published by the Free Software Foundation -- ;;; either version 3 of the License, ;;; or (at your option) any later version. ;;; This program is distributed ;;; in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY -- ;;; without even the implied warranty ;;; of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ;;; See the GNU General Public License for more details. ;;; You should have received a copy ;;; of the GNU General Public License ;;; along with this program. ;;; If not, it is available on the World Wide Web ;;; at https://www.gnu.org/licenses/gpl.html. ;;; The extention to add lists as an expressed value and coresponding tests, if any, ;;; are copytight (C) 2019 by Samantha Orion Hafner and are likewise released ;;; under the Creative Commons Attribution-Noncommercial 3.0 Unported License.
false
509d75bf32461b11c63beb8a6cdf424f91938b90
ae0d7be8827e8983c926f48a5304c897dc32bbdc
/nekoie/okurairi/gauche-old01/cgi-test.cgi
a871ce9272509521d670bf607e4ed111fc6d34e5
[]
no_license
ayamada/copy-of-svn.tir.jp
96c2176a0295f60928d4911ce3daee0439d0e0f4
101cd00d595ee7bb96348df54f49707295e9e263
refs/heads/master
2020-04-04T01:03:07.637225
2015-05-28T07:00:18
2015-05-28T07:00:18
1,085,533
3
2
null
2015-05-28T07:00:18
2010-11-16T15:56:30
Scheme
UTF-8
Scheme
false
false
447
cgi
cgi-test.cgi
#!/usr/local/bin/gosh ;;; coding: euc-jp ;;; -*- scheme -*- ;;; vim:set ft=scheme ts=8 sts=2 sw=2 et: ;;; $Id$ (add-load-path "/home/nekoie/Gauche-tir/trunk") (add-load-path "/home/nekoie/nekoie/tmp/scheme") (add-load-path ".") ;(use tir.cgi-framework) (use cgi-framework) (define (hoge) #f) (define *cgi-framework* (make <cgi-framework> :session-dbm-path "./hoge" )) (define (main args) (cgi-framework-main *cgi-framework*))
false
50195bbadde38741d27c5c6b9014ec159e725e40
37c751fc27e790303b84730013217d1c8cbb60cc
/s48/continuation-data-type/continuation-data-type.scm
e48333471d2dbeab663dc1bf743156fc14fecfde
[ "LicenseRef-scancode-public-domain", "BSD-3-Clause" ]
permissive
gitGNU/gnu_sunterlib
e82df45894f0075e2ad2df88ce6edf0f1704c6a0
96d443b55c990506e81f2c893e02245b7e2b5f4c
refs/heads/master
2023-08-06T09:32:59.463520
2017-03-07T14:31:05
2017-03-07T14:31:05
90,394,267
0
0
null
null
null
null
UTF-8
Scheme
false
false
523
scm
continuation-data-type.scm
;; Taken from Marc Feeley's paper "A Better API for First-Class Continunations" ;; The version from the workshop proceedings contains a bug in continuation-capture. ;; This is the corrected version. (define (continuation-capture receiver) ((call-with-current-continuation (lambda (cont) (lambda () (receiver cont)))))) (define (continuation-graft cont thunk) (cont thunk)) (define (continuation-return cont . returned-values) (continuation-graft cont (lambda () (apply values returned-values))))
false
a98f494bfa5f3df21d3580072b69736dd8901d39
f59b3ca0463fed14792de2445de7eaaf66138946
/section-5/5_11a.scm
ca0390e48ab5e30ecd899eca680391ff066ca518
[]
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
1,463
scm
5_11a.scm
(load "./register") (define fib (make-machine '(n val continue) (list (list '< <) (list '- -) (list '+ +)) '(test-fib (assign continue (label fib-done)) fib-loop (test (op <) (reg n) (const 2)) (branch (label immediate-answer)) ;; Fib(n-1)を計算するよう設定 (save continue) (assign continue (label afterfib-n-1)) (save n) ; nの昔の値を退避 (assign n (op -) (reg n) (const 1)); nを n-1 に変える (goto (label fib-loop)) ; 再帰呼出しを実行 afterfib-n-1 ; 戻った時 Fib(n-1)はvalにある (restore n) (restore continue) ;; Fib(n-2)を計算するよう設定 (assign n (op -) (reg n) (const 2)) (save continue) (assign continue (label afterfib-n-2)) (save val) ; Fib(n-1)を退避 (goto (label fib-loop)) afterfib-n-2 (restore n) ; 戻った時Fib(n-2)の値はvalにある (restore continue) (assign val ; Fib(n-1)+Fib(n-2) (op +) (reg val) (reg n)) (goto (reg continue)) ; 呼出し側に戻る. 答えはvalにある immediate-answer (assign val (reg n)) ; 基底の場合: Fib(n)=n (goto (reg continue)) fib-done))) (set-register-contents! fib 'n 4) (start fib) (get-register-contents fib 'val)
false
15ac17a71ba02f360aebc2c0f39e19a62f761a80
eb4c9cc6036c985065fec67e3116115be1d7fc12
/lisp/tests/extensions.scm
b8bcb4653acad05e9accb8eadc9ad7b904975c97
[ "MIT" ]
permissive
jorendorff/cell-gc
31d751a1d854248bb894a43c4d10a951e203cd6a
1d73457069b93b6af1adbfeb390ba1fbae8a291a
refs/heads/master
2021-07-12T10:24:19.880104
2017-12-13T16:11:33
2017-12-13T16:11:33
49,678,729
62
5
null
2017-11-14T19:35:38
2016-01-14T22:12:58
Pascal
UTF-8
Scheme
false
false
299
scm
extensions.scm
(assert (symbol? (gensym))) (assert (gensym? (gensym))) (assert (not (eq? (gensym) (gensym)))) (define s (gensym)) (define t (string->symbol (symbol->string s))) (assert (gensym? s)) (assert (not (gensym? t))) (assert (not (eq? s t))) (assert (not (gensym? 'ponies))) (assert (not (gensym? '())))
false
c2ab5e230fe54595e7f6dd203453eddd49233482
97c107938d7a7b80d319442337316604200fc0ae
/engine/game.ss
2ce7abd4140b3141e86fb9fb05a12371f8c0228d
[]
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,872
ss
game.ss
#lang scheme (require "../lib/tree.ss" "../lib/posn.ss" "../copy-obj/this-class.ss" "placement.ss" "level-gen.ss" "timed.ss" "mob.ss" "char.ss" "ai.ss" "tile.ss" "obj.ss" "map.ss") (define game<%> (interface () increment-game-time game-time get-char update-char update-map tick)) (define game% (class%* object% (game<%>) (init-slot [time 0] map objs) (define/public (increment-game-time) (copy [time (add1 time)])) (define/public (game-time) time) (define/public (update-map new-map) (copy [map new-map])) (define/public (get-char) (findf (lambda (o) (is-a? o char%)) (timed-elements objs))) (define/public (update-char new-char) (copy [objs (timed-map (lambda (o) (if (is-a? o char%) new-char o)) objs)])) (define/public (tick) (match (progress objs this) [#f #f] [(struct progress-result (new-objs new-this updated-posns)) (define changed updated-posns) (define final-this (send new-this update-objs (timed-map (lambda (a) ; XXX Generalize this to be a general event delivery mechanism for everyone (if (is-a? a char%) (let-values ([(a-changed new-a) (send a look (get-field map new-this))]) (set! changed (tree-union changed a-changed)) new-a) a)) new-objs))) (cons changed final-this)])) (define/public (update-objs new-objs) (copy [objs new-objs])) (super-new))) (define clock% (timed-mixin (class%* object% (timed<%>) (define/public (speed) NORMAL-SPEED) (define/public (activate game) (make-activate-result NORMAL-SPEED this (send game increment-game-time) tree-empty empty)) (super-new)))) (define (initial-game #:rows map-rows #:cols map-cols) (define map0 (generate-map map-rows map-cols)) (define the-clock (new clock%)) (define-values (char-posn map2 ps) (place map0)) (define-values (char map3) (create&place map2 char% char-posn)) (define qi (make-timed-objects char)) (define qj (for/fold ([q qi]) ([p (in-list ps)]) (register-timed-object q p))) (define the-game (new game% [map map3] [objs (register-timed-object qj the-clock)])) the-game) (provide/contract [initial-game (#:rows exact-positive-integer? #:cols exact-positive-integer? . -> . (is-a?/c game%))])
false
fe4ebdae4546ef0b0a57035440df11f6061d1092
3508dcd12d0d69fec4d30c50334f8deb24f376eb
/v8/src/runtime/conpar.scm
3688cf9d64f68ca6a7a7a89767c6171b0db12b0e
[]
no_license
barak/mit-scheme
be625081e92c2c74590f6b5502f5ae6bc95aa492
56e1a12439628e4424b8c3ce2a3118449db509ab
refs/heads/master
2023-01-24T11:03:23.447076
2022-09-11T06:10:46
2022-09-11T06:10:46
12,487,054
12
1
null
null
null
null
UTF-8
Scheme
false
false
43,701
scm
conpar.scm
#| -*-Scheme-*- Copyright (c) 1988-1999 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. |# ;;;; Continuation Parser ;;; package: (runtime continuation-parser) (declare (usual-integrations)) (define number-of-argument-registers 15) ;;;; Stack Frames (define-structure (stack-frame (constructor make-stack-frame (type elements dynamic-state block-thread-events? interrupt-mask history previous-history-offset previous-history-control-point offset previous-type %next)) (conc-name stack-frame/)) (type #f read-only #t) (elements #f read-only #t) (dynamic-state #f read-only #t) (block-thread-events? #f read-only #t) (interrupt-mask #f read-only #t) (history #f read-only #t) (previous-history-offset #f read-only #t) (previous-history-control-point #f read-only #t) (offset #f read-only #t) ;; PREVIOUS-TYPE is the stack-frame-type of the frame above this one ;; on the stack (closer to the stack's top). In at least two cases ;; we need to know this information. (previous-type #f read-only #t) ;; %NEXT is either a parser-state object or the next frame. In the ;; former case, the parser-state is used to compute the next frame. %next (properties (make-1d-table) read-only #t)) (define (stack-frame/reductions stack-frame) (let ((history (stack-frame/history stack-frame))) (if (eq? history undefined-history) '() (history-reductions history)))) (define undefined-history "no history") (define (stack-frame/next stack-frame) (let ((next (stack-frame/%next stack-frame))) (if (parser-state? next) (let ((next (parse-one-frame next))) (set-stack-frame/%next! stack-frame next) next) next))) (define-integrable (continuation/first-subproblem continuation) (stack-frame/skip-non-subproblems (continuation->stack-frame continuation))) (define (stack-frame/next-subproblem stack-frame) (if (stack-frame/subproblem? stack-frame) (let ((stack-frame (stack-frame/next stack-frame))) (and stack-frame (stack-frame/skip-non-subproblems stack-frame))) (stack-frame/skip-non-subproblems stack-frame))) (define-integrable (stack-frame/length stack-frame) (vector-length (stack-frame/elements stack-frame))) (define (stack-frame/ref stack-frame index) (let ((elements (stack-frame/elements stack-frame))) (let ((length (vector-length elements))) (if (< index length) (map-reference-trap (lambda () (vector-ref elements index))) (stack-frame/ref (stack-frame/next stack-frame) (- index length)))))) (define-integrable (stack-frame/real-return-address stack-frame) (stack-frame/ref stack-frame 0)) (define (stack-frame/return-code stack-frame) (let ((return-address (stack-frame/real-return-address stack-frame))) (and (interpreter-return-address? return-address) (return-address/code return-address)))) (define-integrable (stack-frame/compiled-code? stack-frame) (compiled-return-address? (stack-frame/real-return-address stack-frame))) (define (stack-frame/compiled-interrupt? frame) ;; returns the interrupted compiled entry or #F (let ((type (stack-frame/type frame))) (and (or (eq? type stack-frame-type/interrupt-compiled-procedure) (eq? type stack-frame-type/interrupt-compiled-expression) (eq? type stack-frame-type/interrupt-compiled-return-address)) (vector-ref (stack-frame/elements frame) 4)))) (define (stack-frame/return-address frame) (or (stack-frame/compiled-interrupt? frame) (stack-frame/real-return-address frame))) (define (stack-frame/subproblem? stack-frame) (if (stack-frame/stack-marker? stack-frame) (stack-marker-frame/repl-eval-boundary? stack-frame) (stack-frame-type/subproblem? (stack-frame/type stack-frame)))) (define (stack-frame/resolve-stack-address frame address) (let loop ((frame frame) (offset (stack-address->index address (stack-frame/offset frame)))) (let ((length (stack-frame/length frame))) (if (< offset length) (values frame offset) (loop (stack-frame/next frame) (- offset length)))))) (define (stack-frame/skip-non-subproblems stack-frame) (let ((type (stack-frame/type stack-frame))) (cond ((and (stack-frame/subproblem? stack-frame) (not (and (eq? type stack-frame-type/compiled-return-address) (eq? (stack-frame/real-return-address stack-frame) continuation-return-address)))) stack-frame) ((stack-frame/stack-marker? stack-frame) (let loop ((stack-frame stack-frame)) (let ((stack-frame (stack-frame/next stack-frame))) (and stack-frame (if (stack-frame/subproblem? stack-frame) (stack-frame/next-subproblem stack-frame) (loop stack-frame)))))) (else (let ((stack-frame (stack-frame/next stack-frame))) (and stack-frame (stack-frame/skip-non-subproblems stack-frame))))))) (define continuation-return-address) (define (initialize-special-frames!) (set! continuation-return-address (let ((stack-frame (call-with-current-continuation (lambda (k) k (call-with-current-continuation continuation/first-subproblem))))) (and (eq? (stack-frame/type stack-frame) stack-frame-type/compiled-return-address) (stack-frame/real-return-address stack-frame)))) unspecific) ;;;; Parser (define-structure (parser-state (constructor make-parser-state) (conc-name parser-state/)) (dynamic-state #f read-only #t) (block-thread-events? #f read-only #t) (interrupt-mask #f read-only #t) (history #f read-only #t) (previous-history-offset #f read-only #t) (previous-history-control-point #f read-only #t) (element-stream #f read-only #t) (n-elements #f read-only #t) (next-control-point #f read-only #t) (previous-type #f read-only #t)) (define (continuation->stack-frame continuation) (parse-control-point (continuation/control-point continuation) (continuation/dynamic-state continuation) (continuation/block-thread-events? continuation) #f)) (define (parse-control-point control-point dynamic-state block-thread-events? type) (let ((element-stream (control-point/element-stream control-point))) (parse-one-frame (make-parser-state dynamic-state block-thread-events? (control-point/interrupt-mask control-point) (let ((history (history-transform (control-point/history control-point)))) (if (and (stream-pair? element-stream) (eq? return-address/reenter-compiled-code (element-stream/head element-stream))) history (history-superproblem history))) (control-point/previous-history-offset control-point) (control-point/previous-history-control-point control-point) element-stream (control-point/n-elements control-point) (control-point/next-control-point control-point) type)))) (define (parse-one-frame state) (define (handle-ordinary stream) (let ((type (identify-stack-frame-type stream))) (let ((length (let ((length (stack-frame-type/length type))) (if (exact-nonnegative-integer? length) length (length stream (parser-state/n-elements state)))))) ((stack-frame-type/parser type) type (list->vector (stream-head stream length)) (make-intermediate-state state length (stream-tail stream length)))))) (let ((the-stream (parser-state/element-stream state))) (if (stream-pair? the-stream) (handle-ordinary the-stream) (let ((control-point (parser-state/next-control-point state))) (and control-point (if (not (zero? (parser-state/n-elements state))) ;; Construct invisible join-stacklets frame. (handle-ordinary (stream return-address/join-stacklets control-point)) (parse-control-point control-point (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (parser-state/previous-type state)))))))) ;;; `make-intermediate-state' is used to construct an intermediate ;;; parser state that is passed to the frame parser. This ;;; intermediate state is identical to `state' except that it shows ;;; `length' items having been removed from the stream. (define (make-intermediate-state state length stream) (let ((previous-history-control-point (parser-state/previous-history-control-point state)) (new-length (- (parser-state/n-elements state) length))) (make-parser-state (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (parser-state/interrupt-mask state) (parser-state/history state) (let ((previous (parser-state/previous-history-offset state))) (if (or previous-history-control-point (>= new-length previous)) previous 0)) previous-history-control-point stream new-length (parser-state/next-control-point state) (parser-state/previous-type state)))) ;;; After each frame parser is done, it either tail recurses into the ;;; parsing loop, or it calls `parser/standard' to produces a new ;;; output frame. The argument `state' is usually what was passed to ;;; the frame parser (i.e. the state that was returned by the previous ;;; call to `make-intermediate-state'). However, several of the ;;; parsers change the values of some of the components of `state' ;;; before calling `parser/standard' -- for example, ;;; RESTORE-INTERRUPT-MASK changes the `interrupt-mask' component. (define (parse/standard-next type elements state history? force-pop?) (let ((n-elements (parser-state/n-elements state)) (history-subproblem? (stack-frame-type/history-subproblem? type)) (history (parser-state/history state)) (previous-history-offset (parser-state/previous-history-offset state)) (previous-history-control-point (parser-state/previous-history-control-point state))) (make-stack-frame type elements (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (parser-state/interrupt-mask state) (if history? history undefined-history) previous-history-offset previous-history-control-point (+ (vector-length elements) n-elements) (parser-state/previous-type state) (make-parser-state (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (parser-state/interrupt-mask state) (if (or force-pop? history-subproblem?) (history-superproblem history) history) previous-history-offset previous-history-control-point (parser-state/element-stream state) n-elements (parser-state/next-control-point state) type)))) (define (parser/standard type elements state) (parse/standard-next type elements state (and (stack-frame-type/history-subproblem? type) (stack-frame-type/subproblem? type)) #f)) (define (parser/standard-compiled type elements state) (parse/standard-next type elements state (let ((stream (parser-state/element-stream state))) (and (stream-pair? stream) (eq? (identify-stack-frame-type stream) stack-frame-type/return-to-interpreter))) #f)) (define (parser/apply type elements state) (let ((valid-history? (not (let ((stream (parser-state/element-stream state))) (and (stream-pair? stream) (eq? return-address/reenter-compiled-code (element-stream/head stream))))))) (parse/standard-next type elements state valid-history? valid-history?))) (define (parser/restore-interrupt-mask type elements state) (parser/standard type elements (make-parser-state (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (vector-ref elements 1) (parser-state/history state) (parser-state/previous-history-offset state) (parser-state/previous-history-control-point state) (parser-state/element-stream state) (parser-state/n-elements state) (parser-state/next-control-point state) (parser-state/previous-type state)))) (define (parser/restore-history type elements state) (parser/standard type elements (make-parser-state (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (parser-state/interrupt-mask state) (history-transform (vector-ref elements 1)) (vector-ref elements 2) (vector-ref elements 3) (parser-state/element-stream state) (parser-state/n-elements state) (parser-state/next-control-point state) (parser-state/previous-type state)))) (define-integrable code/special-compiled/internal-apply 0) (define-integrable code/special-compiled/restore-interrupt-mask 1) (define-integrable code/special-compiled/stack-marker 2) (define-integrable code/special-compiled/compiled-code-bkpt 3) (define-integrable code/interrupt-restart 4) (define-integrable code/restore-regs 5) (define-integrable code/apply-compiled 6) (define-integrable code/continue-linking 7) (define (parser/restore-regs type elements state) (let ((code (vector-ref elements 1))) (if (not (and (fix:fixnum? code) (fix:= code code/restore-regs))) (error "Unknown special compiled frame" code)) (parse/standard-next type elements state #f #f))) (define (parser/special-compiled type elements state) (let ((code (vector-ref elements 1))) (cond ((fix:= code code/special-compiled/internal-apply) (parse/standard-next type elements state #f #f)) ((fix:= code code/special-compiled/restore-interrupt-mask) (parser/%stack-marker (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (vector-ref elements 2) type elements state)) ((fix:= code code/special-compiled/stack-marker) (parser/stack-marker type elements state)) ((or (fix:= code code/special-compiled/compiled-code-bkpt) (fix:= code code/restore-regs) (fix:= code code/apply-compiled) (fix:= code code/continue-linking)) (parse/standard-next type elements state #f #f)) (else (error "Unknown special compiled frame" code))))) (define (parser/interrupt-compiled-procedure type elements state) ;; At this point the parsing state and frame elements may be incorrect. ;; This happens when some of the procedure's parameters are passed ;; on the stack: the return address pushed by the assembly level ;; interrupt handler is earlier in the stack. We handle this by ;; making an element vector with the continuation `squeezed' out, ;; and putting the return address back on the stream. ;; Stack: [deeper to shallower]. ;; `|' mark values in ELEMENTS (last to first) ;; BEFORE AFTER ;; [continuation's closed values] [same] ;; stack argument continuation ;; | ... | stack argument ;; | stack argument | ... ;; | continuation (return-address) | stack argument ;; | register argument | same from here on ;; | register argument | .... ;; | register argument ;; | <other saved data> (0 words) ;; | entry (that which has been interrupted) ;; | number of arguments (register+stack) ;; | number words of other saved data (0) ;; | REFLECT_CODE_INTERRUPT_RESTART ;; | reflect_to_interface (let ((entry (vector-ref elements 4))) (let ((frame-size (compiled-procedure-frame-size entry)) (saved-words (vector-ref elements 3)) (extra-words (vector-ref elements 2))) (if (or (not (= 0 extra-words)) (not (= frame-size (- saved-words 1)))) (error "Inconsistent interrupt frame" frame-size elements)) (if (<= frame-size number-of-argument-registers) (parser/standard type elements state) (let* ((ret-addr-offset (+ number-of-argument-registers extra-words 5)) (element-stream (parser-state/element-stream state)) (extra-argument (stream-first element-stream)) (return-address (vector-ref elements ret-addr-offset))) (let ((elements* (vector-append (vector-head elements ret-addr-offset) (vector-tail elements (+ ret-addr-offset 1)) (vector extra-argument))) (stream* (cons-stream return-address (stream-rest element-stream)))) (parser/standard type elements* (make-parser-state (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (parser-state/interrupt-mask state) (parser-state/history state) (parser-state/previous-history-offset state) (parser-state/previous-history-control-point state) stream* (parser-state/n-elements state) (parser-state/next-control-point state) (parser-state/previous-type state))))))))) (define (parser/interrupt-compiled-return-address type elements state) (parser/standard type elements state)) (define (parser/stack-marker type elements state) (call-with-values (lambda () (if (eq? type stack-frame-type/stack-marker) (values (vector-ref elements 1) (vector-ref elements 2)) (values (vector-ref elements 2) (vector-ref elements 3)))) (lambda (marker-type marker-instance) (let ((continue (lambda (dynamic-state block-thread-events? interrupt-mask) (parser/%stack-marker dynamic-state block-thread-events? interrupt-mask type elements state)))) (cond ((eq? marker-type %translate-to-state-point) (continue (merge-dynamic-state (parser-state/dynamic-state state) marker-instance) (parser-state/block-thread-events? state) (parser-state/interrupt-mask state))) ((eq? marker-type set-interrupt-enables!) (continue (parser-state/dynamic-state state) (parser-state/block-thread-events? state) marker-instance)) ((eq? marker-type with-thread-events-blocked) (continue (parser-state/dynamic-state state) marker-instance (parser-state/interrupt-mask state))) (else (continue (parser-state/dynamic-state state) (parser-state/block-thread-events? state) (parser-state/interrupt-mask state)))))))) (define (parser/%stack-marker dynamic-state block-thread-events? interrupt-mask type elements state) (parser/standard type elements (make-parser-state dynamic-state block-thread-events? interrupt-mask (parser-state/history state) (parser-state/previous-history-offset state) (parser-state/previous-history-control-point state) (parser-state/element-stream state) (parser-state/n-elements state) (parser-state/next-control-point state) (parser-state/previous-type state)))) (define (stack-frame/stack-marker? stack-frame) (or (%stack-frame/stack-marker? stack-frame) (and (stack-frame/special-compiled? stack-frame) (let ((code (vector-ref (stack-frame/elements stack-frame) 1))) (or (fix:= code/special-compiled/restore-interrupt-mask code) (fix:= code/special-compiled/stack-marker code)))))) (define (stack-marker-frame/type stack-frame) (if (%stack-frame/stack-marker? stack-frame) (vector-ref (stack-frame/elements stack-frame) 1) (vector-ref (stack-frame/elements stack-frame) 2))) (define (stack-marker-frame/instance stack-frame) (if (%stack-frame/stack-marker? stack-frame) (vector-ref (stack-frame/elements stack-frame) 2) (vector-ref (stack-frame/elements stack-frame) 3))) (define-integrable (%stack-frame/stack-marker? stack-frame) (eq? stack-frame-type/stack-marker (stack-frame/type stack-frame))) (define-integrable (stack-frame/special-compiled? stack-frame) (eq? stack-frame-type/special-compiled (stack-frame/type stack-frame))) (define (stack-frame/repl-eval-boundary? stack-frame) (and (stack-frame/stack-marker? stack-frame) (stack-marker-frame/repl-eval-boundary? stack-frame))) (define-integrable (stack-marker-frame/repl-eval-boundary? stack-frame) (eq? with-repl-eval-boundary (stack-marker-frame/type stack-frame))) ;;;; Unparser (define (stack-frame->continuation stack-frame) (make-continuation 'REENTRANT (stack-frame->control-point stack-frame) (stack-frame/dynamic-state stack-frame) #f)) (define (stack-frame->control-point stack-frame) (with-values (lambda () (unparse/stack-frame stack-frame)) (lambda (element-stream next-control-point) (make-control-point #f 0 (stack-frame/interrupt-mask stack-frame) (let ((history (stack-frame/history stack-frame))) (if (eq? history undefined-history) (fixed-objects-item 'DUMMY-HISTORY) (history-untransform history))) (stack-frame/previous-history-offset stack-frame) (stack-frame/previous-history-control-point stack-frame) (if (stack-frame/compiled-code? stack-frame) (cons-stream return-address/reenter-compiled-code (cons-stream #f element-stream)) element-stream) next-control-point)))) (define (unparse/stack-frame stack-frame) (if (eq? (stack-frame/real-return-address stack-frame) return-address/join-stacklets) (values (stream) (vector-ref (stack-frame/elements stack-frame) 1)) (with-values (lambda () (let ((next (stack-frame/%next stack-frame))) (cond ((stack-frame? next) (unparse/stack-frame next)) ((parser-state? next) (values (parser-state/element-stream next) (parser-state/next-control-point next))) (else (values (stream) #f))))) (lambda (element-stream next-control-point) (values ((stack-frame-type/stream (stack-frame/type stack-frame)) (stack-frame/elements stack-frame) element-stream) next-control-point))))) (define (subvector->stream* elements start end stream-tail) (let loop ((index start)) (if (< index end) (cons-stream (vector-ref elements index) (loop (1+ index))) stream-tail))) (define (stream/standard elements deeper-stream) (subvector->stream* elements 0 (vector-length elements) deeper-stream)) (define (stream/interrupt-compiled elements deeper-stream) ;; Re-assemble stream with the continuation in the place where the ;; interrupt-hander would have saved it. (let* ((size (vector-length elements)) (join (min (+ number-of-argument-registers 5) size)) (cont (stream-first deeper-stream)) (deeper-stream* (stream-rest deeper-stream))) (subvector->stream* elements 0 join ; standard prefix + register arguments (cons-stream cont (subvector->stream* elements join size ; stack arguments deeper-stream*))))) (define return-address/join-stacklets) (define return-address/reenter-compiled-code) ;;;; Special Frame Lengths (define (length/combination-save-value stream offset) offset (+ 3 (system-vector-length (element-stream/ref stream 1)))) (define ((length/application-frame index missing) stream offset) offset (+ index 1 (- (object-datum (element-stream/ref stream index)) missing))) (define (length/compiled-return-address stream offset) (let ((entry (element-stream/head stream))) (let ((frame-size (compiled-continuation/next-continuation-offset entry))) (if frame-size (1+ frame-size) (stack-address->index (element-stream/ref stream 1) offset))))) (define (length/restore-regs stream offset) ;; return address is reflect-to-interface offset (let ((code (element-stream/ref stream 1))) (if (and (fix:fixnum? code) (fix:= code code/restore-regs)) (let ((guess (fix:+ 3 (object-datum (element-stream/ref stream 2))))) (let loop ((guess* guess)) (if (compiled-return-address? (element-stream/ref stream guess*)) (+ guess* 1) (loop (+ guess 1))))) (error "length/resyspecial-compiled: Unknown code" code)))) (define (length/special-compiled stream offset) ;; return address is reflect-to-interface offset (let ((code (element-stream/ref stream 1))) (define (default) (error "length/special-compiled: Unknown code" code)) (cond ((not (fix:fixnum? code)) (default)) ((fix:= code code/special-compiled/internal-apply) ;; Very infrequent! (fix:+ 3 (object-datum (element-stream/ref stream 2)))) ((fix:= code code/special-compiled/restore-interrupt-mask) 3) ((fix:= code code/special-compiled/stack-marker) 4) ((fix:= code code/special-compiled/compiled-code-bkpt) ;; Very infrequent! (let ((fsize (compiled-code-address/frame-size (element-stream/ref stream 2)))) (if (not fsize) 5 (fix:+ 5 fsize)))) ((fix:= code code/interrupt-restart) (default)) ((fix:= code code/restore-regs) (default)) ((fix:= code code/apply-compiled) ;; Stream[2] is code entry point, [3] is frame size (+ 3 (object-datum (element-stream/ref stream 3)))) ((fix:= code code/continue-linking) ;; return code, reflect code, entry size, original count, ;; block, environment, offset, last header offset,sections, ;; return address (fix:- 10 1)) (else (default))))) (define (length/interrupt-compiled-common stream extra) (let ((homes-saved (object-datum (element-stream/ref stream 2))) (regs-saved (object-datum (element-stream/ref stream 3)))) ;; . There are five words in every interrupt frame: Return code/address, ;; reflect code, homes saved, regs saved and entry point. ;; . One of the regs saved is the continuation (even if the interrupted ;; entry is itself a continuation, in which case it is #F), ;; which counts as part of the next frame, hence the -1. (We ;; are not worried about which one it is at this point.) (define fixed-words (+ 5 -1)) (fix:+ (fix:+ fixed-words extra) (fix:+ homes-saved regs-saved)))) (define (length/interrupt-compiled-return-address stream offset) offset (let ((entry (stream-ref stream 4))) (let ((frame-size (compiled-continuation/next-continuation-offset entry))) (if frame-size (length/interrupt-compiled-common stream (+ frame-size 1)) (error "Unexpected dynamic link" stream))))) (define (length/interrupt-compiled-procedure stream offset) offset (length/interrupt-compiled-common stream 0)) (define (compiled-code-address/frame-size cc-address) (cond ((not (compiled-code-address? cc-address)) (error "compiled-code-address/frame-size: Unexpected object" cc-address)) ((compiled-return-address? cc-address) (let ((offset (compiled-continuation/next-continuation-offset cc-address))) (and offset (fix:+ offset 1)))) ((compiled-procedure? cc-address) (fix:+ (compiled-procedure-frame-size cc-address) 1)) (else (error "compiled-code-address/frame-size: Unexpected object" cc-address)))) (define (verify paranoia-index stream offset) (or (zero? paranoia-index) (stream-null? stream) (let* ((type (identify-stack-frame-type stream)) (length (let ((length (stack-frame-type/length type))) (if (exact-nonnegative-integer? length) length (length stream offset)))) (ltail (stream-tail* stream length))) (and ltail (return-address? (element-stream/head ltail)) (verify (-1+ paranoia-index) ltail (+ offset length)))))) (define (stream-tail* stream n) (cond ((or (zero? n) (stream-null? stream)) stream) ((stream-pair? stream) (stream-tail* (stream-cdr stream) (-1+ n))) (else (error "stream-tail*: not a proper stream" stream)))) (define (element-stream/head stream) (if (not (stream-pair? stream)) (error "not a stream-pair" stream)) (map-reference-trap (lambda () (stream-car stream)))) (define-integrable (element-stream/ref stream index) (map-reference-trap (lambda () (stream-ref stream index)))) ;;;; Stack Frame Types (define-structure (stack-frame-type (constructor make-stack-frame-type (code subproblem? history-subproblem? length parser stream)) (conc-name stack-frame-type/)) (code #f read-only #t) (subproblem? #f read-only #t) (history-subproblem? #f read-only #t) (properties (make-1d-table) read-only #t) (length #f read-only #t) (parser #f read-only #t) (stream #f read-only #t)) (define (microcode-return/code->type code) (if (not (< code (vector-length stack-frame-types))) (error "return-code too large" code)) (vector-ref stack-frame-types code)) (define (microcode-return/name->type name) (microcode-return/code->type (microcode-return name))) (define (identify-stack-frame-type stream) (define (interrupt-frame) (let* ((entry (element-stream/ref stream 4)) (type (compiled-entry-type entry))) (case type ((COMPILED-PROCEDURE) stack-frame-type/interrupt-compiled-procedure) ((COMPILED-RETURN-ADDRESS) stack-frame-type/interrupt-compiled-return-address) (else (error "Unexpected interrupted" type stream))))) (let ((return-address (element-stream/head stream))) (cond ((interpreter-return-address? return-address) (let ((code (return-address/code return-address))) (let ((type (microcode-return/code->type code))) (if (not type) (error "return-code has no type" code)) type))) ((compiled-return-address? return-address) (cond ((compiled-continuation/return-to-interpreter? return-address) stack-frame-type/return-to-interpreter) ((compiled-continuation/reflect-to-interface? return-address) (cond ((= (element-stream/ref stream 1) code/interrupt-restart) (interrupt-frame)) ((= (element-stream/ref stream 1) code/restore-regs) stack-frame-type/restore-regs) (else stack-frame-type/special-compiled))) (else stack-frame-type/compiled-return-address))) (else (error "illegal return address" return-address stream))))) (define (initialize-package!) (set! return-address/join-stacklets (make-return-address (microcode-return 'JOIN-STACKLETS))) (set! return-address/reenter-compiled-code (make-return-address (microcode-return 'REENTER-COMPILED-CODE))) (set! stack-frame-types (make-stack-frame-types)) (set! stack-frame-type/hardware-trap (microcode-return/name->type 'HARDWARE-TRAP)) (set! stack-frame-type/stack-marker (microcode-return/name->type 'STACK-MARKER)) (set! stack-frame-type/compiled-return-address (make-stack-frame-type #f #t #f length/compiled-return-address parser/standard-compiled stream/standard)) (set! stack-frame-type/return-to-interpreter (make-stack-frame-type #f #f #t 1 parser/standard stream/standard)) (set! stack-frame-type/restore-regs (make-stack-frame-type #f #t #f length/restore-regs parser/restore-regs stream/standard)) (set! stack-frame-type/special-compiled (make-stack-frame-type #f #t #f length/special-compiled parser/special-compiled stream/standard)) (set! stack-frame-type/interrupt-compiled-procedure (make-stack-frame-type #f #t #f length/interrupt-compiled-procedure parser/interrupt-compiled-procedure stream/interrupt-compiled)) (set! stack-frame-type/interrupt-compiled-return-address (make-stack-frame-type #f #t #f length/interrupt-compiled-return-address parser/interrupt-compiled-return-address stream/interrupt-compiled)) (set! stack-frame-type/interrupt-compiled-expression (make-stack-frame-type #f #t #f 1 parser/standard stream/interrupt-compiled)) (set! word-size (let ((initial (system-vector-length (make-bit-string 1 #f)))) (let loop ((size 2)) (if (= (system-vector-length (make-bit-string size #f)) initial) (loop (1+ size)) (-1+ size))))) (set! continuation-return-address #f) unspecific) (define stack-frame-types) (define stack-frame-type/compiled-return-address) (define stack-frame-type/return-to-interpreter) (define stack-frame-type/restore-regs) (define stack-frame-type/special-compiled) (define stack-frame-type/hardware-trap) (define stack-frame-type/stack-marker) (define stack-frame-type/interrupt-compiled-procedure) (define stack-frame-type/interrupt-compiled-expression) (define stack-frame-type/interrupt-compiled-return-address) (define (make-stack-frame-types) (let ((types (make-vector (microcode-return/code-limit) #f))) (define (stack-frame-type name subproblem? history-subproblem? length parser stream) (let ((code (microcode-return name))) (let ((type (make-stack-frame-type code subproblem? history-subproblem? length parser stream))) (vector-set! types code type) type))) (define (standard-frame name length #!optional parser) (stack-frame-type name #f #f length (if (default-object? parser) parser/standard parser) stream/standard)) (define (standard-subproblem name length) (stack-frame-type name #t #t length parser/standard stream/standard)) (define (non-history-subproblem name length #!optional parser) (stack-frame-type name #t #f length (if (default-object? parser) parser/standard parser) stream/standard)) (standard-frame 'RESTORE-INTERRUPT-MASK 2 parser/restore-interrupt-mask) (standard-frame 'RESTORE-HISTORY 4 parser/restore-history) (standard-frame 'RESTORE-DONT-COPY-HISTORY 4 parser/restore-history) (standard-frame 'STACK-MARKER 3 parser/stack-marker) (standard-frame 'NON-EXISTENT-CONTINUATION 2) (standard-frame 'HALT 2) (standard-frame 'JOIN-STACKLETS 2) (standard-frame 'POP-RETURN-ERROR 2) (standard-frame 'RESTORE-VALUE 2) (standard-subproblem 'IN-PACKAGE-CONTINUE 2) (standard-subproblem 'ACCESS-CONTINUE 2) (standard-subproblem 'PRIMITIVE-COMBINATION-1-APPLY 2) (standard-subproblem 'FORCE-SNAP-THUNK 2) (standard-subproblem 'GC-CHECK 2) (standard-subproblem 'ASSIGNMENT-CONTINUE 3) (standard-subproblem 'DEFINITION-CONTINUE 3) (standard-subproblem 'SEQUENCE-2-SECOND 3) (standard-subproblem 'SEQUENCE-3-SECOND 3) (standard-subproblem 'SEQUENCE-3-THIRD 3) (standard-subproblem 'CONDITIONAL-DECIDE 3) (standard-subproblem 'DISJUNCTION-DECIDE 3) (standard-subproblem 'COMBINATION-1-PROCEDURE 3) (standard-subproblem 'COMBINATION-2-FIRST-OPERAND 3) (standard-subproblem 'EVAL-ERROR 3) (standard-subproblem 'PRIMITIVE-COMBINATION-2-FIRST-OPERAND 3) (standard-subproblem 'PRIMITIVE-COMBINATION-2-APPLY 3) (standard-subproblem 'PRIMITIVE-COMBINATION-3-SECOND-OPERAND 3) (standard-subproblem 'COMBINATION-2-PROCEDURE 4) (standard-subproblem 'REPEAT-DISPATCH 4) (standard-subproblem 'PRIMITIVE-COMBINATION-3-FIRST-OPERAND 4) (standard-subproblem 'PRIMITIVE-COMBINATION-3-APPLY 4) (standard-subproblem 'MOVE-TO-ADJACENT-POINT 6) (standard-subproblem 'COMBINATION-SAVE-VALUE length/combination-save-value) (let ((length (length/application-frame 2 0))) (standard-subproblem 'COMBINATION-APPLY length) (non-history-subproblem 'INTERNAL-APPLY length parser/apply) (non-history-subproblem 'INTERNAL-APPLY-VAL length parser/apply)) (let ((compiler-frame (lambda (name length) (stack-frame-type name #f #t length parser/standard stream/standard))) (compiler-subproblem (lambda (name length) (stack-frame-type name #t #t length parser/standard stream/standard)))) (let ((length (length/application-frame 4 0))) (compiler-subproblem 'COMPILER-LOOKUP-APPLY-TRAP-RESTART length) (compiler-subproblem 'COMPILER-OPERATOR-LOOKUP-TRAP-RESTART length)) (compiler-frame 'COMPILER-INTERRUPT-RESTART 3) (compiler-frame 'COMPILER-LINK-CACHES-RESTART 8) (compiler-frame 'REENTER-COMPILED-CODE 2) (compiler-subproblem 'COMPILER-ACCESS-RESTART 4) (compiler-subproblem 'COMPILER-ASSIGNMENT-RESTART 5) (compiler-subproblem 'COMPILER-ASSIGNMENT-TRAP-RESTART 5) (compiler-subproblem 'COMPILER-DEFINITION-RESTART 5) (compiler-subproblem 'COMPILER-LOOKUP-APPLY-RESTART (length/application-frame 4 1)) (compiler-subproblem 'COMPILER-REFERENCE-RESTART 4) (compiler-subproblem 'COMPILER-REFERENCE-TRAP-RESTART 4) (compiler-subproblem 'COMPILER-SAFE-REFERENCE-RESTART 4) (compiler-subproblem 'COMPILER-SAFE-REFERENCE-TRAP-RESTART 4) (compiler-subproblem 'COMPILER-UNASSIGNED?-RESTART 4) (compiler-subproblem 'COMPILER-UNASSIGNED?-TRAP-RESTART 4) (compiler-subproblem 'COMPILER-UNBOUND?-RESTART 4) (compiler-subproblem 'COMPILER-ERROR-RESTART 3)) (non-history-subproblem 'HARDWARE-TRAP length/hardware-trap) types)) ;;;; Hardware trap parsing (define-integrable hardware-trap/frame-size 9) (define-integrable hardware-trap/signal-index 1) (define-integrable hardware-trap/signal-name-index 2) (define-integrable hardware-trap/code-index 3) (define-integrable hardware-trap/stack-index 4) (define-integrable hardware-trap/state-index 5) (define-integrable hardware-trap/pc-info1-index 6) (define-integrable hardware-trap/pc-info2-index 7) (define-integrable hardware-trap/extra-info-index 8) (define (length/hardware-trap stream offset) (let ((state (element-stream/ref stream hardware-trap/state-index)) (stack-recovered? (element-stream/ref stream hardware-trap/stack-index))) (if (not stack-recovered?) hardware-trap/frame-size (let ((after-header (stream-tail stream hardware-trap/frame-size))) (case state ((1) ;; primitive (let* ((primitive (element-stream/ref stream hardware-trap/pc-info1-index)) (arity (primitive-procedure-arity primitive)) (nargs (if (negative? arity) (element-stream/ref stream hardware-trap/pc-info2-index) arity))) (if (return-address? (element-stream/ref after-header nargs)) (+ hardware-trap/frame-size nargs) (- (heuristic (stream-tail after-header nargs) (+ hardware-trap/frame-size nargs offset)) offset)))) ((0 2 3 4 5) ;; unknown, cc, probably cc, builtin, or utility (- (heuristic after-header (+ hardware-trap/frame-size offset)) offset)) (else (error "length/hardware-trap: Unknown state" state))))))) (define (heuristic stream offset) (if (or (stream-null? stream) (and (return-address? (element-stream/head stream)) (verify 2 stream offset))) offset (heuristic (stream-cdr stream) (1+ offset)))) (define (hardware-trap-frame? frame) (and (stack-frame? frame) (eq? (stack-frame/type frame) stack-frame-type/hardware-trap))) (define (hardware-trap-frame/code frame) (guarantee-hardware-trap-frame frame) (let ((code (stack-frame/ref frame hardware-trap/code-index))) (cond ((pair? code) (cdr code)) ((string? code) code) (else #f)))) (define (guarantee-hardware-trap-frame frame) (if (not (hardware-trap-frame? frame)) (error "guarantee-hardware-trap-frame: invalid" frame))) (define (hardware-trap-frame/print-registers frame) (guarantee-hardware-trap-frame frame) (let ((block (stack-frame/ref frame hardware-trap/extra-info-index))) (if block (let ((nregs (- (system-vector-length block) 2))) (print-register block 0 "pc") (print-register block 1 "sp") (let loop ((i 0)) (if (< i nregs) (begin (print-register block (+ 2 i) (string-append "register " (number->string i))) (loop (1+ i))))))))) (define (print-register block index name) (let ((value (let ((bit-string (bit-string-allocate word-size))) (read-bits! block (* word-size (1+ index)) bit-string) (bit-string->unsigned-integer bit-string)))) (newline) (write-string " ") (write-string name) (write-string " = ") (write-string (number->string value 16)))) (define word-size) (define (hardware-trap-frame/print-stack frame) (guarantee-hardware-trap-frame frame) (let ((elements (let ((elements (stack-frame/elements frame))) (subvector->list elements hardware-trap/frame-size (vector-length elements))))) (if (null? elements) (begin (newline) (write-string ";; Empty stack")) (begin (newline) (write-string ";; Bottom of the stack") (for-each (lambda (element) (newline) (write-string " ") (write element)) (reverse elements)) (newline) (write-string ";; Top of the stack"))))) (define (write-hex value) (if (< value #x10) (write value) (begin (write-string "#x") (write-string (number->string value #x10))))) (define (hardware-trap-frame/describe frame long?) (guarantee-hardware-trap-frame frame) (let ((name (stack-frame/ref frame hardware-trap/signal-name-index)) (state (stack-frame/ref frame hardware-trap/state-index))) (if (not name) (write-string "User microcode reset") (let ((code (stack-frame/ref frame hardware-trap/code-index))) (write-string "Hardware trap ") (write-string name) (write-string " (") (if (and (pair? code) (cdr code)) (write-string (cdr code)) (begin (write-string "code = ") (write-hex (if (pair? code) (car code) code)))) (write-string ")"))) (if long? (case state ((0) ; unknown (write-string " at an unknown location.")) ((1) ; primitive (write-string " within ") (write (stack-frame/ref frame hardware-trap/pc-info1-index))) ((2) ; compiled code (let ((block (stack-frame/ref frame hardware-trap/pc-info1-index)) (offset (stack-frame/ref frame hardware-trap/pc-info2-index))) (write-string " at offset ") (write-hex offset) (newline) (write-string "within ") (write block) (let ((descriptor (compiled-code-block/dbg-descriptor block))) (if descriptor (begin (write-string " (") (display (dbg-locator/file (car descriptor))) (flush-output) ; incase following is slow... (let ((name (compiled-code-block/name block offset))) (if name (begin (write-string " ") (display name)))) (write-string ")")))))) ((3) ; probably compiled-code (write-string " at an unknown compiled-code location.")) ((4) ; builtin (i.e. hook) (let* ((index (stack-frame/ref frame hardware-trap/pc-info1-index)) (name ((ucode-primitive builtin-index->name 1) index))) (if name (begin (write-string " in assembly-language utility ") (write-string name)) (begin (write-string " in unknown assembly-language utility ") (write-hex index))))) ((5) ; utility (let* ((index (stack-frame/ref frame hardware-trap/pc-info1-index)) (name ((ucode-primitive utility-index->name 1) index))) (if name (begin (write-string " in compiled-code utility ") (write-string name)) (begin (write-string " in unknown compiled-code utility ") (write-hex index))))) (else (error "hardware-trap/describe: Unknown state" state))))))
false
9ef6594716f0461f6454021ba174fbcdac4ff2ce
8f1401b60f1a0b73577a80129ec7fe7027a27eba
/src/utility/gen-id.scm
89ed8e9656a3599b784ed55351677c560c7bbe29
[ "Apache-2.0" ]
permissive
bluelight1324/geometric-algebra
347409d5ef023ab1109b4d6079ef1e73721ebc0b
fdc9332a4f5e2dd526c55bbaa57fd043d78f40d1
refs/heads/main
2023-04-18T08:41:57.832044
2021-05-05T20:08:21
2021-05-05T20:08:21
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
420
scm
gen-id.scm
(library (utility gen-id) (export gen-id) (import (rnrs (6))) (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)))))) )
false
da32e2127dd6f251c3f3daadcaeb3fc935f5f7de
5355071004ad420028a218457c14cb8f7aa52fe4
/3.3/e-3.13.scm
e547885c8e38188e6b2efd0b9e39294e55a002ea
[]
no_license
ivanjovanovic/sicp
edc8f114f9269a13298a76a544219d0188e3ad43
2694f5666c6a47300dadece631a9a21e6bc57496
refs/heads/master
2022-02-13T22:38:38.595205
2022-02-11T22:11:18
2022-02-11T22:11:18
2,471,121
376
90
null
2022-02-11T22:11:19
2011-09-27T22:11:25
Scheme
UTF-8
Scheme
false
false
805
scm
e-3.13.scm
(load "3.3.scm") ; Exercise 3.13. Consider the following make-cycle procedure, which ; uses the last-pair procedure defined in exercise 3.12: (define (make-cycle x) (set-cdr! (last-pair x) x) x) ; Draw a box-and-pointer diagram that shows the structure z created by (define z (make-cycle (list 'a 'b 'c))) ; What happens if we try to compute (last-pair z)? ; ------------------------------------------------------------ (load "../helpers.scm") ; cycle will make this kind of structure ; ; z ---> | a | | -> | b | | -> | c | | -| ; ^ | ; |-----------------------------------| ; ; ; So, it will make link from last to first element. ; ; This can not return last pair, since it will loop forever, given the ; condition in (last-pair) procedure ;
false
1fb229d4a6cf21abec91f3dfbc3092ffaa55bfa0
dd4cc30a2e4368c0d350ced7218295819e102fba
/vendored_parsers/tree-sitter-racket/queries/tags.scm
3fb7e9cdcf4bfbeb1aafe3542a26ecea11a97a1f
[ "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
199
scm
tags.scm
(list . (symbol) @reference._define (#match? @reference._define "^(define|define/contract)$") . (list . (symbol) @name) @definition.function) (list . (symbol) @reference.call)
false
d3e15b6cd0e5f9857bacca39c7254d0de079cbc9
86a7d9ada5a7978cc6b3dc51c73a61abf82a6023
/src/parse-tree-test.ss
b4e475509726dfaf8797b97f69d36d1ad133c5b9
[]
no_license
themetaschemer/rackscad
6b249559ae9dbced4c12d3562284a41ab0265fe4
8915919c24bb93a63d13546610871bd11a823411
refs/heads/master
2021-06-26T07:31:04.723127
2017-09-15T15:32:41
2017-09-15T15:32:41
103,672,527
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,429
ss
parse-tree-test.ss
(module+ test (check-equal? (2d-point 3 4) (point 3 4 0)) (check-true (2d-object? (circle-object 4))) (check-false (2d-object? (sphere-object 4))) (check-false (2d-object? #f)) (check-false (3d-object? (circle-object 4))) (check-true (3d-object? (sphere-object 4))) (check-false (3d-object? #f)) (check-equal? (height-map-with-args "somefile" (list (sphere-object 4)) #:center #t #:convexity 12) (height-map-transform "somefile"(list (sphere-object 4)) #t 12)) (check-equal? (linear-extrude-with-args (list (sphere-object 4)) #:height 4 #:center #t #:convexity 13 #:twist #f #:slices 10 #:scale 1.0) (linear-extrude-transform (list (sphere-object 4)) 4 #t 13 #f 10 1.0)) (check-equal? (rotate-extrude-with-args (list (sphere-object 4)) #:angle 20 #:convexity 12) (rotate-extrude-transform (list (sphere-object 4)) 20 12)) (check-true (extrude? (rotate-extrude-with-args (list (sphere-object 4)) #:angle 20 #:convexity 12))) (check-false (extrude? #f)) (check-true (extrude? (linear-extrude-with-args (list (sphere-object 4)) #:height 4 #:center #t #:convexity 13 #:twist #f #:slices 10 #:scale 1.0))) (check-true (transform? (basic-transform "name" 0 0 0 (list (sphere-object 4))))) (check-true (transform? (basic-color-transform 0 0 0 1.0 (list (sphere-object 4))))) (check-true (transform? (offset-transform 0 0 0 (list (sphere-object 4))))) (check-true (transform? (affine-transform '((0 0 0 1) (0 0 0 1) (0 0 0 1)) (list (sphere-object 4))))) )
false
c66174058c837810dc2c2bbaf180a98a7f8d7c69
2543c5f8bef7548ce2ea5e805b74df61b953528a
/tutorial-thursday-3/fsm-bit.scm
02cc37434fe88a5dafc8cb0ccc01a9384ca06f0c
[ "MIT" ]
permissive
edhowland/tutorial_transcripts
4776ca9ffd62bcbc71bc888a7c462bbd6ff4ac21
1a2c3ce46253790a1488a9a3e945531ecef2e774
refs/heads/master
2020-03-25T12:28:23.089618
2018-11-27T19:20:58
2018-11-27T19:20:58
143,778,009
1
0
null
null
null
null
UTF-8
Scheme
false
false
491
scm
fsm-bit.scm
;;; fsm-bit.scm (define fsm-bit (lambda (str) (define fsm-aux (lambda (state str) (if (null? str) (state 'end) (fsm-aux (state (car str)) (cdr str))) )) (fsm-aux (letrec ( [S0 (lambda (bit) (case bit [0 S0] [1 S1] [else 'accept]) )] [S1 (lambda (bit) (case bit [0 S2] [1 S0] [else 'reject] ) )] [S2 (lambda (bit) (case bit [0 S1] [1 S2] [else 'reject] ) )] ) S0 ) str) ))
false
1862023853f213e856441d9744c7504aec16c0a9
424b80e2c2a1829f8815378dd08ed6b6021310f7
/exams/02/variant-b/task-1.scm
44e3079dbe30baef4ec042f6913e5869d9030d48
[ "MIT" ]
permissive
fmi-lab/fp-elective-2017
b8238b413f346f6e74a02af043293d27822c9ce2
e88d5c0319b6d03c0ecd8a12a2856fb1bf5dcbf3
refs/heads/master
2021-09-06T22:01:16.421169
2018-02-12T09:53:52
2018-02-12T09:53:52
106,176,573
7
3
MIT
2018-01-15T15:00:40
2017-10-08T13:02:09
Scheme
UTF-8
Scheme
false
false
933
scm
task-1.scm
(require rackunit rackunit/text-ui) (define (for-all? p? l) (foldl (lambda (x acc) (and (p? x) acc)) #t l)) (define (extremum ll) (define minimums (map (lambda (l) (apply min l)) ll)) (define maximums (map (lambda (l) (apply max l)) ll)) (define (all-extrema-same-as? x) (for-all? (lambda (min-max) (or (= (car min-max) x) (= (cdr min-max) x))) (map cons minimums maximums))) (cond ((null? ll) 0) ((all-extrema-same-as? (car minimums)) (car minimums)) ((all-extrema-same-as? (car maximums)) (car maximums)) (else 0))) (define extremum-tests (test-suite "Tests for extremum" (check = (extremum '((1 2 3 2) (3 5) (3 3) (1 1 3 3))) 3) (check = (extremum '((1 2 3 2) (1 3 5) (0 1) (1 1 3 3))) 1) (check = (extremum '((0 0 3 2) (0 3 5) (0 1) (1 1 0 3))) 0) (check = (extremum '((1 2 3 2) (2 3 5) (3 3) (2 2 3 3))) 0))) (run-tests extremum-tests)
false
2d7e7133b6d793db3e26a1205a9320c64afcafc4
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/runtime/compiler-services/is-volatile.sls
f137ce0473fbfbec3202c8ff4d78ce59b4c6d74a
[]
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
277
sls
is-volatile.sls
(library (system runtime compiler-services is-volatile) (export is? is-volatile?) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Runtime.CompilerServices.IsVolatile a)) (define (is-volatile? a) (clr-is System.Runtime.CompilerServices.IsVolatile a)))
false
55cdfa5c6dd2f673591747e4981f0ea05e06ab0d
4b480cab3426c89e3e49554d05d1b36aad8aeef4
/chapter-03/ex3.52-falsetru.scm
032819f1d733a611ec49c2b9aaf509839b9744dd
[]
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
1,008
scm
ex3.52-falsetru.scm
#lang racket/base (require "stream-base-falsetru.scm") (define (stream-enumerate-interval low high) (if (> low high) the-empty-stream (cons-stream low (stream-enumerate-interval (+ low 1) high)))) (define (stream-filter pred stream) (cond ((stream-null? stream) the-empty-stream) ((pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))) (else (stream-filter pred (stream-cdr stream))))) (define sum 0) (define (accum x) (set! sum (+ x sum)) sum) (define seq (stream-map accum (stream-enumerate-interval 1 20))) (define y (stream-filter even? seq)) (define z (stream-filter (lambda (x) (= (remainder x 5) 0)) seq)) (stream-ref y 7) (display-stream z) ; memoized delay ; ; 136 ; ; 10 ; 15 ; 45 ; 55 ; 105 ; 120 ; 190 ; 210'done ; ; sum -> 210 ; non-memoized delay ; ; 162 ; ; 15 ; 180 ; 230 ; 305'done ; sum -> 362
false
c3f7eb951eb6ddb817c9d8b9b00ca916b8c815bd
6c6cf6e4b77640825c2457e54052a56d5de6f4d2
/test/let.scm
4fe29b743bff564e1d5316f3ddd17d5b41ddd2da
[]
no_license
leonacwa/sicp
a469c7bc96e0c47e4658dccd7c5309350090a746
d880b482d8027b7111678eff8d1c848e156d5374
refs/heads/master
2018-12-28T07:20:30.118868
2015-02-07T16:40:10
2015-02-07T16:40:10
11,738,761
0
0
null
null
null
null
UTF-8
Scheme
false
false
130
scm
let.scm
(let ((x 2) (y 5)) (let* ((x 6)(z (+ x y))) ;此时x的值已为6,所以z的值应为11,如此最后的值为66 (* z x)))
false
8505ce1add001e4b01178cb1acea2e03c7b80e5a
bdcc255b5af12d070214fb288112c48bf343c7f6
/autodiff/stochastic-constraints.sls
a725f5caff9bf73c68ee10eaaa88d37f0f740fe1
[]
no_license
xaengceilbiths/chez-lib
089af4ab1d7580ed86fc224af137f24d91d81fa4
b7c825f18b9ada589ce52bf5b5c7c42ac7009872
refs/heads/master
2021-08-14T10:36:51.315630
2017-11-15T11:43:57
2017-11-15T11:43:57
109,713,952
5
1
null
null
null
null
UTF-8
Scheme
false
false
8,353
sls
stochastic-constraints.sls
#!chezscheme ;Thursday 20 May 2010 ; ;Jeffrey Mark Siskind ;School of Electrical and Computer Engineering ;Purdue University ;465 Northwestern Avenue ;West Lafayette IN 47907-2035 USA ;voice: 765/496-3197 ;fax: 765/494-6440 ;[email protected] ;http://engineering.purdue.edu/~qobi ; ;The entire contents of this directory copyright 2010 Purdue University. All ;rights reserved. ; ;These are some AD (Automatic Differentiation) tools for both forward ;and reverse mode written for R6RS Scheme. They run under Ikarus and ;PLT Scheme. Also included are some experimental packages to support ;nondeterministic and stochastic programming, including constraint ;satisfaction problems. ; ;This code is completely unsupported. ; ;It is licensed under the GPL v2 or later, see the enclosed file COPYING. ; ;This material is based upon work supported by the National Science ;Foundation under Grant No. 0438806. ;Any opinions, findings, and conclusions or recommendations expressed in ;this material are those of the author(s) and do not necessarily reflect ;the views of the National Science Foundation. ;; Packaged for R7RS Scheme by Peter Lane, 2017 (library (autodiff stochastic-constraints) (export set-stochastic-strategy! create-distribution-variable distribution-variable-distribution stochastic-solution assert-stochastic-constraint!) (import (scheme base) (autodiff QobiScheme) (autodiff stochastic-scheme)) (begin (define *strategy* #f) (define-record-type <distribution-variable> (make-distribution-variable distribution demons) distribution-variable? (distribution distribution-variable-distribution distribution-variable-distribution-set!) (demons distribution-variable-demons distribution-variable-demons-set!)) (define (set-stochastic-strategy! strategy) (set! *strategy* strategy)) (define (distribution-variable-distribution-local-set! distribution-variable distribution) (let ((distribution (distribution-variable-distribution distribution-variable))) (upon-bottom (distribution-variable-distribution-set! distribution-variable distribution))) (distribution-variable-distribution-set! distribution-variable distribution)) (define (distribution-variable-demons-local-set! distribution-variable demons) (let ((demons (distribution-variable-demons distribution-variable))) (upon-bottom (distribution-variable-demons-set! distribution-variable demons))) (distribution-variable-demons-set! distribution-variable demons)) (define (create-distribution-variable distribution) (let ((distribution (coalesce-duplicates distribution))) (when (null? distribution) (bottom)) (make-distribution-variable distribution '()))) (define (restrict-distribution! d distribution) (when (null? distribution) (bottom)) (when (< (length distribution) (length (distribution-variable-distribution d))) (distribution-variable-distribution-local-set! d distribution) (for-each (lambda (demon) (demon)) (distribution-variable-demons d)))) (define (bound? d) (null? (rest (distribution-variable-distribution d)))) (define (binding d) (car (first (distribution-variable-distribution d)))) (define (stochastic-solution ds) (let loop ((ds ds) (xs '())) (if (null? ds) (reverse xs) (let ((pair (draw-pair (distribution-variable-distribution (first ds))))) (restrict-distribution! (first ds) (list pair)) (loop (rest ds) (cons (first pair) xs)))))) (define (some-element predicate d) (some (lambda (pair) (predicate (car pair))) (distribution-variable-distribution d))) (define (one-element predicate d) (one (lambda (pair) (predicate (car pair))) (distribution-variable-distribution d))) (define (the-element predicate d) (list (find-if (lambda (pair) (predicate (car pair))) (distribution-variable-distribution d)))) (define (the-elements predicate d) (remove-if-not (lambda (pair) (predicate (car pair))) (distribution-variable-distribution d))) (define (attach-demon! demon d) (distribution-variable-demons-local-set! d (cons demon (distribution-variable-demons d))) (demon)) (define (assert-constraint-efd! constraint ds) (for-each (lambda (d) (attach-demon! (lambda () (when (every bound? ds) (unless (apply constraint (map binding ds)) (bottom)))) d)) ds)) (define (assert-constraint-fc! constraint ds) (for-each (lambda (d) (attach-demon! (lambda () (when (one (lambda (d) (not (bound? d))) ds) (let* ((i (position-if (lambda (d) (not (bound? d))) ds)) (d (list-ref ds i))) (unless (some-element (lambda (x) (apply constraint (map-indexed (lambda (d j) (if (= j i) x (binding d))) ds))) d) (bottom))))) d)) ds)) (define (assert-constraint-vp! constraint ds) (for-each (lambda (d) (attach-demon! (lambda () (when (one (lambda (d) (not (bound? d))) ds) (let* ((i (position-if (lambda (d) (not (bound? d))) ds)) (d (list-ref ds i))) (when (one-element (lambda (x) (apply constraint (map-indexed (lambda (d j) (if (= j i) x (binding d))) ds))) d) (restrict-distribution! d (the-element (lambda (x) (apply constraint (map-indexed (lambda (d j) (if (= j i) x (binding d))) ds))) d)))))) d)) ds)) (define (assert-constraint-gfc! constraint ds) (for-each (lambda (d) (attach-demon! (lambda () (when (one (lambda (d) (not (bound? d))) ds) (let* ((i (position-if (lambda (d) (not (bound? d))) ds)) (d (list-ref ds i))) (restrict-distribution! d (the-elements (lambda (x) (apply constraint (map-indexed (lambda (d j) (if (= j i) x (binding d))) ds))) d))))) d)) ds)) (define (assert-constraint-ac! constraint ds) (for-each (lambda (d) (attach-demon! (lambda () (for-each-indexed (lambda (d i) (restrict-distribution! d (the-elements (lambda (x) (let loop ((ds ds) (xs '()) (j 0)) (if (null? ds) (apply constraint (reverse xs)) (if (= j i) (loop (rest ds) (cons x xs) (+ j 1)) (some-element (lambda (pair) (loop (rest ds) (cons (car pair) xs) (+ j 1))) (first ds)))))) d))) ds)) d)) ds)) (define (assert-stochastic-constraint! constraint . ds) (case *strategy* ((efd) (assert-constraint-efd! constraint ds)) ((fc) (assert-constraint-efd! constraint ds) (assert-constraint-fc! constraint ds)) ((vp) (assert-constraint-efd! constraint ds) (assert-constraint-fc! constraint ds) (assert-constraint-vp! constraint ds)) ((gfc) (assert-constraint-efd! constraint ds) (assert-constraint-gfc! constraint ds)) ((ac) (assert-constraint-ac! constraint ds)) (else (error #f "Unrecognized strategy")))) ))
false
ddd71c657eea8720ac3402871bed3ecb4009ebc1
c95b424d826780d088a1e797db26717c8b335669
/mouseedit.scm
590c0ca428e428d6b273bbc98e823af336ec161f
[]
no_license
kdltr/ezd
c6bb38ef25c22030f09dc4be9bc2bdec2a575242
2e372a159903d674d29b5b3f32e560d35fcac397
refs/heads/master
2021-01-13T17:02:40.005029
2020-01-26T11:09:23
2020-01-26T11:11:28
76,651,078
7
1
null
null
null
null
UTF-8
Scheme
false
false
15,176
scm
mouseedit.scm
;;; ezd - easy drawing for X11 displays. ;;; ;;; The procedures in this module implement a mouse based editor for use inside ;;; a TEXT-DRAWING. In order to test the utility of attributes, all ;;; communication with the text drawing is via attributes. ;* Copyright 1990-1993 Digital Equipment Corporation ;* All Rights Reserved ;* ;* Permission to use, copy, and modify this software and its documentation is ;* hereby granted only under the following terms and conditions. Both the ;* above copyright notice and this permission notice must appear in all copies ;* of the software, derivative works or modified versions, and any portions ;* thereof, and both notices must appear in supporting documentation. ;* ;* Users of this software agree to the terms and conditions set forth herein, ;* and hereby grant back to Digital a non-exclusive, unrestricted, royalty-free ;* right and license under any changes, enhancements or extensions made to the ;* core functions of the software, including but not limited to those affording ;* compatibility with other hardware or software environments, but excluding ;* applications which incorporate this software. Users further agree to use ;* their best efforts to return to Digital any such changes, enhancements or ;* extensions that they make and inform Digital of noteworthy uses of this ;* software. Correspondence should be provided to Digital at: ;* ;* Director of Licensing ;* Western Research Laboratory ;* Digital Equipment Corporation ;* 250 University Avenue ;* Palo Alto, California 94301 ;* ;* This software may be distributed (but not offered for sale or transferred ;* for compensation) to third parties, provided such third parties agree to ;* abide by the terms and conditions of this notice. ;* ;* THE SOFTWARE IS PROVIDED "AS IS" AND DIGITAL EQUIPMENT CORP. DISCLAIMS ALL ;* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF ;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT ;* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL ;* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR ;* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ;* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS ;* SOFTWARE. ;;; When a TEXT-DRAWING is created, the following procedure is called to ;;; install mouse based editting. (define (mouse-edit-init drawing object options) (let* ((read-only (memq 'read-only options)) (current-window #f) (first-line #f) (last-line #f) (slider #f) (button1 #f) (button1down-line #f) (button1down-char #f) (cursor-line 0) (cursor-char 0) (selection #f) (begin-line 0) (begin-char 0) (end-line 0) (end-char 0) (undo-cursor #f) (undo-text #f)) ;;; Change cursor on drawing entry and exit. Find out viewed lines ;;; and slider name on entry. (define (enter) (when (not current-window) (set! current-window *user-event-window*) (let ((view (get-attribute drawing object `(view ,current-window)))) (set! first-line (car view)) (set! last-line (cadr view)) (set! slider (caddr view))) (set! button1 #f) (ezd `(save-cursor ,current-window) `(set-cursor ,current-window XC_XTERM)))) (define (exit) (when (and current-window (or (not (eq? (car *user-event-misc*) current-window)) (not (eq? (cadr *user-event-misc*) drawing)))) (ezd `(restore-cursor ,current-window)) (set! current-window #f))) ;;; Covert the mouse position in the current event to the cursor ;;; position stored here. Note that the screen cursor is not ;;; updated at this time. (define (mouse->cursor) (let* ((line-char-text (get-attribute drawing object `(xy->line-char-text ,*user-event-x* ,*user-event-y*))) (line (car line-char-text)) (char (cadr line-char-text)) (text (caddr line-char-text))) (set! cursor-line line) (set! cursor-char (if (and (positive? char) (eq? char (string-length text)) (eq? (string-ref text (- char 1)) #\newline)) (- char 1) char)))) ;;; Query the drawing for the current cursor position. If the ;;; cursor is not visibile in the current window, then scroll it to ;;; make it visible. (define (read-cursor) (let ((line-char (get-attribute drawing object 'cursor))) (set! cursor-line (car line-char)) (set! cursor-char (cadr line-char)) (if (not (<= first-line cursor-line last-line)) (let ((newfirst (if (< cursor-line first-line) cursor-line (+ first-line (- cursor-line last-line))))) (set! last-line (+ last-line (- newfirst first-line))) (set! first-line newfirst) (if slider (set-attributes slider 'slider `(value ,newfirst))) (set-attributes drawing object '(mouse-edit) `(scroll ,current-window ,newfirst)))))) ;;; Mouse button 1 going down sets the cursor and clears any ;;; current selection. (define (button1down) (mouse->cursor) (set! button1down-line cursor-line) (set! button1down-char cursor-char) (set! selection #f) (set! button1 #t) (set-attributes drawing object '(mouse-edit) `(cursor ,cursor-line ,cursor-char) '(highlight))) ;;; Motion with mouse button 1 down causes the cursor to move and ;;; starts/extends the current selection. Completion of the ;;; selection causes the selection to be copied to the X cut buffer ;;; when in READ-ONLY mode. (define (motion-button1up) (if button1 (let ((event *user-event-xevent*)) (mouse->cursor) (set! button1 *mouse-button1*) (extend-selection cursor-line cursor-char) (if (and read-only (not button1)) (cut/copy #f (xevent-xbutton-time event)))))) ;;; The current selection is extended by the following function. The ;;; cursor is placed at the end of the selection. If the selection ;;; turns out to be null when the button comes up, it disappears. (define (extend-selection line char) (if (lc<? button1down-line button1down-char line char) (let* ((lc (inc-line-char drawing object line char #f -1)) (new-line (car lc)) (new-char (cadr lc))) (set! begin-line button1down-line) (set! begin-char button1down-char) (set! end-line new-line) (set! end-char new-char)) (let* ((lc (inc-line-char drawing object button1down-line button1down-char #f -1)) (new-line (car lc)) (new-char (cadr lc))) (set! begin-line line) (set! begin-char char) (set! end-line new-line) (set! end-char new-char))) (if (lc=? line char button1down-line button1down-char) (begin (set! selection #f) (set! cursor-line line) (set! cursor-char char) (set-attributes drawing object '(mouse-edit) `(cursor ,line ,char) '(highlight))) (let ((lc (inc-line-char drawing object end-line end-char #f 1))) (set! cursor-line (car lc)) (set! cursor-char (cadr lc)) (set! selection #t) (set-attributes drawing object '(mouse-edit) `(cursor ,cursor-line ,cursor-char) `(highlight ,begin-line ,begin-char ,end-line ,end-char))))) ;;; Keyboard input is handled here. (define (keypress) (let* ((key (car *user-event-misc*)) (keysym (cadr *user-event-misc*)) (ascii-code (if (equal? key "") 0 (char->integer (string-ref key 0)))) (key-state (xevent-xkey-state *user-event-xevent*)) (time (xevent-xkey-time *user-event-xevent*))) (cond (read-only (ezd '(bell))) ((or (eq? ascii-code 8) ;;; control-h (eq? ascii-code 127));;; backspace (if selection (delete-selection) (delete-before-cursor))) ((eq? ascii-code 13) ;;; return (delete-selection) (set-attributes drawing object '(mouse-edit) `(insert ,cursor-line ,cursor-char ,(list->string '(#\newline)))) (read-cursor) (unless (zero? cursor-char) (set! cursor-line (+ cursor-line 1)) (set! cursor-char 0) (set-attributes drawing object '(mouse-edit) `(cursor ,cursor-line ,cursor-char)) (read-cursor))) ((not (zero? (bit-and key-state MOD1MASK))) (cond ((equal? key "z") (undo)) ((equal? key "x") (cut/copy #t time)) ((equal? key "c") (cut/copy #f time)) ((equal? key "v") (paste)) (else (ezd '(bell))))) ((or (and (string<=? " " key) (string<=? key "~")) (eq? ascii-code 9)) ;;; tab (delete-selection) (set-attributes drawing object '(mouse-edit) `(insert ,cursor-line ,cursor-char ,key)) (read-cursor)) ((<= XK_LEFT keysym XK_DOWN) (cursor-motion keysym)) ((and (not (<= XK_SHIFT_L keysym XK_HYPER_R)) (not (= keysym XK_MULTI_KEY))) (ezd '(bell)))))) ;;; Delete the currently selected text. (define (delete-selection) (when selection (set! selection #f) (set! undo-cursor (list begin-line begin-char)) (set! undo-text (selection->string)) (set-attributes drawing object '(mouse-edit) '(highlight) `(delete ,begin-line ,begin-char ,end-line ,end-char)) (read-cursor))) ;;; Delete the character behind the cursor. (define (delete-before-cursor) (when (lc>? cursor-line cursor-char 0 0) (if (zero? cursor-char) (cursor-motion XK_LEFT)) (cursor-motion XK_LEFT) (set-attributes drawing object '(mouse-edit) `(delete ,cursor-line ,cursor-char ,cursor-line ,cursor-char)) (read-cursor) (if (zero? cursor-char) (cursor-motion XK_LEFT)))) ;;; Undo the last edit command. (define (undo) (when undo-cursor (set-attributes drawing object '(mouse-edit) `(cursor ,@undo-cursor) `(insert ,@undo-cursor ,undo-text) '(highlight)) (set! undo-cursor #f) (set! undo-text #f))) ;;; Return a string containing the current selection. (define (selection->string) (define cut-buffer #f) (let loop ((i begin-line) (len 0)) (if (<= i end-line) (let* ((whole-line (get-attribute drawing object `(text-line ,i))) (line (if (or (< begin-line i end-line) (eq? whole-line "")) whole-line (substring whole-line (if (eq? i begin-line) begin-char 0) (if (eq? i end-line) (min (+ end-char 1) (string-length whole-line)) (string-length whole-line))))) (line-len (string-length line))) (case (and (< i end-line) (positive? line-len) (string-ref line (- line-len 1))) ((#f #\tab #\space #\newline) (loop (+ i 1) (+ line-len len))) ((#\.) (loop (+ i 1) (+ line-len len 2))) (else (loop (+ i 1) (+ line-len len 1)))) (do ((j 0 (+ j 1))) ((= j line-len)) (string-set! cut-buffer (+ j len) (string-ref line j)))) (set! cut-buffer (make-string len #\space)))) cut-buffer) ;;; Cut or copy the current selection to the X selection. (define (cut/copy cut time) (let ((cut-buffer (selection->string))) (xsetselectionowner *dpy* XA_PRIMARY NONE time) (xstorebytes *dpy* (make-locative cut-buffer) (string-length cut-buffer)) (if cut (delete-selection)))) ;;; Paste the current X selection into the document. (define (paste) (let* ((ptr-cnt (make-s32vector 1 0)) (ptr (xfetchbytes *dpy* (make-locative ptr-cnt))) (cnt (s32vector-ref ptr-cnt 0)) (buffer (make-string cnt))) (delete-selection) (move-memory! ptr buffer) (if ptr (xfree ptr)) (set-attributes drawing object '(mouse-edit) `(insert ,cursor-line ,cursor-char ,buffer)) (read-cursor))) ;;; Handle a cursor character. (define (cursor-motion keysym) (let ((line-char (inc-line-char drawing object cursor-line cursor-char (cond ((eq? keysym XK_UP) -1) ((eq? keysym XK_DOWN) 1) (else #f)) (cond ((eq? keysym XK_LEFT) -1) ((eq? keysym XK_RIGHT) 1) (else #f))))) (set! cursor-line (car line-char)) (set! cursor-char (cadr line-char)) (set! selection #f) (set-attributes drawing object '(mouse-edit) `(cursor ,cursor-line ,cursor-char) '(highlight)) (read-cursor))) ;;; Get current cursor position and highlight information from ;;; the drawing. (let ((cursor-line-char (get-attribute drawing object 'cursor)) (l-c-l-c (get-attribute drawing object 'highlight))) (set! cursor-line (car cursor-line-char)) (set! cursor-char (cadr cursor-line-char)) (when (not (negative? (cadr l-c-l-c))) (set! selection #t) (set! begin-line (car l-c-l-c)) (set! begin-char (cadr l-c-l-c)) (set! end-line (caddr l-c-l-c)) (set! end-char (cadddr l-c-l-c)))) ;;; Install event handlers. (ezd '(save-drawing) `(set-drawing ,drawing) `(when * enter ,enter) `(when * exit ,exit) `(when * button1down ,button1down) `(when * motion ,motion-button1up) `(when * button1up ,motion-button1up) `(when * keypress ,keypress) '(restore-drawing)))) ;;; Booleans for comparing line/character positions. (define (lc=? l0 c0 l1 c1) (and (eq? l0 l1) (eq? c0 c1))) (define (lc<? l0 c0 l1 c1) (or (< l0 l1) (and (eq? l0 l1) (< c0 c1)))) (define (lc>? l0 c0 l1 c1) (or (> l0 l1) (and (eq? l0 l1) (> c0 c1)))) (define (lc<=? l0 c0 l1 c1) (not (lc>? l0 c0 l1 c1))) (define (lc>=? l0 c0 l1 c1) (not (lc<? l0 c0 l1 c1))) ;;; Procedure to move a line-character position either a number of lines or a ;;; number of characters. A list consisting of the new line and character ;;; positions is returned. (define (inc-line-char drawing object line char delta-line delta-char) (if delta-line (let* ((line (min (get-attribute drawing object 'lines) (max 0 (+ line delta-line)))) (text (get-attribute drawing object `(text-line ,line))) (text-len (string-length text)) (char (min char text-len))) (list line char)) (let* ((text (get-attribute drawing object `(text-line ,line))) (text-len (string-length text)) (char (+ delta-char char))) (cond ((negative? char) (inc-line-char drawing object line 1000000 -1 #f)) ((<= char text-len) (list line char)) (else (inc-line-char drawing object line 0 1 #f))))))
false
22f0e6c28b2e7caed45d4d21f3f3b9136a799d93
370ebaf71b077579ebfc4d97309ce879f97335f7
/seasonedSchemer/seasonedSchemerCh20.sld
009a05a9b72f8b692fc0e3680d7b7e13ce6a0dab
[]
no_license
jgonis/sicp
7f14beb5b65890a86892a05ba9e7c59fc8bceb80
fd46c80b98c408e3fd18589072f02ba444d35f53
refs/heads/master
2023-08-17T11:52:23.344606
2023-08-13T22:20:42
2023-08-13T22:20:42
376,708,557
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,474
sld
seasonedSchemerCh20.sld
(define-library (seasoned-schemer ch20) (export jeff-ch20) (import (scheme base) (scheme write) (little-schemer ch1) (little-schemer ch4) (little-schemer ch5) (seasoned-schemer ch11)) (begin (define the-empty-table (lambda (name) )) (define lookup (lambda (table name) (table name))) ;; How does extend work? It is a function that receives a name ;; a value and a table, and returns a function that receives another ;; name. If the name passed to the returned function is the same as ;; the name used when extend was first called, we return the value ;; that was passed in when it was called. Otherwise we apply table ;; to the name passed in to the returned function. In this way you ;; can keep adding on the values associated with a name in a table. ;; Each time you call extend you get a new table with a name associated ;; with a value. If this name passed to this new table is not the one it ;; has associated with a value, then it recursively delegates to the ;; table it has inside to see if that table has a value associated with ;; the name and so on, until it reaches the "base" table, or empty table (define extend (lambda (name1 value table) (lambda (name2) (cond ((eq? name1 name2) value) (else (table name2)))))) (define value (lambda (expression) ))))
false
5417ca0d093bae1a3114f6e2c7c9c455acfc057b
8eb21733f83949941fadcb268dd4f0efab594b7f
/100/srfi-104/library-files-utilities/srfi/%3A%104.r6rs-lib
26737fedc5253d923f77952c3b8bc0b3bd4f6f54
[]
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
316
%3A%104.r6rs-lib
#!r6rs (library (srfi :104) (export searched-directories recognized-extensions file-name-component-separator directories-from-env-var extensions-from-env-var library-name->file-name library-file-name-info find-library-file-names) (import (srfi :104 library-files-utilities)))
false
9097f5eac92c3cd0744900269321ab63ab06cb0c
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine/unity-engine/audio-low-pass-filter.sls
f382172d396e446bc834743c23838bf97b79aef3
[]
no_license
futsuki/ironscheme-port
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
4e7a81b0fbeac9a47440464988e53fb118286c54
refs/heads/master
2016-09-06T17:13:11.462593
2015-09-26T18:20:40
2015-09-26T18:20:40
42,757,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,320
sls
audio-low-pass-filter.sls
(library (unity-engine audio-low-pass-filter) (export new is? audio-low-pass-filter? cutoff-frequency-get cutoff-frequency-set! cutoff-frequency-update! lowpass-resonance-q-get lowpass-resonance-q-set! lowpass-resonance-q-update! lowpass-resonace-q-get lowpass-resonace-q-set! lowpass-resonace-q-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new UnityEngine.AudioLowPassFilter a ...))))) (define (is? a) (clr-is UnityEngine.AudioLowPassFilter a)) (define (audio-low-pass-filter? a) (clr-is UnityEngine.AudioLowPassFilter a)) (define-field-port cutoff-frequency-get cutoff-frequency-set! cutoff-frequency-update! (property:) UnityEngine.AudioLowPassFilter cutoffFrequency System.Single) (define-field-port lowpass-resonance-q-get lowpass-resonance-q-set! lowpass-resonance-q-update! (property:) UnityEngine.AudioLowPassFilter lowpassResonanceQ System.Single) (define-field-port lowpass-resonace-q-get lowpass-resonace-q-set! lowpass-resonace-q-update! (property:) UnityEngine.AudioLowPassFilter lowpassResonaceQ System.Single))
true
387e360c1dc9285822c02cb775740a3f21975fd9
92b8d8f6274941543cf41c19bc40d0a41be44fe6
/testsuite/sva40494.scm
b6094c3457a7cb4fd3f4c38cb44ff15d1c326644
[ "MIT" ]
permissive
spurious/kawa-mirror
02a869242ae6a4379a3298f10a7a8e610cf78529
6abc1995da0a01f724b823a64c846088059cd82a
refs/heads/master
2020-04-04T06:23:40.471010
2017-01-16T16:54:58
2017-01-16T16:54:58
51,633,398
6
0
null
null
null
null
UTF-8
Scheme
false
false
260
scm
sva40494.scm
(module-export top-class) (begin (define (bottom proc) (proc)) ) (define (top proc) (bottom (lambda () (proc)))) (define-simple-class top-class () ((frob) (top (lambda () #f)))) (format #t "frob: ~a~%" ((make top-class):frob)) ;; Output: frob: #f
false
63d0214ad27923074862697caebc7b58b778e192
203ad0bd8ae7276ddb4c12041b1644538957c386
/subst/settings.scm
1f0ce1194ab0f3497ec461e1eb0115234be3cca6
[]
no_license
lkuper/relational-research
b432a6a9b76723a603406998dcbe9f0aceace97c
7ab9955b08d2791fe63a08708415ae3f100f6df5
refs/heads/master
2021-01-25T10:07:27.074811
2010-05-15T04:13:07
2010-05-15T04:13:07
2,870,499
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,072
scm
settings.scm
(module settings (name dl-worst-case-assoc build-random-assoc-br choose-size-s choose-var choose-walk choose-birth-record choose-assoc-repr choose-copy-term choose-walk-return) (define name "walk-bst") (define dl-worst-case-assoc #f) (define build-random-assoc-br #f) (define-syntax choose-var (syntax-rules () [(_ var-1 var-2 var-2-k var-2-kd var-bst) var-bst])) (define-syntax choose-walk (syntax-rules () [(_ wassq wbasic wrhs wstep wsref wsreff wtrie wbst wskew wskewd wfb wfb-opt wno-rec-stk wno-rec-stkf wpinch wpinch-s wfoldr) wbst])) (define-syntax choose-size-s (syntax-rules () [(_ size-s-l size-s-t size-s-bst size-s-skew size-s-skew-def) size-s-bst])) (define-syntax choose-birth-record (syntax-rules () [(_ nbr cbr sbr) nbr])) (define-syntax choose-assoc-repr (syntax-rules () [(_ sl dl t b k kd) b])) (define-syntax choose-copy-term (syntax-rules () [(_ n k kd) n])) (define-syntax choose-walk-return (syntax-rules () [(_ sv mv) sv])))
true
f94cd2f398b4d7985139db5aeeb8a85ea39d46ed
37245ece3c767e9434a93a01c2137106e2d58b2a
/src/scheme/process-context.sld
271f002edab26d29a8d16dda2f9badea1ead9686
[ "MIT" ]
permissive
mnieper/unsyntax
7ef93a1fff30f20a2c3341156c719f6313341216
144772eeef4a812dd79515b67010d33ad2e7e890
refs/heads/master
2023-07-22T19:13:48.602312
2021-09-01T11:15:54
2021-09-01T11:15:54
296,947,908
12
0
null
null
null
null
UTF-8
Scheme
false
false
1,402
sld
process-context.sld
;; Copyright © Marc Nieper-Wißkirchen (2020). ;; This file is part of unsyntax. ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation files ;; (the "Software"), to deal in the Software without restriction, ;; including without limitation the rights to use, copy, modify, merge, ;; publish, distribute, sublicense, and/or sell copies of the Software, ;; and to permit persons to whom the Software is furnished to do so, ;; subject to the following conditions: ;; The above copyright notice and this permission notice (including the ;; next paragraph) shall be included in all copies or substantial ;; portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (define-library (scheme process-context) (export command-line emergency-exit exit get-environment-variable get-environment-variables) (import (unsyntax $bootstrap) (unsyntax command-line)))
false
50bca8d6f55b1b677a4cc1bf9576eb81f537098c
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 2/2.3/Ex2.71.scm
7eb047b3e568e5bb0a65a9e849c9f1d1ec68b5c2
[]
no_license
yaowenqiang/SICPBook
ef559bcd07301b40d92d8ad698d60923b868f992
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
refs/heads/master
2020-04-19T04:03:15.888492
2015-11-02T15:35:46
2015-11-02T15:35:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
337
scm
Ex2.71.scm
#lang planet neil/sicp ;; One bit needed for the most frequent symbol while n-1 bits are ;; needed for the least frequent symbol ;; Sample tree is shown below a,b,c,d,e /\ a {b,c,d,e} /\ b {c,d,e} /\ c {d,e} /\ d e
false
e39cb1534d4c3bee85039599d298bd0dc27d855d
074200eeaf6a79a72dd17651fdb471b7c7fbf1b5
/framework/macros.scm
b94ec494a005af6e6cfd8d8d75acbc07f26bf273
[ "MIT" ]
permissive
big-data-europe/mu-query-rewriter
4b687636e39c3eeb12b45c1ababc6b6d331c7289
31da5b908d3c43179fc56c8be3c6d17e406faaa7
refs/heads/master
2018-06-29T12:19:42.584292
2018-05-31T13:31:03
2018-05-31T13:31:03
108,171,918
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,796
scm
macros.scm
(define-syntax timed-let (syntax-rules () ((_ label (let-exp (vars/vals ...) body ...)) (let-values (((ut1 st1) (cpu-time))) (let ((t1 (current-milliseconds))) (let-exp (vars/vals ...) (let-values (((ut2 st2) (cpu-time))) (let ((t2 (current-milliseconds))) (debug-message "~%~A Time [~A]: ~Ams / ~Ams / ~Ams ~%" label (logkey) (- ut2 ut1) (- st2 st1) (- t2 t1)) body ...)))))))) (define-syntax timed (syntax-rules () ((_ label body ...) (let-values (((ut1 st1) (cpu-time))) (let ((t1 (current-milliseconds))) (let ((result body ...)) (let-values (((ut2 st2) (cpu-time))) (let ((t2 (current-milliseconds))) (debug-message "~%~A Time [~A]: ~Ams / ~Ams / ~Ams~%" label (logkey) (- ut2 ut1) (- st2 st1) (- t2 t1)) result)))))))) (define-syntax timed-limit (syntax-rules () ((_ limit label expression body ...) (let-values (((ut1 st1) (cpu-time))) (let ((t1 (current-milliseconds))) (let ((result body ...)) (let-values (((ut2 st2) (cpu-time))) (let ((t2 (current-milliseconds))) (when (> (- ut2 ut1) limit) (debug-message "~%Exceeded time limit for ~A [~A]: ~Ams / ~Ams / ~Ams~%~A~%~%" label (logkey) (- ut2 ut1) (- st2 st1) (- t2 t1) expression)) result)))))))) (define-syntax try-safely (syntax-rules () ((_ label exp body ...) (handle-exceptions exn (begin (log-message "~%==Error ~A== [~A]~%~A~%~%" label (logkey) exp) #f) body ...))))
true
9e7920a514bc35db2d2c2342a2172d26cac58935
c01a4c8a6cee08088b26e2a2545cc0e32aba897b
/medikanren2/etc/config.defaults.scm
1a653ff207df6f0eef7399f8fb4051151d4bac0d
[ "MIT" ]
permissive
webyrd/mediKanren
c8d25238db8afbaf8c3c06733dd29eb2d7dbf7e7
b3615c7ed09d176e31ee42595986cc49ab36e54f
refs/heads/master
2023-08-18T00:37:17.512011
2023-08-16T00:53:29
2023-08-16T00:53:29
111,135,120
311
48
MIT
2023-08-04T14:25:49
2017-11-17T18:03:59
Racket
UTF-8
Scheme
false
false
1,308
scm
config.defaults.scm
;; DO NOT EDIT THIS FILE! ;; Instead, add overrides to: config.scm ( (buffer-size . 100000) (progress-logging-threshold . 1000000) ;; interactive, always, never (update-policy . interactive) (cleanup-policy . interactive) (migrate-policy . interactive) (allow-missing-data-policy . always) ;; biased-interleaving (default), depth-first (search-strategy . #f) ;; These keys have to be in the file to let the configref.rkt library know ;; that the keys exist so they can be populated at runtime. (relation-root-path . relation-root-path-placeholder) (temporary-root-path . temporary-root-path-placeholder) ;; Specify installed databases as a list of symbols, e.g.: ;; (databases . (rtx2-20210204)) ;; ;; Unless more specifically configured, we assume no databases have been installed: (databases . ()) ;; Disable this flag to prevent translator-web-server.rkt ;; and open-api/ from making downstream HTTP requests. Useful ;; for functional CI tests, and for offline development. (trapi-enable-external-requests? . #t) (migrated-to-new-db-versioning . #f) (version-for-database . ( (rtx-kg2 . "20210204") )) ;; Add new configuration options as new association pairs. )
false
aeb28ecc8b7cac3bd2cd26c0d525dec0ad9d7fe0
5780d7dda6a094e35d4adf75ce2cfd6b2458eab6
/worm0101.scm
fbb35922a513cd7075a4d0e6ccd5020c6fe24e65
[]
no_license
Hamayama/Gauche-gl-examples
d780b69c6e4ff5c1b7c57e7ba361cb618ff3070d
2b69b3ca8427365989526d1cd547a4d10a4a4fd8
refs/heads/master
2023-05-11T08:55:20.958306
2023-05-01T11:41:27
2023-05-01T11:43:51
39,393,082
2
0
null
null
null
null
UTF-8
Scheme
false
false
11,335
scm
worm0101.scm
;; -*- coding: utf-8 -*- ;; ;; worm0101.scm ;; 2019-6-19 v1.42 ;; ;; <内容> ;; Gauche-gl を使用した、ワームシミュレータです。 ;; (末尾から移動していくタイプ) ;; 矢印キーかマウスボタン1でカーソルを移動します。 ;; 空腹状態のワームはカーソルを追跡します。 ;; ESCキーを押すと終了します。 ;; (add-load-path "lib" :relative) (add-load-path "model" :relative) (use gl) (use gl.glut) (use gauche.uvector) (use gauche.sequence) (use math.const) (use glmintool) (use gltextscrn) (use glmodelkit) (use glwormkit) ;(use model0501) (define *wait* 20) ; ウェイト(msec) (define *title* "worm0101") ; ウィンドウのタイトル (define *width* 624) ; ウィンドウ上の画面幅(px) (define *height* 480) ; ウィンドウ上の画面高さ(px) (define *vangle* 45) ; 視野角(度) (define *tanvan* (tan (* (/. *vangle* 2) pi/180))) ; 視野角/2のタンジェント(計算用) (define *aratio* (/. *width* *height*)) ; アスペクト比(計算用) (define *wd/2* 520) ; 画面幅/2 (define *ht/2* 400) ; 画面高さ/2 (define *zd/2* 100) ; 画面奥行き/2 (define *minx* (- *wd/2*)) ; X座標の最小値 (define *maxx* *wd/2*) ; X座標の最大値 (define *miny* (- *ht/2*)) ; Y座標の最小値 (define *maxy* *ht/2*) ; Y座標の最大値 (define *cx* 0) ; カーソルのX座標 (define *cy* 0) ; カーソルのY座標 (define *cr* 20) ; カーソルの半径 (define *cd* 8) ; カーソルの移動量 (define *wnum* 2) ; ワームの数 (define *wlen* 8) ; ワームの長さ(関節の数) (define *waku* 4) ; 当たり判定調整用 (define *backcolor* #f32(0.2 0.2 0.2 1.0)) ; 背景色 (define *flatdisp* 0) ; フラット表示(=0:OFF,=1:ON) (define *wormkind* 0) ; ワームの種別(=0:ワーム0101,=1:ワーム0201) ; ; (変更する場合は、ワームクラスの変更も必要) ;; ウィンドウ情報クラスのインスタンス生成 (define *win* (make <wininfo>)) (win-init *win* *width* *height* (* *wd/2* 2) (* *ht/2* 2)) ;; マウス状態管理クラスのインスタンス生成 (define *msinfo* (make <mousestateinfo>)) ;; キー入力状態管理クラスのインスタンス生成 (define *ksinfo* (make <keystateinfo>)) ;; ウェイト時間調整クラスのインスタンス生成 (define *wcinfo* (make <waitcalcinfo> :waittime *wait*)) ;; ワームクラス ;; (ワーム0101クラスを継承) (define-class <worm> (<worm0101>) ((state :init-value 0) ; 状態(=0:追跡中,=1:食事中,=2:ランダム動作中) (count1 :init-value 0) ; 動作カウンタ1 (count2 :init-value 0) ; 動作カウンタ2 (wtime1 :init-value 1000) ; 食事時間(msec) (wtime2 :init-value 8000) ; ランダム動作時間最小値(msec) (wtime3 :init-value 15000) ; ランダム動作時間最大値(msec) (wtime4 :init-value 2000) ; ランダム動作切換時間最小値(msec) (wtime5 :init-value 8000) ; ランダム動作切換時間最大値(msec) )) ;; ワームの初期化 ;; anum 関節の数 ;; x X座標 ;; y Y座標 ;; c 角度(度) (define-method worm-init ((w1 <worm>) (anum <integer>) (x <real>) (y <real>) (c <real>)) (next-method w1 anum x y c)) ;; ワームの目標設定 ;; gx 目標のX座標 ;; gy 目標のY座標 (define-method worm-set-goal ((w1 <worm>) (gx <real>) (gy <real>)) (next-method w1 gx gy)) ;; ワームの目標到達チェック (define-method worm-goal? ((w1 <worm>)) (worm-goal? w1 *waku*)) ;; ワームの移動 (define-method worm-move ((w1 <worm>)) (define state (~ w1 'state)) (define count1 (~ w1 'count1)) (define count2 (~ w1 'count2)) ;; 状態によって場合分け (case state ((0 1) ; 追跡中/食事中 (set! state 0) (worm-set-goal w1 *cx* *cy*) (if (= *wormkind* 0) (%worm-calc-angle w1)) (cond ((worm-goal? w1) (set! state 1) (set! count1 (+ count1 *wait*)) (when (>= count1 (~ w1 'wtime1)) (set! state 2))) (else (if (= *wormkind* 0) (%worm-move-tail w1) ;; 追跡中に10秒経過したら乱数を加算 (%worm-move-front w1 (>= count2 10000))))) (%worm-calc-point w1) ;; 3分で強制移行(永久パターン防止のため) (set! count2 (+ count2 *wait*)) (when (>= count2 180000) (set! state 2)) (when (= state 2) (set! count1 (randint (~ w1 'wtime2) (~ w1 'wtime3))) (set! count2 (randint (~ w1 'wtime4) (~ w1 'wtime5))) (worm-set-goal w1 (randint *minx* *maxx*) (randint *miny* *maxy*)) )) ((2) ; ランダム動作中 (if (= *wormkind* 0) (%worm-calc-angle w1)) (if (worm-goal? w1) (set! count2 0) (if (= *wormkind* 0) (%worm-move-tail w1) (%worm-move-front w1))) (%worm-calc-point w1) (set! count1 (- count1 *wait*)) (set! count2 (- count2 *wait*)) (cond ((<= count1 0) (set! state 0) (set! count1 0) (set! count2 0)) ((<= count2 0) (set! count2 (randint (~ w1 'wtime4) (~ w1 'wtime5))) (worm-set-goal w1 (randint *minx* *maxx*) (randint *miny* *maxy*)) )))) (set! (~ w1 'state) state) (set! (~ w1 'count1) count1) (set! (~ w1 'count2) count2)) ;; ワームの表示 (define-method worm-disp ((w1 <worm>)) (define color (case (~ w1 'state) ((0) (if (= *flatdisp* 0) #f32(0.5 0.0 0.0 1.0) #f32(0.9 0.5 0.2 1.0))) ((1) (if (= *flatdisp* 0) #f32(0.0 0.7 0.3 1.0) #f32(0.0 0.8 0.4 1.0))) ((2) #f32(1.0 1.0 1.0 1.0)))) (define wedge (case (~ w1 'state) ((0) 120) ((1) (randint 0 90)) ((2) 70))) (if (= *flatdisp* 0) (worm-disp w1 color wedge) (worm-disp-flat w1 *win* color wedge))) ;; ワームクラスのインスタンス生成 (define *worms* (make-vector-of-class *wnum* <worm>)) ;; カーソルの表示 (define (disp-cursor) (gl-material GL_FRONT GL_DIFFUSE #f32(1.0 1.0 0.0 1.0)) (gl-material GL_FRONT GL_AMBIENT #f32(0.5 0.5 0.0 1.0)) (gl-push-matrix) (gl-translate *cx* *cy* 0) (cross-cursor *cr* (/. *cr* 10)) (gl-pop-matrix)) ;; カーソルの移動 (define (move-cursor) (cond ((mouse-button? *msinfo* GLUT_LEFT_BUTTON) (set! *cx* (clamp (win-gl-x *win* (mouse-x *msinfo*)) (- *wd/2*) *wd/2*)) (set! *cy* (clamp (win-gl-y *win* (mouse-y *msinfo*)) (- *ht/2*) *ht/2*))) (else (let ((vx 0) (vy 0)) (if (spkey-on? *ksinfo* GLUT_KEY_LEFT) (set! vx (- vx *cd*))) (if (spkey-on? *ksinfo* GLUT_KEY_RIGHT) (set! vx (+ vx *cd*))) (if (spkey-on? *ksinfo* GLUT_KEY_DOWN) (set! vy (- vy *cd*))) (if (spkey-on? *ksinfo* GLUT_KEY_UP) (set! vy (+ vy *cd*))) (unless (= vx 0) (set! *cx* (wrap-range (+ *cx* vx) (- *wd/2*) *wd/2*))) (unless (= vy 0) (set! *cy* (wrap-range (+ *cy* vy) (- *ht/2*) *ht/2*)))) ))) ;; 初期化 (define (init) (gl-clear-color 0.0 0.0 0.0 0.0) (gl-enable GL_DEPTH_TEST) ;; 光源設定 ;(gl-light GL_LIGHT0 GL_POSITION #f32(1.0 1.0 1.0 0.0)) (gl-light GL_LIGHT0 GL_POSITION #f32(-1.0 1.0 1.0 0.0)) (gl-light GL_LIGHT0 GL_AMBIENT #f32( 0.5 0.5 0.5 1.0)) ; 環境光 (gl-enable GL_LIGHTING) (gl-enable GL_LIGHT0) (gl-enable GL_NORMALIZE) ;; 材質設定 (gl-material GL_FRONT GL_SPECULAR #f32(1.0 1.0 1.0 1.0)) (gl-material GL_FRONT GL_SHININESS 30.0)) ;; 画面表示 (define (disp) (gl-clear (logior GL_COLOR_BUFFER_BIT GL_DEPTH_BUFFER_BIT)) (gl-matrix-mode GL_MODELVIEW) (gl-load-identity) ;; カーソルの表示 (disp-cursor) ;; ワームの表示 (for-each (lambda (w1) (worm-disp w1)) *worms*) ;; 背景の表示 (gl-color *backcolor*) (draw-win-rect 0 0 *width* *height* *width* *height* 'left -0.999999) ;(gl-flush) (glut-swap-buffers)) ;; 画面のリサイズ (define (reshape w h) (set! *width* (min w (truncate->exact (* h *aratio*)))) (set! *height* (min h (truncate->exact (/. w *aratio*)))) (win-update-size *win* *width* *height*) (mouse-update-offset *msinfo* (quotient (- w *width*) 2) (quotient (- h *height*) 2)) ;; 縦横比を変えずにリサイズ (gl-viewport (quotient (- w *width*) 2) (quotient (- h *height*) 2) *width* *height*) (gl-matrix-mode GL_PROJECTION) (gl-load-identity) (let1 z1 (/. *ht/2* *tanvan*) ;; 透視射影する範囲を設定 (glu-perspective *vangle* (/. *width* *height*) (- z1 *zd/2*) (+ z1 *zd/2*)) ;; 視点の位置と方向を設定 (glu-look-at 0 0 z1 0 0 0 0 1 0))) ;; キー入力ON (define (keyboard key x y) (key-on *ksinfo* key) (cond ;; ESCキーで終了 ((= key (char->integer #\escape)) (exit 0)) ;; [g]キーでGC実行(デバッグ用) ((or (= key (char->integer #\g)) (= key (char->integer #\G))) (gc) (print (gc-stat))) )) ;; キー入力OFF (define (keyboardup key x y) (key-off *ksinfo* key)) ;; 特殊キー入力ON (define (specialkey key x y) (spkey-on *ksinfo* key)) ;; 特殊キー入力OFF (define (specialkeyup key x y) (spkey-off *ksinfo* key)) ;; マウスボタン (define (mouse button state x y) (mouse-button *msinfo* button state) (mouse-move *msinfo* x y)) ;; マウスドラッグ (define (mousedrag x y) (mouse-move *msinfo* x y)) ;; タイマー (define (timer val) ;; カーソルの移動 (move-cursor) ;; ワームの移動 (for-each (lambda (w1) (worm-move w1)) *worms*) ;; 画面表示 (glut-post-redisplay) ;; ウェイト時間調整 (glut-timer-func (waitcalc *wcinfo*) timer 0)) ;; メイン処理 (define (main args) (set! *flatdisp* (x->integer (list-ref args 1 0))) ;; ワームの初期化等 (set! *title* (if (= *wormkind* 0) "worm0101" "worm0201")) (for-each (lambda (w1) ;; class-of により、クラス再定義時のインスタンス更新を行う (class-of w1) (worm-init w1 *wlen* (randint *minx* *maxx*) (randint *miny* *maxy*) (randint -180 179))) *worms*) (glut-init '()) (glut-init-display-mode (logior GLUT_DOUBLE GLUT_RGB GLUT_DEPTH)) (glut-init-window-size *width* *height*) (glut-init-window-position 100 100) (glut-create-window *title*) (init) (glut-display-func disp) (glut-reshape-func reshape) (glut-keyboard-func keyboard) (glut-keyboard-up-func keyboardup) (glut-special-func specialkey) (glut-special-up-func specialkeyup) (glut-mouse-func mouse) (glut-motion-func mousedrag) (glut-timer-func *wait* timer 0) (glut-show-window) ;; コールバック内エラー対策 (guard (ex (else (report-error ex) (exit 1))) (glut-main-loop)) 0)
false
180ca8ad6da9904f74c1c6eaaf7e6befcf7e8770
5355071004ad420028a218457c14cb8f7aa52fe4
/3.5/e-3.80.scm
4afc4ea4a655b0dfd1d0402564f6646d91c3b654
[]
no_license
ivanjovanovic/sicp
edc8f114f9269a13298a76a544219d0188e3ad43
2694f5666c6a47300dadece631a9a21e6bc57496
refs/heads/master
2022-02-13T22:38:38.595205
2022-02-11T22:11:18
2022-02-11T22:11:18
2,471,121
376
90
null
2022-02-11T22:11:19
2011-09-27T22:11:25
Scheme
UTF-8
Scheme
false
false
1,467
scm
e-3.80.scm
; Exercise 3.80. A series RLC circuit consists of a resistor, a ; capacitor, and an inductor connected in series, as shown in figure ; 3.36. If R, L, and C are the resistance, inductance, and capacitance, ; then the relations between voltage (v) and current (i) for the three ; components are described by the equations ; and the circuit connections dictate the relations ; Combining these equations shows that the state of the circuit ; (summarized by vC, the voltage across the capacitor, and iL, the ; current in the inductor) is described by the pair of differential ; equations ; The signal-flow diagram representing this system of differential ; equations is shown in figure 3.37. ; Figure 3.36: A series RLC circuit. ; Figure 3.37: A signal-flow diagram for the solution to a series RLC ; circuit. Write a procedure RLC that takes as arguments the parameters ; R, L, and C of the circuit and the time increment dt. In a manner ; similar to that of the RC procedure of exercise 3.73, RLC should ; produce a procedure that takes the initial values of the state ; variables, vC0 and iL0, and produces a pair (using cons) of the ; streams of states vC and iL. Using RLC, generate the pair of streams ; that models the behavior of a series RLC circuit with R = 1 ohm, C = ; 0.2 farad, L = 1 henry, dt = 0.1 second, and initial values iL0 = 0 ; amps and vC0 = 10 volts. ; This is becoming more exercise from the basics of electronics circuits ; ;)
false
24d8db7769a25f2ef3966684741c22059ddc7b31
03de0e9f261e97d98f70145045116d7d1a664345
/scheme-cml/mailbox.scm
95244e37799da4ae765ccf6b006b92d8059abacd
[]
no_license
arcfide/riastradh
4929cf4428307b926e4c16e85bc39e5897c14447
9714b5c8b642f2d6fdd94d655ec5d92aa9b59750
refs/heads/master
2020-05-26T06:38:54.107723
2010-10-18T16:52:23
2010-10-18T16:52:23
3,235,881
2
1
null
null
null
null
UTF-8
Scheme
false
false
4,259
scm
mailbox.scm
;;; -*- Mode: Scheme -*- ;;;; Concurrent ML for Scheme ;;;; Mailboxes: Asynchronous Interprocess Communication ;;; Copyright (c) 2009, Taylor R. Campbell ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in ;;; the documentation and/or other materials provided with the ;;; distribution. ;;; ;;; * Neither the names of the authors nor the names of contributors ;;; may be used to endorse or promote products derived from this ;;; software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (define-locked-record-type <mailbox> (%make-mailbox priority queue) (priority) mailbox? with-mailbox-locked (priority mailbox.priority set-mailbox.priority!) (queue mailbox.queue set-mailbox.queue!)) (define (make-mailbox) (%make-mailbox #f (make-queue))) (define (mailbox-send mailbox message) (enter-critical-section (lambda (critical-token) ;** Do not beta-reduce -- bug in Scheme48's auto-integrator. (let ((continuation (let ((queue (mailbox.queue mailbox))) (let loop () ((with-mailbox-locked mailbox (lambda () (if (or (mailbox.priority mailbox) (and (queue-empty? queue) (begin (set-mailbox.priority! mailbox 1) #t))) (begin (enqueue! queue message) (lambda () (lambda () (values)))) (with-suspension-claimed (dequeue! queue) (lambda (resume disclaim) disclaim ;ignore (lambda () (lambda () (resume (lambda () message))))) (lambda () loop)))))))))) (exit-critical-section critical-token continuation))))) (define (mailbox-receive mailbox) (synchronize (mailbox-receive-rendezvous mailbox))) (define (mailbox-receive-rendezvous mailbox) (define (frobnitz if-enabled if-lost/locked) ((let ((queue (mailbox.queue mailbox))) (with-mailbox-locked mailbox (lambda () (if (queue-empty? queue) (if-lost/locked) (let ((message (dequeue! queue))) (set-mailbox.priority! mailbox (if (queue-empty? queue) #f 1)) (lambda () (if-enabled (lambda () message)))))))))) (define (poll) (with-mailbox-locked mailbox (lambda () (let ((priority (mailbox.priority mailbox))) (if priority (begin (set-mailbox.priority! mailbox (+ priority 1)) priority) #f))))) (define (enable if-enabled if-disabled) (frobnitz if-enabled (lambda () if-disabled))) (define (block suspension if-enabled if-blocked) (frobnitz if-enabled (lambda () (enqueue! (mailbox.queue mailbox) suspension) if-blocked))) (base-rendezvous poll enable block))
false
46a87bfc4c4b6dacbee6a7c42d07339c7ce6eeb1
ca235fd647f28d36835c8c40479ad6f0ad5e8ff2
/string-parser.scm
521f65bf471d58d7180d58e930c775fafb81c10f
[]
no_license
k16shikano/tinypeg
5382128485eae82c6d5415ea0eda95d3100f212a
41700156431645c26eb7c95b9185bccf5e42ba2a
refs/heads/master
2021-01-19T08:04:09.437814
2010-11-29T03:06:18
2010-11-29T03:06:18
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,624
scm
string-parser.scm
;; toy parser combinator for strings ;; Copyright (c) 2010, Keiichirou SHIKANO <[email protected]> ;; All rights reserved. ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; * Redistributions of source code must retain the above copyright ;; notice,this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above ;; copyright notice, this list of conditions and the following ;; disclaimer in the documentation and/or other materials provided ;; with the distribution. ;; * Neither the name of the Keiichirou SHIKANO nor the names of its ;; contributors may be used to endorse or promote products derived ;; from this software without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, ;; OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY ;; OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (define-condition-type <parser-error> <error> #f) (define (make-parser pred) (lambda (ts) (cond ((null? ts) (error <parser-error> "no character" ts)) ((pred (car ts)) (values (list (car ts)) (cdr ts))) (else (error <parser-error> "doesn't match at" ts))))) (define-syntax parser-or (syntax-rules (error) ((_) (values '() ts)) ((_ p) (lambda (ts) (p ts))) ((_ p1 p2 ...) (lambda (ts) (guard (e ((<parser-error> e) ((parser-or p2 ...) ts))) (p1 ts)))))) (define-syntax parser-cont (syntax-rules () ((_) (lambda (ts) (values '() ts))) ((_ p) (lambda (ts) (p ts))) ((_ p1 p2 ...) (lambda (ts) (receive (match-p1 rest-p1) (p1 ts) (receive (match-p2 rest-p2) ((parser-cont p2 ...) rest-p1) (values `(,@match-p1 ,@match-p2) rest-p2))))))) (define-syntax parser-do (syntax-rules (<- return in) ((_ return <r>) (lambda (ts) (values <r> ts))) ((_ return <r> in <x1> <- p1) (lambda (ts) (receive (match-p1 rest-p1) (p1 ts) (let ((<x1> match-p1)) (values <r> rest-p1))))) ((_ return <r> in <x1> <- p1 <x2> <- p2 ...) (lambda (ts) (receive (match-p1 rest-p1) (p1 ts) (let ((<x1> match-p1)) (receive (match-p2 rest-p2) ((parser-do return <r> in <x2> <- p2 ... ) rest-p1) (let ((<x2> match-p2)) (values match-p2 rest-p2))))))))) (define anychar (make-parser char?)) (define (char-parser char) (make-parser (pa$ char=? char))) (define (char-set-parser charset) (make-parser (pa$ char-set-contains? charset))) (define (skip p) (lambda (ts) (guard (e ((<parser-error> e) (values '() ts))) (receive (m r) (p ts) (values '() r))))) (define (parser-many p) (lambda (ts) (let R ((match '()) (rest ts)) (guard (e ((<parser-error> e) (values match rest))) (receive (m r) (p rest) (R (append match m) r)))))) (define (parser-many1 p) (parser-cont p (parser-many p))) (define space1 (char-set-parser #[\s])) (define nill (lambda (ts) (values '() ts))) (define extra-space1 (parser-or space1 nill)) (define extra-space (skip space1)) ;;; Example 1 (define (run parser str) (receive (matched rest) (parser (string->list str)) (values (list->string matched) (list->string rest)))) (define parser-group (parser-or (parser-cont (char-parser #\{) (parser-or (parser-many1 (char-set-parser #[^{}])) parser-group) (char-parser #\}) parser-group) nill)) (run parser-group "{{abc}{123}}rest...") ;;; Example 2 (define count-nest (parser-or (parser-do return (max (+ n 1) m) in op <- (char-parser #\{) n <- count-nest cp <- (char-parser #\}) m <- count-nest) (lambda (ts) (values 0 ts)))) (count-nest (string->list "{{}}{{{}}}"))
true
7e13ca2f17ec7e1b937a3ba2bbc463a6a275bd57
dfa3c518171b330522388a9faf70e77caf71b0be
/support/gambit/glut/glut.scm
ff5a6b079545c143442617272f60e38dade8b410
[ "BSD-2-Clause" ]
permissive
dharmatech/abstracting
c3ff314917857f92e79200df59b889d7f69ec34b
9dc5d9f45a9de03c6ee379f1928ebb393dfafc52
refs/heads/master
2021-01-19T18:08:22.293608
2009-05-12T02:03:55
2009-05-12T02:03:55
122,992
3
0
null
null
null
null
UTF-8
Scheme
false
false
15,878
scm
glut.scm
(include "glut-header.scm") (c-declare #<<declare-end #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> declare-end ) ; os dependent macros: (define GLUT_STROKE_ROMAN ((c-lambda () void* "___result_voidstar = GLUT_STROKE_ROMAN;"))) (define GLUT_STROKE_MONO_ROMAN ((c-lambda () void* "___result_voidstar = GLUT_STROKE_MONO_ROMAN;"))) (define GLUT_BITMAP_9_BY_15 ((c-lambda () void* "___result_voidstar = GLUT_BITMAP_9_BY_15;"))) (define GLUT_BITMAP_8_BY_13 ((c-lambda () void* "___result_voidstar = GLUT_BITMAP_8_BY_13;"))) (define GLUT_BITMAP_TIMES_ROMAN_10 ((c-lambda () void* "___result_voidstar = GLUT_BITMAP_TIMES_ROMAN_10;"))) (define GLUT_BITMAP_TIMES_ROMAN_24 ((c-lambda () void* "___result_voidstar = GLUT_BITMAP_TIMES_ROMAN_24;"))) (define GLUT_BITMAP_HELVETICA_10 ((c-lambda () void* "___result_voidstar = GLUT_BITMAP_HELVETICA_10;"))) (define GLUT_BITMAP_HELVETICA_12 ((c-lambda () void* "___result_voidstar = GLUT_BITMAP_HELVETICA_12;"))) (define GLUT_BITMAP_HELVETICA_18 ((c-lambda () void* "___result_voidstar = GLUT_BITMAP_HELVETICA_18;"))) ;; /* ;; * Initialization see fglut_init.c ;; */ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define basic-glut-init ;; (c-lambda () void ;; " ;; int argc = 0 ; ;; glutInit( &argc , NULL ) ; ")) ;; (define glutInit (c-lambda ( int* nonnull-char-string-list ) void "glutInit")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define (glutInit argc argv) ;; ((c-lambda () void "int argc = 0 ; glutInit ( &argc , NULL ) ;"))) (c-declare " int argc = 0 ; ") (define (glutInit a b) (let ((argc ((c-lambda () (pointer int) " ___result_voidstar = &argc ; ")))) (let ((proc (c-lambda ( int* nonnull-char-string-list ) void "glutInit"))) (proc argc '())))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define glutInitWindowPosition (c-lambda ( int int ) void "glutInitWindowPosition")) (define glutInitWindowSize (c-lambda ( int int ) void "glutInitWindowSize")) (define glutInitDisplayMode (c-lambda ( unsigned-int ) void "glutInitDisplayMode")) (define glutInitDisplayString (c-lambda ( char-string ) void "glutInitDisplayString")) ;; /* ;; * Process loop see freeglut_main.c ;; */ (define glutMainLoop (c-lambda ( ) void "glutMainLoop")) ;; /* ;; * Window management see freeglut_window.c ;; */ (define glutCreateWindow (c-lambda ( char-string ) int "glutCreateWindow")) (define glutCreateSubWindow (c-lambda ( int int int int int ) int "glutCreateSubWindow")) (define glutDestroyWindow (c-lambda ( int ) void "glutDestroyWindow")) (define glutSetWindow (c-lambda ( int ) void "glutSetWindow")) (define glutGetWindow (c-lambda ( ) int "glutGetWindow")) (define glutSetWindowTitle (c-lambda ( char-string ) void "glutSetWindowTitle")) (define glutSetIconTitle (c-lambda ( char-string ) void "glutSetIconTitle")) (define glutReshapeWindow (c-lambda ( int int ) void "glutReshapeWindow")) (define glutPositionWindow (c-lambda ( int int ) void "glutPositionWindow")) (define glutShowWindow (c-lambda ( ) void "glutShowWindow")) (define glutHideWindow (c-lambda ( ) void "glutHideWindow")) (define glutIconifyWindow (c-lambda ( ) void "glutIconifyWindow")) (define glutPushWindow (c-lambda ( ) void "glutPushWindow")) (define glutPopWindow (c-lambda ( ) void "glutPopWindow")) (define glutFullScreen (c-lambda ( ) void "glutFullScreen")) ;; /* ;; * Display-connected see freeglut_display.c ;; */ (define glutPostWindowRedisplay (c-lambda ( int ) void "glutPostWindowRedisplay")) (define glutPostRedisplay (c-lambda ( ) void "glutPostRedisplay")) (define glutSwapBuffers (c-lambda ( ) void "glutSwapBuffers")) ;; /* ;; * Mouse cursor see freeglut_cursor.c ;; */ (define glutWarpPointer (c-lambda ( int int ) void "glutWarpPointer")) (define glutSetCursor (c-lambda ( int ) void "glutSetCursor")) ;; /* ;; * Overlay see freeglut_overlay.c ;; */ (define glutEstablishOverlay (c-lambda ( ) void "glutEstablishOverlay")) (define glutRemoveOverlay (c-lambda ( ) void "glutRemoveOverlay")) (define glutUseLayer (c-lambda ( GLenum ) void "glutUseLayer")) (define glutPostOverlayRedisplay (c-lambda ( ) void "glutPostOverlayRedisplay")) (define glutPostWindowOverlayRedisplay (c-lambda ( int ) void "glutPostWindowOverlayRedisplay")) (define glutShowOverlay (c-lambda ( ) void "glutShowOverlay")) (define glutHideOverlay (c-lambda ( ) void "glutHideOverlay")) ;; /* ;; * Menu see freeglut_menu.c ;; */ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glutCreateMenu (c-lambda ( (function (int) void) ) int "glutCreateMenu")) (define *glut-create-menu-func* #f) (c-define (basic-create-menu-func a) (int) void "basicCreateMenuFunc" "" (*glut-create-menu-func* a)) (define (glutCreateMenu proc) (set! *glut-create-menu-func* proc) ((c-lambda () void " glutCreateMenu ( basicCreateMenuFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define glutDestroyMenu (c-lambda ( int ) void "glutDestroyMenu")) (define glutGetMenu (c-lambda ( ) int "glutGetMenu")) (define glutSetMenu (c-lambda ( int ) void "glutSetMenu")) (define glutAddMenuEntry (c-lambda ( char-string int ) void "glutAddMenuEntry")) (define glutAddSubMenu (c-lambda ( char-string int ) void "glutAddSubMenu")) (define glutChangeToMenuEntry (c-lambda ( int char-string int ) void "glutChangeToMenuEntry")) (define glutChangeToSubMenu (c-lambda ( int char-string int ) void "glutChangeToSubMenu")) (define glutRemoveMenuItem (c-lambda ( int ) void "glutRemoveMenuItem")) (define glutAttachMenu (c-lambda ( int ) void "glutAttachMenu")) (define glutDetachMenu (c-lambda ( int ) void "glutDetachMenu")) ;; /* ;; * Global callback see freeglut_callbacks.c ;; */ (define glutTimerFunc (c-lambda ( unsigned-int (function (int) void) int ) void "glutTimerFunc")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glutIdleFunc (c-lambda ( (function () void) ) void "glutIdleFunc")) (define *glut-idle-func* #f) (c-define (basic-idle-func) () void "basicIdleFunc" "" (*glut-idle-func*)) (define (glutIdleFunc proc) (set! *glut-idle-func* proc) ((c-lambda () void " glutIdleFunc ( basicIdleFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; /* ;; * Window-specific callback see freeglut_callbacks.c ;; */ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glutKeyboardFunc (c-lambda ( (function (unsigned-char int int) void) ) void "glutKeyboardFunc")) (define *glut-keyboard-func* #f) (c-define (basic-keyboard-func a b c) (unsigned-char int int) void "basicKeyboardFunc" "" (*glut-keyboard-func* a b c)) (define (glutKeyboardFunc proc) (set! *glut-keyboard-func* proc) ((c-lambda () void " glutKeyboardFunc ( basicKeyboardFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glutSpecialFunc (c-lambda ( (function (int int int) void) ) void "glutSpecialFunc")) (define *glut-special-func* #f) (c-define (basic-special-func a b c) (int int int) void "basicSpecialFunc" "" (*glut-special-func* a b c)) (define (glutSpecialFunc proc) (set! *glut-special-func* proc) ((c-lambda () void " glutSpecialFunc ( basicSpecialFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glut-reshape-func #f) ;; (c-define (basic-reshape-func width height) ;; (int int) ;; void ;; "basicReshapeFunc" ;; "" ;; (glut-reshape-func width height)) ;; (define glutReshapeFunc ;; (c-lambda (scheme-object) void "glutReshapeFunc( basicReshapeFunc ) ;")) ;; (define (glutReshapeFunc proc) ;; (set! glut-reshape-func proc) ;; ((c-lambda () void "glutReshapeFunc( basicReshapeFunc ) ;"))) ;; (define glutReshapeFunc (c-lambda ( (function (int int) void) ) void "glutReshapeFunc")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define *glut-reshape-func* #f) (c-define (basic-reshape-func width height) (int int) void "basicReshapeFunc" "" (*glut-reshape-func* width height)) (define (glutReshapeFunc proc) (set! *glut-reshape-func* proc) ((c-lambda () void " glutReshapeFunc ( basicReshapeFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define glutVisibilityFunc (c-lambda ( (function (int) void) ) void "glutVisibilityFunc")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glutDisplayFunc (c-lambda ( (function () void) ) void "glutDisplayFunc")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define *glut-display-func* #f) (c-define (basid-display-func) () void "basicDisplayFunc" "" (*glut-display-func*)) (define (glutDisplayFunc proc) (set! *glut-display-func* proc) ((c-lambda () void " glutDisplayFunc ( basicDisplayFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glutMouseFunc (c-lambda ( (function (int int int int) void) ) void "glutMouseFunc")) (define *glut-mouse-func* #f) (c-define (basic-mouse-func a b c d) (int int int int) void "basicMouseFunc" "" (*glut-mouse-func* a b c d)) (define (glutMouseFunc proc) (set! *glut-mouse-func* proc) ((c-lambda () void " glutMouseFunc ( basicMouseFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define glutMotionFunc (c-lambda ( (function (int int) void ) ) void "glutMotionFunc")) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (define glutPassiveMotionFunc (c-lambda ( (function (int int) void) ) void "glutPassiveMotionFunc")) (define *glut-passive-motion-func* #f) (c-define (basic-passive-motion-func a b) (int int) void "basicPassiveMotionFunc" "" (*glut-passive-motion-func* a b)) (define (glutPassiveMotionFunc proc) (set! *glut-passive-motion-func* proc) ((c-lambda () void " glutPassiveMotionFunc ( basicPassiveMotionFunc ) ; "))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define glutEntryFunc (c-lambda ( (function (int) void) ) void "glutEntryFunc")) (define glutKeyboardUpFunc (c-lambda ( (function (unsigned-char int int) void) ) void "glutKeyboardUpFunc")) (define glutSpecialUpFunc (c-lambda ( (function (int int int) void) ) void "glutSpecialUpFunc")) (define glutJoystickFunc (c-lambda ( (function (unsigned-int int int int) void) int ) void "glutJoystickFunc")) (define glutMenuStateFunc (c-lambda ( (function (int) void) ) void "glutMenuStateFunc")) (define glutMenuStatusFunc (c-lambda ( (function (int int int) void) ) void "glutMenuStatusFunc")) (define glutOverlayDisplayFunc (c-lambda ( (function () void) ) void "glutOverlayDisplayFunc")) (define glutWindowStatusFunc (c-lambda ( (function (int) void) ) void "glutWindowStatusFunc")) (define glutSpaceballMotionFunc (c-lambda ( (function (int int int) void) ) void "glutSpaceballMotionFunc")) (define glutSpaceballRotateFunc (c-lambda ( (function (int int int) void) ) void "glutSpaceballRotateFunc")) (define glutSpaceballButtonFunc (c-lambda ( (function (int int) void) ) void "glutSpaceballButtonFunc")) (define glutButtonBoxFunc (c-lambda ( (function (int int) void) ) void "glutButtonBoxFunc")) (define glutDialsFunc (c-lambda ( (function (int int) void) ) void "glutDialsFunc")) (define glutTabletMotionFunc (c-lambda ( (function (int int) void) ) void "glutTabletMotionFunc")) (define glutTabletButtonFunc (c-lambda ( (function (int int int int) void) ) void "glutTabletButtonFunc")) ;; /* ;; * State setting and retrieval see freeglut_state.c ;; */ (define glutGet (c-lambda ( GLenum ) int "glutGet")) (define glutDeviceGet (c-lambda ( GLenum ) int "glutDeviceGet")) (define glutGetModifiers (c-lambda ( ) int "glutGetModifiers")) (define glutLayerGet (c-lambda ( GLenum ) int "glutLayerGet")) ;; /* ;; * Font see freeglut_font.c ;; */ (define glutBitmapCharacter (c-lambda ( void* int ) void "glutBitmapCharacter")) (define glutBitmapWidth (c-lambda ( void* int ) int "glutBitmapWidth")) (define glutStrokeCharacter (c-lambda ( void* int ) void "glutStrokeCharacter")) (define glutStrokeWidth (c-lambda ( void* int ) int "glutStrokeWidth")) (define glutBitmapLength (c-lambda ( void* (pointer unsigned-char) ) int "glutBitmapLength")) (define glutStrokeLength (c-lambda ( void* (pointer unsigned-char) ) int "glutStrokeLength")) ;; /* ;; * Geometry see freeglut_geometry.c ;; */ (define glutWireCube (c-lambda ( GLdouble ) void "glutWireCube")) (define glutSolidCube (c-lambda ( GLdouble ) void "glutSolidCube")) (define glutWireSphere (c-lambda ( GLdouble GLint GLint ) void "glutWireSphere")) (define glutSolidSphere (c-lambda ( GLdouble GLint GLint ) void "glutSolidSphere")) (define glutWireCone (c-lambda ( GLdouble GLdouble GLint GLint ) void "glutWireCone")) (define glutSolidCone (c-lambda ( GLdouble GLdouble GLint GLint ) void "glutSolidCone")) (define glutWireTorus (c-lambda ( GLdouble GLdouble GLint GLint ) void "glutWireTorus")) (define glutSolidTorus (c-lambda ( GLdouble GLdouble GLint GLint ) void "glutSolidTorus")) (define glutWireDodecahedron (c-lambda ( ) void "glutWireDodecahedron")) (define glutSolidDodecahedron (c-lambda ( ) void "glutSolidDodecahedron")) (define glutWireOctahedron (c-lambda ( ) void "glutWireOctahedron")) (define glutSolidOctahedron (c-lambda ( ) void "glutSolidOctahedron")) (define glutWireTetrahedron (c-lambda ( ) void "glutWireTetrahedron")) (define glutSolidTetrahedron (c-lambda ( ) void "glutSolidTetrahedron")) (define glutWireIcosahedron (c-lambda ( ) void "glutWireIcosahedron")) (define glutSolidIcosahedron (c-lambda ( ) void "glutSolidIcosahedron")) ;; /* ;; * Teapot rendering found in freeglut_teapot.c ;; */ (define glutWireTeapot (c-lambda ( GLdouble ) void "glutWireTeapot")) (define glutSolidTeapot (c-lambda ( GLdouble ) void "glutSolidTeapot")) ;; /* ;; * Game mode see freeglut_gamemode.c ;; */ (define glutGameModeString (c-lambda ( char-string ) void "glutGameModeString")) (define glutEnterGameMode (c-lambda ( ) int "glutEnterGameMode")) (define glutLeaveGameMode (c-lambda ( ) void "glutLeaveGameMode")) (define glutGameModeGet (c-lambda ( GLenum ) int "glutGameModeGet")) ;; /* ;; * Video resize see freeglut_videoresize.c ;; */ (define glutVideoResizeGet (c-lambda ( GLenum ) int "glutVideoResizeGet")) (define glutSetupVideoResizing (c-lambda ( ) void "glutSetupVideoResizing")) (define glutStopVideoResizing (c-lambda ( ) void "glutStopVideoResizing")) (define glutVideoResize (c-lambda ( int int int int ) void "glutVideoResize")) (define glutVideoPan (c-lambda ( int int int int ) void "glutVideoPan")) ;; /* ;; * Colormap see freeglut_misc.c ;; */ (define glutSetColor (c-lambda ( int GLfloat GLfloat GLfloat ) void "glutSetColor")) (define glutGetColor (c-lambda ( int int ) GLfloat "glutGetColor")) (define glutCopyColormap (c-lambda ( int ) void "glutCopyColormap")) ;; /* ;; * Misc keyboard and joystick see freeglut_misc.c ;; */ (define glutIgnoreKeyRepeat (c-lambda ( int ) void "glutIgnoreKeyRepeat")) (define glutSetKeyRepeat (c-lambda ( int ) void "glutSetKeyRepeat")) (define glutForceJoystickFunc (c-lambda ( ) void "glutForceJoystickFunc")) ;; /* ;; * Misc see freeglut_misc.c ;; */ (define glutExtensionSupported (c-lambda ( char-string ) int "glutExtensionSupported")) (define glutReportErrors (c-lambda ( ) void "glutReportErrors"))
false
5e1d8608b2e52a63debc0fb6f4870c2e362d327c
0768e217ef0b48b149e5c9b87f41d772cd9917f1
/bench/gambit-benchmarks/divrec.scm
a1fac67e82b895ecd8b14b4bf31d14edbc64e860
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
fujita-y/ypsilon
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
62e73643a4fe87458ae100e170bf4721d7a6dd16
refs/heads/master
2023-09-05T00:06:06.525714
2023-01-25T03:56:13
2023-01-25T04:02:59
41,003,666
45
7
BSD-2-Clause
2022-06-25T05:44:49
2015-08-19T00:05:35
Scheme
UTF-8
Scheme
false
false
852
scm
divrec.scm
;;; DIVREC -- Benchmark which divides by 2 using lists of n ()'s. (define (create-n n) (do ((n n (- n 1)) (a '() (cons '() a))) ((= n 0) a))) (define *ll* (create-n 200)) (define (recursive-div2 l) (cond ((null? l) '()) (else (cons (car l) (recursive-div2 (cddr l)))))) (define (main . args) (run-benchmark "divrec" divrec-iters (lambda (result) (equal? result '(() () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () () ()))) (lambda (l) (lambda () (recursive-div2 l))) *ll*))
false
7b4ddad5e67d41bc27d033cd109d14f14e6e9d64
6c6cf6e4b77640825c2457e54052a56d5de6f4d2
/ch1/1_24.scm
ef14cd0b42f4ef02b4be7498b9ca5ce8d608cd2f
[]
no_license
leonacwa/sicp
a469c7bc96e0c47e4658dccd7c5309350090a746
d880b482d8027b7111678eff8d1c848e156d5374
refs/heads/master
2018-12-28T07:20:30.118868
2015-02-07T16:40:10
2015-02-07T16:40:10
11,738,761
0
0
null
null
null
null
UTF-8
Scheme
false
false
210
scm
1_24.scm
(load "1_22.scm") (load "fast-prime.scm") (define (prime? n) (fast-prime? n 10)) (define (search-for-prime n) (let ((start-time (real-time-clock))) (get-primes n 12) (- (real-time-clock) start-time)))
false
3b266fc7439751e61530734587f3f86a59ace389
23122d4bae8acdc0c719aa678c47cd346335c02a
/2021/3.scm
2b9bbf5f4f70e19c36c2bd7b1e4974c42e5ec7cd
[]
no_license
Arctice/advent-of-code
9076ea5d2e455d873da68726b047b64ffe11c34c
2a2721e081204d4fd622c2e6d8bf1778dcedab3e
refs/heads/master
2023-05-24T23:18:02.363340
2023-05-04T09:04:01
2023-05-04T09:06:24
225,228,308
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,440
scm
3.scm
(define-syntax λ (identifier-syntax lambda)) (define (readlines path) (call-with-input-file path (λ (f) (let line () (if (port-eof? f) '() (cons (get-line f) (line))))))) (define input (map (λ (line) (string->number line 2)) (readlines "3.input"))) (define width (fold-left max 0 (map fxlength input))) (define (count-column pos nums) (fold-left + 0 (map (λ (n) (fxand 1 (fxsrl n pos))) nums))) ;; part 1 (let* ([counts (map (λ (i) (count-column i input)) (iota width))] [best (map (λ (n) (if (< n (/ (length input) 2)) 0 1)) counts)] [gamma (apply + (map fxsll best (enumerate best)))] [epsilon (fxxor gamma (- (expt 2 width) 1))]) (printf "~s\n" (* gamma epsilon))) ;; part 2 (let* ([a (fold-left (λ (xs i) (if (= 1 (length xs)) xs (let* ([ones (count-column i xs)] [best (if (< ones (/ (length xs) 2)) 0 1)]) (filter (λ (x) (= best (fxand 1 (fxsrl x i)))) xs)))) input (reverse (iota width)))] [b (fold-left (λ (xs i) (if (= 1 (length xs)) xs (let* ([ones (count-column i xs)] [best (if (< ones (/ (length xs) 2)) 0 1)]) (filter (λ (x) (not (= best (fxand 1 (fxsrl x i))))) xs)))) input (reverse (iota width)))]) (printf "~s\n" (* (car a) (car b))))
true
486329a5de7cae94627b470e2ef23884d94d1d72
db6f1095242eb0040bb5049d469cd3c92ad68b2c
/PStore/persistent-tree.scm
1797f2ad4a2cef942d036446fdf7902530d1907e
[]
no_license
defin/jrm-code-project
1767523c7964a998c6035f67ed227c22518e0aeb
0716e271f449b52bfabe4c2fefe8fc5e62902f42
refs/heads/master
2021-01-16T19:00:05.028804
2014-08-23T23:20:49
2014-08-23T23:20:49
33,170,588
1
0
null
null
null
null
UTF-8
Scheme
false
false
9,520
scm
persistent-tree.scm
;;; -*- Mode: Scheme -*- (declare (usual-integrations)) ;;; Feel free to copy or adapt this code as you wish. ;;;; A persistent weight-balanced tree abstraction. (define-structure (persistent-tree (conc-name persistent-tree/) (constructor make-persistent-tree (left-child-address right-child-address %weight %address left-child right-child object-map-entry))) ;; Address of left child of the tree. ;; This field is persistent. (left-child-address #f read-only #t) ;; Address of right child of the tree. ;; This field is persistent. (right-child-address #f read-only #t) ;; Weight of this tree. ;; This field is persistent. (%weight #f read-only #t) ;; Where the persistent version is in the durable store. ;; This field is transient and reconstructed upon deserialization. (%address #f read-only #t) ;; Cached left child. ;; A transient copy of the deserialized left child. (left-child #f read-only #t) ;; Cached right child. ;; A transient copy of the deserialized right child. (right-child #f read-only #t) ;; The object map entry stored at the root of this tree. (object-map-entry #f read-only #t)) (define (persistent-tree/address tree) (if (null? tree) 0 (persistent-tree/%address tree))) (define (persistent-tree/weight tree) (if (null? tree) 0 (persistent-tree/%weight tree))) (define (persistent-tree/add durable-store root new-entry) (if (null? root) (persistent-tree/make-leaf durable-store new-entry) (let ((root-entry (persistent-tree/object-map-entry root)) (left-child (persistent-tree/left-child root)) (right-child (persistent-tree/right-child root))) (cond ((< (object-map-entry/object-id new-entry) (object-map-entry/object-id root-entry)) (persistent-tree/t-join durable-store (persistent-tree/add durable-store left-child new-entry) right-child root-entry)) ((< (object-map-entry/object-id root-entry) (object-map-entry/object-id new-entry)) (persistent-tree/t-join durable-store left-child (persistent-tree/add durable-store right-child new-entry) root-entry)) (else (persistent-tree/make-branch durable-store left-child right-child new-entry)))))) (define (persistent-tree/descend object-id current-tree best-tree) (cond ((null? current-tree) best-tree) ((< object-id (object-map-entry/object-id (persistent-tree/object-map-entry current-tree))) (persistent-tree/descend object-id (persistent-tree/left-child current-tree) best-tree)) (else (persistent-tree/descend object-id (persistent-tree/right-child current-tree) current-tree)))) (define (persistent-tree/find-entry root object-id) (let ((best-tree (persistent-tree/descend object-id root '()))) (if (null? best-tree) #f (let ((entry (persistent-tree/object-map-entry best-tree))) (if (< (object-map-entry/object-id entry) object-id) #f entry))))) (define (recover-persistent-tree durable-store address) (if (zero? address) '() (let ((info (deserialize durable-store address))) (cond ((not (pair? info)) (error "Bad info.")) ((eq? (car info) 'leaf) (call-with-values (lambda () (deserialize durable-store (second info))) (lambda (object-id base-address object) (make-persistent-tree 0 0 1 address '() '() (%make-object-map-entry object-id (second info) object))))) ((eq? (car info) 'branch) (let* ((left-child-address (second info)) (right-child-address (third info)) (object-address (fourth info)) (left-child (recover-persistent-tree durable-store left-child-address)) (right-child (recover-persistent-tree durable-store right-child-address))) (call-with-values (lambda () (deserialize durable-store object-address)) (lambda (object-id base-address object) (make-persistent-tree left-child-address right-child-address (+ 1 (persistent-tree/weight left-child) (persistent-tree/weight right-child)) address left-child right-child (%make-object-map-entry object-id object-address object)))))) (else "Bad info." info))))) (define (persistent-tree/t-join durable-store left-child right-child entry) (let ((l.n (persistent-tree/weight left-child)) (r.n (persistent-tree/weight right-child))) (cond ((< (+ l.n r.n) 2) (persistent-tree/make-branch durable-store left-child right-child entry)) ((> r.n (* 5 l.n)) (persistent-tree/l-join durable-store left-child right-child entry)) ((> l.n (* 5 r.n)) (persistent-tree/r-join durable-store left-child right-child entry)) (else (persistent-tree/make-branch durable-store left-child right-child entry))))) (define (persistent-tree/make-leaf durable-store entry) (let* ((weight 1) ;; Serialize the persistent information from the ;; object-map-entry. (the object-id and the address). (address (primitive-serialize-leaf durable-store (object-map-entry/address entry)))) (make-persistent-tree 0 0 weight address '() '() entry))) (define (primitive-serialize-leaf durable-store entry-address) (write-leaf-record! durable-store (lambda (oport) ;; store the delta because it is likely to be a small number. (write entry-address oport)))) (define (deserialize-ptree-leaf base-adress record) (list 'leaf (third record))) (define (persistent-tree/make-branch durable-store left-child right-child entry) (if (and (null? left-child) (null? right-child)) (persistent-tree/make-leaf durable-store entry) (let* ((weight (+ 1 (persistent-tree/weight left-child) (persistent-tree/weight right-child))) (left-child-address (persistent-tree/address left-child)) (right-child-address (persistent-tree/address right-child)) ;; Serialize the addresses of the ;; left and right child, and the persistent information ;; from the object-map-entry (the object-id and the address). (address (primitive-serialize-branch durable-store left-child-address right-child-address (object-map-entry/address entry)))) (make-persistent-tree left-child-address right-child-address weight address left-child right-child entry)))) (define (primitive-serialize-branch durable-store left-child-address right-child-address entry-address) (write-branch-record! durable-store (lambda (output-port) (write left-child-address output-port) (write-char #\space output-port) (write right-child-address output-port) (write-char #\space output-port) (write entry-address output-port)))) (define (deserialize-ptree-branch base-address record) (list 'branch (third record) (fourth record) (fifth record))) (define (persistent-tree/l-join durable-store left-child right-child entry) (if (< (persistent-tree/weight (persistent-tree/left-child right-child)) (persistent-tree/weight (persistent-tree/right-child right-child))) (persistent-tree/single-l durable-store left-child right-child entry) (persistent-tree/double-l durable-store left-child right-child entry))) (define (persistent-tree/single-l durable-store x r entry) (persistent-tree/make-branch durable-store (persistent-tree/make-branch durable-store x (persistent-tree/left-child r) entry) (persistent-tree/right-child r) (persistent-tree/object-map-entry r))) (define (persistent-tree/double-l durable-store x r entry) (let ((r.l (persistent-tree/left-child r))) (persistent-tree/make-branch durable-store (persistent-tree/make-branch durable-store x (persistent-tree/left-child r.l) entry) (persistent-tree/make-branch durable-store (persistent-tree/right-child r.l) (persistent-tree/right-child r) (persistent-tree/object-map-entry r)) (persistent-tree/object-map-entry r.l)))) (define (persistent-tree/r-join durable-store left-child right-child entry) (if (< (persistent-tree/weight (persistent-tree/right-child left-child)) (persistent-tree/weight (persistent-tree/left-child left-child))) (persistent-tree/single-r durable-store left-child right-child entry) (persistent-tree/double-r durable-store left-child right-child entry))) (define (persistent-tree/single-r durable-store l z entry) (persistent-tree/make-branch durable-store (persistent-tree/left-child l) (persistent-tree/make-branch durable-store (persistent-tree/right-child l) z entry) (persistent-tree/object-map-entry l))) (define (persistent-tree/double-r durable-store l z entry) (let ((l.r (persistent-tree/right-child l))) (persistent-tree/make-branch durable-store (persistent-tree/make-branch durable-store (persistent-tree/left-child l) (persistent-tree/left-child l.r) (persistent-tree/object-map-entry l)) (persistent-tree/make-branch durable-store (persistent-tree/right-child l.r) z entry) (persistent-tree/object-map-entry l.r))))
false
2fa73e0de5d88249f3b6ecb14ca10605c09c1637
b6f9b024997307f09661f67f4575645c63cb718c
/fib.ss
12363fe82e111e2c44055bd30c316059c0b24168
[ "BSD-3-Clause" ]
permissive
jpverkamp/schempy
eb1a4e28a302240efb9975f24ee68ac765ac930e
7df89e8cd54e475c24d9b22fc563e58ae2f1799d
refs/heads/master
2020-05-03T19:39:36.089478
2014-08-04T01:34:52
2014-08-04T01:34:52
22,587,984
1
0
null
null
null
null
UTF-8
Scheme
false
false
137
ss
fib.ss
(define fib-h (lambda (n a b) (if (zero? n) a (fib-h (sub1 n) b (+ a b))))) (define fib (lambda (n) (fib-h n 1 1)))
false
fcae851f85701c727b8d875f932a2dcad74dfa01
15b3f9425594407e43dd57411a458daae76d56f6
/bin/compiler/test/init.scm
c4ead319b25b616e38f0e0d4ce0c62786f6998d3
[]
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
83
scm
init.scm
; This file is loaded on startup of my scheme implementation (load "scm/init.scm")
false
268f4dcf4f658303945e0ee977a303509a0cfc7b
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 2/2.5/Ex2.79.scm
39efc26311d19411b1bf932f150835fcec14d69b
[]
no_license
yaowenqiang/SICPBook
ef559bcd07301b40d92d8ad698d60923b868f992
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
refs/heads/master
2020-04-19T04:03:15.888492
2015-11-02T15:35:46
2015-11-02T15:35:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
580
scm
Ex2.79.scm
#lang planet neil/sicp ;; Generic predicate (define (equ? x y) (apply-generic 'equ? x y)) ;; Scheme number package (put 'equ? ('scheme-number 'scheme-number) =) ;; Rational number package ;; Internal procedure (define (equ? x y) (and (eq? (numer x) (numer y)) (eq? (denom x) (denom y)))) ;; External interface (put 'equ? ('rational 'rational) equ?) ;; Complex number package ;; Internal procedure (define (equ? x y) (and (eq? (real-part x) (real-part y)) (eq? (imag-part x) (imag-part y)))) ;; External interface (put 'equ? ('complex 'complex) equ?)
false
89b79150eb4acb4a30ce4cf52397cc88c50a90ba
ccd36329266324496e5ee15a51d87971a4ad2295
/kawa_jogl/music_test/music_test.scm
4b384f0e34337c5250a7a68bef204958a4e1d814
[]
no_license
aweinstock314/lisp-stuff
5b15366836190fbde37227d3ec77cdc08e026091
ef132d54907a3ee152c91e776f08689dae7243f6
refs/heads/master
2021-01-22T09:18:02.485208
2014-12-09T21:45:50
2014-12-09T21:45:50
20,958,912
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,255
scm
music_test.scm
(require <scheme_util_general>) (require <scheme_util_math>) (define synth::javax.sound.midi.Synthesizer (javax.sound.midi.MidiSystem:getSynthesizer)) (synth:open) (define-macro (with-channel synthesizer name num . body) `(let ((,name :: javax.sound.midi.MidiChannel ((invoke ,synthesizer 'getChannels) ,num))) ,@body ) ) (dotimes (i 3) (future (begin (define pitch 127) (define pitchsweeper (sweep 30 70 4)) (define lastpitch 0) (define instr (->int (truncate (random 127)))) (java.lang.Thread:sleep (* 5000 i)) (with-channel synth ch i (with-min-ms-per-iteration (+ 500 (* 250 i)) (ch:noteOff lastpitch) (printf "instrument %s; pitch %s\n" instr pitch) (ch:programChange instr) (synchronized pitch (set! lastpitch (pitchsweeper pitch)) (set! pitch lastpitch) ) ;(inc! instr 7) ;(inplace! (wrap 0 127) instr) (ch:noteOn lastpitch #x7f) ) ) ))) (define pitch2 00) (define sweeper2 (sweep 35 38 100)) (with-channel synth ch 9 (with-min-ms-per-iteration 500 (ch:noteOff pitch2) (inplace! sweeper2 pitch2) (ch:noteOn pitch2 #x7f) ) )
false
ee63e594051377a5eeb3d6909e941950abfa16ce
acc632afe0d8d8b94b781beb1442bbf3b1488d22
/deps/utf8/utf8-lolevel.scm
225cebcdad62d71d90d5aa73ed65bfe465aedaab
[]
no_license
kdltr/life-is-so-pretty
6cc6e6c6e590dda30c40fdbfd42a5a3a23644794
5edccf86702a543d78f8c7e0f6ae544a1b9870cd
refs/heads/master
2021-01-20T21:12:00.963219
2016-05-13T12:19:02
2016-05-13T12:19:02
61,128,206
1
0
null
null
null
null
UTF-8
Scheme
false
false
14,524
scm
utf8-lolevel.scm
;;;; utf8-lolevel.scm -- encoding utils ;; ;; Copyright (c) 2004-2009 Alex Shinn. All rights reserved. ;; BSD-style license: http://synthcode.com/license.txt ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; This is an internal library used by the utf8 interface. ;; You probably don't want to use this. ;; ;; Notes: ;; ;; 'pos' and 'index' refer to conceptual utf8 indices (Unicode codepoints). ;; 'off' and 'pointer' refer to actual byte offsets. ;; 'sp-' is a string-pointer function referring to offsets. ;; Uses ##sys#become! since all types are correct at runtime. ;; ;; Assumes string-length, string-ref & string-set! are rewritten by ;; the compiler. (declare (no-argc-checks) (no-bound-checks) (no-procedure-checks) (bound-to-procedure ##sys#char->utf8-string ##sys#become!)) (require-library data-structures lolevel) (module utf8-lolevel ( ;; utils string-int-ref string-int-set! ascii-string? ;; utf8 encoding string-set-at-byte-in-place! string-set-at-byte utf8-start-byte->length ucs-integer->length utf8-index->offset utf8-offset->index utf8-string-ref utf8-string-set! utf8-string-length utf8-substring utf8-string->list utf8-prev-char utf8-next-char make-utf8-string utf8-string? with-substring-offsets with-two-substring-offsets ;; string-pointers make-string-pointer string-pointer? sp-copy sp-first sp-last sp-next sp-prev sp-ref sp-ref->string sp-set! sp-before sp-after sp-substring sp-check? sp-check-lo? sp-check-hi? ;; I/O read-utf8-char write-utf8-char char->utf8-string ;; fast-loop iterator in-utf8-string ) (import scheme chicken extras lolevel) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; utilities which take and return integers (define (string-int-ref s i) (char->integer (string-ref s i))) (define (string-int-set! s i c) (string-set! s i (integer->char c))) ;; determine if a string only has 7-bit ASCII characters (define (ascii-string? str) (let ((limit (string-length str))) (let loop ((i 0)) (or (= i limit) (and (> 128 (string-int-ref str i)) (loop (+ i 1))))))) ;; from SRFI-33, useful in splitting up the bit patterns used to ;; represent unicode values in utf8 (define (extract-bit-field size position n) (bitwise-and (bitwise-not (arithmetic-shift -1 size)) (arithmetic-shift n (- position)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; indexing utils ;; number of total bytes in a utf8 char given the 1st byte (define utf8-start-byte->length (let ((table '#( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 0x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 1x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 2x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 3x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 4x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 5x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 6x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 7x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 8x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; 9x 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; ax 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ; bx 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ; cx 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 ; dx 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 ; ex 4 4 4 4 4 4 4 4 5 5 5 5 6 6 0 0 ; fx ))) (lambda (i) (vector-ref table i)))) (define (ucs-integer->length x) (cond ((<= x #x7F) 1) ((<= x #x7FF) 2) ((<= x #xFFFF) 3) ((<= x #x1FFFFF) 4) (else (error "unicode codepoint out of range:" x)))) (define (utf8-index->offset s pos) (if (zero? pos) 0 (let ((limit (string-length s))) (let loop ((i 0) (count 0)) (cond ((= count pos) i) ((>= i limit) (error "index out of range" s pos)) (else (loop (+ i (utf8-start-byte->length (string-int-ref s i))) (+ count 1)))))))) (define (utf8-offset->index s off) (let ((limit (string-length s))) (let loop ((i 0) (count 0)) (cond ((>= i off) (if (= i off) count (- count 1))) ((>= i limit) (error "index out of range" s off)) (else (loop (+ i (utf8-start-byte->length (string-int-ref s i))) (+ count 1))))))) ;; return offset of previous char, or #f if at start of string (define (utf8-prev-char s off) (let loop ((i (- off 1))) (cond ((negative? i) #f) ((= #b10000000 (bitwise-and #b11000000 (string-int-ref s i))) (loop (- i 1))) (else i)))) ;; return offset of next char, or #f if at end of string (define (utf8-next-char s off) (let ((limit (string-length s))) (and (< off limit) (let ((res (+ off (utf8-start-byte->length (string-int-ref s off))))) (and (<= res limit) res))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; redefine string primitives (define (utf8-substring s start . opt) (with-substring-offsets substring s (cons start opt))) (define (utf8-string-length s) (let ((limit (string-length s))) (let lp ((i 0) (res 0)) (if (>= i limit) res (lp (+ i (utf8-start-byte->length (string-int-ref s i))) (+ res 1)))))) (define (with-substring-offsets proc s opt) (let* ((start (if (pair? opt) (car opt) 0)) (b1 (utf8-index->offset s start)) (opt2 (if (pair? opt) (cdr opt) '()))) (let ((limit (string-length s))) (if (pair? opt2) (let ((end (car opt2))) (let lp ((b2 b1) (count start)) (cond ((= count end) (proc s b1 b2)) ((> b2 limit) (error "index out of range" s end)) (else (lp (+ b2 (utf8-start-byte->length (string-int-ref s b2))) (+ count 1)))))) (proc s b1 limit)))) ) (define (with-two-substring-offsets proc s1 s2 opt) (with-substring-offsets (lambda (s1 start1 end1) (with-substring-offsets (lambda (s2 start2 end2) (proc s1 s2 start1 end1 start2 end2)) s2 (if (and (pair? opt) (pair? (cdr opt))) (cddr opt) '()))) s1 opt) ) (define (utf8-string->list str) (let ((limit (string-length str))) (let lp ((i 0) (res '())) (if (>= i limit) (reverse res) (lp (+ i (utf8-start-byte->length (string-int-ref str i))) (cons (sp-ref str i) res)))))) (define (make-utf8-string len . opt) (if (pair? opt) (let* ((c (car opt)) (c-i (char->integer c)) (c-len (ucs-integer->length c-i))) (if (<= c-len 1) (make-string len c) (let* ((size (* len c-len)) (res (make-string size))) (let lp ((i 0)) (if (>= i size) res (begin (string-set-at-byte-in-place! res size c-len i c-i) (lp (+ i c-len)))))))) (make-string len))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; accessors (define (sp-ref s off) (let* ((c (string-int-ref s off)) (len (utf8-start-byte->length c)) (limit (string-length s))) (if (<= len 1) (integer->char c) (let ((end (+ off len))) (if (> end limit) (error "utf8 trailing char overflow" s off) (let loop ((i (+ off 1)) (res (extract-bit-field (- 7 len) 0 c))) (if (= i end) (integer->char res) (loop (+ i 1) (bitwise-ior (arithmetic-shift res 6) (bitwise-and #b00111111 (string-int-ref s i))))))))))) (define (sp-ref->string s off) (let* ((c (string-int-ref s off)) (len (utf8-start-byte->length c)) (limit (string-length s)) (end (+ off len))) (if (> end limit) (error "utf8 trailing char overflow" s off) (substring s off end)))) (define (utf8-string-ref s pos) (sp-ref s (utf8-index->offset s pos))) (define (string-set-at-byte-in-place! s limit c-len off val-i) (let ((end (+ off c-len))) (cond ((> end limit) (error "utf8 trailing char overflow" s off)) ((<= c-len 1) (string-int-set! s off val-i)) (else (let* ((tag (- (expt 2 c-len) 1)) (tag-shift (arithmetic-shift tag (- 8 c-len))) (body (extract-bit-field (- 7 c-len) (* 6 (- c-len 1)) val-i)) (b1 (bitwise-ior tag-shift body))) (string-int-set! s off b1)) (let loop ((i 1)) (unless (= i c-len) (let ((b (bitwise-ior #b10000000 (extract-bit-field 6 (* 6 (- c-len i 1)) val-i)))) (string-int-set! s (+ off i) b) (loop (+ i 1))))))))) (define (string-set-at-byte s size byte c-len val) (let ((s1 (substring s 0 byte)) (s2 (char->utf8-string val)) (s3 (substring s (+ byte c-len) size))) (string-append s1 s2 s3))) (define (sp-set! s off val) (let* ((limit (string-length s)) (c (string-int-ref s off)) (c-len (utf8-start-byte->length c)) (val-i (char->integer val)) (val-len (ucs-integer->length val-i))) (if (not (= c-len val-len)) ;; different size, allocate & become new string (let ((res (string-set-at-byte s limit off c-len val))) (##sys#become! (list (cons s res)))) ;; modify in place (string-set-at-byte-in-place! s limit c-len off val-i)))) (define (utf8-string-set! s pos val) (sp-set! s (utf8-index->offset s pos) val)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; String Pointers (define (make-string-pointer s . opt) (if (pair? opt) (let ((pos (car opt))) (if (negative? pos) (sp-prev s (utf8-prev-char s (string-length s)) (+ pos 1)) (sp-next s 0 pos))) 0)) (define (string-pointer? obj) (integer? obj)) (define (sp-copy sp) sp) (define (sp-check-lo? s sp) (positive? sp)) (define (sp-check-hi? s sp) (< sp (string-length s))) (define (sp-check? s sp) (and (sp-check-lo? s sp) (sp-check-hi? s sp))) ;; returns the next string-pointer, or the string-length (an invalid ;; pointer) otherwise (define (sp-next s sp . opt) (let loop ((i (if (pair? opt) (car opt) 1)) (sp sp)) (if (positive? i) (let ((res (utf8-next-char s sp))) (if res (loop (- i 1) res) (string-length s))) sp))) (define (sp-prev s sp . opt) (let loop ((i (if (pair? opt) (car opt) 1)) (sp sp)) (if (positive? i) (let ((res (utf8-prev-char s sp))) (if res (loop (- i 1) res) -1)) sp))) (define (sp-first s) 0) (define (sp-last s) (string-length s)) (define (sp-before s sp) (substring s 0 sp)) (define (sp-after s sp) (substring s sp)) (define (sp-substring s . opt) (if (null? opt) (substring s 0) (apply substring s opt))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Basic I/O ;; now in the core library (define (char->utf8-string c) (##sys#char->utf8-string c)) (define (write-utf8-char c . opt) (display (char->utf8-string c) (if (pair? opt) (car opt) (current-output-port)))) (define (read-utf8-char . opt) (let* ((p (if (pair? opt) (car opt) (current-input-port))) (b1 (read-byte p))) (if (eof-object? b1) b1 (let ((len (utf8-start-byte->length b1))) (if (<= len 1) (integer->char b1) (let loop ((res (extract-bit-field (- 7 len) 0 b1)) (i (- len 1))) (if (zero? i) (integer->char res) (let ((b2 (read-byte p))) (cond ((eof-object? b2) b2) ((not (= #b10 (extract-bit-field 2 6 b2))) (error "invalid utf8 sequence")) (else (loop (bitwise-ior (arithmetic-shift res 6) (bitwise-and #b00111111 b2)) (- i 1)))))))))))) (define-syntax char<= (syntax-rules () ((char<= a b) (char<=? a b)) ((char<= a b c) (and (char<=? a b) (char<=? b c))))) (define (utf8-tail? c) (char<= #\x80 c #\xBF)) (define (utf8-2? c0 c1) (and (utf8-tail? c1) (char<=? #\xC2 c0))) ;; C0-C1 can only be overlong (define (utf8-3? c0 c1 c2) (and (utf8-tail? c1) (utf8-tail? c2) (cond ((char=? c0 #\xE0) ;; check overlong (char<=? #\xA0 c1)) ((char=? c0 #\xED) ;; check surrogate (char<=? c1 #\x9F)) (else #t)))) (define (utf8-4? c0 c1 c2 c3) (and (utf8-tail? c1) (utf8-tail? c2) (utf8-tail? c3) (cond ((char=? c0 #\xF0) ;; check overlong (char<=? #\x90 c1)) ((char=? c0 #\xF4) ;; check in range (char<=? c1 #\x8F)) (else (char<=? c0 #\xF3))))) ;; check in range ;; Ensure all codepoints within range, not overlong, are not UTF-16 ;; surrogate halves, and have the right number of continuation bytes. (define (utf8-string? str) (let ((len (string-length str))) (let loop ((pos 0)) (or (fx= pos len) (let ((c0 (string-ref str pos))) (let-syntax ((validate (syntax-rules () ((_ valid? c ... n) (and (fx<= n (fx- len pos)) (valid? c0 (string-ref str (fx+ pos c)) ...) (loop (fx+ pos n))))))) (if (char<=? c0 #\x7F) (loop (fx+ pos 1)) (case (utf8-start-byte->length (char->integer c0)) ((2) (validate utf8-2? 1 2)) ((3) (validate utf8-3? 1 2 3)) ((4) (validate utf8-4? 1 2 3 4)) (else #f))))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-syntax in-utf8-string (syntax-rules () ((in-utf8-string ((var) (str)) next . rest) (in-utf8-string ((var off) (str)) next . rest)) ((in-utf8-string ((var off) (str)) next . rest) (next ((tmp str) (lim (sp-last tmp))) ((off (sp-first tmp) (fx+ off (utf8-start-byte->length (string-int-ref str off))))) ((fx>= off lim)) ((var (sp-ref tmp off))) () . rest)))) )
true
3c177954866740df88ded0ab1c8bdaeddcf893e0
4a9bde514c789982d7dda8362cd50b9d7482913f
/Chapter2/sicp2.27-2.28.scm
740ff4abfb3a64de031569219a5270f72398c7d0
[]
no_license
atsfour/sicp
7e8e0deefa16201da6d01db34e24ad3245dbb052
f6f2818cbe440ac2ec557453945c0782e7267842
refs/heads/master
2020-03-30T08:12:36.638041
2015-12-03T15:50:47
2015-12-08T06:51:04
39,726,082
0
0
null
null
null
null
UTF-8
Scheme
false
false
365
scm
sicp2.27-2.28.scm
;Exercise 2.27 (define (deep-reverse x) (if (pair? x) (append (deep-reverse (cdr x)) (list (deep-reverse (car x)))) x)) ;Exercise 2.28 (define (fringe x) (cond ((null? x) x) ((pair? x) (append (fringe (car x)) (fringe (cdr x)))) (else (list x)))) (define sample-1 (list (list 1 2) 3)) (define sample-2 (list 1 (list 2 3 (list 4 5)))) ;((7 6) 5 4)
false
aff378e4dd2a837fbbfc8f4c426c45c8b172f96c
e82d67e647096e56cb6bf1daef08552429284737
/ex3-16.scm
ba8069c83dcd5948b9f3c656938dbec8d9800dce
[]
no_license
ashishmax31/sicp-exercises
97dfe101dd5c91208763dcc4eaac2c17977d1dc1
097f76a5637ccb1fba055839d389541a1a103e0f
refs/heads/master
2020-03-28T11:16:28.197294
2019-06-30T20:25:18
2019-06-30T20:25:18
148,195,859
6
0
null
null
null
null
UTF-8
Scheme
false
false
407
scm
ex3-16.scm
(define (count-pairs x) (if (not (pair? x)) 0 (+ (count-pairs (car x)) (count-pairs (cdr x)) 1))) (define three-pairs '(a b c)) (count-pairs three-pairs) (define b-nil (cons 'b '())) (define four-pairs (cons 'a (cons b-nil b-nil))) (count-pairs four-pairs) (define a.a (cons 'a 'a )) (define a.a-a.a (cons a.a a.a)) (define seven-pairs (cons a.a-a.a a.a-a.a)) (count-pairs seven-pairs)
false