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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
582698add804d654e4669f7018b48e4263a907be | c22faca441eb0c96c35bd3f225dc8d4de8ba1b16 | /tests/test-radix.scm | b379c1917b8fcc8180120b13ba9099fb5149a543 | []
| no_license | buhman/route-mux | 30c783137fc0600c46d4d020f5e2a996497a5b85 | 3e8c470e5af671b382c56fd55a9b69bf880acfa2 | refs/heads/master | 2020-04-13T10:49:25.004039 | 2019-03-26T05:53:04 | 2019-03-26T05:53:04 | 163,154,310 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,470 | scm | test-radix.scm | (import (route-mux radix)
matchable)
;; test data
(define +names+
'((romane . 1)
(romanus . 2)
(romulus . 3)
(rubens . 4)
(ruber . 5)
(rubicon . 6)
(rubicundus . 7)))
(define +root+
(compact-root->tree
'(#f
("r" #f
("om" #f
("an" #f
("aa" 99)
("e" 1)
("gg" 99)
("us" 2)
("zz" 99))
("ulus" 3))
("ub" #f
("e" #f
("aa" 99)
("ns" 4)
("oo" 99)
("pp" 99)
("qq" 99)
("r" 5)
("zz" 99))
("ic" #f
("on" 6)
("undus" 7)))))))
(define +root-basic+
(compact-root->tree
'(#f
("r" #f
("om" #f
("an" #f
("e" 1)
("us" 2))
("ulus" 3))
("ub" #f
("e" #f
("ns" 4)
("r" 5))
("ic" #f
("on" 6)
("undus" 7)))))))
(define +one-edge+
(compact-root->tree
'(1
("test" 2))))
;; tests
(test-group "radix node-search"
(test-values "edge-match complete"
(list (make-node 2 #()) "1234" 0 #f)
(node-search +one-edge+ "test1234"))
(test-values "edge-match incomplete"
(list +one-edge+ "oast" 2 (make-edge "test" (make-node 2 #())))
(node-search +one-edge+ "teoast"))
(test-values "edge-match none"
(list +one-edge+ "foo" 0 #f)
(node-search +one-edge+ "foo"))
(test-parameterize "node-search edge recursion"
(romane romanus romulus rubens ruber rubicon rubicundus)
(lambda (s) (alist-ref s +names+))
(lambda (s) (node-value (node-search +root+ (symbol->string s))))))
;; insert tests
(define (test-node-insert alist)
(let ((root (make-node #f #())))
(for-each
(lambda (name)
(match name
((key . value)
(node-insert! root (symbol->string key) value))))
alist)
root))
(test-group "radix node-insert"
(test "sorted-insert start"
#(1 2 4 5)
(sorted-insert #(2 4 5) 1 <))
(test "sorted-insert middle"
#(2 3 4 5)
(sorted-insert #(2 4 5) 3 <))
(test "sorted-insert end"
#(2 4 5 6)
(sorted-insert #(2 4 5) 6 <))
(test "sorted-edge-insert"
(vector (make-edge "a" #f) (make-edge "b" #f) (make-edge "c" #f))
(sorted-edge-insert
(vector (make-edge "a" #f) (make-edge "c" #f))
(make-edge "b" #f)))
(test "node-insert"
+root-basic+
(test-node-insert +names+))
(test "node-insert reverse"
+root-basic+
(test-node-insert (reverse +names+))))
| false |
b20882f9bc8876f4be0d15ce204e878f3fa48fee | a8216d80b80e4cb429086f0f9ac62f91e09498d3 | /lib/srfi/101.scm | 2b8082439c45e476bc6344411507d72429dde8e7 | [
"BSD-3-Clause"
]
| permissive | ashinn/chibi-scheme | 3e03ee86c0af611f081a38edb12902e4245fb102 | 67fdb283b667c8f340a5dc7259eaf44825bc90bc | refs/heads/master | 2023-08-24T11:16:42.175821 | 2023-06-20T13:19:19 | 2023-06-20T13:19:19 | 32,322,244 | 1,290 | 223 | NOASSERTION | 2023-08-29T11:54:14 | 2015-03-16T12:05:57 | Scheme | UTF-8 | Scheme | false | false | 15,534 | scm | 101.scm | ;; Adapted for R7RS by Alex Shinn 2018.
;; SRFI 101: Purely Functional Random-Access Pairs and Lists
;; Copyright (c) David Van Horn 2009. All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without restriction,
;; including without limitation the rights to use, copy, modify, merge,
;; publish, distribute, sublicense, and/or sell copies of the Software,
;; and to permit persons to whom the Software is furnished to do so,
;; subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. REMEMBER, THERE IS NO SCHEME UNDERGROUND. 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-record-type kons
(make-kons size tree rest)
kons?
(size kons-size)
(tree kons-tree)
(rest kons-rest))
(define-record-type node
(make-node val left right)
node?
(val node-val)
(left node-left)
(right node-right))
(define-syntax assert
(syntax-rules ()
((assert expr ...)
(begin (unless expr (error "assertion failed" 'expr)) ...))))
;; Nat -> Nat
(define (sub1 n) (- n 1))
(define (add1 n) (+ n 1))
;; [Tree X] -> X
(define (tree-val t)
(if (node? t)
(node-val t)
t))
;; [X -> Y] [Tree X] -> [Tree Y]
(define (tree-map f t)
(if (node? t)
(make-node (f (node-val t))
(tree-map f (node-left t))
(tree-map f (node-right t)))
(f t)))
;; [X -> Y] [Tree X] -> unspecified
(define (tree-for-each f t)
(if (node? t)
(begin (f (node-val t))
(tree-for-each f (node-left t))
(tree-for-each f (node-right t)))
(f t)))
;; [X Y Z ... -> R] [List [Tree X] [Tree Y] [Tree Z] ...] -> [Tree R]
(define (tree-map/n f ts)
(let recr ((ts ts))
(if (and (pair? ts)
(node? (car ts)))
(make-node (apply f (map node-val ts))
(recr (map node-left ts))
(recr (map node-right ts)))
(apply f ts))))
;; [X Y Z ... -> R] [List [Tree X] [Tree Y] [Tree Z] ...] -> unspecified
(define (tree-for-each/n f ts)
(let recr ((ts ts))
(if (and (pair? ts)
(node? (car ts)))
(begin (apply f (map node-val ts))
(recr (map node-left ts))
(recr (map node-right ts)))
(apply f ts))))
;; Nat [Nat -> X] -> [Tree X]
;; like build-list, but for complete binary trees
(define (build-tree i f) ;; i = 2^j-1
(let rec ((i i) (o 0))
(if (= 1 i)
(f o)
(let ((i/2 (half i)))
(make-node (f o)
(rec i/2 (add1 o))
(rec i/2 (+ 1 o i/2)))))))
;; Consumes n = 2^i-1 and produces 2^(i-1)-1.
;; Nat -> Nat
(define (half n)
(bitwise-arithmetic-shift n -1))
;; Nat X -> [Tree X]
(define (tr:make-tree i x) ;; i = 2^j-1
(let recr ((i i))
(if (= 1 i)
x
(let ((n (recr (half i))))
(make-node x n n)))))
;; Nat [Tree X] Nat [X -> X] -> X [Tree X]
(define (tree-ref/update mid t i f)
(cond ((zero? i)
(if (node? t)
(values (node-val t)
(make-node (f (node-val t))
(node-left t)
(node-right t)))
(values t (f t))))
((<= i mid)
(let-values (((v* t*) (tree-ref/update (half (sub1 mid))
(node-left t)
(sub1 i)
f)))
(values v* (make-node (node-val t) t* (node-right t)))))
(else
(let-values (((v* t*) (tree-ref/update (half (sub1 mid))
(node-right t)
(sub1 (- i mid))
f)))
(values v* (make-node (node-val t) (node-left t) t*))))))
;; Special-cased above to avoid logarathmic amount of cons'ing
;; and any multi-values overhead. Operates in constant space.
;; [Tree X] Nat Nat -> X
;; invariant: (= mid (half (sub1 (tree-count t))))
(define (tree-ref/a t i mid)
(cond ((zero? i) (tree-val t))
((<= i mid)
(tree-ref/a (node-left t)
(sub1 i)
(half (sub1 mid))))
(else
(tree-ref/a (node-right t)
(sub1 (- i mid))
(half (sub1 mid))))))
;; Nat [Tree X] Nat -> X
;; invariant: (= size (tree-count t))
(define (tree-ref size t i)
(if (zero? i)
(tree-val t)
(tree-ref/a t i (half (sub1 size)))))
;; Nat [Tree X] Nat [X -> X] -> [Tree X]
(define (tree-update size t i f)
(let recr ((mid (half (sub1 size))) (t t) (i i))
(cond ((zero? i)
(if (node? t)
(make-node (f (node-val t))
(node-left t)
(node-right t))
(f t)))
((<= i mid)
(make-node (node-val t)
(recr (half (sub1 mid))
(node-left t)
(sub1 i))
(node-right t)))
(else
(make-node (node-val t)
(node-left t)
(recr (half (sub1 mid))
(node-right t)
(sub1 (- i mid))))))))
;; ------------------------
;; Random access lists
;; [RaListof X]
(define ra:null (quote ()))
;; [Any -> Boolean]
(define ra:pair? kons?)
;; [Any -> Boolean]
(define ra:null? null?)
;; X [RaListof X] -> [RaListof X] /\
;; X Y -> [RaPair X Y]
(define (ra:cons x ls)
(if (kons? ls)
(let ((s (kons-size ls)))
(if (and (kons? (kons-rest ls))
(= (kons-size (kons-rest ls))
s))
(make-kons (+ 1 s s)
(make-node x
(kons-tree ls)
(kons-tree (kons-rest ls)))
(kons-rest (kons-rest ls)))
(make-kons 1 x ls)))
(make-kons 1 x ls)))
;; [RaPair X Y] -> X Y
(define ra:car+cdr
(lambda (p)
(assert (kons? p))
(if (node? (kons-tree p))
(let ((s* (half (kons-size p))))
(values (tree-val (kons-tree p))
(make-kons s*
(node-left (kons-tree p))
(make-kons s*
(node-right (kons-tree p))
(kons-rest p)))))
(values (kons-tree p) (kons-rest p)))))
;; [RaPair X Y] -> X
(define (ra:car p)
(call-with-values (lambda () (ra:car+cdr p))
(lambda (car cdr) car)))
;; [RaPair X Y] -> Y
(define (ra:cdr p)
(call-with-values (lambda () (ra:car+cdr p))
(lambda (car cdr) cdr)))
;; [RaListof X] Nat [X -> X] -> X [RaListof X]
(define (ra:list-ref/update ls i f)
;(assert (< i (ra:length ls)))
(let recr ((xs ls) (j i))
(if (< j (kons-size xs))
(let-values (((v* t*)
(tree-ref/update (half (sub1 (kons-size xs)))
(kons-tree xs) j f)))
(values v* (make-kons (kons-size xs)
t*
(kons-rest xs))))
(let-values (((v* r*)
(recr (kons-rest xs)
(- j (kons-size xs)))))
(values v* (make-kons (kons-size xs)
(kons-tree xs)
r*))))))
;; [RaListof X] Nat [X -> X] -> [RaListof X]
(define (ra:list-update ls i f)
;(assert (< i (ra:length ls)))
(let recr ((xs ls) (j i))
(let ((s (kons-size xs)))
(if (< j s)
(make-kons s (tree-update s (kons-tree xs) j f) (kons-rest xs))
(make-kons s (kons-tree xs) (recr (kons-rest xs) (- j s)))))))
;; [RaListof X] Nat X -> (values X [RaListof X])
(define (ra:list-ref/set ls i v)
(ra:list-ref/update ls i (lambda (_) v)))
;; X ... -> [RaListof X]
(define (ra:list . xs)
(fold-right ra:cons ra:null xs))
;; Nat X -> [RaListof X]
(define ra:make-list
(case-lambda
((k) (ra:make-list k 0))
((k obj)
(let loop ((n k) (a ra:null))
(cond ((zero? n) a)
(else
(let ((t (largest-skew-binary n)))
(loop (- n t)
(make-kons t (tr:make-tree t obj) a)))))))))
;; A Skew is a Nat 2^k-1 with k > 0.
;; Skew -> Skew
(define (skew-succ t) (add1 (bitwise-arithmetic-shift t 1)))
;; Computes the largest skew binary term t <= n.
;; Nat -> Skew
(define (largest-skew-binary n)
(if (= 1 n)
1
(let* ((t (largest-skew-binary (half n)))
(s (skew-succ t)))
(if (> s n) t s))))
;; [Any -> Boolean]
;; Is x a PROPER list?
(define (ra:list? x)
(or (ra:null? x)
(and (kons? x)
(ra:list? (kons-rest x)))))
(define ra:caar (lambda (ls) (ra:car (ra:car ls))))
(define ra:cadr (lambda (ls) (ra:car (ra:cdr ls))))
(define ra:cddr (lambda (ls) (ra:cdr (ra:cdr ls))))
(define ra:cdar (lambda (ls) (ra:cdr (ra:car ls))))
(define ra:caaar (lambda (ls) (ra:car (ra:car (ra:car ls)))))
(define ra:caadr (lambda (ls) (ra:car (ra:car (ra:cdr ls)))))
(define ra:caddr (lambda (ls) (ra:car (ra:cdr (ra:cdr ls)))))
(define ra:cadar (lambda (ls) (ra:car (ra:cdr (ra:car ls)))))
(define ra:cdaar (lambda (ls) (ra:cdr (ra:car (ra:car ls)))))
(define ra:cdadr (lambda (ls) (ra:cdr (ra:car (ra:cdr ls)))))
(define ra:cdddr (lambda (ls) (ra:cdr (ra:cdr (ra:cdr ls)))))
(define ra:cddar (lambda (ls) (ra:cdr (ra:cdr (ra:car ls)))))
(define ra:caaaar (lambda (ls) (ra:car (ra:car (ra:car (ra:car ls))))))
(define ra:caaadr (lambda (ls) (ra:car (ra:car (ra:car (ra:cdr ls))))))
(define ra:caaddr (lambda (ls) (ra:car (ra:car (ra:cdr (ra:cdr ls))))))
(define ra:caadar (lambda (ls) (ra:car (ra:car (ra:cdr (ra:car ls))))))
(define ra:cadaar (lambda (ls) (ra:car (ra:cdr (ra:car (ra:car ls))))))
(define ra:cadadr (lambda (ls) (ra:car (ra:cdr (ra:car (ra:cdr ls))))))
(define ra:cadddr (lambda (ls) (ra:car (ra:cdr (ra:cdr (ra:cdr ls))))))
(define ra:caddar (lambda (ls) (ra:car (ra:cdr (ra:cdr (ra:car ls))))))
(define ra:cdaaar (lambda (ls) (ra:cdr (ra:car (ra:car (ra:car ls))))))
(define ra:cdaadr (lambda (ls) (ra:cdr (ra:car (ra:car (ra:cdr ls))))))
(define ra:cdaddr (lambda (ls) (ra:cdr (ra:car (ra:cdr (ra:cdr ls))))))
(define ra:cdadar (lambda (ls) (ra:cdr (ra:car (ra:cdr (ra:car ls))))))
(define ra:cddaar (lambda (ls) (ra:cdr (ra:cdr (ra:car (ra:car ls))))))
(define ra:cddadr (lambda (ls) (ra:cdr (ra:cdr (ra:car (ra:cdr ls))))))
(define ra:cddddr (lambda (ls) (ra:cdr (ra:cdr (ra:cdr (ra:cdr ls))))))
(define ra:cdddar (lambda (ls) (ra:cdr (ra:cdr (ra:cdr (ra:car ls))))))
;; [RaList X] -> Nat
(define (ra:length ls)
(assert (ra:list? ls))
(let recr ((ls ls))
(if (kons? ls)
(+ (kons-size ls) (recr (kons-rest ls)))
0)))
(define (ra:length<=? ls k)
(let lp ((ls ls) (k k))
(if (positive? k)
(and (ra:pair? ls)
(lp (ra:cdr ls) (- k 1)))
#t)))
(define (make-foldl empty? first rest)
(letrec ((f (lambda (cons empty ls)
(if (empty? ls)
empty
(f cons
(cons (first ls) empty)
(rest ls))))))
f))
(define (make-foldr empty? first rest)
(letrec ((f (lambda (cons empty ls)
(if (empty? ls)
empty
(cons (first ls)
(f cons empty (rest ls)))))))
f))
;; [X Y -> Y] Y [RaListof X] -> Y
(define ra:foldl/1 (make-foldl ra:null? ra:car ra:cdr))
(define ra:foldr/1 (make-foldr ra:null? ra:car ra:cdr))
;; [RaListof X] ... -> [RaListof X]
(define (ra:append . lss)
(cond ((null? lss) ra:null)
(else (let recr ((lss lss))
(cond ((null? (cdr lss)) (car lss))
(else (ra:foldr/1 ra:cons
(recr (cdr lss))
(car lss))))))))
;; [RaListof X] -> [RaListof X]
(define (ra:reverse ls)
(ra:foldl/1 ra:cons ra:null ls))
;; [RaListof X] Nat -> [RaListof X]
(define (ra:list-tail ls i)
(let loop ((xs ls) (j i))
(cond ((zero? j) xs)
(else (loop (ra:cdr xs) (sub1 j))))))
;; [RaListof X] Nat -> X
;; Special-cased above to avoid logarathmic amount of cons'ing
;; and any multi-values overhead. Operates in constant space.
(define (ra:list-ref ls i)
;(assert (< i (ra:length ls)))
(let loop ((xs ls) (j i))
(if (< j (kons-size xs))
(tree-ref (kons-size xs) (kons-tree xs) j)
(loop (kons-rest xs) (- j (kons-size xs))))))
;; [RaListof X] Nat X -> [RaListof X]
(define (ra:list-set ls i v)
(let-values (((_ l*) (ra:list-ref/set ls i v))) l*))
;; [X ... -> y] [RaListof X] ... -> [RaListof Y]
;; Takes advantage of the fact that map produces a list of equal size.
(define ra:map
(case-lambda
((f ls)
(let recr ((ls ls))
(if (kons? ls)
(make-kons (kons-size ls)
(tree-map f (kons-tree ls))
(recr (kons-rest ls)))
ra:null)))
((f . lss)
;(check-nary-loop-args 'ra:map (lambda (x) x) f lss)
(let recr ((lss lss))
(cond ((ra:null? (car lss)) ra:null)
(else
;; IMPROVE ME: make one pass over lss.
(make-kons (kons-size (car lss))
(tree-map/n f (map kons-tree lss))
(recr (map kons-rest lss)))))))))
;; [X ... -> Y] [RaListof X] ... -> unspecified
(define ra:for-each
(case-lambda
((f ls)
(when (kons? ls)
(tree-for-each f (kons-tree ls))
(ra:for-each f (kons-rest ls))))
((f . lss)
;(check-nary-loop-args 'ra:map (lambda (x) x) f lss)
(let recr ((lss lss))
(when (ra:pair? (car lss))
(tree-map/n f (map kons-tree lss))
(recr (map kons-rest lss)))))))
;; [RaListof X] -> [Listof X]
(define (ra:random-access-list->linear-access-list x)
(ra:foldr/1 cons '() x))
;; [Listof X] -> [RaListof X]
(define (ra:linear-access-list->random-access-list x)
(fold-right ra:cons '() x))
;; This code based on code written by Abdulaziz Ghuloum
;; http://ikarus-scheme.org/pipermail/ikarus-users/2009-September/000595.html
(define get-cached
(let ((h (make-hash-table eq?)))
(lambda (x)
(define (f x)
(cond
((pair? x) (ra:cons (f (car x)) (f (cdr x))))
((vector? x) (vector-map f x))
(else x)))
(cond
((not (or (pair? x) (vector? x))) x)
((hash-table-ref/default h x #f))
(else
(let ((v (f x)))
(hash-table-set! h x v)
v))))))
(define-syntax ra:quote
(syntax-rules ()
((ra:quote datum) (get-cached 'datum))))
| true |
85f0d2ca2398222acf3fb9d198d9c35f1fd77800 | 6b961ef37ff7018c8449d3fa05c04ffbda56582b | /bbn_cl/mach/runtime/debug.scm | 4dfba68a129300c18c093561e363d5ce817c0c92 | []
| 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 | 18,436 | scm | debug.scm | ;;; -*-Scheme-*-
;;;
;;;
;;; Copyright (c) 1987 Massachusetts Institute of Technology
;;;
;;; This material was developed by the Scheme project at the
;;; Massachusetts Institute of Technology, Department of
;;; Electrical Engineering and Computer Science. Permission to
;;; copy this software, to redistribute it, and to use it for any
;;; purpose is granted, subject to the following restrictions and
;;; understandings.
;;;
;;; 1. Any copy made of this software must include this copyright
;;; notice in full.
;;;
;;; 2. Users of this software agree to make their best efforts (a)
;;; to return to the MIT Scheme project any improvements or
;;; extensions that they make, so that these may be included in
;;; future releases; and (b) to inform MIT of noteworthy uses of
;;; this software.
;;;
;;; 3. All materials developed as a consequence of the use of this
;;; software shall duly acknowledge such use, in accordance with
;;; the usual standards of acknowledging credit in academic
;;; research.
;;;
;;; 4. MIT has made no warrantee or representation that the
;;; operation of this software will be error-free, and MIT is
;;; under no obligation to provide any services, by way of
;;; maintenance, update, or otherwise.
;;;
;;; 5. In conjunction with products arising from the use of this
;;; material, there shall be no use of the name of the
;;; Massachusetts Institute of Technology nor of any adaptation
;;; thereof in any advertising, promotional, or sales literature
;;; without prior written consent from MIT in each case.
;;;
;;;; Debugger
(declare (usual-integrations))
(define debug-compiled-continuation false)
(define debug-package
(make-environment
(define current-continuation)
(define previous-continuations)
(define current-reduction-number)
(define current-number-of-reductions)
(define current-reduction)
(define current-environment)
(define command-set
(make-command-set 'DEBUG-COMMANDS))
(define reduction-wrap-around-tag
'WRAP-AROUND)
(define print-user-friendly-name
(access print-user-friendly-name env-package))
(define print-expression
pp)
(define student-walk?
false)
(define print-return-values?
false)
(define environment-arguments-truncation
68)
(define (define-debug-command letter function help-text)
(define-letter-command command-set letter function help-text))
;;; Basic Commands
(define-debug-command #\? (standard-help-command command-set)
"Help, list command letters")
(define-debug-command #\Q standard-exit-command "Quit (exit DEBUG)")
(define (debug #!optional the-continuation)
(fluid-let ((current-continuation)
(previous-continuations '())
(current-reduction-number)
(current-number-of-reductions)
(current-reduction false)
(current-environment '()))
(debug-abstract-continuation
(cond ((unassigned? the-continuation) (rep-continuation))
((raw-continuation? the-continuation); Must precede next test!
(raw-continuation->continuation the-continuation))
((continuation? the-continuation) the-continuation)
(else (error "DEBUG: Not a continuation" the-continuation))))))
(define (debug-abstract-continuation continuation)
(set-current-continuation! continuation initial-reduction-number)
(letter-commands command-set
(lambda ()
(print-current-expression)
((standard-rep-message "Debugger")))
"Debug-->"))
(define (undefined-environment? environment)
(or (continuation-undefined-environment? environment)
(eq? environment system-global-environment)
(and (environment? environment)
((access system-external-environment? environment-package)
environment))))
(define (print-undefined-environment)
(format "~%Undefined environment at this subproblem/reduction level"))
(define (with-rep-alternative env receiver)
(if (undefined-environment? env)
(begin
(print-undefined-environment)
(format "~%Using the read-eval-print environment instead!")
(receiver (rep-environment)))
(receiver env)))
(define (if-valid-environment env receiver)
(if (undefined-environment? env)
(print-undefined-environment)
(receiver env)))
(define (current-expression)
(if current-reduction
(reduction-expression current-reduction)
(let ((exp (continuation-expression current-continuation)))
(if (or (not (continuation-undefined-expression? exp))
(null? (continuation-annotation current-continuation)))
exp
(cons 'UNDEFINED-EXPRESSION
(continuation-annotation current-continuation))))))
;;;; Random display commands
(define (pretty-print-current-expression)
(print-expression (current-expression)))
(define-debug-command #\L pretty-print-current-expression
"(list expression) Pretty-print the current expression")
(define (pretty-print-reduction-function)
(if-valid-environment (if current-reduction
(reduction-environment current-reduction)
current-environment)
(lambda (env) (pp (environment-procedure env)))))
(define-debug-command #\P pretty-print-reduction-function
"Pretty print current procedure")
(define (print-current-expression)
(define (print-current-reduction)
(format "~2xReduction Number:~x~o~%Expression:" current-reduction-number)
(print-expression (reduction-expression current-reduction)))
(define (print-application-information env)
(let ((do-it
(lambda (return?)
(if return? (newline))
(write-string "within ")
(print-user-friendly-name env)
(if return? (newline))
(write-string " applied to ")
(write-string
(cdr (write-to-string (environment-arguments env)
environment-arguments-truncation))))))
(let ((output (with-output-to-string (lambda () (do-it false)))))
(if (< (string-length output)
(access printer-width implementation-dependencies))
(begin (newline) (write-string output))
(do-it true)))))
(newline)
(if (null-continuation? current-continuation)
(write-string "Null continuation")
(begin
(write-string "Subproblem Level: ")
(write (length previous-continuations))
(if current-reduction
(print-current-reduction)
(begin
(newline)
(write-string "Possibly Incomplete Expression:")
(print-expression
(continuation-expression current-continuation))))
(if-valid-environment current-environment
print-application-information))))
(define-debug-command #\S print-current-expression
"Print the current subproblem/reduction")
(define (reductions-command)
(if (null-continuation? current-continuation)
(format "~%Null continuation")
(let loop ((r (continuation-reductions current-continuation)))
(cond ((pair? r)
(print-expression (reduction-expression (car r)))
(loop (cdr r)))
((wrap-around-in-reductions? r)
(format "~%Wrap Around in the reductions at this level."))
(else 'done)))))
(define-debug-command #\R reductions-command
"Print the reductions of the current subproblem level")
;;;; Short history display
(define (summarize-history-command)
(define (print-continuations cont level)
(define (print-reductions reductions show-all?)
(define (print-reduction red number)
(terse-print-expression level
(reduction-expression red)
(reduction-environment red)))
(let loop ((reductions reductions) (number 0))
(if (pair? reductions)
(begin
(print-reduction (car reductions) number)
(if show-all? (loop (cdr reductions) (1+ number)))))))
(if (null-continuation? cont)
*the-non-printing-object*
(begin
(let ((reductions (continuation-reductions cont)))
(if (not (pair? reductions))
(terse-print-expression level
(continuation-expression cont)
(continuation-environment cont))
(print-reductions reductions (= level 0))))
(print-continuations (continuation-next-continuation cont)
(1+ level)))))
(let ((top-continuation (if (null? previous-continuations)
current-continuation
(car (last-pair previous-continuations)))))
(if (null-continuation? top-continuation)
(format "~%No history available")
(begin
(format "~%Sub Prb. Procedure Name Expression~%")
(print-continuations top-continuation 0)))))
(define (terse-print-expression level expression environment)
(format "~%~@3o~:20o~4x~@:52c"
level
;; procedure name
(if (or (undefined-environment? environment)
(special-name? (environment-name environment)))
*the-non-printing-object*
(environment-name environment))
expression))
(define-debug-command #\H summarize-history-command
"Prints a summary of the entire history")
;;;; Motion to earlier expressions
(define (earlier-reduction)
(define (up! message)
(format "~%~s~%Going to the previous (earlier) continuation!" message)
(earlier-continuation-command))
(cond ((and student-walk?
(> (length previous-continuations) 0)
(= current-reduction-number 0))
(earlier-continuation-command))
((< current-reduction-number (-1+ current-number-of-reductions))
(set-current-reduction! (1+ current-reduction-number))
(print-current-expression))
((wrap-around-in-reductions?
(continuation-reductions current-continuation))
(up! "Wrap around in reductions at this level!"))
(else (up! "No more reductions at this level!"))))
(define-debug-command #\B earlier-reduction "Earlier reduction (Back in time)")
(define (earlier-subproblem)
(let ((new (continuation-next-continuation current-continuation)))
(set! previous-continuations
(cons current-continuation previous-continuations))
(set-current-continuation! new normal-reduction-number)))
(define (earlier-continuation-command)
(if (not (null-continuation? (continuation-next-continuation
current-continuation)))
(earlier-subproblem)
(format "~%There are only ~o subproblem levels"
(length previous-continuations)))
(print-current-expression))
(define-debug-command #\U earlier-continuation-command
"Move (Up) to the previous (earlier) continuation")
;;;; Motion to later expressions
(define (later-reduction)
(cond ((> current-reduction-number 0)
(set-current-reduction! (-1+ current-reduction-number))
(print-current-expression))
((or (not student-walk?)
(= (length previous-continuations) 1))
(later-continuation-TO-LAST-REDUCTION))
(else (later-continuation))))
(define-debug-command #\F later-reduction "Later reduction (Forward in time)")
(define (later-continuation)
(if (null? previous-continuations)
(format "~%Already at lowest subproblem level")
(begin (later-subproblem) (print-current-expression))))
(define (later-continuation-TO-LAST-REDUCTION)
(define (later-subproblem-TO-LAST-REDUCTION)
(set-current-continuation!
(car (set! previous-continuations (cdr previous-continuations)))
last-reduction-number))
(if (null? previous-continuations)
(format "~%Already at lowest subproblem level")
(begin (later-subproblem-TO-LAST-REDUCTION)
(print-current-expression))))
(define (later-subproblem)
(set-current-continuation!
(car (set! previous-continuations (cdr previous-continuations)))
normal-reduction-number))
(define (later-continuation-command)
(if (null? previous-continuations)
(format "~%Already at oldest continuation")
(begin (later-subproblem) (print-current-expression))))
(define-debug-command #\D later-continuation-command
"Move (Down) to the next (later) continuation")
;;;; General motion command
(define (goto-command)
(define (get-reduction-number)
(let ((red
(prompt-for-expression
(format false
"Reduction Number (0 through ~o inclusive): "
(-1+ current-number-of-reductions)))))
(cond ((not (number? red))
(beep)
(format "~%Reduction number must be numeric!")
(get-reduction-number))
((not (and (>= red 0)
(< red current-number-of-reductions)))
(format "~%Reduction number out of range.!")
(get-reduction-number))
(else (set-current-reduction! red)))))
(define (choose-reduction)
(cond ((> current-number-of-reductions 1) (get-reduction-number))
((= current-number-of-reductions 1)
(format "~%There is only one reduction for this subproblem")
(set-current-reduction! 0))
(else (format "~%There are no reductions for this subproblem."))))
(define (get-subproblem-number)
(let ((len (length previous-continuations))
(sub (prompt-for-expression "Subproblem number: ")))
(cond ((not (number? sub))
(beep)
(format "~%Subproblem level must be numeric!")
(get-subproblem-number))
((< sub len) (repeat later-subproblem (- len sub))
(choose-reduction))
(else
(let loop ((len len))
(cond ((= sub len) (choose-reduction))
((null-continuation?
(continuation-next-continuation current-continuation))
(format "~%There is no such subproblem.")
(format "~%Now at subproblem number: ~o"
(length previous-continuations))
(choose-reduction))
(else (earlier-subproblem) (loop (1+ len)))))))))
(get-subproblem-number)
(print-current-expression))
(define-debug-command #\G goto-command
"Go to a particular Subproblem/Reduction level")
;;;; Evaluation and frame display commands
(define (enter-read-eval-print-loop)
(with-rep-alternative current-environment
(lambda (env)
(debug/read-eval-print env
"You are now in the desired environment"
"Eval-in-env-->"))))
(define-debug-command #\E enter-read-eval-print-loop
"Enter a read-eval-print loop in the current environment")
(define (eval-in-current-environment)
(with-rep-alternative current-environment
(lambda (env)
(environment-warning-hook env)
(debug/eval (prompt-for-expression "Eval--> ") env))))
(define-debug-command #\V eval-in-current-environment
"Evaluate expression in current environment")
(define show-current-frame
(let ((show-frame (access show-frame env-package)))
(named-lambda (show-current-frame)
(if-valid-environment current-environment
(lambda (env) (show-frame env -1))))))
(define-debug-command #\C show-current-frame
"Show Bindings of identifiers in the current environment")
(define (enter-where-command)
(with-rep-alternative current-environment debug/where))
(define-debug-command #\W enter-where-command
"Enter WHERE on the current environment")
(define (error-info-command)
(format "~% Message: ~s~%Irritant: ~o" (error-message) (error-irritant)))
(define-debug-command #\I error-info-command "Redisplay the error message")
;;;; Advanced hacking commands
(define (return-command) ;command Z
(define (do-it environment next)
(environment-warning-hook environment)
(let ((value
(debug/eval
(let ((expression
(prompt-for-expression
"Expression to EVALUATE and CONTINUE with ($ to retry): "
)))
(if (eq? expression '$)
(unsyntax (current-expression))
expression))
environment)))
(if print-return-values?
(begin
(format "~%That evaluates to:~%~o" value)
(if (prompt-for-confirmation "Confirm: ") (next value)))
(next value))))
(let ((next (continuation-next-continuation current-continuation)))
(if (null-continuation? next)
(begin (beep) (format "~%Can't continue!!!"))
(with-rep-alternative current-environment
(lambda (env) (do-it env next))))))
(define-debug-command #\Z return-command
"Return (continue with) an expression after evaluating it")
(define user-debug-environment (make-environment))
(define (internal-command)
(debug/read-eval-print user-debug-environment
"You are now in the debugger environment"
"Debugger-->"))
(define-debug-command #\X internal-command
"Create a read eval print loop in the debugger environment")
(define (debug-compiled)
(if debug-compiled-continuation
(debug-compiled-continuation current-continuation)
(begin (beep)
(format "~%The compiled code debugger is not present in this system."))))
(define-debug-command #\A debug-compiled
"Invoke the compiled code debugger on the current continuation")
;;;; Reduction and continuation motion low-level
(define reduction-expression car)
(define reduction-environment cadr)
(define (last-reduction-number)
(-1+ current-number-of-reductions))
(define (normal-reduction-number)
(min (-1+ current-number-of-reductions) 0))
(define (initial-reduction-number)
(let ((environment (continuation-environment current-continuation)))
(if (and (environment? environment)
(let ((procedure (environment-procedure environment)))
(or (eq? procedure error-procedure)
(eq? procedure breakpoint-procedure))))
1
0)))
(define (set-current-continuation! continuation hook)
(set! current-continuation continuation)
(set! current-number-of-reductions
(if (null-continuation? continuation)
0
(dotted-list-length
(continuation-reductions current-continuation))))
(set-current-reduction! (hook)))
(define (set-current-reduction! number)
(set! current-reduction-number number)
(if (and (not (= current-number-of-reductions 0)) (>= number 0))
(set! current-reduction
(list-ref (continuation-reductions current-continuation) number))
(set! current-reduction false))
(set! current-environment
(if current-reduction
(reduction-environment current-reduction)
(continuation-environment current-continuation))))
(define (repeat f n)
(if (> n 0)
(begin (f)
(repeat f (-1+ n)))))
(define (dotted-list-length l)
(let count ((n 0) (L L))
(if (pair? l)
(count (1+ n) (CDR L))
n)))
(define (wrap-around-in-reductions? reductions)
(eq? (list-tail reductions (dotted-list-length reductions))
reduction-wrap-around-tag))
;;; end DEBUG-PACKAGE.
))
(define debug
(access debug debug-package debug-package))
(define special-name?
(let ((the-special-names
(list lambda-tag:unnamed
(access internal-lambda-tag lambda-package)
(access internal-lexpr-tag lambda-package)
lambda-tag:let
lambda-tag:shallow-fluid-let
lambda-tag:deep-fluid-let
lambda-tag:common-lisp-fluid-let
lambda-tag:make-environment)))
(named-lambda (special-name? symbol)
(memq symbol the-special-names))))
| false |
98bc62e23aa603810a25334c4da955fd44ed434f | b8df279d7dfa28666f0a76cd59c6f4c93afec15d | /plt-load.ss | 43e39162fdfa8fa82b817ec8561ff42f2097e980 | []
| no_license | duncanmak/terminfo | 5beb7546f6a838dfb44e006190e91f3aec4c665b | 63950b8aaf1b1239ec387827cd7b41b31bdb449b | refs/heads/master | 2016-09-05T19:29:20.715080 | 2008-04-01T21:51:46 | 2008-04-01T21:51:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,539 | ss | plt-load.ss | (require (lib "1.ss" "srfi"))
(require (lib "6.ss" "srfi"))
(require (lib "9.ss" "srfi"))
(require (lib "11.ss" "srfi"))
(require (lib "13.ss" "srfi"))
(require (lib "14.ss" "srfi"))
(require (lib "23.ss" "srfi"))
(require (lib "60.ss" "srfi"))
(require (lib "69.ss" "srfi"))
(require (lib "optional.ss" "srfi"))
(define-syntax let-optionals
(syntax-rules ()
((let-optionals body ...)
(let-optionals* body ...))))
(define ignore void)
(define (tty-info port) ignore)
(define (uname) ignore)
;; Modify as necessary
(define (uname:os-name uname)
(let ((type (system-type 'os)))
(case type
((macosx) "Darwin")
(else (symbol->string type)))))
(define (tty-info:output-speed ttyinfo) 'extb)
(define (path-list->file-name path-list)
(string-join path-list "/"))
(define (infix-splitter delimiter)
(lambda (input-string)
(string-tokenize input-string
(char-set-complement (string->char-set delimiter)))))
(define (file-readable? filename)
(member 'read (file-or-directory-permissions filename)))
(define (file-not-exists? filename)
(not (file-exists? filename)))
(define-syntax with-current-input-port
(syntax-rules ()
((with-current-input-port port body ...)
(parameterize ((current-input-port port)) body ...))))
(define-syntax with-current-output-port
(syntax-rules ()
((with-current-output-port port body ...)
(parameterize ((current-output-port port)) body ...))))
(load "terminfo.scm")
(load "terminfo-capabilities.scm")
(load "utilities.scm") | true |
f4d36e77380f5a0296adb0ef567fe0e47bbc9beb | 2d1029e750a1cd71a650cceea8b7e02ae854ec01 | /various-prologs-exp/prolog-first-pass/prolog_staged8/create-large-db.ss | 266ed0793c225f738fdd2226e3d98324ec17857d | []
| no_license | chinacat/unsorted | 97f5ce41d228b70452861df707ceff9d503a0a89 | 46696319d2585c723bbc5bdff3a03743b1425243 | refs/heads/master | 2018-12-28T22:05:34.628279 | 2013-08-09T06:36:07 | 2013-08-09T06:36:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 263 | ss | create-large-db.ss | #lang scheme
(require "prolog.ss")
(define (create-predicate name num)
(add-clause (list (list name num))))
(define (loop m n)
(if (< m n)
(begin (create-predicate (gensym 'abc) m)
(loop (+ m 1) n))
(void)))
(loop 0 1000000)
| false |
afd4c5c43162cbc37a39f5a1caf50d3fd1b96d8c | b9d0fc9d5d0d135aadd1e4644b45004fd2c94b94 | /scheme/functional-postscript/.svn/text-base/fps.util.scm.svn-base | 4f3ebe26c86ee9fc8c82e9d94cd1ee8c4855d989 | []
| no_license | alvatar/snippets | f704413d39b6c9363e1c435444ec82e270184f75 | 89ce0c71ff1554a9307ed0726b84dfa5782babe6 | refs/heads/master | 2021-06-28T21:59:15.358791 | 2016-10-25T16:26:52 | 2016-10-25T16:26:52 | 2,073,559 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 7,787 | fps.util.scm.svn-base | ;; ===================================================================
;; Functional PostScript
;; Copyright (C) 1996 by Wandy Sae-Tan and Olin Shivers
;; fps.util.scm
;; This file contains utility procedures.
;; (add-pts point1 point2) -> pt
;; (negate-pt point) -> pt
;; (scale-pt x-factor y-factor point) -> pt
;; (deg->rad number) -> number
;; (rad->deg number) -> number
;; (matrix* matrix1 matrix2) -> matrix
;; (inch int) -> int
;; (bounding-box->rect box) -> path
;; ===================================================================
;; add two points together
(define (add-pts pt1 . pts)
(letrec ((add-2-pt (lambda (pt1 pt2)
(pt (+ (pt:x pt1) (pt:x pt2))
(+ (pt:y pt1) (pt:y pt2))))))
(let lp ((pt-lst (cons pt1 pts)))
(if (null? pt-lst)
(pt 0 0)
(add-2-pt (car pt-lst)
(lp (cdr pt-lst)))))))
;; multiply x or y coord or both by -1
(define (negate-pt point)
(pt (- (pt:x point)) (- (pt:y point))))
;; scale x or y coord or both by factor
(define (scale-pt x-factor y-factor point)
(pt (* x-factor (pt:x point)) (* y-factor (pt:y point))))
;; convert degree to radian
(define (deg->rad degree) (/ (* degree pi) 180))
;; convert radian to degree
(define (rad->deg rad) (/ (* rad 180) pi))
;; multiply two 3x3 matrices together
(define (matrix* matrix1 matrix2)
(let* ((a1 (matrix:a matrix1))(b1 (matrix:b matrix1))
(p1 (matrix:p matrix1))(q1 (matrix:q matrix1))
(x1 (matrix:x matrix1))(y1 (matrix:y matrix1))
(a2 (matrix:a matrix2))(b2 (matrix:b matrix2))
(p2 (matrix:p matrix2))(q2 (matrix:q matrix2))
(x2 (matrix:x matrix2))(y2 (matrix:y matrix2)))
(matrix (+ (* a1 a2) (* b1 p2))
(+ (* a1 b2) (* b1 q2))
(+ (* p1 a2) (* q1 p2))
(+ (* p1 b2) (* q1 q2))
(+ (* x1 a2) (* y1 p2) x2)
(+ (* x1 b2) (* y1 q2) y2))))
;; converts to inches (* 72)
(define (inch n)
(* 72 n))
;; converts bounding box into a rectangular path
(define (bounding-box->rect box)
(let ((min (bounding-box:min box))
(max (bounding-box:max box)))
(rect min (- (pt:x max) (pt:x min))
(- (pt:y max) (pt:y min)))))
;; ===== Internal Util ===============================================
;; (receive ...)
;; (forward-list-reduce proc seed lst) ;; needed the forwardness
;; (vector-copy v . opt-len)
;; (vector-assoc key vect)
;; (vector-map proc v)
;; (vector-for-each proc vec)
;; (vector-reduce proc seed vec)
;; (string-for-each proc str)
;; (string-reduce proc seed str)
;; (PSnum num)
;; (comp f g)
;; (display-line thing port)
;; (repeat thunk n)
;; (tf filename thunk) ;; testing util, write output to file
;; (last-pair pair)
;; (dot-produce v1 v2)
;; (mag v)
;; (first-in-composite obj)
;; (last-in-composite obj)
;; (char->hex c)
;; (make-style-with-optional-args opt-args)
;; syntax for receiving multiple values
#;(define-syntax receive
(syntax-rules ()
((receive var-lst exp body ...)
(call-with-values (lambda () exp)
(lambda var-lst body ...)))))
(define (forward-list-reduce proc seed lst)
(let lp ((l lst) (val seed))
(if (null? l)
val
(lp (cdr l) (proc (car l) val)))))
;; Duplicates a vector.
(define (vector-copy v . opt-len)
(let* ((v-len (vector-length v))
(len (if (null? opt-len)
v-len
(if (> v-len (car opt-len))
v-len
(car opt-len))))
(dup-v (make-vector len #f)))
(let lp ((n 0))
(if (>= n v-len)
dup-v
(begin (vector-set! dup-v n (vector-ref v n))
(lp (+ n 1)))))))
;; assoc for vectors.
(define (vector-assoc key vect)
(let loop ((pos (- (vector-length vect) 1)))
(if (>= pos 0)
(let ((test-v (vector-ref vect pos)))
(if (equal? key (vector-ref test-v 0))
test-v
(loop (- pos 1))))
#f)))
;; Utility procedure for vector that works just like the list map.
(define (vector-map proc vect)
(let* ((len (vector-length vect))
(new-vect (make-vector len)))
(let loop ((n (- len 1)))
(if (< n 0)
new-vect
(begin
(vector-set! new-vect n (proc (vector-ref vect n)))
(loop (- n 1)))))))
(define (vector-for-each proc vec)
(let ((len (vector-length vec)))
(let loop ((n 0))
(if (< n len)
(proc (vector-ref vec n))))))
(define (vector-reduce proc seed vec)
(let* ((len (vector-length vec))
(new-vec (make-vector len)))
(let lp ((index (- len 1)) (seed seed))
(if (= index -1)
seed
(lp (- index 1) (proc seed (vector-ref vec index)))))))
(define (string-reduce proc seed str)
(let* ((len (string-length str))
(new-str (make-string len)))
(let lp ((index (- len 1)) (seed seed))
(if (= index -1)
seed
(lp (- index 1) (proc seed (string-ref str index)))))))
(define (string-for-each proc str)
(let ((len (string-length str)))
(let loop ((n 0))
(if (< n len)
(proc (string-ref str n))))))
;; Utiltiy procedure. Puts out PostScript numerals. i.e. integers
;; and floats.
(define (PSnum num)
(cond ((integer? num)
(if (exact? num) num (inexact->exact num)))
((real? num)
(cond ((exact? num) (exact->inexact num))
(else num)))
(else (error PSnum
"Cannot be represented as a PostScript numeral"
num))))
;; Composes two functions.
(define (comp f g) (lambda (x) (f (g x))))
;; Testing util. Repeat a procedure by n times
(define (repeat thunk n)
(if (not (= n 0))
(begin (thunk) (repeat thunk (- n 1)))))
;; Testing util. Repeat and time a procedure by n times
(define (repeat-and-time thunk n)
(let loop ((start (current-milliseconds)) (n n))
(if (= n 0)
(- (current-milliseconds) start)
(begin (thunk) (loop start (- n 1))))))
;; find last-pair of any list
#;(define (last-pair x)
(if (pair? x)
(let loop ((x x))
(let ((y (cdr x)))
(if (pair? y)
(loop y)
x)))))
;; Utility. Make a Internal-Bug error message
(define (internal-bug . stuff)
(apply error (cons "FPS internal error. Please report this bug." stuff)))
;; build a bbox record out of the four min max numbers
(define (min-max-coords->bbox min-x min-y max-x max-y)
(bbox (pt max-x max-y) (pt min-x max-y)
(pt min-x min-y) (pt max-x min-y)
(pt max-x max-y) (pt min-x min-y)))
;; find the dot-product of two vectors
(define (dot-product v1 v2) (+ (* (pt:x v1) (pt:x v2))
(* (pt:y v1) (pt:y v2))))
;; find the magnitude of a vector
(define (mag v) (sqrt (+ (expt (pt:x v) 2)
(expt (pt:y v) 2))))
;; returns the first obj in the composite list
(define (first-in-composite obj)
(car (composite:objs obj)))
;; returns the last obj in the composite list
(define (last-in-composite obj)
(car (reverse (composite:objs obj))))
;; initilize a vector with a init value
(define (initialize-vector len init)
(let ((vec (make-vector len))
(i 0))
(do ((i (- len 1) (- i 1)))
((< i 0) vec)
(vector-set! vec i (init i)))
vec))
;; converts a char to a hex integer
(define (char->hex c)
(case c
((#\0) 0)
((#\1) 1)
((#\2) 2)
((#\3) 3)
((#\4) 4)
((#\5) 5)
((#\6) 6)
((#\7) 7)
((#\8) 8)
((#\9) 9)
((#\a #\A) 10)
((#\b #\B) 11)
((#\c #\C) 12)
((#\d #\D) 13)
((#\e #\E) 14)
((#\f #\F) 15)
(else (error parse-hex "c is not a valid hex digit" c))))
(define (make-style-with-optional-args opt-arg)
(cond ((null? opt-arg) (default-style))
((null? (cdr opt-arg))
(let ((arg (car opt-arg)))
(if (style? arg) arg (vary-default arg))))
(else (apply vary-default opt-arg))))
(define (check-arg pred val caller)
(if (pred val) val
(check-arg pred (error "Bad argument" val pred caller) caller)))
;; ===== End of fps.util.scm =========================================
| true |
|
70c2f26af082a37e500625d1709cfc5dc1fc2682 | 0768e217ef0b48b149e5c9b87f41d772cd9917f1 | /sitelib/srfi/98.scm | a608aa771afc7f6bb575615433ab30ec57a771aa | [
"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 | 203 | scm | 98.scm | #!nobacktrace
(define-library (srfi 98)
(import (core))
(export (rename lookup-process-environment get-environment-variable)
(rename process-environment->alist get-environment-variables)))
| false |
68cca632f1a8b6a48b664b97a98efcaaa508bb2f | 51d30de9d65cc3d5079f050de33d574584183039 | /utility/sxml.scm | 67617ca06612332a968ac3ee094e76f01404c412 | [
"BSD-2-Clause",
"BSD-3-Clause"
]
| permissive | langmartin/ykk | 30feb00265d603ef765b5c664d2f759be34b7b89 | dd6e441dddd5b6363ee9adbbdd0f346c1522ffcf | refs/heads/master | 2016-09-05T20:01:19.353224 | 2009-12-10T16:25:55 | 2009-12-10T16:25:55 | 408,478 | 0 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 3,586 | scm | sxml.scm |
(define (path-run make path nodes)
(let ((path (if (procedure? path) path (make path))))
(path nodes)))
(define (sxpath-run path nodes)
(path-run sxpath path nodes))
(define (txpath-run path nodes)
(path-run txpath path nodes))
(define-syntax let-sxml-attrs
(syntax-rules ()
((_ item (attrs keys ...) expr ...)
(let* ((attrs (sxml:attr-list-u item))
(keys ... (bind-spec (keys ...) attrs)))
expr ...))))
(define-syntax let-sxml-pluck-attrs
(syntax-rules ()
((_ item (attrs keys ...) expr ...)
(let* ((attrs (sxml:attr-list-u item))
(keys ... attrs (pluck-spec (keys ...) attrs)))
expr ...))))
(define-syntax bind-attributes
(syntax-rules ()
((_ names attributes)
(bind-spec names (remove-@ attributes)))))
(define-syntax pluck-attributes
(syntax-rules ()
((_ names attributes)
(pluck-spec names (remove-@ attributes)))))
;; ADD-CLASS is a restricted form of UPDATE-ATTRIBUTES that only
;; affects the `class' attribute.
(define (add-class attributes classes)
(update-attributes
attributes
`((class ,classes))))
;; JOIN-CLASSES is a stricter form of MERGE-CLASS-SETS that returns a
;; class-string instead of a list of classes.
(define (join-classes . sets)
(string-join (apply merge-class-sets sets)))
;; MERGE-CLASS-SETS takes a list of class sets and merges them
;; together. Each set can be a string of one or more classes (i.e. "a
;; b c") or a list of strings (i.e. '("a" "b" "c")). The result is a
;; unique list of classes in the order they first appear in SETS from
;; left to right.
(define merge-class-sets
(let ((kons (unique-conser string=?)))
(lambda sets
(reverse
(apply fold-append
kons
'()
(map-in-order maybe-tokenize sets))))))
;; UPDATE-ATTRIBUTES is a "canonical" attribute list merger. It takes a
;; number of attribute SETS and combines them. Subsequent attributes
;; replace previous attributes with the same name. The exception is
;; the `class' attribute which is merged using JOIN-CLASSES.
(define (update-attributes . sets)
(cons '@
(apply attribute-updater
(map-in-order remove-@ sets))))
(define attribute-updater
(let ((template `((class ,join-classes))))
(lambda sets
(apply merge-attribute-sets template sets))))
;; MERGE-ATTRIBUTE-SETS is an abstract attribute list merger. It
;; takes a TEMPLATE that can specifiy how to merge certain attributes.
;; The default behavior is for subsequent attributes to replace
;; previous attributes with the same name.
(define (merge-attribute-sets template . sets)
(apply merge-alists/template
list
cadr
template
proj-1
sets))
(define (remove-@ set)
(if (and (pair? set)
(eq? (car set) '@))
(cdr set)
set))
;;;; Tests
;(define test '(div (@ (class "foo") (width "90")) "some text"))
(begin
(let ((a b (bind-attributes (a b) `(@ (a 1) (b 2) (c 3)))))
(assert a => 1)
(assert b => 2))
(let ((c rest (pluck-attributes (c) `(@ (a 1) (b 2) (c 3)))))
(assert c => 3)
(assert rest => '((a 1) (b 2))))
(assert (merge-class-sets "foo bar" "bar baz" "bum foo quux")
=> '("foo" "bar" "baz" "bum" "quux"))
(assert (join-classes "a b" "c")
=> "a b c")
(assert (add-class '(@ (class "foo bar")) "baz bar")
=> '(@ (class "foo bar baz")))
(assert
(update-attributes
'(@ (a 1) (class "foo"))
'(@ (a 2) (b 3) (class "bar")))
=> '(@ (a 2) (class "foo bar") (b 3)))
)
| true |
8ae5675f568837aa8897921c693f2b33f3771d9b | 382706a62fae6f24855ab689b8b2d87c6a059fb6 | /0.3/interpreter/src/protocol-addressing.scm | ade2d2fca75963df745ec96ebfa7922b4190f800 | [
"Apache-2.0"
]
| permissive | mstram/bard | ddb1e72a78059617403bea1842840bb9e979198e | 340d6919603a30c7944fb66e04df0562180bc0bb | refs/heads/master | 2021-01-21T00:12:27.174597 | 2014-07-10T13:20:39 | 2014-07-10T13:20:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,347 | scm | protocol-addressing.scm | ;;;; ***********************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name: protocol-addressing.scm
;;;; Project: Bard
;;;; Purpose: locating resources
;;;; Author: mikel evins
;;;; Copyright: 2012 by mikel evins
;;;;
;;;; ***********************************************************************
(declare (extended-bindings))
(##include "type-signature-macros.scm")
(##include "protocol-macros.scm")
;;; url {scheme: Name domain: Name port: Name path: Name query: Name } -> URL
;;; ---------------------------------------------------------------------
(define-protocol-function Addressing url
signatures: (list (signature ()
(%alist-table scheme: "file"
domain: "localhost"
port: #f
path: "/"
query: "")
(URL))))
(define-primitive-method url () %make-url)
;;; url-domain URL -> Name
;;; ---------------------------------------------------------------------
(define-protocol-function Addressing url-domain
signatures: (list (signature (URL) #f (Name))))
(define-primitive-method url-domain (<url>) url-domain)
;;; url-path URL -> Name
;;; ---------------------------------------------------------------------
(define-protocol-function Addressing url-path
signatures: (list (signature (URL) #f (Name))))
(define-primitive-method url-path (<url>) url-path)
;;; url-port URL -> Name
;;; ---------------------------------------------------------------------
(define-protocol-function Addressing url-port
signatures: (list (signature (URL) #f (Name))))
(define-primitive-method url-port (<url>) url-port)
;;; url-query URL -> Name
;;; ---------------------------------------------------------------------
(define-protocol-function Addressing url-query
signatures: (list (signature (URL) #f (Name))))
(define-primitive-method url-query (<url>) url-query)
;;; url-scheme URL -> Name
;;; ---------------------------------------------------------------------
(define-protocol-function Addressing url-scheme
signatures: (list (signature (URL) #f (Name))))
(define-primitive-method url-scheme (<url>) url-scheme)
| false |
8e04c86d64683175095b935c250e2a6e152a3f93 | abc7bd420c9cc4dba4512b382baad54ba4d07aa8 | /src/old/main_plt.ss | 5bcddeb470da52d43f057107789ab24ac5466479 | [
"BSD-3-Clause"
]
| permissive | rrnewton/WaveScript | 2f008f76bf63707761b9f7c95a68bd3e6b9c32ca | 1c9eff60970aefd2177d53723383b533ce370a6e | refs/heads/master | 2021-01-19T05:53:23.252626 | 2014-10-08T15:00:41 | 2014-10-08T15:00:41 | 1,297,872 | 10 | 2 | null | null | null | null | UTF-8 | Scheme | false | false | 16,869 | ss | main_plt.ss |
;; Ryan Newton
;; Started 2004.03.26
;; Here is the main file for my compiler.
;=======================================================================
#cs ;; Case Sensitivity
(module main_plt mzscheme
;; [2004.06.16] This should have been done already, but just for good measure...
(define current_interpreter 'mzscheme)
(define simulator-batch-mode #f)
#;
(fprintf stderr "Regiment: Loading ~a compiler in chezscheme~a...\n"
(let ([ws #f] [reg #f])
(IFWAVESCOPE (set! ws #t) (set! reg #t))
(cond
[(and ws reg) "ws+reg"]
[ws "ws"]
[reg "reg"]))
(if (top-level-bound? 'regiment-origin)
(format " (from ~a)" regiment-origin)
"(LOADED VIA UNKNOWN METHOD!?)"
))
(require (lib "include.ss")
; (all-except "generic/util/helpers.ss" id rec)
; (all-except "generic/compiler_components/regiment_helpers.ss")
"plt/hashtab.ss"
"plt/chez_compat.ss"
"generic/util/hash.ss"
; (all-except "generic/grammars/grammar_checker.ss" these-tests test-this)
)
(require-for-syntax "plt/identifier-syntax.ss")
(require "generic/constants.ss"
"plt/iu-match.ss"
;; [2004.12.06] I think I had this working:
"plt/critical_section.ss")
;; Set parameter:
(REGIMENTD (cond
[(getenv "REGIMENTD") (getenv "REGIMENTD")]
[(directory-exists? "~/wavescript") "~/wavescript/"]
[(directory-exists? "~/WaveScope/src/wavescript") "~/WaveScope/src/wavescript/"]
[(directory-exists? "~/regiment_alpha") "~/regiment_alpha/"]
[else
(string-append (path->string (current-directory)) "../")
]))
;; Set Misc PLT parameters:
;(print-graph #t )
;(print-gensym #f)
;(print-level 20))
;(print-length 80)
;(print-vector-length #f)
;(pretty-maximum-lines 700)
(print-struct #f)
(define-syntax (common:load-source x)
(syntax-case x ()
[(_ file)
(with-syntax ([req (datum->syntax-object #'_ 'require)]
[prov (datum->syntax-object #'_ 'provide)]
[allfr (datum->syntax-object #'_ 'all-from)]
;[testths (datum->syntax-object #'_ 'test-this)]
;[thesetsts (datum->syntax-object #'_ 'these-tests)]
)
;(display (cons 'yayexpanding #'file))(newline)
;#'(req (all-except file these-tests test-this))
#'(begin (req file)
(prov (allfr file)))
)]))
;================================================================================
;; This loads the bulk of the source files.
(include "common_loader.ss")
(require
;(all-except "generic/compiler_components/hm_type_inference.ss" these-tests test-this)
;(all-except "generic/passes/normalize_source/desugar-pattern-matching.ss" these-tests test-this)
;(all-except "generic/passes/normalize_source/verify-regiment.ss" these-tests test-this)
(all-except "generic/passes/normalize_source/resolve-varrefs.ss" these-tests test-this)
(all-except "generic/passes/normalize_source/ws-label-mutable.ss")
;(all-except "generic/passes/normalize_source/typecheck.ss" these-tests test-this)
(all-except "generic/passes/normalize_source/desugar-misc.ss" these-tests test-this)
(all-except "generic/passes/normalize_source/eta-primitives.ss" these-tests test-this)
(all-except "generic/passes/normalize_source/rename-vars.ss" these-tests test-this)
(all-except "generic/passes/normalize_source/remove-unquoted-constant.ss" these-tests test-this)
(all-except "generic/passes/static_elaborate/static-elaborate.ss" these-tests test-this)
(all-except "generic/passes/static_elaborate/interpret-meta.ss" these-tests test-this)
(all-except "generic/passes/static_elaborate/verify-elaborated.ss" these-tests test-this)
(all-except "generic/passes/static_elaborate/degeneralize-arithmetic.ss" these-tests test-this)
(all-except "generic/passes/static_elaborate/split-union-types.ss" these-tests test-this)
(all-except "generic/passes/optimizations/smoosh-together.ss")
(all-except"generic/passes/optimizations/rewrite_opts.ss")
;(all-except"generic/passes/optimizations/data_reps.ss")
(all-except "generic/passes/normalize_query/reduce-primitives.ss" these-tests test-this)
;(all-except "generic/passes/optimizations/merge-iterates.ss")
(all-except "generic/passes/optimizations/simple-merge-iterates.ss")
;(all-except "generic/passes/wavescope_bkend/purify-iterate.ss" these-tests test-this)
(all-except "generic/passes/wavescope_bkend/nominalize-types.ss" these-tests test-this)
(all-except "generic/passes/wavescope_bkend/convert-sums-to-tuples.ss")
(all-except "generic/passes/wavescope_bkend/reify-certain-types.ss")
(all-except "generic/passes/wavescope_bkend/type-annotate-misc.ss" these-tests test-this)
"generic/passes/wavescope_bkend/convert-sums-to-tuples.ss"
(all-except "generic/passes/wavescope_bkend/flatten-iterate-spine.ss" these-tests test-this)
(all-except "generic/passes/wavescope_bkend/anihilate-higher-order.ss" these-tests test-this)
;; These are miscellaneous small passes used by wavescript:
(all-except "generic/passes/small-ws-passes.ss" these-tests test-this)
(all-except "generic/passes/wavescope_bkend/explicit-stream-wiring.ss" these-tests test-this)
(all-except "generic/passes/wavescope_bkend/emit-c.ss" these-tests test-this)
(all-except "generic/passes/wavescope_bkend/emit-c2.ss")
"generic/passes/partition-graph.ss"
(all-except "generic/passes/wavescope_bkend/insert-refcounts.ss")
(all-except "generic/passes/ocaml_bkend/emit-caml.ss" these-tests test-this)
(all-except "generic/passes/mlton_bkend/emit-mlton.ss" these-tests test-this)
(all-except "generic/passes/normalize_query/remove-complex-constant.ss" these-tests test-this)
; pass07_verify-stage2.ss
(all-except "generic/passes/normalize_query/uncover-free.ss" these-tests test-this)
(all-except "generic/passes/normalize_query/lift-letrec.ss" these-tests test-this)
(all-except "generic/passes/normalize_query/lift-letrec-body.ss" these-tests test-this)
(all-except "generic/passes/normalize_query/remove-complex-opera.ss" these-tests test-this)
(all-except "generic/passes/normalize_query/ws-remove-letrec.ss")
(all-except "generic/passes/normalize_query/remove-lazy-letrec.ss" these-tests test-this)
(all-except "generic/passes/normalize_query/verify-core.ss" these-tests test-this)
(all-except "generic/passes/normalize_query/ws-remove-letrec.ss")
(all-except "generic/passes/normalize_query/ws-remove-complex-opera.ss")
(all-except "generic/passes/normalize_query/ws-lift-let.ss")
(all-except "generic/passes/normalize_query/ws-normalize-context.ss")
)
(IFWAVESCOPE (begin) (require
(all-except "generic/passes/analyze_query/classify-names.ss" these-tests test-this)
(all-except "generic/passes/analyze_query/add-heartbeats.ss" these-tests test-this)
(all-except "generic/passes/analyze_query/add-control-flow.ss" these-tests test-this)
(all-except "generic/passes/analyze_query/add-places.ss" these-tests test-this)
(all-except "generic/passes/analyze_query/analyze-places.ss" these-tests test-this)
(all-except "generic/passes/analyze_query/add-data-flow.ss" these-tests test-this)
(all-except "generic/passes/analyze_query/resolve-fold-trees.ss" these-tests test-this)
(all-except "generic/passes/deglobalize/deglobalize.ss" these-tests test-this)
(all-except "generic/passes/deglobalize/deglobalize2.ss" these-tests test-this)
;(all-except "generic/passes/tokmac_bkend/cleanup-token-machine.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/desugar-macros.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/find-emittoks.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/desugar-gradients.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/desugar-let-stored.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/rename-stored.ss" these-tests test-this)
;;;(all-except "plt/pass09_separate-graph" these-tests test-this)
;;;(all-except "plt/pass18_add-routing.ss" these-tests test-this
;;(all-except "plt/pass24_analyze-calls.ss" these-tests test-this)
;;(all-except "plt/pass25_inline.ss" these-tests test-this)
;;(all-except "plt/pass26_prune-returns.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/cps-tokmac.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/sever-cont-state.ss" these-tests test-this)
(all-except "generic/passes/tokmac_bkend/closure-convert.ss" these-tests test-this)
"generic/passes/tokmac_bkend/inline-tokens.ss"
(all-except "generic/passes/nesc_bkend/flatten-tokmac.ss" these-tests test-this)
(all-except "generic/passes/nesc_bkend/emit-nesc.ss" these-tests test-this)
))
(IF_GRAPHICS
(require
;;;; (all-except "plt/simulator_nought.ss" these-tests test-this)
;; (all-except "plt/simulator_nought_graphics.ss" these-tests test-this wrap-def-simulate)
(all-except "plt/graphics_stub.ss" these-test test-this)))
;; Import these for the benefit of the unit tests below:
;(IFWAVESCOPE (begin) (require "generic/sim/simulator_alpha_datatypes.ss"))
;(require (all-except "generic/sim/wavescript_sim_library_push.ss" these-tests test-this))
;(require (all-except "generic/langs/lang_wavescript.ss" these-tests test-this))
(require (all-except "generic/compiler_components/source_loader.ss" these-tests test-this))
#;
(IFWAVESCOPE (begin) (begin
; (require (all-except "generic/compiler_components/logfiles.ss" these-tests test-this))
; (require "generic/sim/alpha_lib.ss")
; (require (all-except "generic/sim/simulator_alpha.ss" these-tests test-this))
))
(include "generic/testing/tests.ss")
;============================================================
;; INLINE THE MAIN COMPILER CODE
;; Bring these into top-level for some of the mini-passes defined in main.ss.
;(require (all-except "generic/passes/pass-mechanism_basic.ss" these-tests test-this))
;(require (all-except "generic/passes/pass-mechanism.ss" these-tests test-this))
;(require (all-except "generic/compiler_components/reg_core_generic_traverse.ss" these-tests test-this) )
;(require "generic/compiler_components/c_generator.ss")
(include "main.ss")
;============================================================
(define error-handler error-display-handler)
;; Bring these into the top-level for our REPL convenience.
(include "generic/shortcuts.ss")
(require "generic/util/reg_macros.ss")
;; [2007.01.23] For now we exit on error unconditionally.
;; [2007.05.17] Making this optional again. The command line interface should turn it
(when (and (top-level-bound? 'REGIMENT-BATCH-MODE)
(top-level-value 'REGIMENT-BATCH-MODE))
(uncaught-exception-handler
(lambda (exn)
(printf "ERROR:\n ~a\n\nException: ~s\n" (exn-message exn) exn)
(exit 1))))
;; This could get verbose... ideally we'd like to export all of it:
;; THIS IS REALLY REDUNDANT... I WISH THERE WERE SOME WAY AROUND THIS:
(provide (all-defined)
(all-from "plt/chez_compat.ss")
(all-from "generic/constants.ss")
(all-from "plt/iu-match.ss")
; (all-from "generic/util/helpers.ss")
(all-from "generic/compiler_components/source_loader.ss")
; (all-from "generic/util/streams.ss")
; (all-from "generic/passes/normalize_source/typecheck.ss")
; (all-from "generic/grammars/grammar_checker.ss")
(all-from "generic/compiler_components/regiment_helpers.ss")
(all-from "generic/compiler_components/hm_type_inference.ss")
; (all-from "generic/passes/pass-mechanism_basic.ss")
; (all-from "generic/passes/pass-mechanism.ss")
; (all-from "generic/compiler_components/reg_core_generic_traverse.ss")
(all-from "plt/hashtab.ss")
(all-from "generic/util/hash.ss")
; (all-from "generic/langs/lang_wavescript.ss")
;(all-from "generic/compiler_components/prim_defs.ss" )
(all-from "generic/compiler_components/hm_type_inference.ss" )
; (all-from "generic/passes/normalize_source/desugar-pattern-matching.ss" )
; (all-from "generic/passes/normalize_source/verify-regiment.ss" )
(all-from "generic/passes/normalize_source/resolve-varrefs.ss" )
(all-from "generic/passes/normalize_source/ws-label-mutable.ss")
; (all-from "generic/passes/normalize_source/typecheck.ss" )
(all-from "generic/passes/normalize_source/desugar-misc.ss" )
(all-from "generic/passes/normalize_source/eta-primitives.ss" )
(all-from "generic/passes/normalize_source/rename-vars.ss" )
(all-from "generic/passes/normalize_source/remove-unquoted-constant.ss" )
(all-from "generic/passes/static_elaborate/static-elaborate.ss" )
(all-from "generic/passes/static_elaborate/interpret-meta.ss" )
(all-from "generic/passes/static_elaborate/verify-elaborated.ss" )
(all-from "generic/passes/static_elaborate/degeneralize-arithmetic.ss" )
(all-from "generic/passes/optimizations/smoosh-together.ss")
;(include "generic/passes/optimizations/rewrite_opts.ss")
;(include "generic/passes/optimizations/data_reps.ss")
(all-from "generic/passes/normalize_query/reduce-primitives.ss" )
;; [2007.11.01] Not fully PLT compatible yet:
;(all-from "generic/passes/optimizations/merge-iterates.ss" )
(all-from "generic/passes/optimizations/simple-merge-iterates.ss" )
(all-from "generic/passes/wavescope_bkend/nominalize-types.ss" )
(all-from "generic/passes/wavescope_bkend/type-annotate-misc.ss" )
(all-from "generic/passes/wavescope_bkend/flatten-iterate-spine.ss" )
(all-from "generic/passes/wavescope_bkend/anihilate-higher-order.ss" )
(all-from "generic/passes/small-ws-passes.ss" )
(all-from "generic/passes/wavescope_bkend/explicit-stream-wiring.ss" )
(all-from "generic/passes/wavescope_bkend/emit-c.ss" )
(all-from "generic/passes/normalize_query/remove-complex-constant.ss" )
(all-from "generic/passes/normalize_query/uncover-free.ss" )
(all-from "generic/passes/normalize_query/lift-letrec.ss" )
(all-from "generic/passes/normalize_query/lift-letrec-body.ss" )
(all-from "generic/passes/normalize_query/remove-complex-opera.ss" )
; (all-from "generic/passes/normalize_query/ws-remove-letrec.ss")
(all-from "generic/passes/normalize_query/remove-lazy-letrec.ss" )
(all-from "generic/passes/normalize_query/verify-core.ss" )
(all-from "generic/passes/normalize_query/ws-lift-let.ss")
(all-from "generic/passes/normalize_query/ws-normalize-context.ss")
; (all-from )
; (all-from )
; (all-from )
; (all-from )
)
(IFWAVESCOPE
(void)
(provide
(all-from "generic/compiler_components/logfiles.ss")
(all-from "generic/sim/alpha_lib.ss")
(all-from "generic/sim/simulator_alpha.ss")
; (all-from "generic/passes/tokmac_bkend/cleanup-token-machine.ss" )
(all-from "generic/passes/tokmac_bkend/desugar-macros.ss" )
(all-from "generic/passes/tokmac_bkend/find-emittoks.ss" )
(all-from "generic/passes/tokmac_bkend/desugar-gradients.ss" )
(all-from "generic/passes/tokmac_bkend/desugar-let-stored.ss" )
(all-from "generic/passes/tokmac_bkend/rename-stored.ss" )
(all-from "generic/passes/tokmac_bkend/cps-tokmac.ss" )
(all-from "generic/passes/tokmac_bkend/sever-cont-state.ss" )
(all-from "generic/passes/tokmac_bkend/closure-convert.ss" )
(all-from "generic/passes/tokmac_bkend/inline-tokens.ss")
(all-from "generic/passes/nesc_bkend/flatten-tokmac.ss" )
(all-from "generic/passes/nesc_bkend/emit-nesc.ss" )
(all-from "generic/passes/analyze_query/add-data-flow.ss" )
(all-from "generic/passes/deglobalize/deglobalize.ss" )
(all-from "generic/passes/deglobalize/deglobalize2.ss" )
(all-from "generic/passes/analyze_query/classify-names.ss" )
(all-from "generic/passes/analyze_query/add-heartbeats.ss" )
(all-from "generic/passes/analyze_query/add-control-flow.ss" )
(all-from "generic/passes/analyze_query/add-places.ss" )
(all-from "generic/passes/analyze_query/analyze-places.ss" )
(all-from "generic/passes/analyze_query/add-data-flow.ss" )
(all-from "generic/passes/analyze_query/resolve-fold-trees.ss" )
; (all-from )
; (all-from )
; (all-from )
; (all-from )
))
; (current-directory "demos/wavescope")
; (browse-stream (wsint "demo6c_syncN.ws"))
; (browse-stream (wsint "demo6e_stdlib_sync.ws"))
;(browse-stream (wsint "demo4_fft.ws"))
;(browse-stream (wsint "demo9b_higher_order_prims.ws"))
;(browse-stream (wsint "demo1d_dataFile_binary.ws"))
#;
(begin
(current-directory "~/wavescript/lib")
(wsint "c.ws"))
#;
(begin
(current-directory "~/wavescript/apps/marmot")
(wsint "run_first_phase.ws"))
#;
(begin
(current-directory "~/wavescript/demos/wavescope")
(wsmlton "demo1c_timer.ws"))
(current-directory "~/demos")
;(wsc2 "demo1c_timer.ws")
;(wsc2 "demo3d_tuples_of_tuples.ws")
;(wsc2 "demo2b_iterateState.ws")
;(wsc2 "demo3a_tuples.ws")
;(wsc2 "demo3g_arrays.ws")
;(wsc2 "demo3m_sigsegs.ws")
;(wstiny "demo3d_tuples_of_tuples.ws")
) ; End module
| true |
36552c6a61376596410b9d96d8c57fe598970ea0 | 46244bb6af145cb393846505f37bf576a8396aa0 | /sicp/1_32.scm | 93b619f2b176d81b0876cb00beb4873db968895c | []
| no_license | aoeuidht/homework | c4fabfb5f45dbef0874e9732c7d026a7f00e13dc | 49fb2a2f8a78227589da3e5ec82ea7844b36e0e7 | refs/heads/master | 2022-10-28T06:42:04.343618 | 2022-10-15T15:52:06 | 2022-10-15T15:52:06 | 18,726,877 | 4 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 1,828 | scm | 1_32.scm | #lang racket
; Exercise 1.32. a. Show that sum and product (exercise 1.31) are both special cases of a still more general
; notion called accumulate that combines a collection of terms, using some general accumulation function:
; (accumulate combiner null-value term a next b)
; Accumulate takes as arguments the same term and range specifications as sum and product,
; together with a combiner procedure (of two arguments) that specifies how the current term is to be combined
; with the accumulation of the preceding terms and a null-value that specifies what base value to use
; when the terms run out. Write accumulate and show how sum and product
; can both be defined as simple calls to accumulate.
(define (accumlate combiner null-value term a next b)
(if (> a b)
null-value
(combiner (term a)
(accumlate combiner null-value term (next a) next b))))
; b. If your accumulate procedure generates a recursive process, write one that generates an iterative process.
; If it generates an iterative process, write one that generates a recursive process.
(define (accumlate-iter combiner null-value term a next b)
(define (iter pivort result)
(if (> pivort b)
result
(iter (next a)
(combiner result (term a)))))
(iter a null-value))
(define (sum term a next b)
(accumlate + 0 term a next b))
(define (sum-iter term a next b)
(accumlate-iter * 0 term a next b))
(define (product term a next b)
(accumlate * 1 term a next b))
(define (product-iter term a next b)
(accumlate * 1 term a next b))
; now the tests, use the code in execrise 1.31
(define (square x) (* x x))
(define (pi-next x)
(+ x 2))
(define (pi-term x)
(/ (* (- x 1) (+ x 1) 1.0)
(square x)))
(* 4 (product pi-term 3 pi-next 1511))
(* 4 (product-iter pi-term 3 pi-next 1511)) | false |
6a8f026d78bf6358f1df220d703f402456f31720 | ece1c4300b543df96cd22f63f55c09143989549c | /Chapter3/Exercise3.25.scm | 185a019e061a10f9708d0f2eddc0640a5c84f724 | []
| no_license | candlc/SICP | e23a38359bdb9f43d30715345fca4cb83a545267 | 1c6cbf5ecf6397eaeb990738a938d48c193af1bb | refs/heads/master | 2022-03-04T02:55:33.594888 | 2019-11-04T09:11:34 | 2019-11-04T09:11:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,648 | scm | Exercise3.25.scm | ;Exercise 3.25: Generalizing one- and two-dimensional tables, show how to implement a table in which values are stored under an arbitrary number of keys and different values may be stored under different numbers of keys. The lookup and insert! procedures should take as input a list of keys used to access the table.
(define (make-table)
(let ((local-table (list '*table*)))
(define (lookup key-list)
(define (iter key-list table)
(let ((subtable
(assoc (car key-list) (cdr table)))
(remain-key-list (cdr key-list)))
(if subtable
(if (null? remain-key-list)
(cdr subtable)
(iter remain-key-list subtable))
false)))
(iter key-list local-table))
(define (insert! key-list value)
(define (iter key-list table)
(if (pair? (cdr table))
(let ((subtable
(assoc (car key-list) (cdr table)))
(remain-key-list (cdr key-list)))
(if subtable
(if (null? remain-key-list)
(set-cdr! subtable value)
(iter remain-key-list subtable))
(let ((newtable (list (car key-list))))
(begin
(set-cdr! table
(cons newtable
(cdr table)))
(iter key-list table)))))
(let ((newtable (list (car key-list))))
(begin
(set-cdr! table
(list newtable))
(iter key-list table))))
'ok)
(iter key-list local-table)
'ok local-table)
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else (error "Unknown operation:
TABLE" m))))
dispatch))
(define operation-table (make-table))
(define get (operation-table 'lookup-proc))
(define put (operation-table 'insert-proc!))
(display (put (list 'b) 0))(newline )
(display (put (list 'a) 0))(newline )
(display (put (list 'a 'b) 1))(newline )
(display (put (list 'a 'b 'c) 2))(newline )
(display (put (list 'a 'b 'd) 3))(newline )
(display (get (list 'a 'b)))(newline )
(display (get (list 'a 'b 'c)))(newline )
(display (get (list 'a 'b 'd)))(newline )
; Welcome to DrRacket, version 6.7 [3m].
; Language: SICP (PLaneT 1.18); memory limit: 128 MB.
; (*table* (b . 0))
; (*table* (a . 0) (b . 0))
; (*table* (a (b . 1)) (b . 0))
; (*table* (a (b (c . 2))) (b . 0))
; (*table* (a (b (d . 3) (c . 2))) (b . 0))
; ((d . 3) (c . 2))
; 2
; 3
; > | false |
aece11e031cbc5d6cbda1b3464203c0173ce27ee | 95b65c399510a7a52b7152b821b538b7a8046b3b | /2021/12/main.scm | 7ef64122912b4116f212333308ecea6b02b9266e | []
| no_license | HugoNikanor/Advent-of-code | 168d708092f7a54805e93a249877add418f24f95 | ff6f7c8cb2ab3e6e1fbdf9ff3ca993ef37552857 | refs/heads/master | 2023-04-27T16:00:15.677315 | 2023-04-24T09:52:38 | 2023-04-24T09:52:38 | 225,194,365 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,267 | scm | main.scm | (use-modules (srfi srfi-1)
(ice-9 format)
(ice-9 rdelim))
(define input
(let loop ()
(let ((line (read-line)))
(if (eof-object? line)
'()
(cons (map string->symbol (string-split line #\-))
(loop))))))
(define graph (make-hash-table))
(for-each (lambda (node)
(hashq-set! graph (car node)
(cons (cadr node) (hashq-ref graph (car node) '())))
(hashq-set! graph (cadr node)
(cons (car node) (hashq-ref graph (cadr node) '()))))
input)
(define (large? node)
(char-upper-case? (string-ref (symbol->string node) 0)))
(define (small? node)
(char-lower-case? (string-ref (symbol->string node) 0)))
(define paths
(let loop ((position 'start)
(used-token? #f)
(visited '(start)))
(if (eq? 'end position)
'((end))
(if used-token?
(concatenate
(map (lambda (x)
(map (lambda (path) (cons position path))
(loop x used-token?
(if (small? x)
(cons x visited)
visited))))
(remove (lambda (x) (memv x visited)) (hashq-ref graph position))))
;; else
(append
;; don't use token
(concatenate
(map (lambda (x)
(map (lambda (path) (cons position path))
(loop x used-token?
(if (small? x)
(cons x visited)
visited))))
(remove (lambda (x) (memv x visited)) (hashq-ref graph position))))
;; use token
(concatenate
(map (lambda (x)
(map (lambda (path) (cons position path))
(loop x #t visited)))
(remove (lambda (x) (memv x visited)) (hashq-ref graph position)))))
))))
;; (format #t "~y~%~a paths~%" paths (length paths))
(for-each (lambda (path)
(format #t "~a~%" (string-join (map symbol->string path) ",")))
paths)
| false |
af3bec087c1e64856bda6c283c5f7da853d4ba00 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /System.EnterpriseServices/system/mono-todoattribute.sls | 387475ec9c06c87460a6ce1e83404f7a892bcfdc | []
| 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 | 494 | sls | mono-todoattribute.sls | (library (system mono-todoattribute)
(export new is? mono-todoattribute? comment)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.MonoTODOAttribute a ...)))))
(define (is? a) (clr-is System.MonoTODOAttribute a))
(define (mono-todoattribute? a) (clr-is System.MonoTODOAttribute a))
(define-field-port
comment
#f
#f
(property:)
System.MonoTODOAttribute
Comment
System.String))
| true |
b79496cb8a95a34c5cf5bda8cbbcbb03be2c64e8 | 50458a4961e78714bb12d4b00f0e5e6e76ab8e49 | /core-vector.ss | 9b5d684a823978195ac16048f78ac1f77c3b4ef0 | []
| no_license | gus-massa/not-a-box | 5427e62495a00e4ffe5ea9fccccd293d26a5a2ab | 0599547e2c1ef2a7bf0a10f475c2f08de37f9902 | refs/heads/master | 2021-01-21T08:02:44.911038 | 2017-02-27T04:46:29 | 2017-02-27T04:46:29 | 83,335,532 | 0 | 0 | null | 2017-02-27T17:06:27 | 2017-02-27T17:06:27 | null | UTF-8 | Scheme | false | false | 624 | ss | core-vector.ss | (define vector-copy!
(case-lambda
[(dest dest-start src)
(vector-copy! dest dest-start src 0
(if (vector? src) (vector-length src) 0))]
[(src src-start dest dest-start)
(vector-copy! dest dest-start src src-start
(if (vector? src) (vector-length src) 0))]
[(dest dest-start src src-start src-end)
(let loop ([i (- src-end src-start)])
(unless (zero? i)
(let ([i (sub1 i)])
(vector-set! dest (+ dest-start i) (vector-ref src (+ src-start i)))
(loop i))))]))
(define vector-immutable vector)
(define (vector->immutable-vector x) x)
| false |
6353727da5c8aa5d16c1492b8e2eb920dcad077b | 1f48fb14898799bf9ee1118bf691586b430c5e9e | /324.scm | 6c20628443792709b71b1c438df4500793362b97 | []
| no_license | green-93-nope/sicp | 0fa79dd59414808a9cdcbfa18bd3a1c7f0b8191c | 59241b6c42621c2ef967efebdd281b845f98e923 | refs/heads/master | 2021-01-10T10:51:22.328123 | 2017-05-21T08:33:25 | 2017-05-21T08:33:25 | 48,210,972 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,325 | scm | 324.scm | (define (number-approximate a b epsion)
(< (abs (- a b)) epsion))
(define (same-key? key1 key2)
(let ((epsion 0.001))
(cond ((and (number? key1) (number? key2))
(number-approximate key1 key2 epsion))
((or (number? key1) (number? key2))
#f)
(else
(equal? key1 key2)))))
(define (make-table same-key?)
(let ((local-table (list '*table*)))
(define (assoc key records)
(cond ((null? records) #f)
((same-key? key (caar records)) (car records))
(else
(assoc key (cdr records)))))
(define (lookup key)
(let ((record (assoc key (cdr local-table))))
(if record
(cdr record)
#f)))
(define (insert! key value)
(let ((record (assoc key (cdr local-table))))
(if record
(set-cdr! record value)
(set-cdr! local-table
(cons (cons key value)
(cdr local-table))))))
(define (dispatch m)
(cond ((eq? m 'lookup-proc) lookup)
((eq? m 'insert-proc!) insert!)
(else
(error "Unknown operation -- TABLE" m))))
dispatch))
(define test-table (make-table same-key?))
(define get-test (test-table 'lookup-proc))
(define put-test (test-table 'insert-proc!))
| false |
c79c7b8352e07cf2396eb56db9748d953a39cbb1 | 404313517ba0846313af5226e05d9092d99a38b3 | /Scheme/Exercises/test.scm | d0d4c0a16e4b5805d5033609efc47aafa33267bd | []
| no_license | georgistoilov8/Functional-Programming | 00fab1d97a1ea66d0e63c55ed9ead5d309118514 | 38837b571c7e8b4ecef462d85e2ae47b316050f7 | refs/heads/master | 2020-08-29T00:39:31.773279 | 2020-01-12T17:00:31 | 2020-01-12T17:00:31 | 217,867,904 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 565 | scm | test.scm | #lang racket
(append (cons 1 (list '(2) '(3))) (list (cons 4 '())))
; (1 (2) (3) (4))
(define (all? p? l)
(foldr (lambda (x y) (and x y)) #t (map p? l)))
(define (children v g)
(cdr (assv v g)))
(define (edge? u v g)
(memv v (children u g)))
(define (vertices g) (keys g))
(define (keys alist) (map car alist))
(define (parents v g)
(filter (lambda (u) (edge? u v g)) (vertices g)))
(define (euler? g) (all? (lambda (v) (= (length (children v g))
(length (parents v g))))
(vertices g))) | false |
a155167d421f3e0b544b1850e1584d674b6ace79 | df0ba5a0dea3929f29358805fe8dcf4f97d89969 | /exercises/informatics-2/04-higher-order-functions/count.scm | 05d0316a6f9d4476c342327a754d99e8fe627eb5 | [
"MIT"
]
| permissive | triffon/fp-2019-20 | 1c397e4f0bf521bf5397f465bd1cc532011e8cf1 | a74dcde683538be031186cf18367993e70dc1a1c | refs/heads/master | 2021-12-15T00:32:28.583751 | 2021-12-03T13:57:04 | 2021-12-03T13:57:04 | 210,043,805 | 14 | 31 | MIT | 2019-12-23T23:39:09 | 2019-09-21T19:41:41 | Racket | UTF-8 | Scheme | false | false | 1,157 | scm | count.scm | (require rackunit rackunit/text-ui)
(define (accumulate combiner null-value term a next b)
(define (iter acc a)
(if (> a b)
acc
(iter (combiner (term a) acc) (next a))))
(iter null-value a))
(define (inc x) (+ x 1))
; Идеята е да добавяме 1 за всеки елемент, който удовлетворява predicate, и
; 0 за всеки елемент, който не удовлетворява predicate.
(define (count predicate a b)
(accumulate + 0
(lambda (x) (if (predicate x) 1 0))
a inc b))
; Друг вариант: добавяме 1 към крайния резултат (acc) само ако текущият
; елемент от интервала удовлетворява predicate.
(define (count predicate a b)
(accumulate (lambda (x acc) (if (predicate x) (+ acc 1) acc)) 0
(lambda (x) x)
a inc b))
(define count-tests
(test-suite
"Tests for count"
(check = (count even? 1 5) 2)
(check = (count even? 0 10) 6)
(check = (count odd? 1 5) 3)
(check = (count odd? 0 10) 5)))
(run-tests count-tests)
| false |
8bd17ffbb6022ee61cafb6b17dd47091a5778ba2 | aa0102609ec43e4bd4319b90b65a3125e5c2162a | /interpreter/intepreter.ss | f93f818b8094525ede9248de7553506c373884fc | []
| no_license | Joycexuy2/Code | 9d91dfb9a745d0b9ec51428444e6a4e4491470ec | ed82f0a2cc7b6acf7787e86906f9e2bc5b0142f2 | refs/heads/master | 2021-05-03T18:19:42.294545 | 2016-10-25T22:28:35 | 2016-10-25T22:28:35 | 71,944,295 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 11,618 | ss | intepreter.ss | ;;673-676
; top-level-eval evaluates a form in the global environment
(define top-level-eval
(lambda (form)
; later we may add things that are not expressions.
(eval-exp form init-env)))
; eval-exp is the main component of the interpreter
(define eval-exp
(lambda (exp env)
(cases expression exp
[keys-list-exp (datum) datum]
[lit-exp (datum) datum]
[var-exp (id) (apply-env env id ;look up its value.
(lambda (x) x) ;procedure to call if id is in the environment
(lambda () (eopl:error 'apply-env ;called if id not in env
"variable not found in environment: ~s" id)))]
[app-exp (rator rands)
(let ([proc-value (eval-exp rator env)]
[args (eval-rands rands env)])
(apply-proc proc-value args))]
[quote-exp (datum) datum]
[if-exp (test-exp then-exp else-exp)
(if (eval-exp test-exp env)
(eval-exp then-exp env)
(eval-exp else-exp env))]
[letrec-exp (proc-names idss bodies letrec-body)
(cond [(and (pair? idss)(list? idss)) (eval-bodies letrec-body (extend-env-recursively
(unparse-exp-list proc-names) idss bodies env))]
[else (eopl:error 'eval-exp "Bad idss field: ~a" idss)])]
[letrec-exp-improper (proc-names improper proper letrec-body)
(eval-bodies letrec-body (extend-env-recursively-improper
(unparse-exp-list proc-names) improper proper env))]
[let-exp (vars exps bodies)
(let ([new-env (extend-env (unparse-exp-list vars) (eval-rands exps env) env)])
(eval-bodies bodies new-env))]
[while-exp (test-exp then-exp) (letrec ([loop (lambda ()
(if (eval-exp test-exp env) (begin (eval-exp (syntax-expand then-exp) env) (loop))
(lit-exp (list (void)))))]) (loop))]
[lambda-exp (vars bodies) (cond
[(expression? vars) (closure (unparse-exp vars) bodies env)]
[((list-of expression?) vars)(closure (unparse-exp-list vars) bodies env)]
[else (display vars)]
)]
[lambda-exp-improper (vars improper-var bodies)
(closure-improper (unparse-exp-list vars) (unparse-exp improper-var) bodies env)]
[else (eopl:error 'eval-exp "Bad abstract syntax: ~a" exp)])))
; evaluate the list of operands, putting results into a list
(define eval-bodies (lambda (bodies env)
(let loop ([bodies bodies])
(if (null? (cdr bodies))
(eval-exp (car bodies) env)
(begin
(eval-exp (car bodies) env)
(loop (cdr bodies)))))))
(define eval-rands
(lambda (rands env)
(map (lambda (x) (eval-exp x env)) rands)))
; Apply a procedure to its arguments.
; At this point, we only have primitive procedures.
; User-defined procedures will be added later.
(define make-improper (lambda (args len index)
(cond [(<= index len) (cons (car args)
(make-improper (cdr args) len (+ index 1)))]
[else (list args)])))
(define apply-proc
(lambda (proc-value args)
(cases proc-val proc-value
[prim-proc (op) (apply-prim-proc op args)]
; You will add other cases
[closure (vars bodies env) (cond [((list-of symbol?)vars)(eval-bodies bodies (extend-env vars args env))]
[else (eval-bodies bodies (extend-env (list vars) (list args) env))])]
[closure-improper (vars improper-var bodies env)
(eval-bodies bodies (extend-env (append vars (list improper-var))
(make-improper args (length vars) 1) env))]
[else (error 'apply-proc
"Attempt to apply bad procedure: ~s"
proc-value)])))
(define *prim-proc-names* '(+ - * / sub1 add1 cons = < <= >= > not zero?
car cdr list list? null? eq? equal? eqv? length pair? atom? list-vector
vector-list procedure? vector vector-list vector? make-vector vector-ref number?
symbol? set-car! set-cdr! vector-set! display newline caaar caadr caar cadar
caddr cadr cdaar cdadr cddar cdddr cddr list->vector vector->list vector
vector-list vector? make-vector vector-ref number? symbol? set-car! set-cdr!
vector-set! display newline apply map quotient memv append list-tail))
(define init-env ; for now, our initial global environment only contains
(extend-env ; procedure names. Recall that an environment associates
*prim-proc-names* ; a value (not an expression) with an identifier.
(map prim-proc
*prim-proc-names*)
(empty-env)))
; Usually an interpreter must define each
; built-in procedure individually. We are "cheating" a little bit.
(define apply-prim-proc
(lambda (prim-proc args) (cond [(null? prim-proc) (error 'apply-prim-proc
"You have no primitive procedure specified")]
[(null? args) (error 'apply-prim-proc "You have no arguments specified")]
[else (case prim-proc
[(+) (apply + args)]
[(-) (apply - args)]
[(*) (apply * args)]
[(/) (apply / args)]
[(add1) (if (= 1 (length args)) (+ 1 (1st args)) (error 'apply-prim-proc
"You need to pass one argument into add1, args: " args))]
[(sub1) (if (= 1 (length args)) (- (1st args) 1) (error 'apply-prim-proc
"You need to pass one argument into sub1, args: " args))]
[(cons) (cons (1st args) (2nd args))]
[(=) (apply = args)]
[(<) (apply < args)]
[(<=) (apply <= args)]
[(>=) (apply >= args)]
[(>) (apply > args)]
[(not) (not (1st args))]
[(zero?) (= 0 (1st args))]
[(car) (car (1st args))] [(cadr) (car (cdr (1st args)))]
[(caddr) (car (cdr (cdr (1st args))))] [(cdr) (cdr (1st args))]
[(cddr) (cdr (cdr (1st args)))] [(cdddr) (cdr (cdr (cdr (1st args))))]
[(caar) (car (car (1st args)))] [(caaar) (car (car (car (1st args))))]
[(caadr) (car (car (cdr args)))] [(cadar) (car (cdr (car (1st args))))]
[(cdaar) (cdr (car (car (1st args))))] [(cdadr) (cdr (car (cdr (1st args))))]
[(cddar) (cdr (cdr (car (1st args))))]
[(list) (apply list args)]
[(list?) (apply list? args)]
[(quotient) (quotient (1st args) (2nd args))]
[(null?) (apply null? args)]
[(eq?) (if (null? (cdr args)) (error 'apply-prim-proc "eq? requires 2 args")
(eq? (1st args) (2nd args)))]
[(equal?) (if (null? (cdr args)) (error 'apply-prim-proc "eq? requires 2 args")
(equal? (1st args) (2nd args)))]
[(eqv?) (if (null? (cdr args)) (error 'apply-prim-proc "eq? requires 2 args")
(eqv? (1st args) (2nd args)))]
[(length) (apply length args)]
[(pair?) (pair? args)]
[(atom?) (not (pair? args))]
[(procedure?) (apply proc-val? args)]
[(list->vector) (apply list->vector args)]
[(vector->list) (apply vector->list args)]
[(vector) (apply vector args)]
[(vector-list) (vector-list args)]
[(vector?) (apply vector? args)]
[(make-vector) (if (number? (1st args)) (if (null? (cdr args))
(make-vector (1st args)) (make-vector (1st args) (2nd args)))
(error 'apply-prim-proc "First argument to make-vector must be a number"))]
[(vector-ref) (vector-ref (1st args) (2nd args))]
[(number?) (if (= 1 (length args)) (number? (1st args)) (error
'apply-prim-proc "number? can only be applied to an arg of length 1, not arg: " arg))]
[(symbol?) (if (= 1 (length args)) (symbol? (1st args)) (error
'apply-prim-proc "symbol? can only be applied to an arg of length 1, not arg: " arg))]
[(set-car!) (set-car! (1st args) (2nd args))]
[(set-cdr!) (set-cdr! (1st args) (2nd args))]
[(vector-set!) (vector-set! (1st args) (2nd args) (3rd args))]
[(display) (display args)]
[(newline) (newline)]
[(apply) (apply-proc (car args) (cadr args))]
[(map) (map (lambda (x) (apply-proc (car args) x)) (map list (cadr args)))]
[(memv) (memv (1st args) (2nd args))]
[(append) (append (1st args)(2nd args))]
[(list-tail) (list-tail (1st args)(2nd args))]
[else (error 'apply-prim-proc
"Bad primitive procedure name: ~s"
prim-op)])])))
(define rep ; "read-eval-print" loop.
(lambda ()
(display "--> ")
;; notice that we don't save changes to the environment...
(let ([answer (top-level-eval (parse-exp (read)))])
;; TODO: are there answers that should display differently?
(eopl:pretty-print answer) (newline)
(rep)))) ; tail-recursive, so stack doesn't grow.
(define eval-one-exp
(lambda (x) (top-level-eval (syntax-expand (parse-exp x)))))
;------------------------------------------------------------------
(define begin-loop (lambda (exps)
(let loop ([exps exps])
(if (null? (cdr exps))
(app-exp (lambda-exp (list) (list (car exps))) (list))
(app-exp (lambda-exp (list (var-exp '_)) (list (car exps)))
(list (loop (cdr exps))))))))
(define cond-expand (lambda (exps) (let loop ([exps exps])
(if (null? (cdr exps))
(cadr (car exps))
(if-exp (syntax-expand (car (car exps)))
(syntax-expand(cadr (car exps)))
(syntax-expand(loop (cdr exps))))))))
(define case-expand (lambda (eva cases) (let loop ([cases cases])
(if (null? (cdr cases))
(cadr (car cases))
(if-exp (app-exp (parse-exp 'memv) (list (syntax-expand eva) (car (car cases))))
(syntax-expand (cadr (car cases)))
(syntax-expand(loop (cdr cases))))))))
(define and-expand (lambda (exps)(let loop ([exps exps])
(if (null? exps) (parse-exp #t) (if (null? (cdr exps))
(car exps)
(if-exp (syntax-expand (car exps))
(loop (cdr exps))
(lit-exp #f))))
))
)
(define or-expand (lambda (exps)(let loop ([exps exps])
(if (null? exps) (parse-exp #f) (if (null? (cdr exps))
(car exps)
(if-exp (syntax-expand (car exps))
(syntax-expand (car exps))
(loop (cdr exps)))))
))
)
(define let*-expand (lambda (vars exps bodies)
(let loop ([vars vars] [exps exps])
(if (or (null? (cdr exps))(null? (cdr vars)))
(let-exp (list(car vars))(list (car exps)) bodies)
(let-exp (list(car vars))(list (car exps)) (list (loop (cdr vars) (cdr exps))))))))
(define improper-expand (lambda (idss bodies)
(let loop ([lst idss][blst bodies][resultID '()][resultBody '()])
(if (or (null? lst) (null? blst))
(list resultID resultBody)
(if (and (not (list? (1st lst)))(pair? (1st lst)))
(loop (cdr lst)(cdr blst) (cons (1st lst) resultID) (cons (1st blst) resultBody))
(loop (cdr lst)(cdr blst) resultID resultBody))
))))
(define proper-expand (lambda (idss bodies)
(let loop ([lst idss][blst bodies][resultID '()][resultBody '()])
(if (or (null? lst) (null? blst))
(list resultID resultBody)
(if (and (list? (1st lst))(pair? (1st lst)))
(loop (cdr lst)(cdr blst) (cons (1st lst) resultID) (cons (1st blst) resultBody))
(loop (cdr lst)(cdr blst) resultID resultBody)))
)))
(define syntax-expand (lambda (e)
(cases expression e
[let-exp (vars exps bodies)
(app-exp (lambda-exp vars (map syntax-expand bodies)) exps)]
[letrec-exp (proc-names idss bodies letrec-body)
(cond [((list-of (list-of symbol?)) idss)
(list 'letrec-exp proc-names idss (map syntax-expand bodies)(map syntax-expand letrec-body))]
[else (list 'letrec-exp-improper proc-names idss (map syntax-expand bodies)(map syntax-expand letrec-body))])]
; ;proc-names
; ;(reverse (improper-expand idss (map syntax-expand bodies)))
; ;(reverse(proper-expand idss (map syntax-expand bodies)))
; ;(map syntax-expand letrec-body))])
[begin-exp (exps) (begin-loop (reverse exps))]
[if-exp (test-exp then-exp else-exp)
(if-exp (syntax-expand test-exp) (syntax-expand then-exp)
(syntax-expand else-exp))]
[cond-exp (exps) (cond-expand exps)]
[let*-exp (vars exps bodies) (let*-expand vars exps bodies)]
[case-exp (eva cases) (case-expand eva cases)]
[and-exp (exps) (and-expand exps)]
[or-exp (exps) (or-expand exps)]
[else e])))
| false |
3814dde83206f300f2a9f4bf1baa3d7abe286bf5 | f4cf5bf3fb3c06b127dda5b5d479c74cecec9ce9 | /Sources/LispKit/Resources/Libraries/srfi/87.sld | a83bffe1f15e96fbf4573d7bcdad7dbc5fade48e | [
"Apache-2.0"
]
| permissive | objecthub/swift-lispkit | 62b907d35fe4f20ecbe022da70075b70a1d86881 | 90d78a4de3a20447db7fc33bdbeb544efea05dda | refs/heads/master | 2023-08-16T21:09:24.735239 | 2023-08-12T21:37:39 | 2023-08-12T21:37:39 | 57,930,217 | 356 | 17 | Apache-2.0 | 2023-06-04T12:11:51 | 2016-05-03T00:37:22 | Scheme | UTF-8 | Scheme | false | false | 941 | sld | 87.sld | ;;; SRFI 87
;;; `=>` in case clauses
;;;
;;; This SRFI proposes an extension to the `case` syntax to allow `=>` clauses as in `cond`.
;;;
;;; Author of spec: Chongkai Zhu
;;;
;;; Copyright © 2020 Matthias Zenger. All rights reserved.
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
;;; except in compliance with the License. You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software distributed under the
;;; License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
;;; either express or implied. See the License for the specific language governing permissions
;;; and limitations under the License.
(define-library (srfi 87)
(export case)
(import (lispkit control))
;; The form is implemented natively in library `(lispkit control)`
)
| false |
713492d65201b4c6db89e9cfc51aa5a498007c3d | 81c5cca0a2c901a15803e5659c1a6f5b3d94bbe2 | /examples/normal-diagnostics.scm | 9fbfad9e9c5dc0ae7a941dc44fd3359ae08561ac | [
"BSD-2-Clause"
]
| permissive | ft/scm-test-tap | e46f75dcb61e47e29f65753cc6397f3ef5184654 | 01c6cd288946240cf0ca5488df3fafa4dac2f8bf | refs/heads/master | 2021-07-06T04:59:28.248553 | 2021-05-26T21:29:01 | 2021-05-26T21:29:01 | 15,658,692 | 2 | 2 | null | null | null | null | UTF-8 | Scheme | false | false | 2,172 | scm | normal-diagnostics.scm | ;; Copyright (c) 2016-2020 Frank Terbeck <[email protected]>
;; All rights reserved.
;; Terms for redistribution and use can be found in LICENCE.
(use-modules (test tap))
(with-test-bundle (example diagnostics normal)
(no-plan)
(define-test "pass-if-=: Show diagnostics, part 1"
(pass-if-= 1 0))
(define-test "pass-if-=: Show diagnostics, part 2"
(pass-if-= (/ (+ 1 3) 2) 0))
(define-test "pass-if-~=: Show diagnostics, part 1"
(pass-if-~= 1 0 0.5))
(define-test "pass-if-~=: Show diagnostics, part 2"
(pass-if-~= (/ (+ 1 3) 2) 0 0.5))
(define-test "pass-if-eq?: Show diagnostics, part 1"
(pass-if-eq? 'certainly 'not))
(define-test "pass-if-eq?: Show diagnostics, part 2"
(pass-if-eq? (symbol-append 'cert 'ainly) 'not))
(define-test "pass-if-eq?: Show diagnostics, part 1"
(pass-if-eq? 'certainly 'not))
(define-test "pass-if-eq?: Show diagnostics, part 2"
(pass-if-eq? (symbol-append 'cert 'ainly) 'not))
(define-test "pass-if-eqv?: Show diagnostics, part 1"
(pass-if-eqv? 1 1.0))
(define-test "pass-if-eqv?: Show diagnostics, part 2"
(pass-if-eqv? 1 (/ 2.0 2)))
(define-test "pass-if-equal?: Show diagnostics, part 1"
(pass-if-equal? (list 'a 'b 'c) '(a b c (e f) g)))
(define-test "pass-if-equal?: Show diagnostics, part 2"
(pass-if-equal? '(what (ev (er (the hell) goes) on) around here)
'(sure thing)))
(define-test "pass-if-string=?: Show diagnostics, part 1"
(pass-if-string=? "Not" "the same"))
(define-test "pass-if-string=?: Show diagnostics, part 2"
(pass-if-string=? "different strings" "Entirely."))
(define-test "pass-if-string-ci=?: Show diagnostics, part 1"
(pass-if-string-ci=? "the Same?" "the same!"))
(define-test "pass-if-string-ci=?: Show diagnostics, part 2"
(pass-if-string-ci=? "different strings" "still."))
(define-test "pass-if-re-match: Show diagnostics"
(pass-if-re-match "The.*!" "the same!"))
(define-test "pass-if-true: Show diagnostics"
(pass-if-true #f))
(define-test "pass-if-false: Show diagnostics"
(pass-if-false (member 'ever '(I wonder if anyone ever sees this.)))))
| false |
aa52b22c464f11526a9d144e1dbe56a3e5a3a070 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /mscorlib/system/diagnostics/debugger-visualizer-attribute.sls | 9e59574c8a08aa0570f47dd9388a8d10bd60912b | []
| 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,799 | sls | debugger-visualizer-attribute.sls | (library (system diagnostics debugger-visualizer-attribute)
(export new
is?
debugger-visualizer-attribute?
description-get
description-set!
description-update!
target-get
target-set!
target-update!
target-type-name-get
target-type-name-set!
target-type-name-update!
visualizer-object-source-type-name
visualizer-type-name)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Diagnostics.DebuggerVisualizerAttribute
a
...)))))
(define (is? a)
(clr-is System.Diagnostics.DebuggerVisualizerAttribute a))
(define (debugger-visualizer-attribute? a)
(clr-is System.Diagnostics.DebuggerVisualizerAttribute a))
(define-field-port
description-get
description-set!
description-update!
(property:)
System.Diagnostics.DebuggerVisualizerAttribute
Description
System.String)
(define-field-port
target-get
target-set!
target-update!
(property:)
System.Diagnostics.DebuggerVisualizerAttribute
Target
System.Type)
(define-field-port
target-type-name-get
target-type-name-set!
target-type-name-update!
(property:)
System.Diagnostics.DebuggerVisualizerAttribute
TargetTypeName
System.String)
(define-field-port
visualizer-object-source-type-name
#f
#f
(property:)
System.Diagnostics.DebuggerVisualizerAttribute
VisualizerObjectSourceTypeName
System.String)
(define-field-port
visualizer-type-name
#f
#f
(property:)
System.Diagnostics.DebuggerVisualizerAttribute
VisualizerTypeName
System.String))
| true |
4f33d4a4e041bc2b36e66fe8a936ef110c6cd6de | 4bd59493b25febc53ac9e62c259383fba410ec0e | /Scripts/Task/lucas-lehmer-test/scheme/lucas-lehmer-test.ss | c4b936b2d102fcf2f4553b071d132c62f3a3088f | []
| no_license | stefanos1316/Rosetta-Code-Research | 160a64ea4be0b5dcce79b961793acb60c3e9696b | de36e40041021ba47eabd84ecd1796cf01607514 | refs/heads/master | 2021-03-24T10:18:49.444120 | 2017-08-28T11:21:42 | 2017-08-28T11:21:42 | 88,520,573 | 5 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 792 | ss | lucas-lehmer-test.ss | ;;;The heart of the algorithm
(define (S n)
(let ((m (- (expt 2 n) 1)))
(let loop ((c (- n 2)) (a 4))
(if (zero? c)
a
(loop (- c 1) (remainder (- (* a a) 2) m))))))
(define (mersenne-prime? n)
(if (= n 2)
#t
(zero? (S n))))
;;;Trivial unoptimized implementation for the base primes
(define (next-prime x)
(if (prime? (+ x 1))
(+ x 1)
(next-prime (+ x 1))))
(define (prime? x)
(let loop ((c 2))
(cond ((>= c x) #t)
((zero? (remainder x c)) #f)
(else (loop (+ c 1))))))
;;Main loop
(let loop ((i 45) (p 2))
(if (not (zero? i))
(if (mersenne-prime? p)
(begin
(display "M") (display p) (display " ")
(loop (- i 1) (next-prime p)))
(loop i (next-prime p)))))
| false |
ce4861d6d7af894d958d5cfba9cfc4a30f8c768d | 7460741268185d205c34604a6f792b80ea0e2fa6 | /chez/callcc/effekt.ss | e72424189b4a35cc13c2c43a3112714b822249c0 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | long-long-float/effekt | 359ae7cac3769be9cf7d1433e404eced2627335d | d471192ba6e02d269d8e8126d56125663e1ea523 | refs/heads/master | 2023-01-21T14:08:18.375961 | 2020-11-17T15:21:55 | 2020-11-17T15:21:55 | 294,625,877 | 0 | 0 | MIT | 2020-10-14T10:40:55 | 2020-09-11T07:31:43 | null | UTF-8 | Scheme | false | false | 1,010 | ss | effekt.ss |
(define-syntax while
(syntax-rules ()
[(_ c exp1 exp2 ...)
(letrec ([loop (lambda ()
(if c (begin exp1 exp2 ... (loop)) #f))])
(loop))]))
; ;; EXAMPLE
; ; (handle ([Fail_22 (Fail_109 () resume_120 (Nil_74))])
; ; (let ((tmp86_121 ((Fail_109 Fail_22))))
; ; (Cons_73 tmp86_121 (Nil_74))))
; (define-syntax handle
; (syntax-rules ()
; [(_ ((cap1 (op1 (arg1 ...) k exp ...) ...) ...) body ...)
; (let ([P (newPrompt)])
; (pushPrompt P
; (let ([cap1 (cap1 (define-effect-op P (arg1 ...) k exp ...) ...)] ...)
; body ...)))]))
(define-syntax handle
(syntax-rules ()
[(_ ((cap1 (op1 (arg1 ...) k exp ...) ...) ...) body)
(let ([P (newPrompt)])
(pushPrompt P
(body (cap1 (define-effect-op P (arg1 ...) k exp ...) ...) ...)))]))
(define-syntax define-effect-op
(syntax-rules ()
[(_ P (arg1 ...) k exp ...)
(lambda (arg1 ...)
(shift0-at P k exp ...))]))
(define call/cc/base call/cc)
| true |
1abc353c47853a7c10585daf99d9c79a97512e62 | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /sitelib/net/server.scm | d4261ae08ab805643ba9760f923144461dcd65d6 | [
"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 | 16,663 | scm | server.scm | ;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; net/server.scm - Simple server framework.
;;;
;;; Copyright (c) 2010-2017 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
;; super simple server framework
(library (net server)
(export make-simple-server
make-server-config
server? server-port server-shutdown-port
server-config? server-config server-context
server-start! on-server-start!
;; well for multithreading?
server-stop! on-server-stop!
server-stopped? wait-server-stop!
;; for socket detaching
server-detach-socket!
server-status
server-status?
report-server-status
server-status-target-server
server-status-thread-count
server-status-thread-statuses
thread-status-thread-info
thread-status-thread-id
thread-status-active-socket-count
;; for extension
<simple-server>
<server-config>)
(import (rnrs)
(util concurrent)
(clos user)
(sagittarius)
(sagittarius control)
(sagittarius socket)
(sagittarius object)
(sagittarius threads) ;; need thread-interrupt!
(rename (srfi :1) (alist-cons acons))
(srfi :26)
(srfi :39)
(srfi :117)
(rfc tls)
(net server monitor))
(define (close-socket socket)
;; we don't care if socket sending failed or not...
(socket-shutdown socket SHUT_RDWR)
(socket-close socket))
;; connecting this would shut it donw
(define (default-shutdown-handler server socket) #t)
(define-class <server-config> ()
((shutdown-port :init-keyword :shutdown-port :init-value #f)
(shutdown-handler :init-keyword :shutdown-handler
:init-value default-shutdown-handler)
(exception-handler :init-keyword :exception-handler
:init-value #f)
(max-thread :init-keyword :max-thread :init-value 1)
(max-retry :init-keyword :max-retry :init-value 10)
;; enabling this creates 2 server socket for both IPv4 and IPv6
;; if EADDRINUSE is raised then only IPv6 is created.
;; NOTE: I don't have such environment yet...
(use-ipv6? :init-keyword :use-ipv6? :init-value #f)
;; For TLS socket
(secure? :init-keyword :secure? :init-value #f)
(certificates :init-keyword :certificates :init-value '())
(private-key :init-keyword :private-key :init-value #f)
;; non blocking (default #f for backward compatibility)
(non-blocking? :init-keyword :non-blocking? :init-value #f)))
(define (server-config? o) (is-a? o <server-config>))
(define (default-server-monitor)
(error 'server-monitor "not supported"))
(define-class <simple-server> ()
((server-sockets :init-keyword :server-sockets :init-value #f)
(server-threads :init-keyword :server-threads)
(stopper-socket :init-keyword :stopper-socket :init-value #f)
(stopper-thread :init-keyword :stopper-thread :init-value #f)
(config :init-keyword :config
:reader server-config)
(lock :init-form (make-mutex))
(stop-lock :init-form (make-mutex))
(stop-waiter :init-form (make-condition-variable))
;; private slot not to use thread-terminate!
(stop-request :init-value #f)
(port :init-keyword :port)
(running-port :init-keyword :running-port :reader server-port)
(shutdown-port :init-value #f :reader server-shutdown-port)
(dispatch :init-keyword :dispatch)
;; set if non-blocking mode
(initialiser :init-value #f)
(context :init-keyword :context :init-value #f
:reader server-context)
(monitor :reader server-monitor
:init-value default-server-monitor)))
(define (server-status server) ((server-monitor server)))
(define (server? o) (is-a? o <simple-server>))
(define (server-stopped? server) (not (~ server 'server-sockets)))
(define (make-server-config . opt) (apply make <server-config> opt))
(define *detaching-sockets* (make-parameter #f))
(define (server-detach-socket! server socket)
(let ((queue (*detaching-sockets*)))
(unless (list-queue? queue)
(assertion-violation 'server-detach-socket!
"only non-blocking server can detach socket or it's not in task"))
(list-queue-add-front! queue socket)))
(define (make-non-blocking-process server handler config)
(define num-threads (~ config 'max-thread))
(define thread-pool (make-thread-pool num-threads raise))
(define socket-manager
;; input is (tid . socket-count)
;; tid won't be duplicated
(make-shared-priority-queue
(lambda (a b)
(let ((ac (cdr a)) (bc (cdr b))
(atid (car a)) (btid (car b)))
(cond ((= atid btid) 0)
((< ac bc) -1)
(else 1))))
num-threads))
;; the manager actor is needed to make sure socket-manager operation
;; is done in atomic environment.
(define manager
(make-shared-queue-channel-actor
(lambda (in out)
(let loop ()
(let ((command (in)))
(cond (command
(shared-priority-queue-remove! socket-manager command)
(shared-priority-queue-put! socket-manager command))
(else (out (shared-priority-queue-get! socket-manager)))))
(loop)))))
(define (notify-info tid count)
(actor-send-message! manager (cons tid count)))
(define (retrieve-info)
(actor-send-message! manager #f)
(actor-receive-message! manager))
;; this depends on the thread-pool thread id which is exact integer
;; and less than number of threads
(define channels (make-vector num-threads #f))
(define (make-task server)
(define channel (make-shared-queue))
(define (task)
(define (retrieve-sockets init)
(do ((sockets init (cons (shared-queue-get! channel) sockets)))
((and (shared-queue-empty? channel) (not (null? sockets)))
sockets)))
(define (filter-active sockets)
(define detaching-sockets
(list-queue-remove-all! (*detaching-sockets*)))
(define (check-active o)
(and (not (socket-closed? o))
(not (memq o detaching-sockets))))
(filter check-active sockets))
(*detaching-sockets* (list-queue))
;; get sockets
(let loop ((sockets (retrieve-sockets '())))
(let ((read-sockets (apply socket-read-select #f sockets)))
(dolist (socket read-sockets)
(guard (e ((~ config 'exception-handler)
;; let them handle it
((~ config 'exception-handler) server socket e))
;; if exception-handler is not there
;; close the socket.
(else (socket-shutdown socket SHUT_RDWR)
(socket-close socket)))
(handler server socket)))
(let ((active (filter-active sockets))
(tid (thread-pool-current-thread-id)))
(notify-info tid (length active))
(loop (retrieve-sockets active))))))
(values task channel))
;; must be initialised during server-start!
(set! (~ server 'initialiser)
(lambda ()
(dotimes (i num-threads)
(let-values (((task channel) (make-task server)))
(let ((id (thread-pool-push-task! thread-pool task)))
(notify-info id 0)
(vector-set! channels id channel))))))
(set! (~ server 'monitor)
(make-non-blocking-server-monitor server thread-pool socket-manager))
;; process
(lambda (server socket)
(let* ((info (retrieve-info))
(thread-id (car info)))
(let ((channel (vector-ref channels thread-id)))
(let ((thread (thread-pool-thread thread-pool thread-id)))
(notify-info thread-id (+ (cdr info) 1))
(shared-queue-put! channel socket)
(thread-interrupt! thread))))))
(define (stop-server server)
;; (define (connect ai-family)
;; (guard (e (else #t))
;; (if (~ server 'config 'secure?)
;; (make-client-tls-socket "localhost" (~ server 'port) ai-family)
;; (make-client-socket "localhost" (~ server 'port) ai-family))))
(define (safe-interrupt! t)
(guard (e (else #t)) (thread-interrupt! t)))
(set! (~ server 'stop-request) #t)
(for-each close-socket (~ server 'server-sockets))
;; On FreeBSD, accept(2) can go on even the server
;; socket is closed during the process. So we need
;; to make sure this would stop
;; (when (~ server 'config 'use-ipv6?) (connect AF_INET6))
;; (connect AF_INET)
(for-each safe-interrupt! (~ server 'server-threads)))
(define (make-simple-server port handler
:key (server-class <simple-server>)
;; must have default config
(config (make-server-config))
:allow-other-keys rest)
(define server (apply make server-class :config config :port port
:running-port port
rest))
(define dispatch
(if (~ config 'non-blocking?)
(make-non-blocking-process server handler config)
;; normal one.
(let ((executor (and (> (~ config 'max-thread) 1)
(make-thread-pool-executor
(~ config 'max-thread)
(wait-finishing-handler
(~ config 'max-retry))))))
(lambda (server socket)
(define (handle socket)
(guard (e (else
(when (~ config 'exception-handler)
((~ config 'exception-handler) server socket e))
(close-socket socket)
#t))
(call-with-socket socket
(lambda (sock) (handler server sock)))))
;; ignore error
(if executor
(let ((f (future (class <executor-future>) (handle socket))))
(execute-future! executor f))
(handle socket))))))
(set! (~ server 'dispatch) dispatch)
server)
(define (initialise-server! server)
(define config (~ server 'config))
(define dispatch (~ server 'dispatch))
(define port (~ server 'port))
(define (make-socket ai-family)
(if (and (~ config 'secure?)
(not (null? (~ config 'certificates))))
;; For now no private key, it's simple server
;; anyway
(make-server-tls-socket port (~ config 'certificates)
:private-key (~ config 'private-key)
ai-family)
(make-server-socket port ai-family)))
(let* ((ai-families (if (~ config 'use-ipv6?)
`(,AF_INET6 ,AF_INET)
`(,AF_INET)))
;; hope all platform accepts dual when IPv6 is enabled
(socket&ais (fold-left (lambda (s ai-family)
(guard (e (else s))
(acons (make-socket ai-family) ai-family
s)))
'() ai-families))
(sockets (map car socket&ais)))
(define server-threads
(map (lambda (socket)
(make-thread
(lambda ()
(define stop? #f)
(define (stop) (close-socket socket) (set! stop? #t))
(thread-specific-set! (current-thread) 'done)
(let loop ()
(guard (e ((and (socket-error? e)
;; Don't check, TLS socket wouldn't
;; be the same since the condition
;; contains raw socket
;; (eq? socket (socket-error-socket e))
(socket-closed? socket))
;; the socket is closed, so we can't process
;; anymore.
(set! stop? #t))
(else
(cond ((~ config 'exception-handler) =>
(lambda (h) (h server #f e))))))
(if (socket-closed? socket)
(set! stop? #t)
(let ((client-socket (socket-accept socket)))
(cond ((~ server 'stop-request) (stop))
(client-socket
(dispatch server client-socket))))))
(unless stop? (loop))))))
sockets))
(when (null? sockets)
(error 'make-simple-server "failed to create server sockets" port))
(when (or (not port) (equal? port "0"))
(let ((si (socket-info (car sockets))))
(set! (~ server 'running-port)
(number->string (socket-info-port si)))))
(when (~ server 'initialiser)
((~ server 'initialiser))
(set! (~ server 'initialiser) #f))
(set! (~ server 'server-sockets) sockets)
(set! (~ server 'server-threads) server-threads)
(when (~ config 'shutdown-port)
(set! (~ server 'stopper-thread)
(make-thread
(lambda ()
(define shutdown-port (~ config 'shutdown-port))
(define stop-socket (make-server-socket shutdown-port))
(set! (~ server 'stopper-socket) stop-socket)
(set! (~ server 'shutdown-port)
(if (or (not shutdown-port) (equal? shutdown-port "0"))
(number->string
(socket-info-port (socket-info stop-socket)))
shutdown-port))
;; lock it here
(mutex-lock! (~ server 'stop-lock))
(let loop ()
(let ((sock (socket-accept stop-socket)))
(cond (sock
;; ignore all errors
(mutex-lock! (~ server 'lock))
(guard (e (else #t))
(when ((~ config 'shutdown-handler) server sock)
;; lock to avoid race condition here
(stop-server server)
(for-each thread-join! server-threads)
(set! (~ server 'server-sockets) #f)
(condition-variable-broadcast!
(~ server 'stop-waiter))
(mutex-unlock! (~ server 'stop-lock))))
(mutex-unlock! (~ server 'lock))
(close-socket sock)
(if (server-stopped? server)
(close-socket stop-socket)
(loop)))
(else (loop)))))))))
server))
;; wait until the server started
(define (server-wait! server)
(let loop ()
;; kinda awkward...
(unless (for-all (lambda (t) (eq? (thread-specific t) 'done))
(~ server 'server-threads))
(thread-yield!)
(thread-sleep! 0.1)
(loop))))
;; default do nothing
(define-generic on-server-start!)
(define-generic on-server-stop!)
(define-method on-server-start! ((s <simple-server>) . ignore))
(define-method on-server-stop! ((s <simple-server>) . ignore))
(define (server-start! server :key (background #f)
:rest opts)
(unless (server? server)
(assertion-violation 'start-server! "server object required" server))
(if (~ server 'server-sockets)
(assertion-violation 'start-server! "server is already started" server)
(initialise-server! server))
(when (~ server 'stopper-thread)
(thread-start! (~ server 'stopper-thread)))
;; pass all keyword arguments
(apply on-server-start! server opts)
(guard (e ((terminated-thread-exception? e) #t)
(else (raise e)))
(let ((threads (map thread-start! (~ server 'server-threads))))
(if background
(server-wait! server)
(map thread-join! threads)))))
(define (server-stop! server . opt)
(unless (server? server)
(assertion-violation 'start-server! "server object required" server))
(unless (server-stopped? server)
(let ((ohandler (~ server 'config 'shutdown-handler)))
(set! (~ server 'config 'shutdown-handler) default-shutdown-handler)
(if (~ server 'stopper-thread)
;; we need to stop the shutdown thread as well
(close-socket
(make-client-socket "localhost"
(~ server 'config 'shutdown-port)))
(stop-server server))
(set! (~ server 'config 'shutdown-handler) ohandler))
(map thread-join! (~ server 'server-threads))
(mutex-lock! (~ server 'lock))
(when (~ server 'server-sockets)
(map close-socket (~ server 'server-sockets)))
;; should this be here?
(apply on-server-stop! server opt)
(set! (~ server 'server-sockets) #f)
(mutex-unlock! (~ server 'lock))))
(define (wait-server-stop! server :optional (timeout #f))
(or (server-stopped? server)
;; we don't have to lock again
(mutex-unlock! (~ server 'stop-lock) (~ server 'stop-waiter)
timeout)))
)
| false |
bb65dd86291659646ec670d5aded896d85a7e745 | bf1c9803ae38f9aad027fbe4569ccc6f85ba63ab | /chapter_1/1.3.Formulating.Abstractions.with.Higher-Order.Procedures/ex_1.34.scm | ec49923b12dbfce65589ab03abf04742a89a742d | []
| no_license | mehese/sicp | 7fec8750d3b971dd2383c240798dbed339d0345a | 611b09280ab2f09cceb2479be98ccc5403428c6c | refs/heads/master | 2021-06-12T04:43:27.049197 | 2021-04-04T22:22:47 | 2021-04-04T22:23:12 | 161,924,666 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 571 | scm | ex_1.34.scm | #lang sicp
(define square (lambda (x) (* x x)))
(define (f g) (g 2))
(f square) ; (square 2) -> 4
(f (lambda (z) (* z (+ z 1)))) ; (z*(z+1) 2) -> (2*(2+1)) -> 6
(f f) ; Error: application: not a procedure;
; expected a procedure that can be applied to arguments
; given: 2
; arguments...:
;; Had to check http://www.billthelizard.com/2010/05/sicp-exercise-134-procedures-as.html
;; for an explanation
;;
;; If we use the substitution model
;; (f f)
;; (f 2) (now g takes the value 2)
;; (2 2) -> 2 is not a procedure, so the thing errors | false |
2911a476e218974bb4e7bd78e82143a26fe778c6 | 15b3f9425594407e43dd57411a458daae76d56f6 | /src/callcc1.scm | 6ccaf4610d270cd2f547428f6cff4ae23d3a449c | []
| 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 | 72 | scm | callcc1.scm | (define (callcc1)
(call-with-current-continuation
callcc2))
| false |
4488676b272215231b19c637566218dd0234fad5 | 4b2aeafb5610b008009b9f4037d42c6e98f8ea73 | /10.1/stack-queue.scm | 5d672f6f4fa49d55679a0d79b6a98a6ca9a7c8e3 | []
| no_license | mrinalabrol/clrs | cd461d1a04e6278291f6555273d709f48e48de9c | f85a8f0036f0946c9e64dde3259a19acc62b74a1 | refs/heads/master | 2021-01-17T23:47:45.261326 | 2010-09-29T00:43:32 | 2010-09-29T00:43:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,489 | scm | stack-queue.scm | (define (stack-enqueue! stack x)
(let* ((data (stack-data stack))
(length (vector-length data))
(temp (make-stack (make-vector length #f) -1)))
(push! temp x)
(loop ((until (stack-empty? stack)))
(push! temp (pop! stack)))
(loop ((until (stack-empty? temp)))
(push! stack (pop! temp)))))
(define (stack-dequeue! stack)
(let* ((data (stack-data stack))
(length (vector-length data))
(temp (make-stack (make-vector length #f) -1)))
(loop ((until (stack-empty? stack)))
(push! temp (pop! stack)))
(let ((x (pop! temp)))
(vector-fill! data #f)
(loop ((until (stack-empty? temp)))
(push! stack (pop! temp)))
x)))
(define (queue-push! queue x)
(let* ((data (queue-data queue))
(length (vector-length data))
(temp (make-queue (make-vector length #f) 0 0)))
(enqueue! temp x)
(loop ((until (queue-empty? queue)))
(enqueue! temp (dequeue! queue)))
(loop ((until (queue-empty? temp)))
(enqueue! queue (dequeue! temp)))))
(define (queue-pop! queue)
(let* ((data (queue-data queue))
(length (vector-length data))
(temp (make-queue (make-vector length #f) 0 0)))
(loop ((until (queue-empty? queue)))
(enqueue! temp (dequeue! queue)))
(let ((x (dequeue! temp)))
(vector-fill! data #f)
(loop ((until (queue-empty? temp)))
(enqueue! queue (dequeue! temp)))
x)))
| false |
ba1c1772ee7133bdc4fa552271a91059a0d1e8e1 | aa3c0aed788687ccc10a85d9cb8dd77a8ffbd5e9 | /test-cache.scm | f2e92e4f9915744033ef2b26dc81e69f15a6af79 | []
| no_license | ursetto/sql-de-lite | 22c3cc76127fe2d20f577c638e81b83ab6c3ba2d | 0f974749d5caa0a34e2a7d6dcc4163f2cb4beac3 | refs/heads/master | 2023-03-06T16:12:22.018124 | 2023-02-13T04:11:01 | 2023-02-13T04:11:01 | 157,043,421 | 4 | 7 | null | 2023-02-13T04:11:02 | 2018-11-11T03:19:36 | C | UTF-8 | Scheme | false | false | 6,294 | scm | test-cache.scm | (use srfi-1)
(define selects
(map (lambda (x) (sprintf "select ~A;" x)) (iota 200)))
(define cache-hash
(map (lambda (x)
(cons (hash x)
(cons x (conc "** " x " **"))))
selects))
(define cache-string
(map (lambda (x)
(cons x (conc "** " x " **")))
selects))
(define cache-hash-table
(let ((ht (make-hash-table string=?)))
(for-each (lambda (x)
(hash-table-set! ht x (conc "** " x " **")))
selects)
ht))
(use miscmacros)
(use lru-cache)
(print "alist lookup by hashed value (end of 50 elt list)")
(print (cdr (alist-ref (string-hash "select 49;") cache-hash)))
(time (dotimes (i 1000000)
(let ((s "select 49;"))
(and-let* ((cell (alist-ref (string-hash s) cache-hash)))
(and (string=? (car cell) s)
(cdr cell))))))
(print "hash-table lookup by string=?")
(print (hash-table-ref/default cache-hash-table "select 49;" #f))
(time (dotimes (i 1000000)
(hash-table-ref/default cache-hash-table "select 49;" #f)))
;; Slower than hash table. How is that possible?
(print "alist lookup by hashed value (first element)")
(print (cdr (alist-ref (string-hash "select 0;") cache-hash)))
(time (dotimes (i 1000000)
(let ((s "select 0;"))
(and-let* ((cell (alist-ref (string-hash s) cache-hash)))
(and (string=? (car cell) s)
(cdr cell))))))
(print "(hash \"select 0;\")")
(time (dotimes (i 1000000)
(let ((s "select 0;"))
(hash s))))
(print "(string-hash \"select 0;\")")
(time (dotimes (i 1000000)
(let ((s "select 0;"))
(string-hash s))))
(print "alist lookup by hashed value (100th element)")
(print (cdr (alist-ref (string-hash "select 99;") cache-hash)))
(time (dotimes (i 1000000)
(let ((s "select 99;"))
(and-let* ((cell (alist-ref (string-hash s) cache-hash)))
(and (string=? (car cell) s)
(cdr cell))))))
(print "alist lookup by hashed value (200th element)")
(print (cdr (alist-ref (string-hash "select 199;") cache-hash)))
(time (dotimes (i 1000000)
(let ((s "select 199;"))
(and-let* ((cell (alist-ref (string-hash s) cache-hash)))
(and (string=? (car cell) s)
(cdr cell))))))
(print "hash-table lookup by string=? (200th elt)")
(print (hash-table-ref/default cache-hash-table "select 199;" #f))
(time (dotimes (i 1000000)
(hash-table-ref/default cache-hash-table "select 199;" #f)))
;;; lru
(print "lru-cache populate 100 (capacity 100)")
(define C (make-lru-cache 100 string=?))
(time (for-each (lambda (x)
(lru-cache-set! C x x))
selects)) ; should split up, half and half
(print "lru-cache lookup, select 100;")
(print (lru-cache-ref C "select 100;"))
(time (dotimes (i 1000000)
(lru-cache-ref C "select 100;")))
(define v (list->vector selects))
(print "random number overhead")
(time (dotimes (i 1000000)
(vector-ref v (random 200))))
(print "lru-cache lookup, random (half in cache)")
(print (lru-cache-ref C (vector-ref v (random 200))))
(time (dotimes (i 1000000)
(lru-cache-ref C (vector-ref v (random 200)))))
(print "lru-cache lookup, random (all in cache)")
(print (lru-cache-ref C (vector-ref v (+ 100 (random 100)))))
(time (dotimes (i 1000000)
(lru-cache-ref C (vector-ref v (+ 100 (random 100))))))
(print "lru-cache lookup of static uncached element")
(print (lru-cache-ref C "abcdef;"))
(time (dotimes (i 1000000)
(lru-cache-ref C "abcdef;")))
(print "lru-cache lookup of static uncached element plus random # overhead")
(print (lru-cache-ref C "abcdef;"))
(time (dotimes (i 1000000)
(vector-ref v (random 200))
(lru-cache-ref C "abcdef;")))
(print "cache size: " (lru-cache-size C)) ; 100
;; (lru-cache-walk C (lambda (k v)
;; (write (cons k v)) (write " ")))
(when #f
(print "lru-cache lookup 2 (experimental), random (half in cache)")
(print (lru-cache-ref-2 C (vector-ref v (random 200))))
(time (dotimes (i 1000000)
(lru-cache-ref-2 C (vector-ref v (random 200)))))
;; (lru-cache-walk C (lambda (k v)
;; (write (cons k v)) (write " ")))
(print "lru-cache lookup 2 (experimental), random (all in cache)")
(print (lru-cache-ref-2 C (vector-ref v (+ 100 (random 100)))))
(time (dotimes (i 1000000)
(lru-cache-ref-2 C (vector-ref v (+ 100 (random 100))))))
(print "cache size: " (lru-cache-size C)) ; 100
;; (lru-cache-walk C (lambda (k v)
;; (write (cons k v)) (write " ")))
)
(print "alist lookup by hashed value, size 200, random lookup")
(print (cdr (alist-ref (string-hash (vector-ref v (random 200)))
cache-hash)))
(time (dotimes (i 1000000)
(let ((s (vector-ref v (random 200))))
(and-let* ((cell (alist-ref (string-hash s) cache-hash)))
(and (string=? (car cell) s)
(cdr cell))))))
(print "alist lookup by hashed value, size 200, random lookup in first half")
(print (cdr (alist-ref (string-hash (vector-ref v (random 100)))
cache-hash)))
(time (dotimes (i 1000000)
(let ((s (vector-ref v (random 100))))
(and-let* ((cell (alist-ref (string-hash s) cache-hash)))
(and (string=? (car cell) s)
(cdr cell))))))
;; unused
(define C (make-lru-cache 100 string=?
(lambda (k v)
(printf "deleting (~S ~S)\n" k v))))
;;; unusable
;; (print "alist lookup by string=? (end of 50 elt list)")
;; (print (alist-ref "select 49;" cache-string string=?))
;; (time (dotimes (i 1000000)
;; (alist-ref "select 49;" cache-string string=?)))
;; (print "alist lookup by string=? (200th elt)")
;; (print (alist-ref "select 199;" cache-string string=?))
;; (time (dotimes (i 1000000)
;; (alist-ref "select 199;" cache-string string=?)))
| false |
767bc46e560f962a31fba7aae04193dd0f300885 | 99f659e747ddfa73d3d207efa88f1226492427ef | /datasets/srfi/srfi-114/comparators/comparators.scm | cc7c27d73d0d5ee881d9a3cf4b6c4b1ea95dbbdf | [
"MIT"
]
| permissive | michaelballantyne/n-grams-for-synthesis | 241c76314527bc40b073b14e4052f2db695e6aa0 | be3ec0cf6d069d681488027544270fa2fd85d05d | refs/heads/master | 2020-03-21T06:22:22.374979 | 2018-06-21T19:56:37 | 2018-06-21T19:56:37 | 138,215,290 | 0 | 0 | MIT | 2018-06-21T19:51:45 | 2018-06-21T19:51:45 | null | UTF-8 | Scheme | false | false | 1,991 | scm | comparators.scm | (require-library srfi-4)
(require-library numbers)
(require-library srfi-13)
(module comparators ()
(import scheme chicken)
(import srfi-4)
(import numbers)
(import srfi-13)
(export comparator? comparator-comparison-procedure?
comparator-hash-function?)
(export boolean-comparator char-comparator char-ci-comparator
string-comparator string-ci-comparator symbol-comparator
exact-integer-comparator integer-comparator rational-comparator
real-comparator complex-comparator number-comparator
pair-comparator list-comparator vector-comparator
bytevector-comparator)
(export default-comparator)
(export make-comparator make-inexact-real-comparator make-vector-comparator
make-bytevector-comparator make-list-comparator
make-vectorwise-comparator make-listwise-comparator
make-car-comparator make-cdr-comparator make-pair-comparator
make-improper-list-comparator make-selecting-comparator
make-refining-comparator make-reverse-comparator
make-debug-comparator)
(export eq-comparator eqv-comparator equal-comparator)
(export comparator-type-test-procedure comparator-equality-predicate
comparator-comparison-procedure comparator-hash-function)
(export comparator-test-type comparator-check-type comparator-equal?
comparator-compare comparator-hash)
(export make-comparison< make-comparison> make-comparison<=
make-comparison>= make-comparison=/< make-comparison=/>)
(export if3 if=? if<? if>? if<=? if>=? if-not=?)
(export =? <? >? <=? >=?)
(export make= make< make> make<= make>=)
(export in-open-interval? in-closed-interval? in-open-closed-interval?
in-closed-open-interval?)
(export comparator-min comparator-max)
(export comparator-register-default!)
(include "r7rs-shim.scm")
(include "basics.scm")
(include "default.scm")
(include "constructors.scm")
(include "advanced.scm"))
| false |
5a2fb571bb4591ba416c692b313b892cedba4435 | a92feaae015d1ddfaa0860f23f7cc975998e8a3c | /define-record-and-printer-core.scm | 395a79396f24477977366431c37bf4c594a6b99b | []
| no_license | klutometis/define-record-and-printer | 2e00fdccd7e6b6c6e783c1b9e684663f175210b1 | 3b91909b07c1808fbe0c1184f791bb756a0ab04f | refs/heads/master | 2021-01-15T19:28:29.287903 | 2019-09-24T18:12:40 | 2019-09-24T18:12:40 | 5,171,664 | 0 | 1 | null | 2019-09-24T17:54:07 | 2012-07-24T21:44:58 | Scheme | UTF-8 | Scheme | false | false | 876 | scm | define-record-and-printer-core.scm | (define-syntax define-record-and-printer
@("Define a record and a printer that shows the contents of the
record as a vector; see {{define-record}}."
(name "The name of the record")
(slotname "The name of the slot")
(@to "record"))
(er-macro-transformer
(lambda (expression rename compare)
(match expression
((_ record . fields)
(let ((%define-record (rename 'define-record))
(%define-record-printer (rename 'define-record-printer))
(%begin (rename 'begin))
(%lambda (rename 'lambda))
(%write (rename 'write))
(%record->vector (rename 'record->vector)))
`(,%begin
(,%define-record ,record ,@fields)
(,%define-record-printer
,record
(,%lambda (record out)
(,%write (,%record->vector record) out))))))))))
| true |
ccbb0119c3ad9df9c908739c8ebe9e6114e7b207 | ea4e27735dd34917b1cf62dc6d8c887059dd95a9 | /section3_3_exercise3_16.scm | edcdf1d9d095681d9622cd489f1829263f6ae785 | [
"MIT"
]
| permissive | feliposz/sicp-solutions | 1f347d4a8f79fca69ef4d596884d07dc39d5d1ba | 5de85722b2a780e8c83d75bbdc90d654eb094272 | refs/heads/master | 2022-04-26T18:44:32.025903 | 2022-03-12T04:27:25 | 2022-03-12T04:27:25 | 36,837,364 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 547 | scm | section3_3_exercise3_16.scm | (define (count-pairs x)
(if (not (pair? x))
0
(+ (count-pairs (car x))
(count-pairs (cdr x))
1)))
(define a (cons 1 2))
(define b (cons a a))
(define c (cons 1 b))
(define d (cons b b))
(define e (cons 1 2))
(set-cdr! e e)
a
b
c
d
;e
(count-pairs a) ; 1 pair
(count-pairs b) ; 3 pairs (actually, there are just 2)
(count-pairs c) ; 4 pairs (actually, there are just 3)
(count-pairs d) ; 7 pairs (actyally, there are just 4)
;(count-pairs e)
;e is a circular self-referencing structure
;count-pairs never returns
| false |
3b944a093a3188a139cc1c7156fa4a870114635e | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /test/tests/tlv.scm | 63db6fc0e81f0a9396e9bca9384081c9eecd164e | [
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
]
| permissive | ktakashi/sagittarius-scheme | 0a6d23a9004e8775792ebe27a395366457daba81 | 285e84f7c48b65d6594ff4fbbe47a1b499c9fec0 | refs/heads/master | 2023-09-01T23:45:52.702741 | 2023-08-31T10:36:08 | 2023-08-31T10:36:08 | 41,153,733 | 48 | 7 | NOASSERTION | 2022-07-13T18:04:42 | 2015-08-21T12:07:54 | Scheme | UTF-8 | Scheme | false | false | 4,201 | scm | tlv.scm | #!read-macro=sagittarius/regex
(import (rnrs)
(tlv)
(util bytevector)
(sagittarius regex)
(srfi :64))
(test-begin "TLV library tests")
;; the data is from EMV lab
;; TODO add more tests
(let ()
(define emv-parser (make-tlv-parser EMV))
(define tlv-value
(integer->bytevector
#x6F1A840E315041592E5359532E4444463031A5088801025F2D02656E))
(define tlv-structure '((#xEF (#xA0 (#x80 . #vu8(1 2 3 4 5)))
(#xA1 (#x80 1 2 3 4 5))
(#xA1 (#x80 . #x123456)))
(#xC9)))
(test-assert "tlv-object?"
(tlv-object? (call-with-port
(open-bytevector-input-port tlv-value)
emv-parser)))
(let ((tlv (call-with-port (open-bytevector-input-port tlv-value)
emv-parser)))
(test-equal "tlv-tag" #x6F (tlv-tag tlv))
(test-assert "tlv-data" (not (tlv-data tlv)))
(test-assert "tlv-components" (not (null? (tlv-components tlv))))
(test-equal "tlv->bytevector" tlv-value (tlv->bytevector tlv))
(test-equal "write-tlv" tlv-value
(call-with-bytevector-output-port
(lambda (out) (write-tlv tlv out))))
)
(test-equal "read-tlv" 2 (length (read-tlv (open-bytevector-input-port
(bytevector-concatenate
(map tlv->bytevector
(->tlv tlv-structure))))
emv-parser)))
)
(let ()
(define dgi-parser (make-tlv-parser DGI))
(define tlv-value #vu8(00 01 05 01 02 03 04 05))
(test-assert "tlv-object?"
(tlv-object? (call-with-port
(open-bytevector-input-port tlv-value)
dgi-parser)))
(let ((tlv (call-with-port (open-bytevector-input-port tlv-value)
dgi-parser)))
(test-equal "tlv-tag" #x0001 (tlv-tag tlv))
(test-equal "tlv-data (dgi)" #vu8(1 2 3 4 5) (tlv-data tlv))
;; so far we don't have DGI style writer...
(test-equal "tlv->bytevector" tlv-value
(tlv->bytevector tlv :writer write-dgi-tlv))
(test-equal "write-tlv" tlv-value
(call-with-bytevector-output-port
(lambda (out) (write-dgi-tlv tlv out)))))
)
;; some of the length related issue tests
(let ()
(define (make-bogus-tlv-bytevector len)
(let ((tlv (make-tlv-unit #x80 (make-bytevector len #xFF))))
(open-bytevector-input-port (tlv->bytevector tlv))))
(test-assert "length #x7F" (read-tlv (make-bogus-tlv-bytevector #x7F)))
(test-assert "length #xFF" (read-tlv (make-bogus-tlv-bytevector #xFF)))
(test-assert "length #xFFFF" (read-tlv (make-bogus-tlv-bytevector #xFFFF)))
(test-assert "length #x1FFFF" (read-tlv (make-bogus-tlv-bytevector #x1FFFF))))
;; multiple length tags
(let ()
(define (bytevector->tlv bv)
(car (read-tlv (open-bytevector-input-port bv))))
(test-equal "3 length tag" #x1FFF7F
(tlv-tag (bytevector->tlv #vu8(#x1F #xFF #x7F #x00))))
(test-equal "4 length tag" #x1FFFFF7F
(tlv-tag (bytevector->tlv #vu8(#x1F #xFF #xFF #x7F #x00)))))
;; LV
(let ()
(define LV "41 042cb5deaf002307ea866c32af628a59\
a5b24d3cefc615ba924660819ee96461\
9770f3175e53e2bfea58bad28465ed1e\
2dc463c8ae33a950ae54136c2cd6f8c8\
08\
1d a61b9002aa0295011080018881011083\
01319103000000450411223344\
10 601c32691f0c339b1136770a2ab060cd\
03 f2367b\
40 afcb1b01887d58d0e628e2bc2986f41d\
82de36e35e1cd35413032bc7fa8c3b2f\
d88492edff456712c9e5f805b3e0cae2\
142e12a3b37099a10763986a39da4690")
(define Vs '("042cb5deaf002307ea866c32af628a59\
a5b24d3cefc615ba924660819ee96461\
9770f3175e53e2bfea58bad28465ed1e\
2dc463c8ae33a950ae54136c2cd6f8c8\
08"
"a61b9002aa0295011080018881011083\
01319103000000450411223344"
"601c32691f0c339b1136770a2ab060cd"
"f2367b"
"afcb1b01887d58d0e628e2bc2986f41d\
82de36e35e1cd35413032bc7fa8c3b2f\
d88492edff456712c9e5f805b3e0cae2\
142e12a3b37099a10763986a39da4690"))
(test-equal "read-lv"
(map hex-string->bytevector Vs)
(read-lv (open-bytevector-input-port
(hex-string->bytevector
(regex-replace-all #/\s+/ LV "")))))
)
(test-end)
| false |
0cb72956e46e4c9bededb1815d55e77f93a69941 | a8216d80b80e4cb429086f0f9ac62f91e09498d3 | /lib/srfi/95.sld | f4575ad5bd5180bb452768c1968a474a50c33483 | [
"BSD-3-Clause"
]
| permissive | ashinn/chibi-scheme | 3e03ee86c0af611f081a38edb12902e4245fb102 | 67fdb283b667c8f340a5dc7259eaf44825bc90bc | refs/heads/master | 2023-08-24T11:16:42.175821 | 2023-06-20T13:19:19 | 2023-06-20T13:19:19 | 32,322,244 | 1,290 | 223 | NOASSERTION | 2023-08-29T11:54:14 | 2015-03-16T12:05:57 | Scheme | UTF-8 | Scheme | false | false | 157 | sld | 95.sld |
(define-library (srfi 95)
(export sorted? merge merge! sort sort! object-cmp)
(import (chibi))
(include-shared "95/qsort")
(include "95/sort.scm"))
| false |
2918b81ae97fb609ef5e9711f369b0b6e1bd9556 | f08220a13ec5095557a3132d563a152e718c412f | /logrotate/skel/usr/share/guile/2.0/ice-9/boot-9.scm | 426d8310e5e6a432fa862c29a0a41d1c3c17764c | [
"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 | 153,682 | scm | boot-9.scm | ;;; -*- mode: scheme; coding: utf-8; -*-
;;;; Copyright (C) 1995-2014 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;; This file is the first thing loaded into Guile. It adds many mundane
;;; definitions and a few that are interesting.
;;;
;;; The module system (hence the hierarchical namespace) are defined in this
;;; file.
;;;
;;; Code:
;; Before compiling, make sure any symbols are resolved in the (guile)
;; module, the primary location of those symbols, rather than in
;; (guile-user), the default module that we compile in.
(eval-when (compile)
(set-current-module (resolve-module '(guile))))
;; Prevent this file being loaded more than once in a session. Just
;; doesn't make sense!
(if (current-module)
(error "re-loading ice-9/boot-9.scm not allowed"))
;;; {Error handling}
;;;
;; Define delimited continuation operators, and implement catch and throw in
;; terms of them.
(define make-prompt-tag
(lambda* (#:optional (stem "prompt"))
(gensym stem)))
(define default-prompt-tag
;; not sure if we should expose this to the user as a fluid
(let ((%default-prompt-tag (make-prompt-tag)))
(lambda ()
%default-prompt-tag)))
(define (call-with-prompt tag thunk handler)
(@prompt tag (thunk) handler))
(define (abort-to-prompt tag . args)
(@abort tag args))
;; Define catch and with-throw-handler, using some common helper routines and a
;; shared fluid. Hide the helpers in a lexical contour.
(define with-throw-handler #f)
(let ()
(define (default-exception-handler k . args)
(cond
((eq? k 'quit)
(primitive-exit (cond
((not (pair? args)) 0)
((integer? (car args)) (car args))
((not (car args)) 1)
(else 0))))
(else
(format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
(primitive-exit 1))))
(define %running-exception-handlers (make-fluid '()))
(define %exception-handler (make-fluid default-exception-handler))
(define (default-throw-handler prompt-tag catch-k)
(let ((prev (fluid-ref %exception-handler)))
(lambda (thrown-k . args)
(if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
(apply abort-to-prompt prompt-tag thrown-k args)
(apply prev thrown-k args)))))
(define (custom-throw-handler prompt-tag catch-k pre)
(let ((prev (fluid-ref %exception-handler)))
(lambda (thrown-k . args)
(if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
(let ((running (fluid-ref %running-exception-handlers)))
(with-fluids ((%running-exception-handlers (cons pre running)))
(if (not (memq pre running))
(apply pre thrown-k args))
;; fall through
(if prompt-tag
(apply abort-to-prompt prompt-tag thrown-k args)
(apply prev thrown-k args))))
(apply prev thrown-k args)))))
(set! catch
(lambda* (k thunk handler #:optional pre-unwind-handler)
"Invoke @var{thunk} in the dynamic context of @var{handler} for
exceptions matching @var{key}. If thunk throws to the symbol
@var{key}, then @var{handler} is invoked this way:
@lisp
(handler key args ...)
@end lisp
@var{key} is a symbol or @code{#t}.
@var{thunk} takes no arguments. If @var{thunk} returns
normally, that is the return value of @code{catch}.
Handler is invoked outside the scope of its own @code{catch}.
If @var{handler} again throws to the same key, a new handler
from further up the call chain is invoked.
If the key is @code{#t}, then a throw to @emph{any} symbol will
match this call to @code{catch}.
If a @var{pre-unwind-handler} is given and @var{thunk} throws
an exception that matches @var{key}, Guile calls the
@var{pre-unwind-handler} before unwinding the dynamic state and
invoking the main @var{handler}. @var{pre-unwind-handler} should
be a procedure with the same signature as @var{handler}, that
is @code{(lambda (key . args))}. It is typically used to save
the stack at the point where the exception occurred, but can also
query other parts of the dynamic state at that point, such as
fluid values.
A @var{pre-unwind-handler} can exit either normally or non-locally.
If it exits normally, Guile unwinds the stack and dynamic context
and then calls the normal (third argument) handler. If it exits
non-locally, that exit determines the continuation."
(if (not (or (symbol? k) (eqv? k #t)))
(scm-error 'wrong-type-arg "catch"
"Wrong type argument in position ~a: ~a"
(list 1 k) (list k)))
(let ((tag (make-prompt-tag "catch")))
(call-with-prompt
tag
(lambda ()
(with-fluids
((%exception-handler
(if pre-unwind-handler
(custom-throw-handler tag k pre-unwind-handler)
(default-throw-handler tag k))))
(thunk)))
(lambda (cont k . args)
(apply handler k args))))))
(set! with-throw-handler
(lambda (k thunk pre-unwind-handler)
"Add @var{handler} to the dynamic context as a throw handler
for key @var{k}, then invoke @var{thunk}."
(if (not (or (symbol? k) (eqv? k #t)))
(scm-error 'wrong-type-arg "with-throw-handler"
"Wrong type argument in position ~a: ~a"
(list 1 k) (list k)))
(with-fluids ((%exception-handler
(custom-throw-handler #f k pre-unwind-handler)))
(thunk))))
(set! throw
(lambda (key . args)
"Invoke the catch form matching @var{key}, passing @var{args} to the
@var{handler}.
@var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
If there is no handler at all, Guile prints an error and then exits."
(if (not (symbol? key))
((fluid-ref %exception-handler) 'wrong-type-arg "throw"
"Wrong type argument in position ~a: ~a" (list 1 key) (list key))
(apply (fluid-ref %exception-handler) key args)))))
;;; Boot versions of `map' and `for-each', enough to get the expander
;;; running, and get the "map" used in eval.scm for with-fluids to work.
;;;
(define map
(case-lambda
((f l)
(let map1 ((l l))
(if (null? l)
'()
(cons (f (car l)) (map1 (cdr l))))))
((f l1 l2)
(let map2 ((l1 l1) (l2 l2))
(if (null? l1)
'()
(cons (f (car l1) (car l2))
(map2 (cdr l1) (cdr l2))))))
((f l1 . rest)
(let lp ((l1 l1) (rest rest))
(if (null? l1)
'()
(cons (apply f (car l1) (map car rest))
(lp (cdr l1) (map cdr rest))))))))
(define for-each
(case-lambda
((f l)
(let for-each1 ((l l))
(if (pair? l)
(begin
(f (car l))
(for-each1 (cdr l))))))
((f l1 l2)
(let for-each2 ((l1 l1) (l2 l2))
(if (pair? l1)
(begin
(f (car l1) (car l2))
(for-each2 (cdr l1) (cdr l2))))))
((f l1 . rest)
(let lp ((l1 l1) (rest rest))
(if (pair? l1)
(begin
(apply f (car l1) (map car rest))
(lp (cdr l1) (map cdr rest))))))))
;;; {R4RS compliance}
;;;
(primitive-load-path "ice-9/r4rs")
;;; {Simple Debugging Tools}
;;;
;; peek takes any number of arguments, writes them to the
;; current ouput port, and returns the last argument.
;; It is handy to wrap around an expression to look at
;; a value each time is evaluated, e.g.:
;;
;; (+ 10 (troublesome-fn))
;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
;;
(define (peek . stuff)
(newline)
(display ";;; ")
(write stuff)
(newline)
(car (last-pair stuff)))
(define pk peek)
(define (warn . stuff)
(with-output-to-port (current-warning-port)
(lambda ()
(newline)
(display ";;; WARNING ")
(display stuff)
(newline)
(car (last-pair stuff)))))
;;; {Features}
;;;
(define (provide sym)
(if (not (memq sym *features*))
(set! *features* (cons sym *features*))))
;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
;; provided? also checks to see if the module is available. We should do that
;; too, but don't.
(define (provided? feature)
(and (memq feature *features*) #t))
;;; {Structs}
;;;
(define (make-struct/no-tail vtable . args)
(apply make-struct vtable 0 args))
;; Temporary definition used in the include-from-path expansion;
;; replaced later.
(define (absolute-file-name? file-name)
#t)
;;; {and-map and or-map}
;;;
;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
;;;
;; and-map f l
;;
;; Apply f to successive elements of l until exhaustion or f returns #f.
;; If returning early, return #f. Otherwise, return the last value returned
;; by f. If f has never been called because l is empty, return #t.
;;
(define (and-map f lst)
(let loop ((result #t)
(l lst))
(and result
(or (and (null? l)
result)
(loop (f (car l)) (cdr l))))))
;; or-map f l
;;
;; Apply f to successive elements of l until exhaustion or while f returns #f.
;; If returning early, return the return value of f.
;;
(define (or-map f lst)
(let loop ((result #f)
(l lst))
(or result
(and (not (null? l))
(loop (f (car l)) (cdr l))))))
;; let format alias simple-format until the more complete version is loaded
(define format simple-format)
;; this is scheme wrapping the C code so the final pred call is a tail call,
;; per SRFI-13 spec
(define string-any
(lambda* (char_pred s #:optional (start 0) (end (string-length s)))
(if (and (procedure? char_pred)
(> end start)
(<= end (string-length s))) ;; let c-code handle range error
(or (string-any-c-code char_pred s start (1- end))
(char_pred (string-ref s (1- end))))
(string-any-c-code char_pred s start end))))
;; this is scheme wrapping the C code so the final pred call is a tail call,
;; per SRFI-13 spec
(define string-every
(lambda* (char_pred s #:optional (start 0) (end (string-length s)))
(if (and (procedure? char_pred)
(> end start)
(<= end (string-length s))) ;; let c-code handle range error
(and (string-every-c-code char_pred s start (1- end))
(char_pred (string-ref s (1- end))))
(string-every-c-code char_pred s start end))))
;; A variant of string-fill! that we keep for compatability
;;
(define (substring-fill! str start end fill)
(string-fill! str fill start end))
;; Define a minimal stub of the module API for psyntax, before modules
;; have booted.
(define (module-name x)
'(guile))
(define (module-add! module sym var)
(hashq-set! (%get-pre-modules-obarray) sym var))
(define (module-define! module sym val)
(let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
(if v
(variable-set! v val)
(module-add! (current-module) sym (make-variable val)))))
(define (module-ref module sym)
(let ((v (module-variable module sym)))
(if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
(define (resolve-module . args)
#f)
;; API provided by psyntax
(define syntax-violation #f)
(define datum->syntax #f)
(define syntax->datum #f)
(define syntax-source #f)
(define identifier? #f)
(define generate-temporaries #f)
(define bound-identifier=? #f)
(define free-identifier=? #f)
;; $sc-dispatch is an implementation detail of psyntax. It is used by
;; expanded macros, to dispatch an input against a set of patterns.
(define $sc-dispatch #f)
;; Load it up!
(primitive-load-path "ice-9/psyntax-pp")
;; The binding for `macroexpand' has now been overridden, making psyntax the
;; expander now.
(define-syntax and
(syntax-rules ()
((_) #t)
((_ x) x)
;; Avoid ellipsis, which would lead to quadratic expansion time.
((_ x . y) (if x (and . y) #f))))
(define-syntax or
(syntax-rules ()
((_) #f)
((_ x) x)
;; Avoid ellipsis, which would lead to quadratic expansion time.
((_ x . y) (let ((t x)) (if t t (or . y))))))
(include-from-path "ice-9/quasisyntax")
(define-syntax-rule (when test stmt stmt* ...)
(if test (begin stmt stmt* ...)))
(define-syntax-rule (unless test stmt stmt* ...)
(if (not test) (begin stmt stmt* ...)))
(define-syntax cond
(lambda (whole-expr)
(define (fold f seed xs)
(let loop ((xs xs) (seed seed))
(if (null? xs) seed
(loop (cdr xs) (f (car xs) seed)))))
(define (reverse-map f xs)
(fold (lambda (x seed) (cons (f x) seed))
'() xs))
(syntax-case whole-expr ()
((_ clause clauses ...)
#`(begin
#,@(fold (lambda (clause-builder tail)
(clause-builder tail))
#'()
(reverse-map
(lambda (clause)
(define* (bad-clause #:optional (msg "invalid clause"))
(syntax-violation 'cond msg whole-expr clause))
(syntax-case clause (=> else)
((else e e* ...)
(lambda (tail)
(if (null? tail)
#'((begin e e* ...))
(bad-clause "else must be the last clause"))))
((else . _) (bad-clause))
((test => receiver)
(lambda (tail)
#`((let ((t test))
(if t
(receiver t)
#,@tail)))))
((test => receiver ...)
(bad-clause "wrong number of receiver expressions"))
((generator guard => receiver)
(lambda (tail)
#`((call-with-values (lambda () generator)
(lambda vals
(if (apply guard vals)
(apply receiver vals)
#,@tail))))))
((generator guard => receiver ...)
(bad-clause "wrong number of receiver expressions"))
((test)
(lambda (tail)
#`((let ((t test))
(if t t #,@tail)))))
((test e e* ...)
(lambda (tail)
#`((if test
(begin e e* ...)
#,@tail))))
(_ (bad-clause))))
#'(clause clauses ...))))))))
(define-syntax case
(lambda (whole-expr)
(define (fold f seed xs)
(let loop ((xs xs) (seed seed))
(if (null? xs) seed
(loop (cdr xs) (f (car xs) seed)))))
(define (fold2 f a b xs)
(let loop ((xs xs) (a a) (b b))
(if (null? xs) (values a b)
(call-with-values
(lambda () (f (car xs) a b))
(lambda (a b)
(loop (cdr xs) a b))))))
(define (reverse-map-with-seed f seed xs)
(fold2 (lambda (x ys seed)
(call-with-values
(lambda () (f x seed))
(lambda (y seed)
(values (cons y ys) seed))))
'() seed xs))
(syntax-case whole-expr ()
((_ expr clause clauses ...)
(with-syntax ((key #'key))
#`(let ((key expr))
#,@(fold
(lambda (clause-builder tail)
(clause-builder tail))
#'()
(reverse-map-with-seed
(lambda (clause seen)
(define* (bad-clause #:optional (msg "invalid clause"))
(syntax-violation 'case msg whole-expr clause))
(syntax-case clause ()
((test . rest)
(with-syntax
((clause-expr
(syntax-case #'rest (=>)
((=> receiver) #'(receiver key))
((=> receiver ...)
(bad-clause
"wrong number of receiver expressions"))
((e e* ...) #'(begin e e* ...))
(_ (bad-clause)))))
(syntax-case #'test (else)
((datums ...)
(let ((seen
(fold
(lambda (datum seen)
(define (warn-datum type)
((@ (system base message)
warning)
type
(append (source-properties datum)
(source-properties
(syntax->datum #'test)))
datum
(syntax->datum clause)
(syntax->datum whole-expr)))
(when (memv datum seen)
(warn-datum 'duplicate-case-datum))
(when (or (pair? datum) (array? datum))
(warn-datum 'bad-case-datum))
(cons datum seen))
seen
(map syntax->datum #'(datums ...)))))
(values (lambda (tail)
#`((if (memv key '(datums ...))
clause-expr
#,@tail)))
seen)))
(else (values (lambda (tail)
(if (null? tail)
#'(clause-expr)
(bad-clause
"else must be the last clause")))
seen))
(_ (bad-clause)))))
(_ (bad-clause))))
'() #'(clause clauses ...)))))))))
(define-syntax do
(syntax-rules ()
((do ((var init step ...) ...)
(test expr ...)
command ...)
(letrec
((loop
(lambda (var ...)
(if test
(begin
(if #f #f)
expr ...)
(begin
command
...
(loop (do "step" var step ...)
...))))))
(loop init ...)))
((do "step" x)
x)
((do "step" x y)
y)))
;; XXX FIXME: When 'call-with-values' is fixed to no longer do automatic
;; truncation of values (in 2.2 ?), then this hack can be removed.
(define (%define-values-arity-error)
(throw 'wrong-number-of-args
#f
"define-values: wrong number of return values returned by expression"
'()
#f))
(define-syntax define-values
(lambda (orig-form)
(syntax-case orig-form ()
((_ () expr)
;; XXX Work around the lack of hygienic top-level identifiers
(with-syntax (((dummy) (generate-temporaries '(dummy))))
#`(define dummy
(call-with-values (lambda () expr)
(case-lambda
(() #f)
(_ (%define-values-arity-error)))))))
((_ (var) expr)
(identifier? #'var)
#`(define var
(call-with-values (lambda () expr)
(case-lambda
((v) v)
(_ (%define-values-arity-error))))))
((_ (var0 ... varn) expr)
(and-map identifier? #'(var0 ... varn))
;; XXX Work around the lack of hygienic toplevel identifiers
(with-syntax (((dummy) (generate-temporaries '(dummy))))
#`(begin
;; Avoid mutating the user-visible variables
(define dummy
(call-with-values (lambda () expr)
(case-lambda
((var0 ... varn)
(list var0 ... varn))
(_ (%define-values-arity-error)))))
(define var0
(let ((v (car dummy)))
(set! dummy (cdr dummy))
v))
...
(define varn
(let ((v (car dummy)))
(set! dummy #f) ; blackhole dummy
v)))))
((_ var expr)
(identifier? #'var)
#'(define var
(call-with-values (lambda () expr)
list)))
((_ (var0 ... . varn) expr)
(and-map identifier? #'(var0 ... varn))
;; XXX Work around the lack of hygienic toplevel identifiers
(with-syntax (((dummy) (generate-temporaries '(dummy))))
#`(begin
;; Avoid mutating the user-visible variables
(define dummy
(call-with-values (lambda () expr)
(case-lambda
((var0 ... . varn)
(list var0 ... varn))
(_ (%define-values-arity-error)))))
(define var0
(let ((v (car dummy)))
(set! dummy (cdr dummy))
v))
...
(define varn
(let ((v (car dummy)))
(set! dummy #f) ; blackhole dummy
v))))))))
(define-syntax-rule (delay exp)
(make-promise (lambda () exp)))
(define-syntax current-source-location
(lambda (x)
(syntax-case x ()
((_)
(with-syntax ((s (datum->syntax x (syntax-source x))))
#''s)))))
;; We provide this accessor out of convenience. current-line and
;; current-column aren't so interesting, because they distort what they
;; are measuring; better to use syntax-source from a macro.
;;
(define-syntax current-filename
(lambda (x)
"A macro that expands to the current filename: the filename that
the (current-filename) form appears in. Expands to #f if this
information is unavailable."
(false-if-exception
(canonicalize-path (assq-ref (syntax-source x) 'filename)))))
(define-syntax-rule (define-once sym val)
(define sym
(if (module-locally-bound? (current-module) 'sym) sym val)))
;;; The real versions of `map' and `for-each', with cycle detection, and
;;; that use reverse! instead of recursion in the case of `map'.
;;;
(define map
(case-lambda
((f l)
(let map1 ((hare l) (tortoise l) (move? #f) (out '()))
(if (pair? hare)
(if move?
(if (eq? tortoise hare)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l) #f)
(map1 (cdr hare) (cdr tortoise) #f
(cons (f (car hare)) out)))
(map1 (cdr hare) tortoise #t
(cons (f (car hare)) out)))
(if (null? hare)
(reverse! out)
(scm-error 'wrong-type-arg "map" "Not a list: ~S"
(list l) #f)))))
((f l1 l2)
(let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
(cond
((pair? h1)
(cond
((not (pair? h2))
(scm-error 'wrong-type-arg "map"
(if (list? h2)
"List of wrong length: ~S"
"Not a list: ~S")
(list l2) #f))
((not move?)
(map2 (cdr h1) (cdr h2) t1 t2 #t
(cons (f (car h1) (car h2)) out)))
((eq? t1 h1)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l1) #f))
((eq? t2 h2)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l2) #f))
(else
(map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
(cons (f (car h1) (car h2)) out)))))
((and (null? h1) (null? h2))
(reverse! out))
((null? h1)
(scm-error 'wrong-type-arg "map"
(if (list? h2)
"List of wrong length: ~S"
"Not a list: ~S")
(list l2) #f))
(else
(scm-error 'wrong-type-arg "map"
"Not a list: ~S"
(list l1) #f)))))
((f l1 . rest)
(let ((len (length l1)))
(let mapn ((rest rest))
(or (null? rest)
(if (= (length (car rest)) len)
(mapn (cdr rest))
(scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
(list (car rest)) #f)))))
(let mapn ((l1 l1) (rest rest) (out '()))
(if (null? l1)
(reverse! out)
(mapn (cdr l1) (map cdr rest)
(cons (apply f (car l1) (map car rest)) out)))))))
(define map-in-order map)
(define for-each
(case-lambda
((f l)
(let for-each1 ((hare l) (tortoise l))
(if (pair? hare)
(begin
(f (car hare))
(let ((hare (cdr hare)))
(if (pair? hare)
(begin
(when (eq? tortoise hare)
(scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
(list l) #f))
(f (car hare))
(for-each1 (cdr hare) (cdr tortoise))))))
(if (not (null? hare))
(scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
(list l) #f)))))
((f l1 l2)
(let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
(cond
((and (pair? h1) (pair? h2))
(cond
((not move?)
(f (car h1) (car h2))
(for-each2 (cdr h1) (cdr h2) t1 t2 #t))
((eq? t1 h1)
(scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
(list l1) #f))
((eq? t2 h2)
(scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
(list l2) #f))
(else
(f (car h1) (car h2))
(for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
((if (null? h1)
(or (null? h2) (pair? h2))
(and (pair? h1) (null? h2)))
(if #f #f))
((list? h1)
(scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
(list h2) #f))
(else
(scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
(list h1) #f)))))
((f l1 . rest)
(let ((len (length l1)))
(let for-eachn ((rest rest))
(or (null? rest)
(if (= (length (car rest)) len)
(for-eachn (cdr rest))
(scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
(list (car rest)) #f)))))
(let for-eachn ((l1 l1) (rest rest))
(if (pair? l1)
(begin
(apply f (car l1) (map car rest))
(for-eachn (cdr l1) (map cdr rest))))))))
;;;
;;; Enhanced file opening procedures
;;;
(define* (open-input-file
file #:key (binary #f) (encoding #f) (guess-encoding #f))
"Takes a string naming an existing file and returns an input port
capable of delivering characters from the file. If the file
cannot be opened, an error is signalled."
(open-file file (if binary "rb" "r")
#:encoding encoding
#:guess-encoding guess-encoding))
(define* (open-output-file file #:key (binary #f) (encoding #f))
"Takes a string naming an output file to be created and returns an
output port capable of writing characters to a new file by that
name. If the file cannot be opened, an error is signalled. If a
file with the given name already exists, the effect is unspecified."
(open-file file (if binary "wb" "w")
#:encoding encoding))
(define* (call-with-input-file
file proc #:key (binary #f) (encoding #f) (guess-encoding #f))
"PROC should be a procedure of one argument, and FILE should be a
string naming a file. The file must
already exist. These procedures call PROC
with one argument: the port obtained by opening the named file for
input or output. If the file cannot be opened, an error is
signalled. If the procedure returns, then the port is closed
automatically and the values yielded by the procedure are returned.
If the procedure does not return, then the port will not be closed
automatically unless it is possible to prove that the port will
never again be used for a read or write operation."
(let ((p (open-input-file file
#:binary binary
#:encoding encoding
#:guess-encoding guess-encoding)))
(call-with-values
(lambda () (proc p))
(lambda vals
(close-input-port p)
(apply values vals)))))
(define* (call-with-output-file file proc #:key (binary #f) (encoding #f))
"PROC should be a procedure of one argument, and FILE should be a
string naming a file. The behaviour is unspecified if the file
already exists. These procedures call PROC
with one argument: the port obtained by opening the named file for
input or output. If the file cannot be opened, an error is
signalled. If the procedure returns, then the port is closed
automatically and the values yielded by the procedure are returned.
If the procedure does not return, then the port will not be closed
automatically unless it is possible to prove that the port will
never again be used for a read or write operation."
(let ((p (open-output-file file #:binary binary #:encoding encoding)))
(call-with-values
(lambda () (proc p))
(lambda vals
(close-output-port p)
(apply values vals)))))
(define* (with-input-from-file
file thunk #:key (binary #f) (encoding #f) (guess-encoding #f))
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The file must already exist. The file is opened for
input, an input port connected to it is made
the default value returned by `current-input-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-input-file file
(lambda (p) (with-input-from-port p thunk))
#:binary binary
#:encoding encoding
#:guess-encoding guess-encoding))
(define* (with-output-to-file file thunk #:key (binary #f) (encoding #f))
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The effect is unspecified if the file already exists.
The file is opened for output, an output port connected to it is made
the default value returned by `current-output-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-output-file file
(lambda (p) (with-output-to-port p thunk))
#:binary binary
#:encoding encoding))
(define* (with-error-to-file file thunk #:key (binary #f) (encoding #f))
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The effect is unspecified if the file already exists.
The file is opened for output, an output port connected to it is made
the default value returned by `current-error-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-output-file file
(lambda (p) (with-error-to-port p thunk))
#:binary binary
#:encoding encoding))
;;;
;;; Extensible exception printing.
;;;
(define set-exception-printer! #f)
;; There is already a definition of print-exception from backtrace.c
;; that we will override.
(let ((exception-printers '()))
(define (print-location frame port)
(let ((source (and=> frame frame-source)))
;; source := (addr . (filename . (line . column)))
(if source
(let ((filename (or (cadr source) "<unnamed port>"))
(line (caddr source))
(col (cdddr source)))
(format port "~a:~a:~a: " filename (1+ line) col))
(format port "ERROR: "))))
(set! set-exception-printer!
(lambda (key proc)
(set! exception-printers (acons key proc exception-printers))))
(set! print-exception
(lambda (port frame key args)
(define (default-printer)
(format port "Throw to key `~a' with args `~s'." key args))
(if frame
(let ((proc (frame-procedure frame)))
(print-location frame port)
(format port "In procedure ~a:\n"
(or (false-if-exception (procedure-name proc))
proc))))
(print-location frame port)
(catch #t
(lambda ()
(let ((printer (assq-ref exception-printers key)))
(if printer
(printer port key args default-printer)
(default-printer))))
(lambda (k . args)
(format port "Error while printing exception.")))
(newline port)
(force-output port))))
;;;
;;; Printers for those keys thrown by Guile.
;;;
(let ()
(define (scm-error-printer port key args default-printer)
;; Abuse case-lambda as a pattern matcher, given that we don't have
;; ice-9 match at this point.
(apply (case-lambda
((subr msg args . rest)
(if subr
(format port "In procedure ~a: " subr))
(apply format port msg (or args '())))
(_ (default-printer)))
args))
(define (syntax-error-printer port key args default-printer)
(apply (case-lambda
((who what where form subform . extra)
(format port "Syntax error:\n")
(if where
(let ((file (or (assq-ref where 'filename) "unknown file"))
(line (and=> (assq-ref where 'line) 1+))
(col (assq-ref where 'column)))
(format port "~a:~a:~a: " file line col))
(format port "unknown location: "))
(if who
(format port "~a: " who))
(format port "~a" what)
(if subform
(format port " in subform ~s of ~s" subform form)
(if form
(format port " in form ~s" form))))
(_ (default-printer)))
args))
(define (keyword-error-printer port key args default-printer)
(let ((message (cadr args))
(faulty (car (cadddr args)))) ; I won't do it again, I promise.
(format port "~a: ~s" message faulty)))
(define (getaddrinfo-error-printer port key args default-printer)
(format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
(set-exception-printer! 'goops-error scm-error-printer)
(set-exception-printer! 'host-not-found scm-error-printer)
(set-exception-printer! 'keyword-argument-error keyword-error-printer)
(set-exception-printer! 'misc-error scm-error-printer)
(set-exception-printer! 'no-data scm-error-printer)
(set-exception-printer! 'no-recovery scm-error-printer)
(set-exception-printer! 'null-pointer-error scm-error-printer)
(set-exception-printer! 'out-of-range scm-error-printer)
(set-exception-printer! 'program-error scm-error-printer)
(set-exception-printer! 'read-error scm-error-printer)
(set-exception-printer! 'regular-expression-syntax scm-error-printer)
(set-exception-printer! 'signal scm-error-printer)
(set-exception-printer! 'stack-overflow scm-error-printer)
(set-exception-printer! 'system-error scm-error-printer)
(set-exception-printer! 'try-again scm-error-printer)
(set-exception-printer! 'unbound-variable scm-error-printer)
(set-exception-printer! 'wrong-number-of-args scm-error-printer)
(set-exception-printer! 'wrong-type-arg scm-error-printer)
(set-exception-printer! 'syntax-error syntax-error-printer)
(set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
;;; {Defmacros}
;;;
(define-syntax define-macro
(lambda (x)
"Define a defmacro."
(syntax-case x ()
((_ (macro . args) doc body1 body ...)
(string? (syntax->datum #'doc))
#'(define-macro macro doc (lambda args body1 body ...)))
((_ (macro . args) body ...)
#'(define-macro macro #f (lambda args body ...)))
((_ macro transformer)
#'(define-macro macro #f transformer))
((_ macro doc transformer)
(or (string? (syntax->datum #'doc))
(not (syntax->datum #'doc)))
#'(define-syntax macro
(lambda (y)
doc
#((macro-type . defmacro)
(defmacro-args args))
(syntax-case y ()
((_ . args)
(let ((v (syntax->datum #'args)))
(datum->syntax y (apply transformer v)))))))))))
(define-syntax defmacro
(lambda (x)
"Define a defmacro, with the old lispy defun syntax."
(syntax-case x ()
((_ macro args doc body1 body ...)
(string? (syntax->datum #'doc))
#'(define-macro macro doc (lambda args body1 body ...)))
((_ macro args body ...)
#'(define-macro macro #f (lambda args body ...))))))
(provide 'defmacro)
;;; {Deprecation}
;;;
(define-syntax begin-deprecated
(lambda (x)
(syntax-case x ()
((_ form form* ...)
(if (include-deprecated-features)
#'(begin form form* ...)
#'(begin))))))
;;; {Trivial Functions}
;;;
(define (identity x) x)
(define (compose proc . rest)
"Compose PROC with the procedures in REST, such that the last one in
REST is applied first and PROC last, and return the resulting procedure.
The given procedures must have compatible arity."
(if (null? rest)
proc
(let ((g (apply compose rest)))
(lambda args
(call-with-values (lambda () (apply g args)) proc)))))
(define (negate proc)
"Return a procedure with the same arity as PROC that returns the `not'
of PROC's result."
(lambda args
(not (apply proc args))))
(define (const value)
"Return a procedure that accepts any number of arguments and returns
VALUE."
(lambda _
value))
(define (and=> value procedure)
"When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
(and value (procedure value)))
(define call/cc call-with-current-continuation)
(define-syntax false-if-exception
(syntax-rules ()
((false-if-exception expr)
(catch #t
(lambda () expr)
(lambda args #f)))
((false-if-exception expr #:warning template arg ...)
(catch #t
(lambda () expr)
(lambda (key . args)
(for-each (lambda (s)
(if (not (string-null? s))
(format (current-warning-port) ";;; ~a\n" s)))
(string-split
(call-with-output-string
(lambda (port)
(format port template arg ...)
(print-exception port #f key args)))
#\newline))
#f)))))
;;; {General Properties}
;;;
;; Properties are a lispy way to associate random info with random objects.
;; Traditionally properties are implemented as an alist or a plist actually
;; pertaining to the object in question.
;;
;; These "object properties" have the advantage that they can be associated with
;; any object, even if the object has no plist. Object properties are good when
;; you are extending pre-existing objects in unexpected ways. They also present
;; a pleasing, uniform procedure-with-setter interface. But if you have a data
;; type that always has properties, it's often still best to store those
;; properties within the object itself.
(define (make-object-property)
(define-syntax-rule (with-mutex lock exp)
(dynamic-wind (lambda () (lock-mutex lock))
(lambda () exp)
(lambda () (unlock-mutex lock))))
(let ((prop (make-weak-key-hash-table))
(lock (make-mutex)))
(make-procedure-with-setter
(lambda (obj) (with-mutex lock (hashq-ref prop obj)))
(lambda (obj val) (with-mutex lock (hashq-set! prop obj val))))))
;;; {Symbol Properties}
;;;
;;; Symbol properties are something you see in old Lisp code. In most current
;;; Guile code, symbols are not used as a data structure -- they are used as
;;; keys into other data structures.
(define (symbol-property sym prop)
(let ((pair (assoc prop (symbol-pref sym))))
(and pair (cdr pair))))
(define (set-symbol-property! sym prop val)
(let ((pair (assoc prop (symbol-pref sym))))
(if pair
(set-cdr! pair val)
(symbol-pset! sym (acons prop val (symbol-pref sym))))))
(define (symbol-property-remove! sym prop)
(let ((pair (assoc prop (symbol-pref sym))))
(if pair
(symbol-pset! sym (delq! pair (symbol-pref sym))))))
;;; {Arrays}
;;;
(define (array-shape a)
(map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
(array-dimensions a)))
;;; {Keywords}
;;;
;;; It's much better if you can use lambda* / define*, of course.
(define (kw-arg-ref args kw)
(let ((rem (member kw args)))
(and rem (pair? (cdr rem)) (cadr rem))))
;;; {Structs}
;;;
(define (struct-layout s)
(struct-ref (struct-vtable s) vtable-index-layout))
;;; {Records}
;;;
;; Printing records: by default, records are printed as
;;
;; #<type-name field1: val1 field2: val2 ...>
;;
;; You can change that by giving a custom printing function to
;; MAKE-RECORD-TYPE (after the list of field symbols). This function
;; will be called like
;;
;; (<printer> object port)
;;
;; It should print OBJECT to PORT.
(define (inherit-print-state old-port new-port)
(if (get-print-state old-port)
(port-with-print-state new-port (get-print-state old-port))
new-port))
;; 0: type-name, 1: fields, 2: constructor
(define record-type-vtable
(let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
(lambda (s p)
(display "#<record-type " p)
(display (record-type-name s) p)
(display ">" p)))))
(set-struct-vtable-name! s 'record-type)
s))
(define (record-type? obj)
(and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
(define* (make-record-type type-name fields #:optional printer)
;; Pre-generate constructors for nfields < 20.
(define-syntax make-constructor
(lambda (x)
(define *max-static-argument-count* 20)
(define (make-formals n)
(let lp ((i 0))
(if (< i n)
(cons (datum->syntax
x
(string->symbol
(string (integer->char (+ (char->integer #\a) i)))))
(lp (1+ i)))
'())))
(syntax-case x ()
((_ rtd exp) (not (identifier? #'exp))
#'(let ((n exp))
(make-constructor rtd n)))
((_ rtd nfields)
#`(case nfields
#,@(let lp ((n 0))
(if (< n *max-static-argument-count*)
(cons (with-syntax (((formal ...) (make-formals n))
(n n))
#'((n)
(lambda (formal ...)
(make-struct rtd 0 formal ...))))
(lp (1+ n)))
'()))
(else
(lambda args
(if (= (length args) nfields)
(apply make-struct rtd 0 args)
(scm-error 'wrong-number-of-args
(format #f "make-~a" type-name)
"Wrong number of arguments" '() #f)))))))))
(define (default-record-printer s p)
(display "#<" p)
(display (record-type-name (record-type-descriptor s)) p)
(let loop ((fields (record-type-fields (record-type-descriptor s)))
(off 0))
(cond
((not (null? fields))
(display " " p)
(display (car fields) p)
(display ": " p)
(display (struct-ref s off) p)
(loop (cdr fields) (+ 1 off)))))
(display ">" p))
(let ((rtd (make-struct record-type-vtable 0
(make-struct-layout
(apply string-append
(map (lambda (f) "pw") fields)))
(or printer default-record-printer)
type-name
(copy-tree fields))))
(struct-set! rtd (+ vtable-offset-user 2)
(make-constructor rtd (length fields)))
;; Temporary solution: Associate a name to the record type descriptor
;; so that the object system can create a wrapper class for it.
(set-struct-vtable-name! rtd (if (symbol? type-name)
type-name
(string->symbol type-name)))
rtd))
(define (record-type-name obj)
(if (record-type? obj)
(struct-ref obj vtable-offset-user)
(error 'not-a-record-type obj)))
(define (record-type-fields obj)
(if (record-type? obj)
(struct-ref obj (+ 1 vtable-offset-user))
(error 'not-a-record-type obj)))
(define* (record-constructor rtd #:optional field-names)
(if (not field-names)
(struct-ref rtd (+ 2 vtable-offset-user))
(primitive-eval
`(lambda ,field-names
(make-struct ',rtd 0 ,@(map (lambda (f)
(if (memq f field-names)
f
#f))
(record-type-fields rtd)))))))
(define (record-predicate rtd)
(lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
(define (%record-type-error rtd obj) ;; private helper
(or (eq? rtd (record-type-descriptor obj))
(scm-error 'wrong-type-arg "%record-type-check"
"Wrong type record (want `~S'): ~S"
(list (record-type-name rtd) obj)
#f)))
(define (record-accessor rtd field-name)
(let ((pos (list-index (record-type-fields rtd) field-name)))
(if (not pos)
(error 'no-such-field field-name))
(lambda (obj)
(if (eq? (struct-vtable obj) rtd)
(struct-ref obj pos)
(%record-type-error rtd obj)))))
(define (record-modifier rtd field-name)
(let ((pos (list-index (record-type-fields rtd) field-name)))
(if (not pos)
(error 'no-such-field field-name))
(lambda (obj val)
(if (eq? (struct-vtable obj) rtd)
(struct-set! obj pos val)
(%record-type-error rtd obj)))))
(define (record? obj)
(and (struct? obj) (record-type? (struct-vtable obj))))
(define (record-type-descriptor obj)
(if (struct? obj)
(struct-vtable obj)
(error 'not-a-record obj)))
(provide 'record)
;;; {Booleans}
;;;
(define (->bool x) (not (not x)))
;;; {Symbols}
;;;
(define (symbol-append . args)
(string->symbol (apply string-append (map symbol->string args))))
(define (list->symbol . args)
(string->symbol (apply list->string args)))
(define (symbol . args)
(string->symbol (apply string args)))
;;; {Lists}
;;;
(define (list-index l k)
(let loop ((n 0)
(l l))
(and (not (null? l))
(if (eq? (car l) k)
n
(loop (+ n 1) (cdr l))))))
;; Load `posix.scm' even when not (provided? 'posix) so that we get the
;; `stat' accessors.
(primitive-load-path "ice-9/posix")
(if (provided? 'socket)
(primitive-load-path "ice-9/networking"))
;; For reference, Emacs file-exists-p uses stat in this same way.
(define file-exists?
(if (provided? 'posix)
(lambda (str)
(->bool (stat str #f)))
(lambda (str)
(let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
(lambda args #f))))
(if port (begin (close-port port) #t)
#f)))))
(define file-is-directory?
(if (provided? 'posix)
(lambda (str)
(eq? (stat:type (stat str)) 'directory))
(lambda (str)
(let ((port (catch 'system-error
(lambda () (open-file (string-append str "/.")
OPEN_READ))
(lambda args #f))))
(if port (begin (close-port port) #t)
#f)))))
(define (system-error-errno args)
(if (eq? (car args) 'system-error)
(car (list-ref args 4))
#f))
;;; {Error Handling}
;;;
(define error
(case-lambda
(()
(scm-error 'misc-error #f "?" #f #f))
((message . args)
(let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
(scm-error 'misc-error #f msg (cons message args) #f)))))
;;; {Time Structures}
;;;
(define (tm:sec obj) (vector-ref obj 0))
(define (tm:min obj) (vector-ref obj 1))
(define (tm:hour obj) (vector-ref obj 2))
(define (tm:mday obj) (vector-ref obj 3))
(define (tm:mon obj) (vector-ref obj 4))
(define (tm:year obj) (vector-ref obj 5))
(define (tm:wday obj) (vector-ref obj 6))
(define (tm:yday obj) (vector-ref obj 7))
(define (tm:isdst obj) (vector-ref obj 8))
(define (tm:gmtoff obj) (vector-ref obj 9))
(define (tm:zone obj) (vector-ref obj 10))
(define (set-tm:sec obj val) (vector-set! obj 0 val))
(define (set-tm:min obj val) (vector-set! obj 1 val))
(define (set-tm:hour obj val) (vector-set! obj 2 val))
(define (set-tm:mday obj val) (vector-set! obj 3 val))
(define (set-tm:mon obj val) (vector-set! obj 4 val))
(define (set-tm:year obj val) (vector-set! obj 5 val))
(define (set-tm:wday obj val) (vector-set! obj 6 val))
(define (set-tm:yday obj val) (vector-set! obj 7 val))
(define (set-tm:isdst obj val) (vector-set! obj 8 val))
(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
(define (set-tm:zone obj val) (vector-set! obj 10 val))
(define (tms:clock obj) (vector-ref obj 0))
(define (tms:utime obj) (vector-ref obj 1))
(define (tms:stime obj) (vector-ref obj 2))
(define (tms:cutime obj) (vector-ref obj 3))
(define (tms:cstime obj) (vector-ref obj 4))
;;; {File Descriptors and Ports}
;;;
(define file-position ftell)
(define* (file-set-position port offset #:optional (whence SEEK_SET))
(seek port offset whence))
(define (move->fdes fd/port fd)
(cond ((integer? fd/port)
(dup->fdes fd/port fd)
(close fd/port)
fd)
(else
(primitive-move->fdes fd/port fd)
(set-port-revealed! fd/port 1)
fd/port)))
(define (release-port-handle port)
(let ((revealed (port-revealed port)))
(if (> revealed 0)
(set-port-revealed! port (- revealed 1)))))
(define dup->port
(case-lambda
((port/fd mode)
(fdopen (dup->fdes port/fd) mode))
((port/fd mode new-fd)
(let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
(set-port-revealed! port 1)
port))))
(define dup->inport
(case-lambda
((port/fd)
(dup->port port/fd "r"))
((port/fd new-fd)
(dup->port port/fd "r" new-fd))))
(define dup->outport
(case-lambda
((port/fd)
(dup->port port/fd "w"))
((port/fd new-fd)
(dup->port port/fd "w" new-fd))))
(define dup
(case-lambda
((port/fd)
(if (integer? port/fd)
(dup->fdes port/fd)
(dup->port port/fd (port-mode port/fd))))
((port/fd new-fd)
(if (integer? port/fd)
(dup->fdes port/fd new-fd)
(dup->port port/fd (port-mode port/fd) new-fd)))))
(define (duplicate-port port modes)
(dup->port port modes))
(define (fdes->inport fdes)
(let loop ((rest-ports (fdes->ports fdes)))
(cond ((null? rest-ports)
(let ((result (fdopen fdes "r")))
(set-port-revealed! result 1)
result))
((input-port? (car rest-ports))
(set-port-revealed! (car rest-ports)
(+ (port-revealed (car rest-ports)) 1))
(car rest-ports))
(else
(loop (cdr rest-ports))))))
(define (fdes->outport fdes)
(let loop ((rest-ports (fdes->ports fdes)))
(cond ((null? rest-ports)
(let ((result (fdopen fdes "w")))
(set-port-revealed! result 1)
result))
((output-port? (car rest-ports))
(set-port-revealed! (car rest-ports)
(+ (port-revealed (car rest-ports)) 1))
(car rest-ports))
(else
(loop (cdr rest-ports))))))
(define (port->fdes port)
(set-port-revealed! port (+ (port-revealed port) 1))
(fileno port))
(define (setenv name value)
(if value
(putenv (string-append name "=" value))
(putenv name)))
(define (unsetenv name)
"Remove the entry for NAME from the environment."
(putenv name))
;;; {Load Paths}
;;;
(let-syntax ((compile-time-case
(lambda (stx)
(syntax-case stx ()
((_ exp clauses ...)
(let ((val (primitive-eval (syntax->datum #'exp))))
(let next-clause ((clauses #'(clauses ...)))
(syntax-case clauses (else)
(()
(syntax-violation 'compile-time-case
"all clauses failed to match" stx))
(((else form ...))
#'(begin form ...))
((((k ...) form ...) clauses ...)
(if (memv val (syntax->datum #'(k ...)))
#'(begin form ...)
(next-clause #'(clauses ...))))))))))))
;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
(compile-time-case (system-file-name-convention)
((posix)
(define (file-name-separator? c)
(char=? c #\/))
(define file-name-separator-string "/")
(define (absolute-file-name? file-name)
(string-prefix? "/" file-name)))
((windows)
(define (file-name-separator? c)
(or (char=? c #\/)
(char=? c #\\)))
(define file-name-separator-string "/")
(define (absolute-file-name? file-name)
(define (file-name-separator-at-index? idx)
(and (> (string-length file-name) idx)
(file-name-separator? (string-ref file-name idx))))
(define (unc-file-name?)
;; Universal Naming Convention (UNC) file-names start with \\,
;; and are always absolute. See:
;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
(and (file-name-separator-at-index? 0)
(file-name-separator-at-index? 1)))
(define (has-drive-specifier?)
(and (>= (string-length file-name) 2)
(let ((drive (string-ref file-name 0)))
(or (char<=? #\a drive #\z)
(char<=? #\A drive #\Z)))
(eqv? (string-ref file-name 1) #\:)))
(or (unc-file-name?)
(if (has-drive-specifier?)
(file-name-separator-at-index? 2)
(file-name-separator-at-index? 0)))))))
(define (in-vicinity vicinity file)
(let ((tail (let ((len (string-length vicinity)))
(if (zero? len)
#f
(string-ref vicinity (- len 1))))))
(string-append vicinity
(if (or (not tail) (file-name-separator? tail))
""
file-name-separator-string)
file)))
;;; {Help for scm_shell}
;;;
;;; The argument-processing code used by Guile-based shells generates
;;; Scheme code based on the argument list. This page contains help
;;; functions for the code it generates.
;;;
(define (command-line) (program-arguments))
;; This is mostly for the internal use of the code generated by
;; scm_compile_shell_switches.
(define (load-user-init)
(let* ((home (or (getenv "HOME")
(false-if-exception (passwd:dir (getpwuid (getuid))))
file-name-separator-string)) ;; fallback for cygwin etc.
(init-file (in-vicinity home ".guile")))
(if (file-exists? init-file)
(primitive-load init-file))))
;;; {The interpreter stack}
;;;
;; %stacks defined in stacks.c
(define (%start-stack tag thunk)
(let ((prompt-tag (make-prompt-tag "start-stack")))
(call-with-prompt
prompt-tag
(lambda ()
(with-fluids ((%stacks (acons tag prompt-tag
(or (fluid-ref %stacks) '()))))
(thunk)))
(lambda (k . args)
(%start-stack tag (lambda () (apply k args)))))))
(define-syntax-rule (start-stack tag exp)
(%start-stack tag (lambda () exp)))
;;; {Loading by paths}
;;;
;;; Load a Scheme source file named NAME, searching for it in the
;;; directories listed in %load-path, and applying each of the file
;;; name extensions listed in %load-extensions.
(define (load-from-path name)
(start-stack 'load-stack
(primitive-load-path name)))
(define-syntax-rule (add-to-load-path elt)
"Add ELT to Guile's load path, at compile-time and at run-time."
(eval-when (expand load eval)
(set! %load-path (cons elt (delete elt %load-path)))))
(define %load-verbosely #f)
(define (assert-load-verbosity v) (set! %load-verbosely v))
(define (%load-announce file)
(if %load-verbosely
(with-output-to-port (current-warning-port)
(lambda ()
(display ";;; ")
(display "loading ")
(display file)
(newline)
(force-output)))))
(set! %load-hook %load-announce)
;;; {Reader Extensions}
;;;
;;; Reader code for various "#c" forms.
;;;
(define read-eval? (make-fluid #f))
(read-hash-extend #\.
(lambda (c port)
(if (fluid-ref read-eval?)
(eval (read port) (interaction-environment))
(error
"#. read expansion found and read-eval? is #f."))))
;;; {Low Level Modules}
;;;
;;; These are the low level data structures for modules.
;;;
;;; Every module object is of the type 'module-type', which is a record
;;; consisting of the following members:
;;;
;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
;;;
;;; - obarray: a hash table that maps symbols to variable objects. In this
;;; hash table, the definitions are found that are local to the module (that
;;; is, not imported from other modules). When looking up bindings in the
;;; module, this hash table is searched first.
;;;
;;; - binder: either #f or a function taking a module and a symbol argument.
;;; If it is a function it is called after the obarray has been
;;; unsuccessfully searched for a binding. It then can provide bindings
;;; that would otherwise not be found locally in the module.
;;;
;;; - uses: a list of modules from which non-local bindings can be inherited.
;;; These modules are the third place queried for bindings after the obarray
;;; has been unsuccessfully searched and the binder function did not deliver
;;; a result either.
;;;
;;; - transformer: either #f or a function taking a scheme expression as
;;; delivered by read. If it is a function, it will be called to perform
;;; syntax transformations (e. g. makro expansion) on the given scheme
;;; expression. The output of the transformer function will then be passed
;;; to Guile's internal memoizer. This means that the output must be valid
;;; scheme code. The only exception is, that the output may make use of the
;;; syntax extensions provided to identify the modules that a binding
;;; belongs to.
;;;
;;; - name: the name of the module. This is used for all kinds of printing
;;; outputs. In certain places the module name also serves as a way of
;;; identification. When adding a module to the uses list of another
;;; module, it is made sure that the new uses list will not contain two
;;; modules of the same name.
;;;
;;; - kind: classification of the kind of module. The value is (currently?)
;;; only used for printing. It has no influence on how a module is treated.
;;; Currently the following values are used when setting the module kind:
;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
;;; is set, it defaults to 'module.
;;;
;;; - duplicates-handlers: a list of procedures that get called to make a
;;; choice between two duplicate bindings when name clashes occur. See the
;;; `duplicate-handlers' global variable below.
;;;
;;; - observers: a list of procedures that get called when the module is
;;; modified.
;;;
;;; - weak-observers: a weak-key hash table of procedures that get called
;;; when the module is modified. See `module-observe-weak' for details.
;;;
;;; In addition, the module may (must?) contain a binding for
;;; `%module-public-interface'. This variable should be bound to a module
;;; representing the exported interface of a module. See the
;;; `module-public-interface' and `module-export!' procedures.
;;;
;;; !!! warning: The interface to lazy binder procedures is going
;;; to be changed in an incompatible way to permit all the basic
;;; module ops to be virtualized.
;;;
;;; (make-module size use-list lazy-binding-proc) => module
;;; module-{obarray,uses,binder}[|-set!]
;;; (module? obj) => [#t|#f]
;;; (module-locally-bound? module symbol) => [#t|#f]
;;; (module-bound? module symbol) => [#t|#f]
;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
;;; (module-symbol-interned? module symbol) => [#t|#f]
;;; (module-local-variable module symbol) => [#<variable ...> | #f]
;;; (module-variable module symbol) => [#<variable ...> | #f]
;;; (module-symbol-binding module symbol opt-value)
;;; => [ <obj> | opt-value | an error occurs ]
;;; (module-make-local-var! module symbol) => #<variable...>
;;; (module-add! module symbol var) => unspecified
;;; (module-remove! module symbol) => unspecified
;;; (module-for-each proc module) => unspecified
;;; (make-scm-module) => module ; a lazy copy of the symhash module
;;; (set-current-module module) => unspecified
;;; (current-module) => #<module...>
;;;
;;;
;;; {Printing Modules}
;;;
;; This is how modules are printed. You can re-define it.
(define (%print-module mod port)
(display "#<" port)
(display (or (module-kind mod) "module") port)
(display " " port)
(display (module-name mod) port)
(display " " port)
(display (number->string (object-address mod) 16) port)
(display ">" port))
(letrec-syntax
;; Locally extend the syntax to allow record accessors to be defined at
;; compile-time. Cache the rtd locally to the constructor, the getters and
;; the setters, in order to allow for redefinition of the record type; not
;; relevant in the case of modules, but perhaps if we make this public, it
;; could matter.
((define-record-type
(lambda (x)
(define (make-id scope . fragments)
(datum->syntax #'scope
(apply symbol-append
(map (lambda (x)
(if (symbol? x) x (syntax->datum x)))
fragments))))
(define (getter rtd type-name field slot)
#`(define #,(make-id rtd type-name '- field)
(let ((rtd #,rtd))
(lambda (#,type-name)
(if (eq? (struct-vtable #,type-name) rtd)
(struct-ref #,type-name #,slot)
(%record-type-error rtd #,type-name))))))
(define (setter rtd type-name field slot)
#`(define #,(make-id rtd 'set- type-name '- field '!)
(let ((rtd #,rtd))
(lambda (#,type-name val)
(if (eq? (struct-vtable #,type-name) rtd)
(struct-set! #,type-name #,slot val)
(%record-type-error rtd #,type-name))))))
(define (accessors rtd type-name fields n exp)
(syntax-case fields ()
(() exp)
(((field #:no-accessors) field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
exp))
(((field #:no-setter) field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
#`(begin #,exp
#,(getter rtd type-name #'field n))))
(((field #:no-getter) field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
#`(begin #,exp
#,(setter rtd type-name #'field n))))
((field field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
#`(begin #,exp
#,(getter rtd type-name #'field n)
#,(setter rtd type-name #'field n))))))
(define (predicate rtd type-name fields exp)
(accessors
rtd type-name fields 0
#`(begin
#,exp
(define (#,(make-id rtd type-name '?) obj)
(and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
(define (field-list fields)
(syntax-case fields ()
(() '())
(((f . opts) . rest) (identifier? #'f)
(cons #'f (field-list #'rest)))
((f . rest) (identifier? #'f)
(cons #'f (field-list #'rest)))))
(define (constructor rtd type-name fields exp)
(let ((ctor (make-id rtd type-name '-constructor))
(args (field-list fields)))
(predicate rtd type-name fields
#`(begin #,exp
(define #,ctor
(let ((rtd #,rtd))
(lambda #,args
(make-struct rtd 0 #,@args))))
(struct-set! #,rtd (+ vtable-offset-user 2)
#,ctor)))))
(define (type type-name printer fields)
(define (make-layout)
(let lp ((fields fields) (slots '()))
(syntax-case fields ()
(() (datum->syntax #'here
(make-struct-layout
(apply string-append slots))))
((_ . rest) (lp #'rest (cons "pw" slots))))))
(let ((rtd (make-id type-name type-name '-type)))
(constructor rtd type-name fields
#`(begin
(define #,rtd
(make-struct record-type-vtable 0
'#,(make-layout)
#,printer
'#,type-name
'#,(field-list fields)))
(set-struct-vtable-name! #,rtd '#,type-name)))))
(syntax-case x ()
((_ type-name printer (field ...))
(type #'type-name #'printer #'(field ...)))))))
;; module-type
;;
;; A module is characterized by an obarray in which local symbols
;; are interned, a list of modules, "uses", from which non-local
;; bindings can be inherited, and an optional lazy-binder which
;; is a (CLOSURE module symbol) which, as a last resort, can provide
;; bindings that would otherwise not be found locally in the module.
;;
;; NOTE: If you change the set of fields or their order, you also need to
;; change the constants in libguile/modules.h.
;;
;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
;; NOTE: The getter `module-name' is defined later, due to boot reasons.
;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
;;
(define-record-type module
(lambda (obj port) (%print-module obj port))
(obarray
uses
binder
eval-closure
(transformer #:no-getter)
(name #:no-getter)
kind
duplicates-handlers
(import-obarray #:no-setter)
observers
(weak-observers #:no-setter)
version
submodules
submodule-binder
public-interface
filename)))
;; make-module &opt size uses binder
;;
;; Create a new module, perhaps with a particular size of obarray,
;; initial uses list, or binding procedure.
;;
(define* (make-module #:optional (size 31) (uses '()) (binder #f))
(define %default-import-size
;; Typical number of imported bindings actually used by a module.
600)
(if (not (integer? size))
(error "Illegal size to make-module." size))
(if (not (and (list? uses)
(and-map module? uses)))
(error "Incorrect use list." uses))
(if (and binder (not (procedure? binder)))
(error
"Lazy-binder expected to be a procedure or #f." binder))
(module-constructor (make-hash-table size)
uses binder #f macroexpand
#f #f #f
(make-hash-table %default-import-size)
'()
(make-weak-key-hash-table 31) #f
(make-hash-table 7) #f #f #f))
;;; {Observer protocol}
;;;
(define (module-observe module proc)
(set-module-observers! module (cons proc (module-observers module)))
(cons module proc))
(define* (module-observe-weak module observer-id #:optional (proc observer-id))
;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
;; be any Scheme object). PROC is invoked and passed MODULE any time
;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
;; for instance).
;; The two-argument version is kept for backward compatibility: when called
;; with two arguments, the observer gets unregistered when closure PROC
;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
(hashq-set! (module-weak-observers module) observer-id proc))
(define (module-unobserve token)
(let ((module (car token))
(id (cdr token)))
(if (integer? id)
(hash-remove! (module-weak-observers module) id)
(set-module-observers! module (delq1! id (module-observers module)))))
*unspecified*)
(define module-defer-observers #f)
(define module-defer-observers-mutex (make-mutex 'recursive))
(define module-defer-observers-table (make-hash-table))
(define (module-modified m)
(if module-defer-observers
(hash-set! module-defer-observers-table m #t)
(module-call-observers m)))
;;; This function can be used to delay calls to observers so that they
;;; can be called once only in the face of massive updating of modules.
;;;
(define (call-with-deferred-observers thunk)
(dynamic-wind
(lambda ()
(lock-mutex module-defer-observers-mutex)
(set! module-defer-observers #t))
thunk
(lambda ()
(set! module-defer-observers #f)
(hash-for-each (lambda (m dummy)
(module-call-observers m))
module-defer-observers-table)
(hash-clear! module-defer-observers-table)
(unlock-mutex module-defer-observers-mutex))))
(define (module-call-observers m)
(for-each (lambda (proc) (proc m)) (module-observers m))
;; We assume that weak observers don't (un)register themselves as they are
;; called since this would preclude proper iteration over the hash table
;; elements.
(hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
;;; {Module Searching in General}
;;;
;;; We sometimes want to look for properties of a symbol
;;; just within the obarray of one module. If the property
;;; holds, then it is said to hold ``locally'' as in, ``The symbol
;;; DISPLAY is locally rebound in the module `safe-guile'.''
;;;
;;;
;;; Other times, we want to test for a symbol property in the obarray
;;; of M and, if it is not found there, try each of the modules in the
;;; uses list of M. This is the normal way of testing for some
;;; property, so we state these properties without qualification as
;;; in: ``The symbol 'fnord is interned in module M because it is
;;; interned locally in module M2 which is a member of the uses list
;;; of M.''
;;;
;; module-search fn m
;;
;; return the first non-#f result of FN applied to M and then to
;; the modules in the uses of m, and so on recursively. If all applications
;; return #f, then so does this function.
;;
(define (module-search fn m v)
(define (loop pos)
(and (pair? pos)
(or (module-search fn (car pos) v)
(loop (cdr pos)))))
(or (fn m v)
(loop (module-uses m))))
;;; {Is a symbol bound in a module?}
;;;
;;; Symbol S in Module M is bound if S is interned in M and if the binding
;;; of S in M has been set to some well-defined value.
;;;
;; module-locally-bound? module symbol
;;
;; Is a symbol bound (interned and defined) locally in a given module?
;;
(define (module-locally-bound? m v)
(let ((var (module-local-variable m v)))
(and var
(variable-bound? var))))
;; module-bound? module symbol
;;
;; Is a symbol bound (interned and defined) anywhere in a given module
;; or its uses?
;;
(define (module-bound? m v)
(let ((var (module-variable m v)))
(and var
(variable-bound? var))))
;;; {Is a symbol interned in a module?}
;;;
;;; Symbol S in Module M is interned if S occurs in
;;; of S in M has been set to some well-defined value.
;;;
;;; It is possible to intern a symbol in a module without providing
;;; an initial binding for the corresponding variable. This is done
;;; with:
;;; (module-add! module symbol (make-undefined-variable))
;;;
;;; In that case, the symbol is interned in the module, but not
;;; bound there. The unbound symbol shadows any binding for that
;;; symbol that might otherwise be inherited from a member of the uses list.
;;;
(define (module-obarray-get-handle ob key)
((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
(define (module-obarray-ref ob key)
((if (symbol? key) hashq-ref hash-ref) ob key))
(define (module-obarray-set! ob key val)
((if (symbol? key) hashq-set! hash-set!) ob key val))
(define (module-obarray-remove! ob key)
((if (symbol? key) hashq-remove! hash-remove!) ob key))
;; module-symbol-locally-interned? module symbol
;;
;; is a symbol interned (not neccessarily defined) locally in a given module
;; or its uses? Interned symbols shadow inherited bindings even if
;; they are not themselves bound to a defined value.
;;
(define (module-symbol-locally-interned? m v)
(not (not (module-obarray-get-handle (module-obarray m) v))))
;; module-symbol-interned? module symbol
;;
;; is a symbol interned (not neccessarily defined) anywhere in a given module
;; or its uses? Interned symbols shadow inherited bindings even if
;; they are not themselves bound to a defined value.
;;
(define (module-symbol-interned? m v)
(module-search module-symbol-locally-interned? m v))
;;; {Mapping modules x symbols --> variables}
;;;
;; module-local-variable module symbol
;; return the local variable associated with a MODULE and SYMBOL.
;;
;;; This function is very important. It is the only function that can
;;; return a variable from a module other than the mutators that store
;;; new variables in modules. Therefore, this function is the location
;;; of the "lazy binder" hack.
;;;
;;; If symbol is defined in MODULE, and if the definition binds symbol
;;; to a variable, return that variable object.
;;;
;;; If the symbols is not found at first, but the module has a lazy binder,
;;; then try the binder.
;;;
;;; If the symbol is not found at all, return #f.
;;;
;;; (This is now written in C, see `modules.c'.)
;;;
;;; {Mapping modules x symbols --> bindings}
;;;
;;; These are similar to the mapping to variables, except that the
;;; variable is dereferenced.
;;;
;; module-symbol-binding module symbol opt-value
;;
;; return the binding of a variable specified by name within
;; a given module, signalling an error if the variable is unbound.
;; If the OPT-VALUE is passed, then instead of signalling an error,
;; return OPT-VALUE.
;;
(define (module-symbol-local-binding m v . opt-val)
(let ((var (module-local-variable m v)))
(if (and var (variable-bound? var))
(variable-ref var)
(if (not (null? opt-val))
(car opt-val)
(error "Locally unbound variable." v)))))
;; module-symbol-binding module symbol opt-value
;;
;; return the binding of a variable specified by name within
;; a given module, signalling an error if the variable is unbound.
;; If the OPT-VALUE is passed, then instead of signalling an error,
;; return OPT-VALUE.
;;
(define (module-symbol-binding m v . opt-val)
(let ((var (module-variable m v)))
(if (and var (variable-bound? var))
(variable-ref var)
(if (not (null? opt-val))
(car opt-val)
(error "Unbound variable." v)))))
;;; {Adding Variables to Modules}
;;;
;; module-make-local-var! module symbol
;;
;; ensure a variable for V in the local namespace of M.
;; If no variable was already there, then create a new and uninitialzied
;; variable.
;;
;; This function is used in modules.c.
;;
(define (module-make-local-var! m v)
(or (let ((b (module-obarray-ref (module-obarray m) v)))
(and (variable? b)
(begin
;; Mark as modified since this function is called when
;; the standard eval closure defines a binding
(module-modified m)
b)))
;; Create a new local variable.
(let ((local-var (make-undefined-variable)))
(module-add! m v local-var)
local-var)))
;; module-ensure-local-variable! module symbol
;;
;; Ensure that there is a local variable in MODULE for SYMBOL. If
;; there is no binding for SYMBOL, create a new uninitialized
;; variable. Return the local variable.
;;
(define (module-ensure-local-variable! module symbol)
(or (module-local-variable module symbol)
(let ((var (make-undefined-variable)))
(module-add! module symbol var)
var)))
;; module-add! module symbol var
;;
;; ensure a particular variable for V in the local namespace of M.
;;
(define (module-add! m v var)
(if (not (variable? var))
(error "Bad variable to module-add!" var))
(if (not (symbol? v))
(error "Bad symbol to module-add!" v))
(module-obarray-set! (module-obarray m) v var)
(module-modified m))
;; module-remove!
;;
;; make sure that a symbol is undefined in the local namespace of M.
;;
(define (module-remove! m v)
(module-obarray-remove! (module-obarray m) v)
(module-modified m))
(define (module-clear! m)
(hash-clear! (module-obarray m))
(module-modified m))
;; MODULE-FOR-EACH -- exported
;;
;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
;;
(define (module-for-each proc module)
(hash-for-each proc (module-obarray module)))
(define (module-map proc module)
(hash-map->list proc (module-obarray module)))
;; Submodules
;;
;; Modules exist in a separate namespace from values, because you generally do
;; not want the name of a submodule, which you might not even use, to collide
;; with local variables that happen to be named the same as the submodule.
;;
(define (module-ref-submodule module name)
(or (hashq-ref (module-submodules module) name)
(and (module-submodule-binder module)
((module-submodule-binder module) module name))))
(define (module-define-submodule! module name submodule)
(hashq-set! (module-submodules module) name submodule))
;; It used to be, however, that module names were also present in the
;; value namespace. When we enable deprecated code, we preserve this
;; legacy behavior.
;;
;; These shims are defined here instead of in deprecated.scm because we
;; need their definitions before loading other modules.
;;
(begin-deprecated
(define (module-ref-submodule module name)
(or (hashq-ref (module-submodules module) name)
(and (module-submodule-binder module)
((module-submodule-binder module) module name))
(let ((var (module-local-variable module name)))
(and var (variable-bound? var) (module? (variable-ref var))
(begin
(warn "module" module "not in submodules table")
(variable-ref var))))))
(define (module-define-submodule! module name submodule)
(let ((var (module-local-variable module name)))
(if (and var
(or (not (variable-bound? var))
(not (module? (variable-ref var)))))
(warn "defining module" module ": not overriding local definition" var)
(module-define! module name submodule)))
(hashq-set! (module-submodules module) name submodule)))
;;; {Module-based Loading}
;;;
(define (save-module-excursion thunk)
(let ((inner-module (current-module))
(outer-module #f))
(dynamic-wind (lambda ()
(set! outer-module (current-module))
(set-current-module inner-module)
(set! inner-module #f))
thunk
(lambda ()
(set! inner-module (current-module))
(set-current-module outer-module)
(set! outer-module #f)))))
;;; {MODULE-REF -- exported}
;;;
;; Returns the value of a variable called NAME in MODULE or any of its
;; used modules. If there is no such variable, then if the optional third
;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
;;
(define (module-ref module name . rest)
(let ((variable (module-variable module name)))
(if (and variable (variable-bound? variable))
(variable-ref variable)
(if (null? rest)
(error "No variable named" name 'in module)
(car rest) ; default value
))))
;; MODULE-SET! -- exported
;;
;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
;; to VALUE; if there is no such variable, an error is signaled.
;;
(define (module-set! module name value)
(let ((variable (module-variable module name)))
(if variable
(variable-set! variable value)
(error "No variable named" name 'in module))))
;; MODULE-DEFINE! -- exported
;;
;; Sets the variable called NAME in MODULE to VALUE; if there is no such
;; variable, it is added first.
;;
(define (module-define! module name value)
(let ((variable (module-local-variable module name)))
(if variable
(begin
(variable-set! variable value)
(module-modified module))
(let ((variable (make-variable value)))
(module-add! module name variable)))))
;; MODULE-DEFINED? -- exported
;;
;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
;; uses)
;;
(define (module-defined? module name)
(let ((variable (module-variable module name)))
(and variable (variable-bound? variable))))
;; MODULE-USE! module interface
;;
;; Add INTERFACE to the list of interfaces used by MODULE.
;;
(define (module-use! module interface)
(if (not (or (eq? module interface)
(memq interface (module-uses module))))
(begin
;; Newly used modules must be appended rather than consed, so that
;; `module-variable' traverses the use list starting from the first
;; used module.
(set-module-uses! module (append (module-uses module)
(list interface)))
(hash-clear! (module-import-obarray module))
(module-modified module))))
;; MODULE-USE-INTERFACES! module interfaces
;;
;; Same as MODULE-USE!, but only notifies module observers after all
;; interfaces are added to the inports list.
;;
(define (module-use-interfaces! module interfaces)
(let* ((cur (module-uses module))
(new (let lp ((in interfaces) (out '()))
(if (null? in)
(reverse out)
(lp (cdr in)
(let ((iface (car in)))
(if (or (memq iface cur) (memq iface out))
out
(cons iface out))))))))
(set-module-uses! module (append cur new))
(hash-clear! (module-import-obarray module))
(module-modified module)))
;;; {Recursive Namespaces}
;;;
;;; A hierarchical namespace emerges if we consider some module to be
;;; root, and submodules of that module to be nested namespaces.
;;;
;;; The routines here manage variable names in hierarchical namespace.
;;; Each variable name is a list of elements, looked up in successively nested
;;; modules.
;;;
;;; (nested-ref some-root-module '(foo bar baz))
;;; => <value of a variable named baz in the submodule bar of
;;; the submodule foo of some-root-module>
;;;
;;;
;;; There are:
;;;
;;; ;; a-root is a module
;;; ;; name is a list of symbols
;;;
;;; nested-ref a-root name
;;; nested-set! a-root name val
;;; nested-define! a-root name val
;;; nested-remove! a-root name
;;;
;;; These functions manipulate values in namespaces. For referencing the
;;; namespaces themselves, use the following:
;;;
;;; nested-ref-module a-root name
;;; nested-define-module! a-root name mod
;;;
;;; (current-module) is a natural choice for a root so for convenience there are
;;; also:
;;;
;;; local-ref name == nested-ref (current-module) name
;;; local-set! name val == nested-set! (current-module) name val
;;; local-define name val == nested-define! (current-module) name val
;;; local-remove name == nested-remove! (current-module) name
;;; local-ref-module name == nested-ref-module (current-module) name
;;; local-define-module! name m == nested-define-module! (current-module) name m
;;;
(define (nested-ref root names)
(if (null? names)
root
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-ref cur head #f)
(let ((cur (module-ref-submodule cur head)))
(and cur
(loop cur (car tail) (cdr tail))))))))
(define (nested-set! root names val)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-set! cur head val)
(let ((cur (module-ref-submodule cur head)))
(if (not cur)
(error "failed to resolve module" names)
(loop cur (car tail) (cdr tail)))))))
(define (nested-define! root names val)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-define! cur head val)
(let ((cur (module-ref-submodule cur head)))
(if (not cur)
(error "failed to resolve module" names)
(loop cur (car tail) (cdr tail)))))))
(define (nested-remove! root names)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-remove! cur head)
(let ((cur (module-ref-submodule cur head)))
(if (not cur)
(error "failed to resolve module" names)
(loop cur (car tail) (cdr tail)))))))
(define (nested-ref-module root names)
(let loop ((cur root)
(names names))
(if (null? names)
cur
(let ((cur (module-ref-submodule cur (car names))))
(and cur
(loop cur (cdr names)))))))
(define (nested-define-module! root names module)
(if (null? names)
(error "can't redefine root module" root module)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-define-submodule! cur head module)
(let ((cur (or (module-ref-submodule cur head)
(let ((m (make-module 31)))
(set-module-kind! m 'directory)
(set-module-name! m (append (module-name cur)
(list head)))
(module-define-submodule! cur head m)
m))))
(loop cur (car tail) (cdr tail)))))))
(define (local-ref names)
(nested-ref (current-module) names))
(define (local-set! names val)
(nested-set! (current-module) names val))
(define (local-define names val)
(nested-define! (current-module) names val))
(define (local-remove names)
(nested-remove! (current-module) names))
(define (local-ref-module names)
(nested-ref-module (current-module) names))
(define (local-define-module names mod)
(nested-define-module! (current-module) names mod))
;;; {The (guile) module}
;;;
;;; The standard module, which has the core Guile bindings. Also called the
;;; "root module", as it is imported by many other modules, but it is not
;;; necessarily the root of anything; and indeed, the module named '() might be
;;; better thought of as a root.
;;;
;; The root module uses the pre-modules-obarray as its obarray. This
;; special obarray accumulates all bindings that have been established
;; before the module system is fully booted.
;;
;; (The obarray continues to be used by code that has been closed over
;; before the module system has been booted.)
;;
(define the-root-module
(let ((m (make-module 0)))
(set-module-obarray! m (%get-pre-modules-obarray))
(set-module-name! m '(guile))
m))
;; The root interface is a module that uses the same obarray as the
;; root module. It does not allow new definitions, tho.
;;
(define the-scm-module
(let ((m (make-module 0)))
(set-module-obarray! m (%get-pre-modules-obarray))
(set-module-name! m '(guile))
(set-module-kind! m 'interface)
;; In Guile 1.8 and earlier M was its own public interface.
(set-module-public-interface! m m)
m))
(set-module-public-interface! the-root-module the-scm-module)
;; Now that we have a root module, even though modules aren't fully booted,
;; expand the definition of resolve-module.
;;
(define (resolve-module name . args)
(if (equal? name '(guile))
the-root-module
(error "unexpected module to resolve during module boot" name)))
;; Cheat. These bindings are needed by modules.c, but we don't want
;; to move their real definition here because that would be unnatural.
;;
(define define-module* #f)
(define process-use-modules #f)
(define module-export! #f)
(define default-duplicate-binding-procedures #f)
;; This boots the module system. All bindings needed by modules.c
;; must have been defined by now.
;;
(set-current-module the-root-module)
;; Now that modules are booted, give module-name its final definition.
;;
(define module-name
(let ((accessor (record-accessor module-type 'name)))
(lambda (mod)
(or (accessor mod)
(let ((name (list (gensym))))
;; Name MOD and bind it in the module root so that it's visible to
;; `resolve-module'. This is important as `psyntax' stores module
;; names and relies on being able to `resolve-module' them.
(set-module-name! mod name)
(nested-define-module! (resolve-module '() #f) name mod)
(accessor mod))))))
(define (make-modules-in module name)
(or (nested-ref-module module name)
(let ((m (make-module 31)))
(set-module-kind! m 'directory)
(set-module-name! m (append (module-name module) name))
(nested-define-module! module name m)
m)))
(define (beautify-user-module! module)
(let ((interface (module-public-interface module)))
(if (or (not interface)
(eq? interface module))
(let ((interface (make-module 31)))
(set-module-name! interface (module-name module))
(set-module-version! interface (module-version module))
(set-module-kind! interface 'interface)
(set-module-public-interface! module interface))))
(if (and (not (memq the-scm-module (module-uses module)))
(not (eq? module the-root-module)))
;; Import the default set of bindings (from the SCM module) in MODULE.
(module-use! module the-scm-module)))
(define (version-matches? version-ref target)
(define (sub-versions-match? v-refs t)
(define (sub-version-matches? v-ref t)
(let ((matches? (lambda (v) (sub-version-matches? v t))))
(cond
((number? v-ref) (eqv? v-ref t))
((list? v-ref)
(case (car v-ref)
((>=) (>= t (cadr v-ref)))
((<=) (<= t (cadr v-ref)))
((and) (and-map matches? (cdr v-ref)))
((or) (or-map matches? (cdr v-ref)))
((not) (not (matches? (cadr v-ref))))
(else (error "Invalid sub-version reference" v-ref))))
(else (error "Invalid sub-version reference" v-ref)))))
(or (null? v-refs)
(and (not (null? t))
(sub-version-matches? (car v-refs) (car t))
(sub-versions-match? (cdr v-refs) (cdr t)))))
(let ((matches? (lambda (v) (version-matches? v target))))
(or (null? version-ref)
(case (car version-ref)
((and) (and-map matches? (cdr version-ref)))
((or) (or-map matches? (cdr version-ref)))
((not) (not (matches? (cadr version-ref))))
(else (sub-versions-match? version-ref target))))))
(define (make-fresh-user-module)
(let ((m (make-module)))
(beautify-user-module! m)
m))
;; NOTE: This binding is used in libguile/modules.c.
;;
(define resolve-module
(let ((root (make-module)))
(set-module-name! root '())
;; Define the-root-module as '(guile).
(module-define-submodule! root 'guile the-root-module)
(lambda* (name #:optional (autoload #t) (version #f) #:key (ensure #t))
(let ((already (nested-ref-module root name)))
(cond
((and already
(or (not autoload) (module-public-interface already)))
;; A hit, a palpable hit.
(if (and version
(not (version-matches? version (module-version already))))
(error "incompatible module version already loaded" name))
already)
(autoload
;; Try to autoload the module, and recurse.
(try-load-module name version)
(resolve-module name #f #:ensure ensure))
(else
;; No module found (or if one was, it had no public interface), and
;; we're not autoloading. Make an empty module if #:ensure is true.
(or already
(and ensure
(make-modules-in root name)))))))))
(define (try-load-module name version)
(try-module-autoload name version))
(define (reload-module m)
"Revisit the source file corresponding to the module @var{m}."
(let ((f (module-filename m)))
(if f
(save-module-excursion
(lambda ()
;; Re-set the initial environment, as in try-module-autoload.
(set-current-module (make-fresh-user-module))
(primitive-load-path f)
m))
;; Though we could guess, we *should* know it.
(error "unknown file name for module" m))))
(define (purify-module! module)
"Removes bindings in MODULE which are inherited from the (guile) module."
(let ((use-list (module-uses module)))
(if (and (pair? use-list)
(eq? (car (last-pair use-list)) the-scm-module))
(set-module-uses! module (reverse (cdr (reverse use-list)))))))
;; Return a module that is an interface to the module designated by
;; NAME.
;;
;; `resolve-interface' takes four keyword arguments:
;;
;; #:select SELECTION
;;
;; SELECTION is a list of binding-specs to be imported; A binding-spec
;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
;; is the name in the used module and SEEN is the name in the using
;; module. Note that SEEN is also passed through RENAMER, below. The
;; default is to select all bindings. If you specify no selection but
;; a renamer, only the bindings that already exist in the used module
;; are made available in the interface. Bindings that are added later
;; are not picked up.
;;
;; #:hide BINDINGS
;;
;; BINDINGS is a list of bindings which should not be imported.
;;
;; #:prefix PREFIX
;;
;; PREFIX is a symbol that will be appended to each exported name.
;; The default is to not perform any renaming.
;;
;; #:renamer RENAMER
;;
;; RENAMER is a procedure that takes a symbol and returns its new
;; name. The default is not perform any renaming.
;;
;; Signal "no code for module" error if module name is not resolvable
;; or its public interface is not available. Signal "no binding"
;; error if selected binding does not exist in the used module.
;;
(define* (resolve-interface name #:key
(select #f)
(hide '())
(prefix #f)
(renamer (if prefix
(symbol-prefix-proc prefix)
identity))
version)
(let* ((module (resolve-module name #t version #:ensure #f))
(public-i (and module (module-public-interface module))))
(unless public-i
(error "no code for module" name))
(if (and (not select) (null? hide) (eq? renamer identity))
public-i
(let ((selection (or select (module-map (lambda (sym var) sym)
public-i)))
(custom-i (make-module 31)))
(set-module-kind! custom-i 'custom-interface)
(set-module-name! custom-i name)
;; XXX - should use a lazy binder so that changes to the
;; used module are picked up automatically.
(for-each (lambda (bspec)
(let* ((direct? (symbol? bspec))
(orig (if direct? bspec (car bspec)))
(seen (if direct? bspec (cdr bspec)))
(var (or (module-local-variable public-i orig)
(module-local-variable module orig)
(error
;; fixme: format manually for now
(simple-format
#f "no binding `~A' in module ~A"
orig name)))))
(if (memq orig hide)
(set! hide (delq! orig hide))
(module-add! custom-i
(renamer seen)
var))))
selection)
;; Check that we are not hiding bindings which don't exist
(for-each (lambda (binding)
(if (not (module-local-variable public-i binding))
(error
(simple-format
#f "no binding `~A' to hide in module ~A"
binding name))))
hide)
custom-i))))
(define (symbol-prefix-proc prefix)
(lambda (symbol)
(symbol-append prefix symbol)))
;; This function is called from "modules.c". If you change it, be
;; sure to update "modules.c" as well.
(define* (define-module* name
#:key filename pure version (duplicates '())
(imports '()) (exports '()) (replacements '())
(re-exports '()) (autoloads '()) transformer)
(define (list-of pred l)
(or (null? l)
(and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
(define (valid-export? x)
(or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
(define (valid-autoload? x)
(and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
(define (resolve-imports imports)
(define (resolve-import import-spec)
(if (list? import-spec)
(apply resolve-interface import-spec)
(error "unexpected use-module specification" import-spec)))
(let lp ((imports imports) (out '()))
(cond
((null? imports) (reverse! out))
((pair? imports)
(lp (cdr imports)
(cons (resolve-import (car imports)) out)))
(else (error "unexpected tail of imports list" imports)))))
;; We could add a #:no-check arg, set by the define-module macro, if
;; these checks are taking too much time.
;;
(let ((module (resolve-module name #f)))
(beautify-user-module! module)
(if filename
(set-module-filename! module filename))
(if pure
(purify-module! module))
(if version
(begin
(if (not (list-of integer? version))
(error "expected list of integers for version"))
(set-module-version! module version)
(set-module-version! (module-public-interface module) version)))
(let ((imports (resolve-imports imports)))
(call-with-deferred-observers
(lambda ()
(if (pair? imports)
(module-use-interfaces! module imports))
(if (list-of valid-export? exports)
(if (pair? exports)
(module-export! module exports))
(error "expected exports to be a list of symbols or symbol pairs"))
(if (list-of valid-export? replacements)
(if (pair? replacements)
(module-replace! module replacements))
(error "expected replacements to be a list of symbols or symbol pairs"))
(if (list-of valid-export? re-exports)
(if (pair? re-exports)
(module-re-export! module re-exports))
(error "expected re-exports to be a list of symbols or symbol pairs"))
;; FIXME
(if (not (null? autoloads))
(apply module-autoload! module autoloads))
;; Wait until modules have been loaded to resolve duplicates
;; handlers.
(if (pair? duplicates)
(let ((handlers (lookup-duplicates-handlers duplicates)))
(set-module-duplicates-handlers! module handlers))))))
(if transformer
(if (and (pair? transformer) (list-of symbol? transformer))
(let ((iface (resolve-interface transformer))
(sym (car (last-pair transformer))))
(set-module-transformer! module (module-ref iface sym)))
(error "expected transformer to be a module name" transformer)))
(run-hook module-defined-hook module)
module))
;; `module-defined-hook' is a hook that is run whenever a new module
;; is defined. Its members are called with one argument, the new
;; module.
(define module-defined-hook (make-hook 1))
;;; {Autoload}
;;;
(define (make-autoload-interface module name bindings)
(let ((b (lambda (a sym definep)
(false-if-exception
(and (memq sym bindings)
(let ((i (module-public-interface (resolve-module name))))
(if (not i)
(error "missing interface for module" name))
(let ((autoload (memq a (module-uses module))))
;; Replace autoload-interface with actual interface if
;; that has not happened yet.
(if (pair? autoload)
(set-car! autoload i)))
(module-local-variable i sym)))
#:warning "Failed to autoload ~a in ~a:\n" sym name))))
(module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
(make-hash-table 0) '() (make-weak-value-hash-table 31) #f
(make-hash-table 0) #f #f #f)))
(define (module-autoload! module . args)
"Have @var{module} automatically load the module named @var{name} when one
of the symbols listed in @var{bindings} is looked up. @var{args} should be a
list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
module '(ice-9 q) '(make-q q-length))}."
(let loop ((args args))
(cond ((null? args)
#t)
((null? (cdr args))
(error "invalid name+binding autoload list" args))
(else
(let ((name (car args))
(bindings (cadr args)))
(module-use! module (make-autoload-interface module
name bindings))
(loop (cddr args)))))))
;;; {Autoloading modules}
;;;
;;; XXX FIXME autoloads-in-progress and autoloads-done
;;; are not handled in a thread-safe way.
(define autoloads-in-progress '())
;; This function is called from scm_load_scheme_module in
;; "deprecated.c". Please do not change its interface.
;;
(define* (try-module-autoload module-name #:optional version)
"Try to load a module of the given name. If it is not found, return
#f. Otherwise return #t. May raise an exception if a file is found,
but it fails to load."
(let* ((reverse-name (reverse module-name))
(name (symbol->string (car reverse-name)))
(dir-hint-module-name (reverse (cdr reverse-name)))
(dir-hint (apply string-append
(map (lambda (elt)
(string-append (symbol->string elt)
file-name-separator-string))
dir-hint-module-name))))
(resolve-module dir-hint-module-name #f)
(and (not (autoload-done-or-in-progress? dir-hint name))
(let ((didit #f))
(dynamic-wind
(lambda () (autoload-in-progress! dir-hint name))
(lambda ()
(with-fluids ((current-reader #f))
(save-module-excursion
(lambda ()
(define (call/ec proc)
(let ((tag (make-prompt-tag)))
(call-with-prompt
tag
(lambda ()
(proc (lambda () (abort-to-prompt tag))))
(lambda (k) (values)))))
;; The initial environment when loading a module is a fresh
;; user module.
(set-current-module (make-fresh-user-module))
;; Here we could allow some other search strategy (other than
;; primitive-load-path), for example using versions encoded
;; into the file system -- but then we would have to figure
;; out how to locate the compiled file, do auto-compilation,
;; etc. Punt for now, and don't use versions when locating
;; the file.
(call/ec
(lambda (abort)
(primitive-load-path (in-vicinity dir-hint name)
abort)
(set! didit #t)))))))
(lambda () (set-autoloaded! dir-hint name didit)))
didit))))
;;; {Dynamic linking of modules}
;;;
(define autoloads-done '((guile . guile)))
(define (autoload-done-or-in-progress? p m)
(let ((n (cons p m)))
(->bool (or (member n autoloads-done)
(member n autoloads-in-progress)))))
(define (autoload-done! p m)
(let ((n (cons p m)))
(set! autoloads-in-progress
(delete! n autoloads-in-progress))
(or (member n autoloads-done)
(set! autoloads-done (cons n autoloads-done)))))
(define (autoload-in-progress! p m)
(let ((n (cons p m)))
(set! autoloads-done
(delete! n autoloads-done))
(set! autoloads-in-progress (cons n autoloads-in-progress))))
(define (set-autoloaded! p m done?)
(if done?
(autoload-done! p m)
(let ((n (cons p m)))
(set! autoloads-done (delete! n autoloads-done))
(set! autoloads-in-progress (delete! n autoloads-in-progress)))))
;;; {Run-time options}
;;;
(define-syntax define-option-interface
(syntax-rules ()
((_ (interface (options enable disable) (option-set!)))
(begin
(define options
(case-lambda
(() (interface))
((arg)
(if (list? arg)
(begin (interface arg) (interface))
(for-each
(lambda (option)
(apply (lambda (name value documentation)
(display name)
(let ((len (string-length (symbol->string name))))
(when (< len 16)
(display #\tab)
(when (< len 8)
(display #\tab))))
(display #\tab)
(display value)
(display #\tab)
(display documentation)
(newline))
option))
(interface #t))))))
(define (enable . flags)
(interface (append flags (interface)))
(interface))
(define (disable . flags)
(let ((options (interface)))
(for-each (lambda (flag) (set! options (delq! flag options)))
flags)
(interface options)
(interface)))
(define-syntax-rule (option-set! opt val)
(eval-when (expand load eval)
(options (append (options) (list 'opt val)))))))))
(define-option-interface
(debug-options-interface
(debug-options debug-enable debug-disable)
(debug-set!)))
(define-option-interface
(read-options-interface
(read-options read-enable read-disable)
(read-set!)))
(define-option-interface
(print-options-interface
(print-options print-enable print-disable)
(print-set!)))
;;; {The Unspecified Value}
;;;
;;; Currently Guile represents unspecified values via one particular value,
;;; which may be obtained by evaluating (if #f #f). It would be nice in the
;;; future if we could replace this with a return of 0 values, though.
;;;
(define-syntax *unspecified*
(identifier-syntax (if #f #f)))
(define (unspecified? v) (eq? v *unspecified*))
;;; {Parameters}
;;;
(define <parameter>
;; Three fields: the procedure itself, the fluid, and the converter.
(make-struct <applicable-struct-vtable> 0 'pwprpr))
(set-struct-vtable-name! <parameter> '<parameter>)
(define* (make-parameter init #:optional (conv (lambda (x) x)))
"Make a new parameter.
A parameter is a dynamically bound value, accessed through a procedure.
To access the current value, apply the procedure with no arguments:
(define p (make-parameter 10))
(p) => 10
To provide a new value for the parameter in a dynamic extent, use
`parameterize':
(parameterize ((p 20))
(p)) => 20
(p) => 10
The value outside of the dynamic extent of the body is unaffected. To
update the current value, apply it to one argument:
(p 20) => 10
(p) => 20
As you can see, the call that updates a parameter returns its previous
value.
All values for the parameter are first run through the CONV procedure,
including INIT, the initial value. The default CONV procedure is the
identity procedure. CONV is commonly used to ensure some set of
invariants on the values that a parameter may have."
(let ((fluid (make-fluid (conv init))))
(make-struct <parameter> 0
(case-lambda
(() (fluid-ref fluid))
((x) (let ((prev (fluid-ref fluid)))
(fluid-set! fluid (conv x))
prev)))
fluid conv)))
(define* (fluid->parameter fluid #:optional (conv (lambda (x) x)))
"Make a parameter that wraps a fluid.
The value of the parameter will be the same as the value of the fluid.
If the parameter is rebound in some dynamic extent, perhaps via
`parameterize', the new value will be run through the optional CONV
procedure, as with any parameter. Note that unlike `make-parameter',
CONV is not applied to the initial value."
(make-struct <parameter> 0
(case-lambda
(() (fluid-ref fluid))
((x) (let ((prev (fluid-ref fluid)))
(fluid-set! fluid (conv x))
prev)))
fluid conv))
(define (parameter? x)
(and (struct? x) (eq? (struct-vtable x) <parameter>)))
(define (parameter-fluid p)
(if (parameter? p)
(struct-ref p 1)
(scm-error 'wrong-type-arg "parameter-fluid"
"Not a parameter: ~S" (list p) #f)))
(define (parameter-converter p)
(if (parameter? p)
(struct-ref p 2)
(scm-error 'wrong-type-arg "parameter-fluid"
"Not a parameter: ~S" (list p) #f)))
(define-syntax parameterize
(lambda (x)
(syntax-case x ()
((_ ((param value) ...) body body* ...)
(with-syntax (((p ...) (generate-temporaries #'(param ...))))
#'(let ((p param) ...)
(if (not (parameter? p))
(scm-error 'wrong-type-arg "parameterize"
"Not a parameter: ~S" (list p) #f))
...
(with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
...)
body body* ...)))))))
;;;
;;; Current ports as parameters.
;;;
(let ()
(define-syntax-rule (port-parameterize! binding fluid predicate msg)
(begin
(set! binding (fluid->parameter (module-ref (current-module) 'fluid)
(lambda (x)
(if (predicate x) x
(error msg x)))))
(module-remove! (current-module) 'fluid)))
(port-parameterize! current-input-port %current-input-port-fluid
input-port? "expected an input port")
(port-parameterize! current-output-port %current-output-port-fluid
output-port? "expected an output port")
(port-parameterize! current-error-port %current-error-port-fluid
output-port? "expected an output port")
(port-parameterize! current-warning-port %current-warning-port-fluid
output-port? "expected an output port"))
;;;
;;; Languages.
;;;
;; The language can be a symbolic name or a <language> object from
;; (system base language).
;;
(define current-language (make-parameter 'scheme))
;;; {Running Repls}
;;;
(define *repl-stack* (make-fluid '()))
;; Programs can call `batch-mode?' to see if they are running as part of a
;; script or if they are running interactively. REPL implementations ensure that
;; `batch-mode?' returns #f during their extent.
;;
(define (batch-mode?)
(null? (fluid-ref *repl-stack*)))
;; Programs can re-enter batch mode, for example after a fork, by calling
;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
;; to abort to the outermost prompt, and call a thunk there.
;;
(define (ensure-batch-mode!)
(set! batch-mode? (lambda () #t)))
(define (quit . args)
(apply throw 'quit args))
(define exit quit)
(define (gc-run-time)
(cdr (assq 'gc-time-taken (gc-stats))))
(define abort-hook (make-hook))
(define before-error-hook (make-hook))
(define after-error-hook (make-hook))
(define before-backtrace-hook (make-hook))
(define after-backtrace-hook (make-hook))
(define before-read-hook (make-hook))
(define after-read-hook (make-hook))
(define before-eval-hook (make-hook 1))
(define after-eval-hook (make-hook 1))
(define before-print-hook (make-hook 1))
(define after-print-hook (make-hook 1))
;;; This hook is run at the very end of an interactive session.
;;;
(define exit-hook (make-hook))
;;; The default repl-reader function. We may override this if we've
;;; the readline library.
(define repl-reader
(lambda* (prompt #:optional (reader (fluid-ref current-reader)))
(if (not (char-ready?))
(begin
(display (if (string? prompt) prompt (prompt)))
;; An interesting situation. The printer resets the column to
;; 0 by printing a newline, but we then advance it by printing
;; the prompt. However the port-column of the output port
;; does not typically correspond with the actual column on the
;; screen, because the input is echoed back! Since the
;; input is line-buffered and thus ends with a newline, the
;; output will really start on column zero. So, here we zero
;; it out. See bug 9664.
;;
;; Note that for similar reasons, the output-line will not
;; reflect the actual line on the screen. But given the
;; possibility of multiline input, the fix is not as
;; straightforward, so we don't bother.
;;
;; Also note that the readline implementation papers over
;; these concerns, because it's readline itself printing the
;; prompt, and not Guile.
(set-port-column! (current-output-port) 0)))
(force-output)
(run-hook before-read-hook)
((or reader read) (current-input-port))))
;;; {IOTA functions: generating lists of numbers}
;;;
(define (iota n)
(let loop ((count (1- n)) (result '()))
(if (< count 0) result
(loop (1- count) (cons count result)))))
;;; {While}
;;;
;;; with `continue' and `break'.
;;;
;; The inliner will remove the prompts at compile-time if it finds that
;; `continue' or `break' are not used.
;;
(define-syntax while
(lambda (x)
(syntax-case x ()
((while cond body ...)
#`(let ((break-tag (make-prompt-tag "break"))
(continue-tag (make-prompt-tag "continue")))
(call-with-prompt
break-tag
(lambda ()
(define-syntax #,(datum->syntax #'while 'break)
(lambda (x)
(syntax-case x ()
((_ arg (... ...))
#'(abort-to-prompt break-tag arg (... ...)))
(_
#'(lambda args
(apply abort-to-prompt break-tag args))))))
(let lp ()
(call-with-prompt
continue-tag
(lambda ()
(define-syntax #,(datum->syntax #'while 'continue)
(lambda (x)
(syntax-case x ()
((_)
#'(abort-to-prompt continue-tag))
((_ . args)
(syntax-violation 'continue "too many arguments" x))
(_
#'(lambda ()
(abort-to-prompt continue-tag))))))
(do () ((not cond) #f) body ...))
(lambda (k) (lp)))))
(lambda (k . args)
(if (null? args)
#t
(apply values args)))))))))
;;; {Module System Macros}
;;;
;; Return a list of expressions that evaluate to the appropriate
;; arguments for resolve-interface according to SPEC.
(eval-when (expand)
(if (memq 'prefix (read-options))
(error "boot-9 must be compiled with #:kw, not :kw")))
(define (keyword-like-symbol->keyword sym)
(symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
(define-syntax define-module
(lambda (x)
(define (keyword-like? stx)
(let ((dat (syntax->datum stx)))
(and (symbol? dat)
(eqv? (string-ref (symbol->string dat) 0) #\:))))
(define (->keyword sym)
(symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
(define (parse-iface args)
(let loop ((in args) (out '()))
(syntax-case in ()
(() (reverse! out))
;; The user wanted #:foo, but wrote :foo. Fix it.
((sym . in) (keyword-like? #'sym)
(loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
((kw . in) (not (keyword? (syntax->datum #'kw)))
(syntax-violation 'define-module "expected keyword arg" x #'kw))
((#:renamer renamer . in)
(loop #'in (cons* #',renamer #:renamer out)))
((kw val . in)
(loop #'in (cons* #'val #'kw out))))))
(define (parse args imp exp rex rep aut)
;; Just quote everything except #:use-module and #:use-syntax. We
;; need to know about all arguments regardless since we want to turn
;; symbols that look like keywords into real keywords, and the
;; keyword args in a define-module form are not regular
;; (i.e. no-backtrace doesn't take a value).
(syntax-case args ()
(()
(let ((imp (if (null? imp) '() #`(#:imports `#,imp)))
(exp (if (null? exp) '() #`(#:exports '#,exp)))
(rex (if (null? rex) '() #`(#:re-exports '#,rex)))
(rep (if (null? rep) '() #`(#:replacements '#,rep)))
(aut (if (null? aut) '() #`(#:autoloads '#,aut))))
#`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
;; The user wanted #:foo, but wrote :foo. Fix it.
((sym . args) (keyword-like? #'sym)
(parse #`(#,(->keyword (syntax->datum #'sym)) . args)
imp exp rex rep aut))
((kw . args) (not (keyword? (syntax->datum #'kw)))
(syntax-violation 'define-module "expected keyword arg" x #'kw))
((#:no-backtrace . args)
;; Ignore this one.
(parse #'args imp exp rex rep aut))
((#:pure . args)
#`(#:pure #t . #,(parse #'args imp exp rex rep aut)))
((kw)
(syntax-violation 'define-module "keyword arg without value" x #'kw))
((#:version (v ...) . args)
#`(#:version '(v ...) . #,(parse #'args imp exp rex rep aut)))
((#:duplicates (d ...) . args)
#`(#:duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
((#:filename f . args)
#`(#:filename 'f . #,(parse #'args imp exp rex rep aut)))
((#:use-module (name name* ...) . args)
(and (and-map symbol? (syntax->datum #'(name name* ...))))
(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
((#:use-syntax (name name* ...) . args)
(and (and-map symbol? (syntax->datum #'(name name* ...))))
#`(#:transformer '(name name* ...)
. #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
((#:use-module ((name name* ...) arg ...) . args)
(and (and-map symbol? (syntax->datum #'(name name* ...))))
(parse #'args
#`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
exp rex rep aut))
((#:export (ex ...) . args)
(parse #'args imp #`(#,@exp ex ...) rex rep aut))
((#:export-syntax (ex ...) . args)
(parse #'args imp #`(#,@exp ex ...) rex rep aut))
((#:re-export (re ...) . args)
(parse #'args imp exp #`(#,@rex re ...) rep aut))
((#:re-export-syntax (re ...) . args)
(parse #'args imp exp #`(#,@rex re ...) rep aut))
((#:replace (r ...) . args)
(parse #'args imp exp rex #`(#,@rep r ...) aut))
((#:replace-syntax (r ...) . args)
(parse #'args imp exp rex #`(#,@rep r ...) aut))
((#:autoload name bindings . args)
(parse #'args imp exp rex rep #`(#,@aut name bindings)))
((kw val . args)
(syntax-violation 'define-module "unknown keyword or bad argument"
#'kw #'val))))
(syntax-case x ()
((_ (name name* ...) arg ...)
(and-map symbol? (syntax->datum #'(name name* ...)))
(with-syntax (((quoted-arg ...)
(parse #'(arg ...) '() '() '() '() '()))
;; Ideally the filename is either a string or #f;
;; this hack is to work around a case in which
;; port-filename returns a symbol (`socket') for
;; sockets.
(filename (let ((f (assq-ref (or (syntax-source x) '())
'filename)))
(and (string? f) f))))
#'(eval-when (expand load eval)
(let ((m (define-module* '(name name* ...)
#:filename filename quoted-arg ...)))
(set-current-module m)
m)))))))
;; The guts of the use-modules macro. Add the interfaces of the named
;; modules to the use-list of the current module, in order.
;; This function is called by "modules.c". If you change it, be sure
;; to change scm_c_use_module as well.
(define (process-use-modules module-interface-args)
(let ((interfaces (map (lambda (mif-args)
(or (apply resolve-interface mif-args)
(error "no such module" mif-args)))
module-interface-args)))
(call-with-deferred-observers
(lambda ()
(module-use-interfaces! (current-module) interfaces)))))
(define-syntax use-modules
(lambda (x)
(define (keyword-like? stx)
(let ((dat (syntax->datum stx)))
(and (symbol? dat)
(eqv? (string-ref (symbol->string dat) 0) #\:))))
(define (->keyword sym)
(symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
(define (quotify-iface args)
(let loop ((in args) (out '()))
(syntax-case in ()
(() (reverse! out))
;; The user wanted #:foo, but wrote :foo. Fix it.
((sym . in) (keyword-like? #'sym)
(loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
((kw . in) (not (keyword? (syntax->datum #'kw)))
(syntax-violation 'define-module "expected keyword arg" x #'kw))
((#:renamer renamer . in)
(loop #'in (cons* #'renamer #:renamer out)))
((kw val . in)
(loop #'in (cons* #''val #'kw out))))))
(define (quotify specs)
(let lp ((in specs) (out '()))
(syntax-case in ()
(() (reverse out))
(((name name* ...) . in)
(and-map symbol? (syntax->datum #'(name name* ...)))
(lp #'in (cons #''((name name* ...)) out)))
((((name name* ...) arg ...) . in)
(and-map symbol? (syntax->datum #'(name name* ...)))
(with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
(lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
out)))))))
(syntax-case x ()
((_ spec ...)
(with-syntax (((quoted-args ...) (quotify #'(spec ...))))
#'(eval-when (expand load eval)
(process-use-modules (list quoted-args ...))
*unspecified*))))))
(define-syntax-rule (use-syntax spec ...)
(begin
(eval-when (expand load eval)
(issue-deprecation-warning
"`use-syntax' is deprecated. Please contact guile-devel for more info."))
(use-modules spec ...)))
(include-from-path "ice-9/r6rs-libraries")
(define-syntax-rule (define-private foo bar)
(define foo bar))
(define-syntax define-public
(syntax-rules ()
((_ (name . args) . body)
(begin
(define (name . args) . body)
(export name)))
((_ name val)
(begin
(define name val)
(export name)))))
(define-syntax-rule (defmacro-public name args body ...)
(begin
(defmacro name args body ...)
(export-syntax name)))
;; And now for the most important macro.
(define-syntax-rule (λ formals body ...)
(lambda formals body ...))
;; Export a local variable
;; This function is called from "modules.c". If you change it, be
;; sure to update "modules.c" as well.
(define (module-export! m names)
(let ((public-i (module-public-interface m)))
(for-each (lambda (name)
(let* ((internal-name (if (pair? name) (car name) name))
(external-name (if (pair? name) (cdr name) name))
(var (module-ensure-local-variable! m internal-name)))
(module-add! public-i external-name var)))
names)))
(define (module-replace! m names)
(let ((public-i (module-public-interface m)))
(for-each (lambda (name)
(let* ((internal-name (if (pair? name) (car name) name))
(external-name (if (pair? name) (cdr name) name))
(var (module-ensure-local-variable! m internal-name)))
;; FIXME: use a bit on variables instead of object
;; properties.
(set-object-property! var 'replace #t)
(module-add! public-i external-name var)))
names)))
;; Export all local variables from a module
;;
(define (module-export-all! mod)
(define (fresh-interface!)
(let ((iface (make-module)))
(set-module-name! iface (module-name mod))
(set-module-version! iface (module-version mod))
(set-module-kind! iface 'interface)
(set-module-public-interface! mod iface)
iface))
(let ((iface (or (module-public-interface mod)
(fresh-interface!))))
(set-module-obarray! iface (module-obarray mod))))
;; Re-export a imported variable
;;
(define (module-re-export! m names)
(let ((public-i (module-public-interface m)))
(for-each (lambda (name)
(let* ((internal-name (if (pair? name) (car name) name))
(external-name (if (pair? name) (cdr name) name))
(var (module-variable m internal-name)))
(cond ((not var)
(error "Undefined variable:" internal-name))
((eq? var (module-local-variable m internal-name))
(error "re-exporting local variable:" internal-name))
(else
(module-add! public-i external-name var)))))
names)))
(define-syntax-rule (export name ...)
(eval-when (expand load eval)
(call-with-deferred-observers
(lambda ()
(module-export! (current-module) '(name ...))))))
(define-syntax-rule (re-export name ...)
(eval-when (expand load eval)
(call-with-deferred-observers
(lambda ()
(module-re-export! (current-module) '(name ...))))))
(define-syntax-rule (export! name ...)
(eval-when (expand load eval)
(call-with-deferred-observers
(lambda ()
(module-replace! (current-module) '(name ...))))))
(define-syntax-rule (export-syntax name ...)
(export name ...))
(define-syntax-rule (re-export-syntax name ...)
(re-export name ...))
;;; {Parameters}
;;;
(define* (make-mutable-parameter init #:optional (converter identity))
(let ((fluid (make-fluid (converter init))))
(case-lambda
(() (fluid-ref fluid))
((val) (fluid-set! fluid (converter val))))))
;;; {Handling of duplicate imported bindings}
;;;
;; Duplicate handlers take the following arguments:
;;
;; module importing module
;; name conflicting name
;; int1 old interface where name occurs
;; val1 value of binding in old interface
;; int2 new interface where name occurs
;; val2 value of binding in new interface
;; var previous resolution or #f
;; val value of previous resolution
;;
;; A duplicate handler can take three alternative actions:
;;
;; 1. return #f => leave responsibility to next handler
;; 2. exit with an error
;; 3. return a variable resolving the conflict
;;
(define duplicate-handlers
(let ((m (make-module 7)))
(define (check module name int1 val1 int2 val2 var val)
(scm-error 'misc-error
#f
"~A: `~A' imported from both ~A and ~A"
(list (module-name module)
name
(module-name int1)
(module-name int2))
#f))
(define (warn module name int1 val1 int2 val2 var val)
(format (current-warning-port)
"WARNING: ~A: `~A' imported from both ~A and ~A\n"
(module-name module)
name
(module-name int1)
(module-name int2))
#f)
(define (replace module name int1 val1 int2 val2 var val)
(let ((old (or (and var (object-property var 'replace) var)
(module-variable int1 name)))
(new (module-variable int2 name)))
(if (object-property old 'replace)
(and (or (eq? old new)
(not (object-property new 'replace)))
old)
(and (object-property new 'replace)
new))))
(define (warn-override-core module name int1 val1 int2 val2 var val)
(and (eq? int1 the-scm-module)
(begin
(format (current-warning-port)
"WARNING: ~A: imported module ~A overrides core binding `~A'\n"
(module-name module)
(module-name int2)
name)
(module-local-variable int2 name))))
(define (first module name int1 val1 int2 val2 var val)
(or var (module-local-variable int1 name)))
(define (last module name int1 val1 int2 val2 var val)
(module-local-variable int2 name))
(define (noop module name int1 val1 int2 val2 var val)
#f)
(set-module-name! m 'duplicate-handlers)
(set-module-kind! m 'interface)
(module-define! m 'check check)
(module-define! m 'warn warn)
(module-define! m 'replace replace)
(module-define! m 'warn-override-core warn-override-core)
(module-define! m 'first first)
(module-define! m 'last last)
(module-define! m 'merge-generics noop)
(module-define! m 'merge-accessors noop)
m))
(define (lookup-duplicates-handlers handler-names)
(and handler-names
(map (lambda (handler-name)
(or (module-symbol-local-binding
duplicate-handlers handler-name #f)
(error "invalid duplicate handler name:"
handler-name)))
(if (list? handler-names)
handler-names
(list handler-names)))))
(define default-duplicate-binding-procedures
(make-mutable-parameter #f))
(define default-duplicate-binding-handler
(make-mutable-parameter '(replace warn-override-core warn last)
(lambda (handler-names)
(default-duplicate-binding-procedures
(lookup-duplicates-handlers handler-names))
handler-names)))
;;; {`load'.}
;;;
;;; Load is tricky when combined with relative file names, compilation,
;;; and the file system. If a file name is relative, what is it
;;; relative to? The name of the source file at the time it was
;;; compiled? The name of the compiled file? What if both or either
;;; were installed? And how do you get that information? Tricky, I
;;; say.
;;;
;;; To get around all of this, we're going to do something nasty, and
;;; turn `load' into a macro. That way it can know the name of the
;;; source file with respect to which it was invoked, so it can resolve
;;; relative file names with respect to the original source file.
;;;
;;; There is an exception, and that is that if the source file was in
;;; the load path when it was compiled, instead of looking up against
;;; the absolute source location, we load-from-path against the relative
;;; source location.
;;;
(define %auto-compilation-options
;; Default `compile-file' option when auto-compiling.
'(#:warnings (unbound-variable arity-mismatch format
duplicate-case-datum bad-case-datum)))
(define* (load-in-vicinity dir file-name #:optional reader)
"Load source file FILE-NAME in vicinity of directory DIR. Use a
pre-compiled version of FILE-NAME when available, and auto-compile one
when none is available, reading FILE-NAME with READER."
;; The auto-compilation code will residualize a .go file in the cache
;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
;; function determines the PATH to use as a key into the compilation
;; cache.
(define (canonical->suffix canon)
(cond
((and (not (string-null? canon))
(file-name-separator? (string-ref canon 0)))
canon)
((and (eq? (system-file-name-convention) 'windows)
(absolute-file-name? canon))
;; An absolute file name that doesn't start with a separator
;; starts with a drive component. Transform the drive component
;; to a file name element: c:\foo -> \c\foo.
(string-append file-name-separator-string
(substring canon 0 1)
(substring canon 2)))
(else canon)))
(define compiled-extension
;; File name extension of compiled files.
(cond ((or (null? %load-compiled-extensions)
(string-null? (car %load-compiled-extensions)))
(warn "invalid %load-compiled-extensions"
%load-compiled-extensions)
".go")
(else (car %load-compiled-extensions))))
(define (more-recent? stat1 stat2)
;; Return #t when STAT1 has an mtime greater than that of STAT2.
(or (> (stat:mtime stat1) (stat:mtime stat2))
(and (= (stat:mtime stat1) (stat:mtime stat2))
(>= (stat:mtimensec stat1)
(stat:mtimensec stat2)))))
(define (fallback-file-name canon-file-name)
;; Return the in-cache compiled file name for source file
;; CANON-FILE-NAME.
;; FIXME: would probably be better just to append
;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
;; deep directory stats.
(and %compile-fallback-path
(string-append %compile-fallback-path
(canonical->suffix canon-file-name)
compiled-extension)))
(define (compile file)
;; Compile source FILE, lazily loading the compiler.
((module-ref (resolve-interface '(system base compile))
'compile-file)
file
#:opts %auto-compilation-options
#:env (current-module)))
(define (load-thunk-from-file file)
(let ((objcode (resolve-interface '(system vm objcode)))
(program (resolve-interface '(system vm program))))
((module-ref program 'make-program)
((module-ref objcode 'load-objcode) file))))
;; Returns a thunk loaded from the .go file corresponding to `name'.
;; Does not search load paths, only the fallback path. If the .go
;; file is missing or out of date, and auto-compilation is enabled,
;; will try auto-compilation, just as primitive-load-path does
;; internally. primitive-load is unaffected. Returns #f if
;; auto-compilation failed or was disabled.
;;
;; NB: Unless we need to compile the file, this function should not
;; cause (system base compile) to be loaded up. For that reason
;; compiled-file-name partially duplicates functionality from (system
;; base compile).
(define (fresh-compiled-thunk name scmstat go-file-name)
;; Return GO-FILE-NAME after making sure that it contains a freshly
;; compiled version of source file NAME with stat SCMSTAT; return #f
;; on failure.
(false-if-exception
(let ((gostat (and (not %fresh-auto-compile)
(stat go-file-name #f))))
(if (and gostat (more-recent? gostat scmstat))
(load-thunk-from-file go-file-name)
(begin
(when gostat
(format (current-warning-port)
";;; note: source file ~a\n;;; newer than compiled ~a\n"
name go-file-name))
(cond
(%load-should-auto-compile
(%warn-auto-compilation-enabled)
(format (current-warning-port) ";;; compiling ~a\n" name)
(let ((cfn (compile name)))
(format (current-warning-port) ";;; compiled ~a\n" cfn)
(load-thunk-from-file cfn)))
(else #f)))))
#:warning "WARNING: compilation of ~a failed:\n" name))
(define (sans-extension file)
(let ((dot (string-rindex file #\.)))
(if dot
(substring file 0 dot)
file)))
(define (load-absolute abs-file-name)
;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
;; if needed.
(define scmstat
(false-if-exception
(stat abs-file-name)
#:warning "Stat of ~a failed:\n" abs-file-name))
(define (pre-compiled)
(or-map
(lambda (dir)
(or-map
(lambda (ext)
(let ((candidate (string-append (in-vicinity dir file-name) ext)))
(let ((gostat (stat candidate #f)))
(and gostat
(more-recent? gostat scmstat)
(false-if-exception
(load-thunk-from-file candidate)
#:warning "WARNING: failed to load compiled file ~a:\n"
candidate)))))
%load-compiled-extensions))
%load-compiled-path))
(define (fallback)
(and=> (false-if-exception (canonicalize-path abs-file-name))
(lambda (canon)
(and=> (fallback-file-name canon)
(lambda (go-file-name)
(fresh-compiled-thunk abs-file-name
scmstat
go-file-name))))))
(let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
(if compiled
(begin
(if %load-hook
(%load-hook abs-file-name))
(compiled))
(start-stack 'load-stack
(primitive-load abs-file-name)))))
(save-module-excursion
(lambda ()
(with-fluids ((current-reader reader)
(%file-port-name-canonicalization 'relative))
(cond
((absolute-file-name? file-name)
(load-absolute file-name))
((absolute-file-name? dir)
(load-absolute (in-vicinity dir file-name)))
(else
(load-from-path (in-vicinity dir file-name))))))))
(define-syntax load
(make-variable-transformer
(lambda (x)
(let* ((src (syntax-source x))
(file (and src (assq-ref src 'filename)))
(dir (and (string? file) (dirname file))))
(syntax-case x ()
((_ arg ...)
#`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
(id
(identifier? #'id)
#`(lambda args
(apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
;;; {`cond-expand' for SRFI-0 support.}
;;;
;;; This syntactic form expands into different commands or
;;; definitions, depending on the features provided by the Scheme
;;; implementation.
;;;
;;; Syntax:
;;;
;;; <cond-expand>
;;; --> (cond-expand <cond-expand-clause>+)
;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
;;; <cond-expand-clause>
;;; --> (<feature-requirement> <command-or-definition>*)
;;; <feature-requirement>
;;; --> <feature-identifier>
;;; | (and <feature-requirement>*)
;;; | (or <feature-requirement>*)
;;; | (not <feature-requirement>)
;;; <feature-identifier>
;;; --> <a symbol which is the name or alias of a SRFI>
;;;
;;; Additionally, this implementation provides the
;;; <feature-identifier>s `guile' and `r5rs', so that programs can
;;; determine the implementation type and the supported standard.
;;;
;;; Remember to update the features list when adding more SRFIs.
;;;
(define %cond-expand-features
;; This should contain only features that are present in core Guile,
;; before loading any modules. Modular features are handled by
;; placing 'cond-expand-provide' in the relevant module.
'(guile
guile-2
r5rs
srfi-0 ;; cond-expand itself
srfi-4 ;; homogeneous numeric vectors
;; We omit srfi-6 because the 'open-input-string' etc in Guile
;; core are not conformant with SRFI-6; they expose details
;; of the binary I/O model and may fail to support some characters.
srfi-13 ;; string library
srfi-14 ;; character sets
srfi-16 ;; case-lambda
srfi-23 ;; `error` procedure
srfi-30 ;; nested multi-line comments
srfi-39 ;; parameterize
srfi-46 ;; basic syntax-rules extensions
srfi-55 ;; require-extension
srfi-61 ;; general cond clause
srfi-62 ;; s-expression comments
srfi-87 ;; => in case clauses
srfi-105 ;; curly infix expressions
))
;; This table maps module public interfaces to the list of features.
;;
(define %cond-expand-table (make-hash-table 31))
;; Add one or more features to the `cond-expand' feature list of the
;; module `module'.
;;
(define (cond-expand-provide module features)
(let ((mod (module-public-interface module)))
(and mod
(hashq-set! %cond-expand-table mod
(append (hashq-ref %cond-expand-table mod '())
features)))))
(define-syntax cond-expand
(lambda (x)
(define (module-has-feature? mod sym)
(or-map (lambda (mod)
(memq sym (hashq-ref %cond-expand-table mod '())))
(module-uses mod)))
(define (condition-matches? condition)
(syntax-case condition (and or not)
((and c ...)
(and-map condition-matches? #'(c ...)))
((or c ...)
(or-map condition-matches? #'(c ...)))
((not c)
(if (condition-matches? #'c) #f #t))
(c
(identifier? #'c)
(let ((sym (syntax->datum #'c)))
(if (memq sym %cond-expand-features)
#t
(module-has-feature? (current-module) sym))))))
(define (match clauses alternate)
(syntax-case clauses ()
(((condition form ...) . rest)
(if (condition-matches? #'condition)
#'(begin form ...)
(match #'rest alternate)))
(() (alternate))))
(syntax-case x (else)
((_ clause ... (else form ...))
(match #'(clause ...)
(lambda ()
#'(begin form ...))))
((_ clause ...)
(match #'(clause ...)
(lambda ()
(syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
;; This procedure gets called from the startup code with a list of
;; numbers, which are the numbers of the SRFIs to be loaded on startup.
;;
(define (use-srfis srfis)
(process-use-modules
(map (lambda (num)
(list (list 'srfi (string->symbol
(string-append "srfi-" (number->string num))))))
srfis)))
;;; srfi-55: require-extension
;;;
(define-syntax require-extension
(lambda (x)
(syntax-case x (srfi)
((_ (srfi n ...))
(and-map integer? (syntax->datum #'(n ...)))
(with-syntax
(((srfi-n ...)
(map (lambda (n)
(datum->syntax x (symbol-append 'srfi- n)))
(map string->symbol
(map number->string (syntax->datum #'(n ...)))))))
#'(use-modules (srfi srfi-n) ...)))
((_ (type arg ...))
(identifier? #'type)
(syntax-violation 'require-extension "Not a recognized extension type"
x)))))
;;; Defining transparently inlinable procedures
;;;
(define-syntax define-inlinable
;; Define a macro and a procedure such that direct calls are inlined, via
;; the macro expansion, whereas references in non-call contexts refer to
;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
(lambda (x)
;; Use a space in the prefix to avoid potential -Wunused-toplevel
;; warning
(define prefix (string->symbol "% "))
(define (make-procedure-name name)
(datum->syntax name
(symbol-append prefix (syntax->datum name)
'-procedure)))
(syntax-case x ()
((_ (name formals ...) body ...)
(identifier? #'name)
(with-syntax ((proc-name (make-procedure-name #'name))
((args ...) (generate-temporaries #'(formals ...))))
#`(begin
(define (proc-name formals ...)
(syntax-parameterize ((name (identifier-syntax proc-name)))
body ...))
(define-syntax-parameter name
(lambda (x)
(syntax-case x ()
((_ args ...)
#'((syntax-parameterize ((name (identifier-syntax proc-name)))
(lambda (formals ...)
body ...))
args ...))
((_ a (... ...))
(syntax-violation 'name "Wrong number of arguments" x))
(_
(identifier? x)
#'proc-name))))))))))
(define using-readline?
(let ((using-readline? (make-fluid)))
(make-procedure-with-setter
(lambda () (fluid-ref using-readline?))
(lambda (v) (fluid-set! using-readline? v)))))
;;; {Deprecated stuff}
;;;
(begin-deprecated
(module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
;;; SRFI-4 in the default environment. FIXME: we should figure out how
;;; to deprecate this.
;;;
;; FIXME:
(module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
;;; A few identifiers that need to be defined in this file are really
;;; internal implementation details. We shove them off into internal
;;; modules, removing them from the (guile) module.
;;;
(define-module (system syntax))
(let ()
(define (steal-bindings! from to ids)
(for-each
(lambda (sym)
(let ((v (module-local-variable from sym)))
(module-remove! from sym)
(module-add! to sym v)))
ids)
(module-export! to ids))
(steal-bindings! the-root-module (resolve-module '(system syntax))
'(syntax-local-binding
syntax-module
syntax-locally-bound-identifiers
syntax-session-id)))
;;; Place the user in the guile-user module.
;;;
;; Set filename to #f to prevent reload.
(define-module (guile-user)
#:autoload (system base compile) (compile compile-file)
#:filename #f)
;; Remain in the `(guile)' module at compilation-time so that the
;; `-Wunused-toplevel' warning works as expected.
(eval-when (compile) (set-current-module the-root-module))
;;; boot-9.scm ends here
| true |
64ccc3779dd3f81326bcacf4ecb203d0201a0ef8 | 958488bc7f3c2044206e0358e56d7690b6ae696c | /scheme/types/true.scm | 32f142a908354e716c90aa8441b2f81db9e3237e | []
| no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 | Coq | UTF-8 | Scheme | false | false | 67 | scm | true.scm | (define (true? exp) (eq? exp #t))
(define (evaluate-true exp) #t)
| false |
3c58cd07a0cead1adff63341b8afb7b367d913c6 | c74dcb1facbd920d762017345171f47f8e41d0c5 | /chapter_2/2.37.scm | f70b612f7e1db59d28e453c7f8c8cad19e7498b8 | []
| no_license | akash-akya/sicp-exercises | 5125c1118c7f0e4400cb823508797fb67c745592 | c28f73719740c2c495b7bc38ee8b790219482b67 | refs/heads/master | 2021-06-15T19:12:47.679967 | 2019-08-03T14:03:20 | 2019-08-03T14:03:20 | 136,158,517 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,594 | scm | 2.37.scm | #lang sicp
;; Exercise 2.37: Suppose we represent vectors v = ( v i ) as
;; sequences of numbers, and matrices m = ( m i j ) as sequences of
;; vectors (the rows of the matrix). For example, the matrix
;; ( 1 2 3 4 4 5 6 6 6 7 8 9 ) is represented as the sequence ((1 2 3
;; 4) (4 5 6 6) (6 7 8 9)). With this representation, we can use sequence
;; operations to concisely express the basic matrix and vector
;; operations. These operations (which are described in any book on
;; matrix algebra) are the following:
;; (dot-product v w) returns the sum Σ i v i w i ;
;; (matrix-*-vector m v) returns the vector t , where t i = Σ j m i j v j ;
;; (matrix-*-matrix m n) returns the matrix p , where p i j = Σ k m i k n k j ;
;; (transpose m) returns the matrix n , where n i j = m j i .
;; We can define the dot product as
;; (define (dot-product v w)
;; (accumulate + 0 (map * v w)))
;; Fill in the missing expressions in the following procedures for
;; computing the other matrix operations. (The procedure accumulate-n is
;; defined in Exercise 2.36.)
;; (define (matrix-*-vector m v)
;; (map ⟨??⟩ m))
;; (define (transpose mat)
;; (accumulate-n ⟨??⟩ ⟨??⟩ mat))
;; (define (matrix-*-matrix m n)
;; (let ((cols (transpose n)))
;; (map ⟨??⟩ m)))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op
initial
(cdr sequence)))))
(define (accumulate-n op init seqs)
(if (null? (car seqs))
nil
(cons (accumulate op init (map car seqs))
(accumulate-n op init (map cdr seqs)))))
(define (matrix-*-vector m v)
(map (lambda (y)
(accumulate +
0
(accumulate-n * 1 (list v y)))) m))
(define (transpose mat)
(accumulate-n (lambda (a b)
(cons a b)) nil mat))
(define (matrix-*-matrix m n)
(let ((cols (transpose n)))
(map
(lambda (a) (matrix-*-vector cols a))
m)))
;; test
(define (err msg)
(display msg))
(define (test)
(cond ((not (equal? (matrix-*-vector '((1 2) (2 4)) '(10 20))
'(50 100)))
(err "matrix-*-vector failed"))
((not (equal? (transpose '((1 2) (3 4)))
'((1 3) (2 4))))
(err "transpose failed"))
((not (equal? (matrix-*-matrix '((1 1) (3 4)) '((1 2) (3 4)))
'((4 6) (15 22))))
(err "matrix-*-matrix failed"))
(else (display "All tests passed")))
(newline))
| false |
6d5520eae9eac0ea27f048179437e84a46c31ca2 | dc71a484893cdf604b6dd52ee46c1f8164ab5e7e | /lib/news-reader/sqlite3.scm | 2828588c2cf42272fe19d74aaf74c32eee459f0f | []
| no_license | ktakashi/news-reader | 14d94bf190aed5ec3bf45315a73458226147d951 | 998080a0e01aedc77f82cfda256acc87df694dd4 | refs/heads/master | 2021-01-17T17:55:45.672000 | 2017-05-03T12:37:10 | 2017-05-03T12:37:10 | 70,703,377 | 2 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 3,602 | scm | sqlite3.scm | ;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; lib/news-reader/sqlite3.scm - Id generator for SQLite3
;;;
;;; Copyright (c) 2016 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(library (news-reader sqlite3)
(export dialect-procedures
max-connection)
(import (rnrs)
(rnrs mutable-pairs)
(sagittarius)
(maquette connection)
(dbi)
(srfi :13)
(srfi :18))
(define max-connection 1)
(define (dialect-procedures) (values generator duplicate-insert))
;; in our table model, we don't use autoincrement keyword for
;; simplicity of SQL script. So what we do here is basically
;; manual sequence management.
(define-constant +table-lists+
"select tbl_name from sqlite_master where type = 'table'")
(define-constant +max-id+ "select max(id) from ")
(define (init-sequence dbi-conn)
(define table (make-eq-hashtable))
(define query (dbi-execute-query-using-connection! dbi-conn +table-lists+))
(dbi-do-fetch! (r query)
(let* ((n (string-downcase (vector-ref r 0)))
(q (dbi-execute-query-using-connection!
dbi-conn (string-append +max-id+ n))))
(let ((v (vector-ref (dbi-fetch! q) 0)))
(dbi-close q)
(hashtable-set! table (string->symbol n)
(cons (make-mutex) (if (null? v) 1 (+ v 1)))))))
(dbi-close query)
table)
(define (symbol-downcase s)
(string->symbol (string-downcase (symbol->string s))))
(define generator
(let ((mutex (make-mutex))
(sequence #f))
(lambda (conn table)
(define dbi-conn (maquette-connection-dbi-connection conn))
(unless sequence
(mutex-lock! mutex)
(unless sequence (set! sequence (init-sequence dbi-conn)))
(mutex-unlock! mutex))
(let* ((t (symbol-downcase table))
(p (hashtable-ref sequence t #f)))
(unless p (assertion-violation 'sqlite3-generator "unknown table" t))
(mutex-lock! (car p))
(let ((r (cdr p)))
(set-cdr! p (+ r 1))
(mutex-unlock! (car p))
r)))))
;; On SQLite3 we use insert or ignore
(define (duplicate-insert table uniques columns)
(format "INSERT OR IGNORE INTO ~a (~a) VALUES (~a)"
table
(string-join (map symbol->string columns) ", ")
(string-join (map (lambda (c) "?") columns) ", ")))
)
| false |
2bbe325d19e87457a5363a4fe4c5796614399ba6 | 9b2eb10c34176f47f7f490a4ce8412b7dd42cce7 | /lib-compat/r7rs-common-yuni/compat/eval.sls | 5090ecebb1f71f075b1315ebd453a44f458a8814 | [
"LicenseRef-scancode-public-domain",
"CC0-1.0"
]
| permissive | okuoku/yuni | 8be584a574c0597375f023c70b17a5a689fd6918 | 1859077a3c855f3a3912a71a5283e08488e76661 | refs/heads/master | 2023-07-21T11:30:14.824239 | 2023-06-11T13:16:01 | 2023-07-18T16:25:22 | 17,772,480 | 36 | 6 | CC0-1.0 | 2020-03-29T08:16:00 | 2014-03-15T09:53:13 | Scheme | UTF-8 | Scheme | false | false | 108 | sls | eval.sls | (library (r7rs-common-yuni compat eval)
(export eval environment)
(import (scheme eval)))
| false |
5121f3f37cf2c27712b921de1c2512d13d4d979f | f17ecf48249d4fba76d276ba35248a70b7fa347e | /schemep3-main-menu.scm | d179702928de200b329d4e805827a3b33721cdff | []
| no_license | liulanghaitun/schemep3 | 8f7832d32cc4cf73936ba7a5d6afaa6278b37bb7 | 513a3f2bbe164f510d1d4c6edd02eaadab75ff0c | refs/heads/master | 2023-03-16T10:01:43.121901 | 2019-08-27T00:36:09 | 2019-08-27T00:36:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,847 | scm | schemep3-main-menu.scm | #lang scheme/gui
(provide
main-menu:add
main-menu:find
main-menu:find-or-create
main-menu:generate
make-main-menu-separator
make-main-menu-item
make-main-menu-group
make-main-menu-checkable-item
main-menu:group:file
main-menu:group:view
main-menu:group:playlist
main-menu:group:playback
)
(require srfi/2)
(define main-menu-entity%
(class object%
(init-field label)
(init-field (action #f))
(define/public (instantiate parent-menu)
(void))
(super-new)))
(define main-menu-item%
(class main-menu-entity%
(define/override (instantiate parent)
(new menu-item%
(parent parent)
(label (get-field label this))
(callback
(lambda (menu event)
((get-field action this))))))
(super-new)))
(define main-menu-checkable-item%
(class main-menu-entity%
(init-field (checked #f))
(init-field (init-callback #f))
(define/override (instantiate parent)
(let ([menu-item
(new checkable-menu-item%
(parent parent)
(label (get-field label this))
(checked (get-field checked this))
(callback
(lambda (menu event)
((get-field action this) (send menu is-checked?)))))])
(when init-callback
(init-callback menu-item))
menu-item))
(super-new)))
(define main-menu-separator%
(class main-menu-entity%
(define/override (instantiate parent)
(new separator-menu-item%
(parent parent)))
(super-new)))
(define main-menu-group%
(class main-menu-entity%
(init-field (children (list)))
(define/override (instantiate parent)
(let ((submenu
(new menu%
(parent parent)
(label (get-field label this)))))
(for ((child (get-field children this)))
(send child instantiate submenu))))
(define/public (add item)
(set! children (append (get-field children this) (list item))))
(super-new)))
(define (make-main-menu-group label children)
(new main-menu-group% [label label] [children children]))
(define (make-main-menu-item label action)
(new main-menu-item% [label label] [action action]))
(define (make-main-menu-separator)
(new main-menu-separator% [label #f]))
(define (make-main-menu-checkable-item label action checked (init-callback #f))
(new main-menu-checkable-item% [label label] [action action] [checked checked]
[init-callback init-callback]))
(define main-menu-top-level (make-main-menu-group "top-level" (list)))
(define (main-menu:generate parent)
(for ((item (get-field children main-menu-top-level)))
(send item instantiate parent)))
(define (main-menu:add parent group-or-item)
(let ([real-parent (or parent main-menu-top-level)])
(send real-parent add group-or-item)))
(define (main-menu:find label)
(define (find-in-group group)
(if (equal? (get-field label group) label)
group
(for/or ((child (get-field children group)))
(and
(is-a? child main-menu-group%)
(find-in-group child)))))
(find-in-group main-menu-top-level))
(define (main-menu:create label)
(let ([g (make-main-menu-group label (list))])
(main-menu:add #f g)
g))
(define (main-menu:find-or-create label)
(or (main-menu:find label)
(main-menu:create label)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define main-menu:group:file (main-menu:create "&File"))
(define main-menu:group:playback (main-menu:create "&Playback"))
(define main-menu:group:playlist (main-menu:create "Play&list"))
(define main-menu:group:view (main-menu:create "&View"))
| false |
8027d80e319b83855116873aa671687922b3e90f | c3523080a63c7e131d8b6e0994f82a3b9ed901ce | /hertfordstreet/schemes/dontpanic.scm | 25a4132f9a8b644238150603af31dd5125da75f9 | []
| no_license | johnlawrenceaspden/hobby-code | 2c77ffdc796e9fe863ae66e84d1e14851bf33d37 | d411d21aa19fa889add9f32454915d9b68a61c03 | refs/heads/master | 2023-08-25T08:41:18.130545 | 2023-08-06T12:27:29 | 2023-08-06T12:27:29 | 377,510 | 6 | 4 | null | 2023-02-22T00:57:49 | 2009-11-18T19:57:01 | Clojure | UTF-8 | Scheme | false | false | 106 | scm | dontpanic.scm | (define square (lambda (x) (* y y)))
(define my-fcn (lambda (x y) (+ (* x x) (square y))))
(my-fcn 3 5) | false |
aefe0f1180a769c698c1102869089b0c8e7d3fcb | 7460741268185d205c34604a6f792b80ea0e2fa6 | /chez/lift/effekt.ss | d489d179b1624edcc27189f9d2943ab65ee531f9 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
]
| permissive | long-long-float/effekt | 359ae7cac3769be9cf7d1433e404eced2627335d | d471192ba6e02d269d8e8126d56125663e1ea523 | refs/heads/master | 2023-01-21T14:08:18.375961 | 2020-11-17T15:21:55 | 2020-11-17T15:21:55 | 294,625,877 | 0 | 0 | MIT | 2020-10-14T10:40:55 | 2020-09-11T07:31:43 | null | UTF-8 | Scheme | false | false | 2,599 | ss | effekt.ss | (define-syntax delayed
(syntax-rules ()
[(_ e ...)
(lambda (k) (k
(begin e ...)))]))
(define (pure v)
(lambda (k) (k v)))
; (then m a n) -> (lambda (k) (m (lambda (a) (n k))))
(define-syntax then
(syntax-rules ()
[(_ m a f1 ...)
(lambda (k) (m (lambda (a) ((let () f1 ...) k))))]))
(define ($then m f)
(lambda (k) (m (lambda (a) ((f a) k)))))
(define (here x) x)
(define (while cond exp)
($then cond (lambda (c)
(if c ($then exp (lambda (_) (while cond exp))) (pure #f)))))
; (define-syntax lift
; (syntax-rules ()
; [(_ m)
; (lambda (k1)
; (lambda (k2)
; (m (lambda (a) ((k1 a) k2)))))]))
(define (lift m)
(lambda (k1)
(lambda (k2)
(m (lambda (a) ((k1 a) k2))))))
(define (id x) x)
; (define (reset m) (m (lambda (v) (lambda (k) (k v)))))
(define-syntax reset
(syntax-rules ()
[(_ m)
(m (lambda (v) (lambda (k) (k v))))]))
(define (run m) (m id))
; ;; EXAMPLE
; ; (handle ([Fail_22 (Fail_109 () resume_120 (Nil_74))])
; ; (let ((tmp86_121 ((Fail_109 Fail_22))))
; ; (Cons_73 tmp86_121 (Nil_74))))
; capabilities first take evidence than require selection!
(define-syntax handle
(syntax-rules ()
[(_ ((cap1 (op1 (arg1 ...) kid exp) ...) ...) body)
(reset ((body lift)
(lambda (ev) (cap1 (define-effect-op ev (arg1 ...) kid exp) ...)) ...))]))
(define-syntax state
(syntax-rules ()
[(_ effid getid setid init body)
($then init (lambda (s)
(define cell (box s))
(define (cap ev) cell)
(define (getid c) (lambda () (lambda (k) (k (unbox c)))))
(define (setid c) (lambda (s*) (lambda (k) (set-box! c s*) (k #f))))
(define (lift m) (lambda (k)
(define backup (unbox cell))
(m (lambda (a)
(set-box! cell backup)
(k a)))))
((body lift) cap)))]))
(define-syntax define-effect-op
(syntax-rules ()
[(_ ev1 (arg1 ...) kid exp ...)
(lambda (arg1 ...)
; we apply the outer evidence to the body of the operation
(ev1 (lambda (resume)
; k itself also gets evidence!
(let ([kid (lambda (ev) (lambda (v) (ev (resume v))))])
exp ...))))]))
(define-syntax nested-helper
(syntax-rules ()
[(_ (ev) acc) (ev acc)]
[(_ (ev1 ev2 ...) acc)
(nested-helper (ev2 ...) (ev1 acc))]))
(define-syntax nested
(syntax-rules ()
[(_ ev1 ...) (lambda (m) (nested-helper (ev1 ...) m))]))
; should also work for handlers / capabilities
(define (lift-block f ev)
(lambda (ev2) (f (nested ev ev2)))) | true |
3f0f6c71d4d5f6babd906842b3c04966b310f1f3 | 0011048749c119b688ec878ec47dad7cd8dd00ec | /src/006/solution.scm | 8738a16c8057f6d01c40334f3b88f4766d5489f7 | [
"0BSD"
]
| permissive | turquoise-hexagon/euler | e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5 | 852ae494770d1c70cd2621d51d6f1b8bd249413c | refs/heads/master | 2023-08-08T21:01:01.408876 | 2023-07-28T21:30:54 | 2023-07-28T21:30:54 | 240,263,031 | 8 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 168 | scm | solution.scm | (define (solve n)
(- (expt (quotient (* n (+ n 1)) 2) 2)
(quotient (* n (+ n 1) (+ (* 2 n) 1)) 6)))
(let ((_ (solve 100)))
(print _) (assert (= _ 25164150)))
| false |
c2fe115bed318c09f90636177e1fc34a6abdef93 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /mscorlib/system/runtime/remoting/contexts/context.sls | 87456e4c4f3af64b1dea70e4b0ee09efd3c29763 | []
| no_license | futsuki/ironscheme-port | 2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5 | 4e7a81b0fbeac9a47440464988e53fb118286c54 | refs/heads/master | 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,642 | sls | context.sls | (library (system runtime remoting contexts context)
(export new
is?
context?
do-call-back
set-data
register-dynamic-property?
get-data
to-string
unregister-dynamic-property?
set-property
allocate-named-data-slot
get-named-data-slot
allocate-data-slot
free-named-data-slot
get-property
freeze
default-context
context-id
context-properties)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.Runtime.Remoting.Contexts.Context a ...)))))
(define (is? a) (clr-is System.Runtime.Remoting.Contexts.Context a))
(define (context? a)
(clr-is System.Runtime.Remoting.Contexts.Context a))
(define-method-port
do-call-back
System.Runtime.Remoting.Contexts.Context
DoCallBack
(System.Void System.Runtime.Remoting.Contexts.CrossContextDelegate))
(define-method-port
set-data
System.Runtime.Remoting.Contexts.Context
SetData
(static: System.Void System.LocalDataStoreSlot System.Object))
(define-method-port
register-dynamic-property?
System.Runtime.Remoting.Contexts.Context
RegisterDynamicProperty
(static:
System.Boolean
System.Runtime.Remoting.Contexts.IDynamicProperty
System.ContextBoundObject
System.Runtime.Remoting.Contexts.Context))
(define-method-port
get-data
System.Runtime.Remoting.Contexts.Context
GetData
(static: System.Object System.LocalDataStoreSlot))
(define-method-port
to-string
System.Runtime.Remoting.Contexts.Context
ToString
(System.String))
(define-method-port
unregister-dynamic-property?
System.Runtime.Remoting.Contexts.Context
UnregisterDynamicProperty
(static:
System.Boolean
System.String
System.ContextBoundObject
System.Runtime.Remoting.Contexts.Context))
(define-method-port
set-property
System.Runtime.Remoting.Contexts.Context
SetProperty
(System.Void System.Runtime.Remoting.Contexts.IContextProperty))
(define-method-port
allocate-named-data-slot
System.Runtime.Remoting.Contexts.Context
AllocateNamedDataSlot
(static: System.LocalDataStoreSlot System.String))
(define-method-port
get-named-data-slot
System.Runtime.Remoting.Contexts.Context
GetNamedDataSlot
(static: System.LocalDataStoreSlot System.String))
(define-method-port
allocate-data-slot
System.Runtime.Remoting.Contexts.Context
AllocateDataSlot
(static: System.LocalDataStoreSlot))
(define-method-port
free-named-data-slot
System.Runtime.Remoting.Contexts.Context
FreeNamedDataSlot
(static: System.Void System.String))
(define-method-port
get-property
System.Runtime.Remoting.Contexts.Context
GetProperty
(System.Runtime.Remoting.Contexts.IContextProperty System.String))
(define-method-port
freeze
System.Runtime.Remoting.Contexts.Context
Freeze
(System.Void))
(define-field-port
default-context
#f
#f
(static: property:)
System.Runtime.Remoting.Contexts.Context
DefaultContext
System.Runtime.Remoting.Contexts.Context)
(define-field-port
context-id
#f
#f
(property:)
System.Runtime.Remoting.Contexts.Context
ContextID
System.Int32)
(define-field-port
context-properties
#f
#f
(property:)
System.Runtime.Remoting.Contexts.Context
ContextProperties
System.Runtime.Remoting.Contexts.IContextProperty[]))
| true |
13dbe5143e1d1991c341df5c393b0cdb107df1ee | 6f86602ac19983fcdfcb2710de6e95b60bfb0e02 | /input/exercises/anagram/test.ss | 95193a1e0725264c38b6e07e52f36a6ee923af5c | [
"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 | 789 | ss | test.ss |
(define (parse-test test)
`(test-success ,(lookup 'description test)
(lambda (xs ys)
(equal? (list-sort string<? xs)
(list-sort string<? ys)))
anagram
'(,@(map cdr (lookup 'input test)))
'(,@(lookup 'expected test))))
(define (spec->tests spec)
(map parse-test (lookup 'cases spec)))
(let ((spec (get-test-specification 'anagram)))
(put-problem!
'anagram
`((test . ,(spec->tests spec))
(version . ,(lookup 'version spec))
(skeleton . "anagram.scm")
(solution . "example.scm")
(stubs anagram)
(markdown . ,(splice-exercism 'anagram '(sentence "For purposes
of this exercise, a word is not considered to be an anagram of
itself."))))))
| false |
ef58400a4e52b19d14f63009111b8b6f772ddc3c | 4b480cab3426c89e3e49554d05d1b36aad8aeef4 | /chapter-02/ex2.33-obsidian.scm | cea20c501e9aec42496c48fd5ca4b0293441f5cd | []
| 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 | 573 | scm | ex2.33-obsidian.scm | (load "../misc/scheme-test.scm")
(define (map2 p sequence)
(foldr (lambda (x y)
(cons (p x) y))
null sequence))
(define (append2 seq1 seq2)
(foldr cons
seq2
seq1))
(define (length2 sequence)
(foldr (λ (x y) (+ 1 y))
0
sequence))
(run (make-testcase
'(assert-equal? (+ 1 1) 2)
'(assert-equal? (map2 (λ(x)(* x x)) '(1 2 3 4)) '(1 4 9 16))
'(assert-equal? (append2 '(1 2 3 4) '(5 6 7 8)) '(1 2 3 4 5 6 7 8))
'(assert-equal? (length2 '(1 2 3 4)) 4)
)) | false |
e4582dc41c852488a8497a825d1020a9bb1819c3 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /mscorlib/system/threading/host-execution-context.sls | 20cedf24cd0fc98e2394086a5167b2c142c49dfa | []
| 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 | 589 | sls | host-execution-context.sls | (library (system threading host-execution-context)
(export new is? host-execution-context? create-copy)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.Threading.HostExecutionContext a ...)))))
(define (is? a) (clr-is System.Threading.HostExecutionContext a))
(define (host-execution-context? a)
(clr-is System.Threading.HostExecutionContext a))
(define-method-port
create-copy
System.Threading.HostExecutionContext
CreateCopy
(System.Threading.HostExecutionContext)))
| true |
de1fa00d35cb2a0eed61d324ea39604b2b5b9a5f | f08220a13ec5095557a3132d563a152e718c412f | /logrotate/skel/usr/share/guile/2.0/system/repl/server.scm | 9ece94700b3b01cc4e44ca352d033a46c5550664 | [
"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 | 13,637 | scm | server.scm | ;;; Repl server
;; Copyright (C) 2003, 2010, 2011, 2014, 2016 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
;;; Code:
(define-module (system repl server)
#:use-module (system repl repl)
#:use-module (ice-9 threads)
#:use-module (ice-9 rdelim)
#:use-module (ice-9 match)
#:use-module (ice-9 iconv)
#:use-module (rnrs bytevectors)
#:use-module (rnrs io ports)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26) ; cut
#:export (make-tcp-server-socket
make-unix-domain-server-socket
run-server
spawn-server
stop-server-and-clients!))
;; List of pairs of the form (SOCKET . FORCE-CLOSE), where SOCKET is a
;; socket port, and FORCE-CLOSE is a thunk that forcefully shuts down
;; the socket.
(define *open-sockets* '())
(define sockets-lock (make-mutex))
;; WARNING: it is unsafe to call 'close-socket!' from another thread.
;; Note: although not exported, this is used by (system repl coop-server)
(define (close-socket! s)
(with-mutex sockets-lock
(set! *open-sockets* (assq-remove! *open-sockets* s)))
;; Close-port could block or raise an exception flushing buffered
;; output. Hmm.
(close-port s))
;; Note: although not exported, this is used by (system repl coop-server)
(define (add-open-socket! s force-close)
(with-mutex sockets-lock
(set! *open-sockets* (acons s force-close *open-sockets*))))
(define (stop-server-and-clients!)
(cond
((with-mutex sockets-lock
(match *open-sockets*
(() #f)
(((s . force-close) . rest)
(set! *open-sockets* rest)
force-close)))
=> (lambda (force-close)
(force-close)
(stop-server-and-clients!)))))
(define* (make-tcp-server-socket #:key
(host #f)
(addr (if host (inet-aton host) INADDR_LOOPBACK))
(port 37146))
(let ((sock (socket PF_INET SOCK_STREAM 0)))
(setsockopt sock SOL_SOCKET SO_REUSEADDR 1)
(bind sock AF_INET addr port)
sock))
(define* (make-unix-domain-server-socket #:key (path "/tmp/guile-socket"))
(let ((sock (socket PF_UNIX SOCK_STREAM 0)))
(setsockopt sock SOL_SOCKET SO_REUSEADDR 1)
(bind sock AF_UNIX path)
sock))
;; List of errno values from 'select' or 'accept' that should lead to a
;; retry in 'run-server'.
(define errs-to-retry
(delete-duplicates
(filter-map (lambda (name)
(and=> (module-variable the-root-module name)
variable-ref))
'(EINTR EAGAIN EWOULDBLOCK))))
(define* (run-server #:optional (server-socket (make-tcp-server-socket)))
(run-server* server-socket serve-client))
;; Note: although not exported, this is used by (system repl coop-server)
(define (run-server* server-socket serve-client)
;; We use a pipe to notify the server when it should shut down.
(define shutdown-pipes (pipe))
(define shutdown-read-pipe (car shutdown-pipes))
(define shutdown-write-pipe (cdr shutdown-pipes))
;; 'shutdown-server' is called by 'stop-server-and-clients!'.
(define (shutdown-server)
(display #\! shutdown-write-pipe)
(force-output shutdown-write-pipe))
(define monitored-ports
(list server-socket
shutdown-read-pipe))
(define (accept-new-client)
(catch #t
(lambda ()
(let ((ready-ports (car (select monitored-ports '() '()))))
;; If we've been asked to shut down, return #f.
(and (not (memq shutdown-read-pipe ready-ports))
(accept server-socket))))
(lambda k-args
(let ((err (system-error-errno k-args)))
(cond
((memv err errs-to-retry)
(accept-new-client))
(else
(warn "Error accepting client" k-args)
;; Retry after a timeout.
(sleep 1)
(accept-new-client)))))))
;; Put the socket into non-blocking mode.
(fcntl server-socket F_SETFL
(logior O_NONBLOCK
(fcntl server-socket F_GETFL)))
(sigaction SIGPIPE SIG_IGN)
(add-open-socket! server-socket shutdown-server)
(listen server-socket 5)
(let lp ((client (accept-new-client)))
;; If client is false, we are shutting down.
(if client
(let ((client-socket (car client))
(client-addr (cdr client)))
(make-thread serve-client client-socket client-addr)
(lp (accept-new-client)))
(begin (close shutdown-write-pipe)
(close shutdown-read-pipe)
(close server-socket)))))
(define* (spawn-server #:optional (server-socket (make-tcp-server-socket)))
(make-thread run-server server-socket))
(define (serve-client client addr)
(let ((thread (current-thread)))
;; Close the socket when this thread exits, even if canceled.
(set-thread-cleanup! thread (lambda () (close-socket! client)))
;; Arrange to cancel this thread to forcefully shut down the socket.
(add-open-socket! client (lambda () (cancel-thread thread))))
(guard-against-http-request client)
(with-continuation-barrier
(lambda ()
(parameterize ((current-input-port client)
(current-output-port client)
(current-error-port client)
(current-warning-port client))
(with-fluids ((*repl-stack* '()))
(start-repl))))))
;;;
;;; The following code adds protection to Guile's REPL servers against
;;; HTTP inter-protocol exploitation attacks, a scenario whereby an
;;; attacker can, via an HTML page, cause a web browser to send data to
;;; TCP servers listening on a loopback interface or private network.
;;; See <https://en.wikipedia.org/wiki/Inter-protocol_exploitation> and
;;; <https://www.jochentopf.com/hfpa/hfpa.pdf>, The HTML Form Protocol
;;; Attack (2001) by Tochen Topf <[email protected]>.
;;;
;;; Here we add a procedure to 'before-read-hook' that looks for a possible
;;; HTTP request-line in the first line of input from the client socket. If
;;; present, the socket is drained and closed, and a loud warning is written
;;; to stderr (POSIX file descriptor 2).
;;;
(define (with-temporary-port-encoding port encoding thunk)
"Call THUNK in a dynamic environment in which the encoding of PORT is
temporarily set to ENCODING."
(let ((saved-encoding #f))
(dynamic-wind
(lambda ()
(unless (port-closed? port)
(set! saved-encoding (port-encoding port))
(set-port-encoding! port encoding)))
thunk
(lambda ()
(unless (port-closed? port)
(set! encoding (port-encoding port))
(set-port-encoding! port saved-encoding))))))
(define (with-saved-port-line+column port thunk)
"Save the line and column of PORT before entering THUNK, and restore
their previous values upon normal or non-local exit from THUNK."
(let ((saved-line #f) (saved-column #f))
(dynamic-wind
(lambda ()
(unless (port-closed? port)
(set! saved-line (port-line port))
(set! saved-column (port-column port))))
thunk
(lambda ()
(unless (port-closed? port)
(set-port-line! port saved-line)
(set-port-column! port saved-column))))))
(define (drain-input-and-close socket)
"Drain input from SOCKET using ISO-8859-1 encoding until it would block,
and then close it. Return the drained input as a string."
(dynamic-wind
(lambda ()
;; Enable full buffering mode on the socket to allow
;; 'get-bytevector-some' to return non-trivial chunks.
(setvbuf socket _IOFBF))
(lambda ()
(let loop ((chunks '()))
(let ((result (and (char-ready? socket)
(get-bytevector-some socket))))
(if (bytevector? result)
(loop (cons (bytevector->string result "ISO-8859-1")
chunks))
(string-concatenate-reverse chunks)))))
(lambda ()
;; Close the socket even in case of an exception.
(close-port socket))))
(define permissive-http-request-line?
;; This predicate is deliberately permissive
;; when checking the Request-URI component.
(let ((cs (ucs-range->char-set #x20 #x7E))
(rx (make-regexp
(string-append
"^(OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT) "
"[^ ]+ "
"HTTP/[0-9]+.[0-9]+$"))))
(lambda (line)
"Return true if LINE might plausibly be an HTTP request-line,
otherwise return #f."
;; We cannot simplify this to a simple 'regexp-exec', because
;; 'regexp-exec' cannot cope with NUL bytes.
(and (string-every cs line)
(regexp-exec rx line)))))
(define (check-for-http-request socket)
"Check for a possible HTTP request in the initial input from SOCKET.
If one is found, close the socket and print a report to STDERR (fdes 2).
Otherwise, put back the bytes."
;; Temporarily set the port encoding to ISO-8859-1 to allow lossless
;; reading and unreading of the first line, regardless of what bytes
;; are present. Note that a valid HTTP request-line contains only
;; ASCII characters.
(with-temporary-port-encoding socket "ISO-8859-1"
(lambda ()
;; Save the port 'line' and 'column' counters and later restore
;; them, since unreading what we read is not sufficient to do so.
(with-saved-port-line+column socket
(lambda ()
;; Read up to (but not including) the first CR or LF.
;; Although HTTP mandates CRLF line endings, we are permissive
;; here to guard against the possibility that in some
;; environments CRLF might be converted to LF before it
;; reaches us.
(match (read-delimited "\r\n" socket 'peek)
((? eof-object?)
;; We found EOF before any input. Nothing to do.
'done)
((? permissive-http-request-line? request-line)
;; The input from the socket began with a plausible HTTP
;; request-line, which is unlikely to be legitimate and may
;; indicate an possible break-in attempt.
;; First, set the current port parameters to a void-port,
;; to avoid sending any more data over the socket, to cause
;; the REPL reader to see EOF, and to swallow any remaining
;; output gracefully.
(let ((void-port (%make-void-port "rw")))
(current-input-port void-port)
(current-output-port void-port)
(current-error-port void-port)
(current-warning-port void-port))
;; Read from the socket until we would block,
;; and then close it.
(let ((drained-input (drain-input-and-close socket)))
;; Print a report to STDERR (POSIX file descriptor 2).
;; XXX Can we do better here?
(call-with-port (dup->port 2 "w")
(cut format <> "
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ POSSIBLE BREAK-IN ATTEMPT ON THE REPL SERVER @@
@@ BY AN HTTP INTER-PROTOCOL EXPLOITATION ATTACK. See: @@
@@ <https://en.wikipedia.org/wiki/Inter-protocol_exploitation> @@
@@ Possible HTTP request received: ~S
@@ The associated socket has been closed. @@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"
(string-append request-line
drained-input)))))
(start-line
;; The HTTP request-line was not found, so
;; 'unread' the characters that we have read.
(unread-string start-line socket))))))))
(define (guard-against-http-request socket)
"Arrange for the Guile REPL to check for an HTTP request in the
initial input from SOCKET, in which case the socket will be closed.
This guards against HTTP inter-protocol exploitation attacks, a scenario
whereby an attacker can, via an HTML page, cause a web browser to send
data to TCP servers listening on a loopback interface or private
network."
(%set-port-property! socket 'guard-against-http-request? #t))
(define* (maybe-check-for-http-request
#:optional (socket (current-input-port)))
"Apply check-for-http-request to SOCKET if previously requested by
guard-against-http-request. This procedure is intended to be added to
before-read-hook."
(when (%port-property socket 'guard-against-http-request?)
(check-for-http-request socket)
(unless (port-closed? socket)
(%set-port-property! socket 'guard-against-http-request? #f))))
;; Install the hook.
(add-hook! before-read-hook
maybe-check-for-http-request)
;;; Local Variables:
;;; eval: (put 'with-temporary-port-encoding 'scheme-indent-function 2)
;;; eval: (put 'with-saved-port-line+column 'scheme-indent-function 1)
;;; End:
| false |
55b9340244e4d1b86adcafe764700727260ad277 | 46244bb6af145cb393846505f37bf576a8396aa0 | /sicp/2_11.scm | 16530cd8900ce75291a8b3b6cee21bacc4b2a6eb | []
| no_license | aoeuidht/homework | c4fabfb5f45dbef0874e9732c7d026a7f00e13dc | 49fb2a2f8a78227589da3e5ec82ea7844b36e0e7 | refs/heads/master | 2022-10-28T06:42:04.343618 | 2022-10-15T15:52:06 | 2022-10-15T15:52:06 | 18,726,877 | 4 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 1,220 | scm | 2_11.scm | #lang racket
; Exercise 2.11. In passing, Ben also cryptically comments: ``By testing the signs of the endpoints of the intervals,
; it is possible to break mul-interval into nine cases,
; only one of which requires more than two multiplications.''
; Rewrite this procedure using Ben's suggestion.
; Answer:
; Here I will list the nine scenarios (asume x has bigger width than y):
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; x |__________________________|
; y |______|
; And only the following scenario needs more than 2 multiplication operation
; x |__________________________|
; y |______| | false |
77efe1456da7256069004788a28eacbd634e5045 | bda698f1855d5be6da246d22bd2a3d8457c5a43b | /pkg-config-augeas.scm | 9e69150071e3a6385a1e792137d97015b0f6327f | [
"MIT"
]
| permissive | ursetto/augeas | b5b1abf481a0b07902d72d20e321d685d74b0cf9 | 66fe579a722c3777ca0d7c50e4392d26a65d9cc2 | refs/heads/master | 2021-01-01T05:47:37.467266 | 2012-09-03T23:19:23 | 2012-09-03T23:19:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 705 | scm | pkg-config-augeas.scm | (use posix srfi-13 files)
(define pkg-config-version
(with-input-from-pipe "pkg-config --version" read-line))
(when (eof-object? pkg-config-version)
(error "Unable to locate pkg-config"))
(define augeas-version
(with-input-from-pipe "pkg-config --modversion augeas" read-line))
(when (eof-object? augeas-version)
(error "Unable to obtain augeas version"))
(define augeas-cflags
(with-input-from-pipe "pkg-config --cflags augeas" read-line))
(define augeas-ldflags
(with-input-from-pipe "pkg-config --libs augeas" read-line))
(define augeas-options
(string-append
(string-join (string-split augeas-cflags) " -C " 'prefix)
(string-join (string-split augeas-ldflags) " -L " 'prefix)))
| false |
97decc4e55ce0f189eb279e3fc3dc4e0691377f6 | 53cb8287b8b44063adcfbd02f9736b109e54f001 | /printers/print-valdefs.scm | 908adea503652fe61d9f41b715e0c179b6d1e7a4 | []
| no_license | fiddlerwoaroof/yale-haskell-reboot | 72aa8fcd2ab7346a4990795621b258651c6d6c39 | 339b7d85e940db0b8cb81759e44abbb254c54aad | refs/heads/master | 2021-06-22T10:32:25.076594 | 2020-10-30T00:00:31 | 2020-10-30T00:00:31 | 92,361,235 | 3 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 5,304 | scm | print-valdefs.scm | ;;; print-valdefs.scm -- print AST structures for local declarations
;;;
;;; author : Sandra Loosemore
;;; date : 14 Jan 1992
;;;
;;; This file corresponds to ast/valdef-structs.scm.
;;;
;;;
(define-ast-printer signdecl (object xp)
(with-ast-block (xp)
(write-delimited-list (signdecl-vars object) xp (function write) "," "" "")
(write-string " ::" xp)
(write-whitespace xp)
(write (signdecl-signature object) xp)))
;;; This interacts with the layout rule stuff. See util.scm.
(define-ast-printer valdef (object xp)
(let ((lhs (valdef-lhs object))
(definitions (valdef-definitions object)))
(write-definition lhs (car definitions) xp)
(dolist (d (cdr definitions))
(if (dynamic *print-pretty*)
(pprint-newline 'mandatory xp)
(write-string "; " xp))
(write-definition lhs d xp))))
(define (write-definition lhs d xp)
(with-ast-block (xp)
(let ((args (single-fun-def-args d))
(rhs-list (single-fun-def-rhs-list d))
(where-decls (single-fun-def-where-decls d))
(infix? (single-fun-def-infix? d)))
(write-lhs lhs args infix? xp)
(write-rhs rhs-list xp)
(write-wheredecls where-decls xp)
)))
(define (write-lhs lhs args infix? xp)
(cond ((null? args)
;; pattern definition
(write-apat lhs xp)
)
;; If there are args, the lhs is always a var-pat pointing to a
;; var-ref. The infix? slot from the single-fun-def must override
;; the slot on the var-ref, since there can be a mixture of
;; infix and prefix definitions for the same lhs.
(infix?
;; operator definition
(when (not (null? (cddr args)))
(write-char #\( xp))
(write-apat (car args) xp)
(write-whitespace xp)
(write-varop (var-ref-name (var-pat-var lhs)) xp)
(write-whitespace xp)
(write-apat (cadr args) xp)
(when (not (null? (cddr args)))
(write-char #\) xp)
(write-whitespace xp)
(write-delimited-list (cddr args) xp (function write-apat)
"" "" "")))
(else
;; normal prefix function definition
(write-varid (var-ref-name (var-pat-var lhs)) xp)
(write-whitespace xp)
(write-delimited-list args xp (function write-apat) "" "" ""))
))
(define (write-rhs rhs-list xp)
(let ((guard (guarded-rhs-guard (car rhs-list)))
(rhs (guarded-rhs-rhs (car rhs-list))))
(when (not (is-type? 'omitted-guard guard))
(write-string " | " xp)
(write guard xp))
(write-string " =" xp)
(write-whitespace xp)
(write rhs xp)
(when (not (null? (cdr rhs-list)))
(write-newline xp)
(write-rhs (cdr rhs-list) xp))))
;;; Pattern printers
;;; As per jcp suggestion, don't put whitespace after @; line break comes
;;; before, not after (as is the case for other infix-style punctuation).
(define-ast-printer as-pat (object xp)
(with-ast-block (xp)
(write (as-pat-var object) xp)
(write-whitespace xp)
(write-string "@" xp)
(write-apat (as-pat-pattern object) xp)))
(define (write-apat pat xp)
(if (or (is-type? 'apat pat)
(is-type? 'pp-pat-plus pat) ; hack per jcp
(and (is-type? 'pcon pat)
(or (null? (pcon-pats pat))
(eq? (pcon-con pat) (core-symbol "UnitConstructor"))
(is-tuple-constructor? (pcon-con pat)))))
(write pat xp)
(begin
(write-char #\( xp)
(write pat xp)
(write-char #\) xp))))
(define-ast-printer irr-pat (object xp)
(write-string "~" xp)
(write-apat (irr-pat-pattern object) xp))
(define-ast-printer var-pat (object xp)
(write (var-pat-var object) xp))
(define-ast-printer wildcard-pat (object xp)
(declare (ignore object))
(write-char #\_ xp))
(define-ast-printer const-pat (object xp)
(write (const-pat-value object) xp))
(define-ast-printer plus-pat (object xp)
(write (plus-pat-pattern object) xp)
(write-string " + " xp)
(write (plus-pat-k object) xp))
(define-ast-printer pcon (object xp)
(let ((name (pcon-name object))
(pats (pcon-pats object))
(infix? (pcon-infix? object))
(def (pcon-con object)))
(cond ((eq? def (core-symbol "UnitConstructor"))
(write-string "()" xp))
((is-tuple-constructor? def)
(write-commaized-list pats xp))
((null? pats)
(if infix?
;; infix pcon with no arguments can happen inside pp-pat-list
;; before precedence parsing happens.
(write-conop name xp)
(write-conid name xp)))
(infix?
;; This could be smarter about dealing with precedence of patterns.
(with-ast-block (xp)
(write-apat (car pats) xp)
(write-whitespace xp)
(write-conop name xp)
(write-whitespace xp)
(write-apat (cadr pats) xp)))
(else
(with-ast-block (xp)
(write-conid name xp)
(write-whitespace xp)
(write-delimited-list pats xp (function write-apat) "" "" "")))
)))
(define-ast-printer list-pat (object xp)
(write-delimited-list
(list-pat-pats object) xp (function write) "," "[" "]"))
(define-ast-printer pp-pat-list (object xp)
(write-delimited-list (pp-pat-list-pats object) xp (function write-apat)
"" "" ""))
(define-ast-printer pp-pat-plus (object xp)
(declare (ignore object))
(write-string "+ " xp))
(define-ast-printer pp-pat-negated (object xp)
(declare (ignore object))
(write-string "-" xp))
| false |
0039fa5b419d044b06fce8abcaa7f6cbd9ea0986 | 38d314f38e2e16816af7d992f3470d9e1420dcc3 | /stream/stream.import.scm | 987655f0a1290dcd6d53a0909d58a1014558a584 | []
| no_license | Zeta611/project-euler | 968b8b303941c00b4c39e22f35a92a4f65dff214 | e24e19edc0f62a295e9d232e8ec4c852f93928ae | refs/heads/master | 2023-08-07T11:39:09.046250 | 2023-01-08T02:30:25 | 2023-01-08T02:30:25 | 146,746,689 | 2 | 0 | null | 2023-07-19T00:30:26 | 2018-08-30T12:31:40 | Python | UTF-8 | Scheme | false | false | 1,623 | scm | stream.import.scm | ;;;; stream.import.scm - GENERATED BY CHICKEN 5.1.0 -*- Scheme -*-
(scheme#eval
'(import-syntax
(only r7rs
begin
cond-expand
export
import
import-for-syntax
include
include-ci
syntax-rules)
scheme.base
scheme.lazy))
(import
(only r7rs
begin
cond-expand
export
import
import-for-syntax
include
include-ci
syntax-rules))
(##sys#register-compiled-module
'stream
'stream
(scheme#list '(divisible? . stream#divisible?))
'((stream-car . stream#stream-car)
(stream-cdr . stream#stream-cdr)
(stream-null? . stream#stream-null?)
(the-empty-stream . stream#the-empty-stream)
(stream-map . stream#stream-map)
(stream-filter . stream#stream-filter)
(stream-first . stream#stream-first)
(stream-take . stream#stream-take)
(stream-take-while . stream#stream-take-while)
(stream-accumulate . stream#stream-accumulate)
(stream-add . stream#stream-add)
(stream-zip . stream#stream-zip)
(integers-starting-from . stream#integers-starting-from)
(prime-stream . stream#prime-stream)
(prime? . stream#prime?)
(nat-stream . stream#nat-stream)
(stream-merge-weighted . stream#stream-merge-weighted)
(stream-weighted-tuples . stream#stream-weighted-tuples))
(scheme#list
(scheme#cons 'cons-stream (syntax-rules () ((_ a b) (cons a (delay b)))))
(scheme#cons
'|\x04r7rsstream|
(##sys#er-transformer (##core#lambda (x r c) (##core#undefined)))))
(scheme#list))
;; END OF FILE
| false |
d2e9768443302a709b4939329f843f2237c8f86e | 404799b4b2d5f83ee5304392826a69defc25da77 | /ex3-73.scm | f12a5bf5bd400b21f01bac3793726238a8dbb0b3 | []
| no_license | WuzhangFang/SICP-exercise | 38ae650c63e74bb7c6639bf984285e06743db925 | d9977009ec3e32a74edb13b4f13f6ebbbc44ab32 | refs/heads/master | 2020-04-16T16:01:18.058287 | 2019-10-01T21:52:40 | 2019-10-01T21:52:40 | 165,722,260 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 451 | scm | ex3-73.scm | ;; Exercise 3.73
(load "3.5.scm")
(define (integral integrand initial-value dt)
(define int
(cons-stream
initial-value
(add-streams (scale-stream integrand dt)
int)))
int)
(define (RC R C dt)
(lambda (i v0)
(add-streams (scale-stream i R)
(scale-stream (integral i v0 dt) (/ 1 C)))))
(define RC1 (RC 5 1 0.5))
(define voltage1 (RC1 integers 1))
(show-stream voltage1 10)
| false |
68b0e4b800511344cac8569292321c59f69ef6cb | 4e2bb57118132e64e450671470c132205457d937 | /weinholt/compression/huffman.sls | b03146167285be6bd1869d9ba5d039be1072c29d | [
"MIT"
]
| permissive | theschemer/industria | 8c4d01d018c885c0437e2575787ec987d800514f | 9c9e8c2b44280d3b6bda72154a5b48461aa2aba5 | refs/heads/master | 2021-08-31T23:32:29.440167 | 2017-12-01T23:24:01 | 2017-12-01T23:24:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 15,843 | sls | huffman.sls | ;; -*- mode: scheme; coding: utf-8 -*-
;; Copyright © 2009, 2010, 2012 Göran Weinholt <[email protected]>
;; Permission is hereby granted, free of charge, to any person obtaining a
;; copy of this software and associated documentation files (the "Software"),
;; to deal in the Software without restriction, including without limitation
;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;; and/or sell copies of the Software, and to permit persons to whom the
;; Software is furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;; DEALINGS IN THE SOFTWARE.
#!r6rs
;; Procedures for David Huffman's codes. These are suitable for use
;; with DEFLATE.
;; Version (0 1): Added canonical-codes->lookup-table that builds a
;; two-level lookup table.
(library (weinholt compression huffman)
(export reconstruct-codes
canonical-codes->simple-lookup-table
canonical-codes->lookup-table
get-next-code)
(import (except (rnrs) fxreverse-bit-field)
#;(only (srfi :13 strings) string-pad)
#;(only (srfi :1 lists) iota)
(weinholt compression bitstream))
(define-syntax trace
(syntax-rules ()
#;
((_ . args)
(begin
(for-each display (list . args))
(newline)))
((_ . args) (begin 'dummy))))
(define (fxreverse-bit-field61 v)
;; Based on <http://aggregate.org/MAGIC/#Bit Reversal>.
(assert (= (fixnum-width) 61))
(let* (;; Swap pairs of bits
(v (fxior (fxarithmetic-shift-right (fxand v #b101010101010101010101010101010101010101010101010101010101010) 1)
(fxarithmetic-shift-left (fxand v #b010101010101010101010101010101010101010101010101010101010101) 1)))
;; Swap 2-bit fields
(v (fxior (fxarithmetic-shift-right (fxand v #b110011001100110011001100110011001100110011001100110011001100) 2)
(fxarithmetic-shift-left (fxand v #b001100110011001100110011001100110011001100110011001100110011) 2)))
;; Swap 4-bit fields
(tmp1 (fxarithmetic-shift-right (fxand v #b111100000000000000000000000000000000000000000000000000000000) 56))
(v (fxior (fxarithmetic-shift-right (fxand v #b000011110000111100001111000011110000111100001111000011110000) 4)
(fxarithmetic-shift-left (fxand v #b000000001111000011110000111100001111000011110000111100001111) 4)))
;; Swap bytes
(tmp2 (fxarithmetic-shift-right (fxand v #b000011111111000000000000000000000000000000000000000000000000) 44))
(v (fxior (fxarithmetic-shift-right (fxand v #b111100000000111111110000000011111111000000001111111100000000) 8)
(fxarithmetic-shift-left (fxand v #b000000000000000000001111111100000000111111110000000011111111) 8)))
;; Swap 16-bit fields
(tmp3 (fxarithmetic-shift-right (fxand v #b000000000000111111111111111100000000000000000000000000000000) 20))
(v (fxior (fxarithmetic-shift-right (fxand v #b111111111111000000000000000011111111111111110000000000000000) 16)
(fxarithmetic-shift-left (fxand v #b000000000000000000000000000000000000000000001111111111111111) 16))))
;; Put together the pieces
(fxior (fxarithmetic-shift-left v 28)
tmp1 tmp2 tmp3)))
(define (fxreverse-bit-field30 v)
(assert (= (fixnum-width) 30))
(let* (;; Swap pairs of bits
(tmp1 (fxarithmetic-shift-right (fxand v #b10000000000000000000000000000) 28))
(v (fxior (fxarithmetic-shift-right (fxand v #b01010101010101010101010101010) 1)
(fxarithmetic-shift-left (fxand v #b00101010101010101010101010101) 1)))
;; Swap 2-bit fields
(v (fxior (fxarithmetic-shift-right (fxand v #b01100110011001100110011001100) 2)
(fxarithmetic-shift-left (fxand v #b10011001100110011001100110011) 2)))
;; Swap 4-bit fields
(tmp2 (fxarithmetic-shift-right (fxand v #b01111000000000000000000000000) 23))
(v (fxior (fxarithmetic-shift-right (fxand v #b10000111100001111000011110000) 4)
(fxarithmetic-shift-left (fxand v #b00000000011110000111100001111) 4)))
;; Swap bytes
(tmp3 (fxarithmetic-shift-right (fxand v #b00000111111110000000000000000) 11))
(v (fxior (fxarithmetic-shift-right (fxand v #b11111000000001111111100000000) 8)
(fxarithmetic-shift-left (fxand v #b00000000000000000000011111111) 8))))
;; Put together the pieces
(fxior (fxarithmetic-shift-left v 13)
tmp1 tmp2 tmp3)))
(define (fxreverse-bit-field v start end)
;; This is only for the benefit of Ikarus, which does not
;; implement this procedure as of 2010-01-03.
;; (assert (< -1 end (fixnum-width)))
;; (assert (<= 0 start end))
;; (assert (fixnum? v))
(cond ((= (fixnum-width) 61)
(fxior (fxarithmetic-shift-right
(fxreverse-bit-field61 (fxbit-field v start end))
(fx- 60 end))
(fxcopy-bit-field v start end 0)))
((= (fixnum-width) 30)
(fxior (fxarithmetic-shift-right
(fxreverse-bit-field30 (fxbit-field v start end))
(fx- 29 end))
(fxcopy-bit-field v start end 0)))
(else
(do ((i start (fx+ i 1))
(ret 0 (if (fxbit-set? v i)
(fxior ret (fxarithmetic-shift-left 1 (fx- (fx- end i) 1)))
ret)))
((fx=? i end)
(fxior (fxarithmetic-shift-left ret start)
(fxcopy-bit-field v start end 0)))))))
(define-syntax revtable
(lambda (x)
(define (rev v start end)
(do ((i start (fx+ i 1))
(ret 0 (if (fxbit-set? v i)
(fxior ret (fxarithmetic-shift-left 1 (fx- (fx- end i) 1)))
ret)))
((fx=? i end)
(fxior (fxarithmetic-shift-left ret start)
(fxcopy-bit-field v start end 0)))))
(syntax-case x ()
((table bits)
(let* ((bits (syntax->datum #'bits))
(len (fxarithmetic-shift-left 1 bits)))
(do ((v (make-vector len))
(i 0 (+ i 1)))
((= i len)
(with-syntax ((t v))
#'(begin 't)))
(vector-set! v i (rev i 0 bits))))))))
(define (reverse-bits i end)
(define rev9 (revtable 9))
(if (fx<=? end 9)
(fxarithmetic-shift-right (vector-ref rev9 i) (fx- 9 end))
(fxreverse-bit-field i 0 end)))
;; If you have a canonical Huffman tree, with a known alphabet, then
;; all that is needed to reconstruct the tree is the length of each
;; symbol in the alphabet. This procedure takes a list of ((symbol .
;; bit-length) ...) and computes the codes.
(define (reconstruct-codes sym< syms+lens)
;; The canonical codes are described in RFC 1951 section 3.2.2.
;; Don't try to read their code though...
(define (sort-by-length x)
(list-sort (lambda (x y) (< (cdr x) (cdr y))) x))
(define (sort-by-alphabet x)
(list-sort (lambda (x y) (sym< (car x) (car y))) x))
(let lp ((code 0)
(syms+lens (sort-by-length syms+lens))
(ret '()))
(let ((sym+len+code (list (caar syms+lens) (cdar syms+lens) code)))
(if (null? (cdr syms+lens))
(sort-by-alphabet (cons sym+len+code ret))
(lp (bitwise-arithmetic-shift-left (+ code 1)
(- (cdadr syms+lens)
(cdar syms+lens)))
(cdr syms+lens)
(cons sym+len+code ret))))))
;; (reconstruct-codes char<? '((#\A . 3) (#\B . 3) (#\C . 3) (#\D . 3) (#\E . 3) (#\F . 2) (#\G . 4) (#\H . 4)))
;; (define (depth x)
;; (if (pair? x)
;; (+ 1 (max (depth (car x)) (depth (cdr x))))
;; 0))
;; freqs is a list of (frequency . value) pairs. At least two pairs
;; are needed.
;; (define (frequencies->huffman-tree < freqs)
;; ;; TODO: linear time?
;; (define (sort freqs)
;; (list-sort (lambda (x y) (< (car x) (car y)))
;; freqs))
;; (if (null? (cdr freqs))
;; (cdar freqs)
;; (let* ((freqs (sort freqs))
;; (node (cond ((< (depth (cdar freqs)) (depth (cdadr freqs))) ;help make it unique
;; (cons (cdar freqs) (cdadr freqs)))
;; (else
;; (cons (cdadr freqs) (cdar freqs)))))
;; (weight (+ (caar freqs) (caadr freqs))))
;; (frequencies->huffman-tree < (cons (cons weight node)
;; (cddr freqs))))))
;; (define (flatten-huffman-tree tree)
;; ;; Turns a binary tree into a list of (symbol length code).
;; (define (flatten t len code)
;; (cond
;; ((pair? t)
;; (append (flatten (car t) (+ len 1) (bitwise-arithmetic-shift-left code 1))
;; (flatten (cdr t) (+ len 1) (bitwise-ior 1 (bitwise-arithmetic-shift-left code 1)))))
;; (else
;; (list (list t len code)))))
;; (flatten tree 0 0))
;; Turns a Huffman tree into a list of (symbol length code), where
;; the code is the canonical code.
;; (define (huffman-tree->canonical-codes sym<? tree)
;; (reconstruct-codes ;Assign canonical codes
;; sym<?
;; (map (lambda (s/l/c)
;; ;; Take the symbols and their lenghts
;; (cons (car s/l/c) (cadr s/l/c)))
;; ;; Sort first by code length and then by the symbol.
;; (list-sort (lambda (x y)
;; (if (= (cadr x) (cadr y))
;; (sym<? (car x) (car y))
;; (< (cadr x) (cadr y))))
;; (flatten-huffman-tree tree)))))
;; (flatten-huffman-tree '((#\F #\A . #\B) (#\C . #\D) #\E #\G . #\H))
;; (canonicalize-huffman-tree char<? '((#\F #\D . #\C) (#\B . #\A) #\E #\H . #\G))
;; (graph '((#\F #\A . #\B) (#\C . #\D) #\E #\G . #\H))
;; This takes a list of canonical codes ((symbol bit-length code)
;; ...) and constructs a lookup table. It's a one-level table (so
;; don't use this with a giant code). Let M be the maximum bit
;; length in the table, then this table is 2^M large, and you're
;; supposed to peek M bits into the stream. Use the peek'd value as
;; an index into the table, and the entry will tell you how many
;; bits belong to the symbol, and what the symbol is.
(define (canonical-codes->simple-lookup-table codes)
(let ((maxlen (fold-right max 0 (map cadr codes))))
(do ((t (make-vector (fxarithmetic-shift-left 1 maxlen) #f))
(codes codes (cdr codes)))
((null? codes)
(cons maxlen t))
(let* ((code (car codes))
(symbol (car code)) (bitlen (cadr code)) (bits (caddr code))
(translation (cons bitlen symbol)))
(let* ((start (fxarithmetic-shift-left bits (- maxlen bitlen)))
(end (fxior start (- (fxarithmetic-shift-left 1 (- maxlen bitlen)) 1))))
(do ((i start (fx+ i 1)))
((fx>? i end))
(vector-set! t (fxreverse-bit-field i 0 maxlen) translation)))))))
;; (canonical-codes->simple-lookup-table
;; '((#\A 3 2) (#\B 3 3) (#\C 3 4) (#\D 3 5) (#\E 3 6) (#\F 2 0) (#\G 4 14) (#\H 4 15)))
;; Uses two tables, as described here: http://www.gzip.org/algorithm.txt
(define (canonical-codes->lookup-table codes)
(define maxlen
;; Length of the first table. 9 is a sweet spot, but causes
;; trouble because it can consume a byte too much in lookahead
;; (like at the end of a gzip stream).
(let lp ((m 1) (codes codes))
(if (null? codes)
m
(let ((bitlen (cadar codes)))
(if (fx>=? bitlen 8) 9
(lp (max m bitlen)
(cdr codes)))))))
(define (findmax codes prefix)
;; Find the maximum code length for codes where the first
;; `maxlen' bits are equal to the prefix.
(let lp ((m 0) (codes codes))
(if (null? codes)
m
(let ((bitlen (cadar codes))
(bits (caddar codes)))
(cond ((fx>? maxlen bitlen) (lp m (cdr codes)))
((fx=? (fxarithmetic-shift-right bits (fx- bitlen maxlen))
prefix)
(lp (max m (fx- bitlen maxlen)) (cdr codes)))
(else (lp m (cdr codes))))))))
(define (fill! t bits maxlen bitlen translation)
(let* ((start (fxarithmetic-shift-left bits (fx- maxlen bitlen)))
(end (fxior start (fx- (fxarithmetic-shift-left 1 (fx- maxlen bitlen)) 1))))
(trace "#;start: #b" (string-pad (number->string start 2) bitlen #\0))
(trace "#;end: #b" (string-pad (number->string end 2) bitlen #\0))
(do ((i start (fx+ i 1)))
((fx>? i end))
(trace `(set! ,i ,translation))
(vector-set! t (reverse-bits i maxlen) translation))))
(do ((t (make-vector (fxarithmetic-shift-left 1 maxlen) #f))
(codes codes (cdr codes)))
((null? codes)
(cons maxlen t))
(let* ((code (car codes))
(symbol (car code)) (bitlen (cadr code)) (bits (caddr code)))
(trace "#;symbol: " symbol " #;bitlen: "bitlen " #;bits: #b"
(string-pad (number->string bits 2) bitlen #\0))
(if (fx<=? bitlen maxlen)
(fill! t bits maxlen bitlen (cons bitlen symbol))
(let* ((bitlen (fx- bitlen maxlen)) ;bitlength in table 2
(i (fxarithmetic-shift-right bits bitlen))
(ri (reverse-bits i maxlen))
(t2 (cond ((vector-ref t ri) => cdr)
(else ;; make a second-level table
(let* ((maxlen* (findmax codes i))
(v (make-vector (fxarithmetic-shift-left 1 maxlen*) #f))
(t2 (cons maxlen* v)))
(trace `(set! ,i table))
(vector-set! t ri (cons maxlen t2))
t2))))
(bits (fxand bits (fx- (fxarithmetic-shift-left 1 bitlen) 1))))
(fill! (data t2) bits (len t2) bitlen (cons bitlen symbol)))))))
;; (flatten-huffman-tree '((1 4 . 3) (5 7 10 . 9) 2 (6 . 11) 8 12 . 13))
(define len car)
(define data cdr)
;; This lookup code is the companion of the procedure above.
(define (get-next-code br table)
(let ((code (lookahead-bits br (len table))))
(let ((translation (vector-ref (data table) code)))
(trace "code: " (string-pad (number->string code 2) (len translation) #\0) " => " (data translation))
(get-bits br (len translation))
(if (pair? (data translation))
(get-next-code br (data translation))
(data translation)))))
)
| true |
d8cfb202ff70db2ac92fa7fff06dcb82b5bd9d15 | 9d7417f187812a477793ca23da844b34ab2a139d | /Graphikos/Graphikos/lib/ironscheme/clr/dynamic.sls | cb966f1b5277aba44a724e74bc40a39d8b33e42d | [
"MIT",
"BSD-3-Clause"
]
| permissive | simonmoriat/PLP | 5ae19daba4925919b593b4a21dc91dec9de9a6ce | 3d130acaa45239cdb289462a242a8c15836a39ca | refs/heads/master | 2023-05-11T23:36:28.347462 | 2016-06-08T07:07:50 | 2016-06-08T07:07:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 8,821 | sls | dynamic.sls | #| License
Copyright (c) 2007-2015 Llewellyn Pritchard
All rights reserved.
This source code is subject to terms and conditions of the BSD License.
See docs/license.txt. |#
(library (ironscheme clr dynamic)
(export
clr-call-site
clr-static-call-site
clr-dynamic
clr-cond
else)
(import
(ironscheme)
(ironscheme linq)
(ironscheme strings)
(ironscheme clr)
(ironscheme unsafe)
(ironscheme clr reflection)
(ironscheme fsm-cond-helpers))
(clr-using System.Reflection)
(define-syntax clr-cond
(lambda (x)
(define (gen-predicate pred id)
(list pred
id
(let ((x (symbol->string (syntax->datum pred))))
(if (string-ends-with? x "?")
(let ((p (string->symbol (substring x 0 (- (string-length x) 1)))))
#`($or? (clr-is #,(datum->syntax pred p) #,id) (null? #,id)))
#`(clr-is #,pred #,id)))))
(syntax-case x (else)
[(_ (id ...) ((pred ...) expr) ... (else else-expr))
(let ((preds (vector->list (get-predicates #'(pred ... ...)))))
(with-syntax ((((pred* x test) ...) (map gen-predicate
preds
(generate-temporaries preds))))
#'(let-syntax
((pred* (syntax-rules () [(_ x) test])) ...)
(clr-cond-aux (id ...)
((pred ...) expr) ...
(else else-expr)))))]
[(_ (id ...) ((pred ...) expr) ...)
#'(clr-cond (id ...) ((pred ...) expr) ... (else #f))])))
(define-syntax clr-cond-aux (fsm-cond-transformer #f))
(define (clr-call-targets type meth argtypes)
(let ((len (length argtypes))
(meth (symbol->string meth)))
(find-type-members type
'(method property field)
'(public instance)
(lambda (m c)
(and (string=? (member-name m) meth)
(cond
[(method? m)
(let ((p (method-params m)))
(and (fx=? len (length p))
(for-all type-assignable-from?
(map param-type p)
argtypes)))]
[(property? m)
(case len
[(0) #t]
[(1) (type-assignable-from? (property-type m)
(car argtypes))]
[else #f])]
[(field? m)
(case len
[(0) #t]
[(1) (type-assignable-from? (field-type m)
(car argtypes))]
[else #f])]
[else #f])))
#f)))
(define (clr-dynamic-internal instance mem . args)
(let* ((t (typeof instance))
(m (clr-call-targets t mem (map typeof args))))
(when (null? m)
(assertion-violation 'clr-dynamic "member not found on type" t mem))
(let ((m (car m)))
(cond
[(method? m)
(method-invoke m instance args)]
[(property? m)
(if (null? args)
(property-get-value m instance '())
(begin (property-set-value m instance '() (car args))
(void)))]
[(field? m)
(if (null? args)
(field-get-value m instance)
(begin (field-set-value m instance (car args))
(void)))]))))
(define-syntax clr-dynamic
(lambda (x)
(syntax-case x ()
[(_ instance mem arg ...)
#'(clr-dynamic-internal instance 'mem arg ...)])))
(define (generate-method-sig meth argtypes)
(cons (string->symbol meth) (map type-fullname argtypes)))
(define (type-and-namespace type ns)
(if (zero? (string-length ns))
type
(string-append ns "." type)))
(define get-type
(case-lambda
[(name)
(get-type name '())]
[(name ns)
(or (exists
(lambda (ns)
(let ((t (clr-static-call IronScheme.Runtime.Helpers GetTypeFast (type-and-namespace name ns))))
(if (null? t) #f t)))
(cons "" ns))
(assertion-violation 'get-type "type not found" name ns))]
[(name ns . args)
(let* ((gt args)
(len (length gt))
(t (get-type (string-append name "`" (number->string len)) ns)))
(clr-call Type (MakeGenericType Type[]) t (list->vector gt)))]))
(define-syntax type
(lambda (x)
(syntax-case x ()
[(_ (class typearg ...))
#'(get-type (symbol->string 'class) (clr-namespaces) (type typearg) ...)]
[(_ class)
#'(type (class))])))
(define (prepare-sigs mems)
(iterator->list
(from m in mems
where (not (method-contains-generic-parameters? m))
let p = (method-params m)
let l = (length p)
group p by l into g
orderby (key g)
select (cons
(key g)
(iterator->list
(from m in g
select (iterator->list
(from p in m
select (param-type p)))))))))
(define (make-ids n)
(map syntax->datum (generate-temporaries (make-list n))))
(define (generate-clause p)
(cond
[(type-enum? p)
'Microsoft.Scripting.SymbolId]
[(type-assignable-from? (get-type "System.Delegate") p)
'IronScheme.Runtime.Callable]
[(type-array? p)
'System.Array]
[else
(let ((n (type-fullname p)))
(string->symbol
(if (type-valuetype? p)
n
(string-append n "?"))))]))
(define (wrap-clause t static? cls)
(if static?
cls
`(if (clr-is ,t this)
,cls
(assertion-violation 'clr-call-site "instance not matched" this ,t))))
(define (generate-clauses type meth ids clauses static?)
(let ((t (type-fullname type)))
(wrap-clause t static?
`(clr-cond ,ids
,@(map (lambda (cls)
`[,(map generate-clause cls)
,(if static?
`(clr-static-call ,t ,(generate-method-sig meth cls) ,@ids)
`(clr-call ,t ,(generate-method-sig meth cls) this ,@ids))])
clauses)
(else (assertion-violation ,(string-append t "::" meth)
"failed to match arguments"
,@ids))))))
(define (generate-clr-call-site type meth static?)
(let* ((meth-name (symbol->string meth))
(mems (type-member type meth-name 'method (list 'public (if static? 'static 'instance))))
(sigs (prepare-sigs mems)))
(when (null? sigs)
(assertion-violation 'clr-call-site "no candidates found for method" meth type))
(eval (cons 'case-lambda
(map (lambda (sig)
(let* ((ids (make-ids (car sig)))
(cls (generate-clauses type
meth-name
ids
(cdr sig)
static?)))
(if static?
`[(,@ids) ,cls]
`[(this ,@ids) ,cls])))
sigs))
(environment '(ironscheme) '(ironscheme clr) '(ironscheme clr dynamic)))))
(define-syntax clr-call-site
(syntax-rules ()
[(_ clr-type meth)
(generate-clr-call-site (type clr-type) 'meth #f)]))
(define-syntax clr-static-call-site
(syntax-rules ()
[(_ clr-type meth)
(generate-clr-call-site (type clr-type) 'meth #t)]))) | true |
65febfe002bfb4c6cc556089d110063942a30252 | 6be443e2def01b1f9a5285f1287983e10e167515 | /ch1/1-8.scm | d9a2991bb4b9451e4ef6a1ee9eea702a183598cd | [
"MIT"
]
| permissive | ToruTakefusa/sicp | be62dbdc1e9965f9ad581635b2d73ecfd854c311 | 7ec1ae37845929dc2276bc5b83595ce0e2c52959 | refs/heads/master | 2020-04-08T09:41:41.936219 | 2019-09-28T05:15:18 | 2019-09-28T05:15:18 | 159,235,583 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 391 | scm | 1-8.scm | (define (sqrt-iter guess x)
(if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
(define (improve guess x)
(/ (+ (/ x (square guess)) (* 2.0 guess)) 3.0))
(define (good-enough? guess x)
( < (abs (- (cube guess) x )) 0.0001))
(define (cube x) (* x x x))
(define (sqrt x)
(sqrt-iter 1.0 x))
(define (square x) (* x x))
(print (sqrt 9))
| false |
f2ef93245b1ac25edb2ba7b0e7f8877ff8260efd | 87482c1b1d5dd031a8afa84242e08baad756a829 | /build-pages.ss | 8a5a317e82b1a34c5271abc9efb767733b3ed5d6 | []
| no_license | arcfide/descot | 504d97860c82fb93a1f98fd8781ed2bfc68947d6 | 0b6a5b7422829519bd3a5db8b0aae4bc58fa0ade | refs/heads/master | 2021-01-20T11:04:45.955794 | 2012-01-21T20:23:26 | 2012-01-21T20:23:26 | 3,235,812 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,756 | ss | build-pages.ss | #! /usr/bin/env scheme-script
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Build Static Descot Web Pages
;;;
;;; Copyright (c) 2009 Aaron Hsu <[email protected]>
;;;
;;; Permission to use, copy, modify, and distribute this software for
;;; any purpose with or without fee is hereby granted, provided that the
;;; above copyright notice and this permission notice appear in all
;;; copies.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
;;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
;;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;;; DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
;;; OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
;;; PERFORMANCE OF THIS SOFTWARE.
(import (chezscheme) (riastradh foof-loop) (arcfide descot web parameters))
(meta define script-root "www")
(define descot-web-docroot (make-parameter "www_static"))
(meta define valid-script?
(lambda (fname)
(let ([sl (string-length fname)])
(string=? ".ss" (substring fname (- sl 3) sl)))))
(meta define script-pages
(lambda (root)
(collect-list (for fname (in-list (directory-list root)))
(if (valid-script? fname))
(string-append script-root (string (directory-separator)) fname))))
(define-syntax include-script-files
(lambda (x)
(with-syntax ([(f1 ...) (script-pages script-root)])
#'(begin (include f1) ...))))
(when (pair? (command-line-arguments))
(descot-web-docroot (car (command-line-arguments))))
(include-script-files)
(printf "Done!~%")
(exit)
| true |
5f5e7cf145634794ea2b098ce23609f0c90e489a | fae4190f90ada065bc9e5fe64aab0549d4d4638a | /typed-scheme-lti/optimize/utils.ss | 0b1edeaf86ad39be72423f919311ef95d5f9d8e2 | []
| 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 | 8,736 | ss | utils.ss | (module utils mzscheme
(require (lib "string.ss") (lib "plt-match.ss"))
;; hack to make it work with syntax coverage
(define-syntax (sourced-match stx)
(syntax-case stx ()
[(_ val clause ...)
(datum->syntax-object
stx
(syntax-e (local-expand (syntax/loc stx (match val clause ...))
'expression '()))
stx
stx)]))
(define-syntax (define-predicate-matcher stx)
(syntax-case stx ()
[(_ pred)
(identifier? #'pred)
(let* ([name (symbol->string (syntax-e #'pred))]
[id (lambda (sfx)
(let ([sym (string->symbol (string-append name sfx))])
(datum->syntax-object stx sym stx stx)))])
(with-syntax ([pred: (id ":")] [pred? (id "?")])
#'(define-match-expander pred:
(syntax-rules (pred:) [(pred: pat) (? pred? pat)]))))]))
(define-predicate-matcher number)
(define-predicate-matcher integer)
(define-predicate-matcher symbol)
(define-predicate-matcher string)
(define-predicate-matcher boolean)
(provide (rename sourced-match match)
number: integer: symbol: string: boolean:)
;; ========== a few saner bindings ==========================================
;; some sane bindings, similar to the teaching languages
(provide *if)
(define-syntax *if
(syntax-rules () [(*if cond then else) (if cond then else)]))
(provide *list? *cons)
(define (*list? x)
(or (null? x) (pair? x)))
(define (*cons x l)
(if (*list? l) (cons x l) (raise-type-error 'cons "list" 1 x l)))
;; ========== string "parser" ===============================================
;; build a regexp that matches restricted character expressions, can use only
;; {}s for lists, and limited strings that use '...' (normal mzscheme escapes
;; like \n, and '' for a single ')
(define good-char "(?:[ \t\r\na-zA-Z0-9_{}!?*/<=>:+-]|[.][.][.])")
;; this would make it awkward for students to use \" for strings
;; (define good-string "\"[^\"\\]*(?:\\\\.[^\"\\]*)*\"")
(define good-string "[^\"\\']*(?:''[^\"\\']*)*")
(define expr-re
(regexp (string-append "^"
good-char"*"
"(?:'"good-string"'"good-char"*)*"
"$")))
(define string-re
(regexp (string-append "'("good-string")'")))
(provide string->sexpr)
(define (string->sexpr str)
(unless (string? str)
(raise-type-error 'string->sexpr "string" 0 str))
(unless (regexp-match expr-re str)
(error 'string->sexpr "syntax error (bad contents)"))
(let ([sexprs (read-from-string-all
(regexp-replace*
"''" (regexp-replace* string-re str "\"\\1\"") "'"))])
(if (= 1 (length sexprs))
(car sexprs)
(error 'string->sexpr "bad syntax (multiple expressions)"))))
;; ========== pattern-matching transformations ==============================
(define (transform-fail:syntax thunk from to)
(with-handlers ([exn:fail:syntax?
(lambda (e)
(raise (make-exn:fail:syntax
(string->immutable-string
(regexp-replace (format "^~a:" from)
(exn-message e)
(format "~a:" to)))
(exn-continuation-marks e)
(exn:fail:syntax-exprs e))))])
(thunk)))
(provide make-transformer)
(define (make-transformer literals from+to-list)
(define transformer
(transform-fail:syntax
(lambda () (eval `(syntax-rules ,literals ,@from+to-list)))
'syntax
'transform))
(lambda (expr)
(syntax-object->datum (transformer (datum->syntax-object #f expr)))))
;; ========== tests =========================================================
(provide test test-mode test-postprocess)
(define test-mode (make-parameter 'report))
(define test-inspector (make-parameter (current-inspector)))
(define test-postprocess (make-parameter values))
(define (install-test-inspector)
(test-inspector (current-inspector))
(current-inspector (make-inspector))
(print-struct #t))
(define-syntax (test stx)
(unless (memq (syntax-local-context) '(top-level module module-begin))
(raise-syntax-error
#f "can be used only as a top-level expression"
stx))
(syntax-case* stx (=> <= =error> <error=)
(lambda (x y) (eq? (syntax-e x) (syntax-e y)))
[(test expr)
(syntax/loc stx (test-1 expr 'expr))]
[(test expr1 => expr2)
(syntax/loc stx (test-2 expr1 'expr1 expr2 'expr2))]
[(test expr2 <= expr1)
(syntax/loc stx (test-2 expr1 'expr1 expr2 'expr2))]
[(test expr =error> msg-re)
(syntax/loc stx
(test-e (lambda () ((test-postprocess) expr)) 'expr msg-re))]
[(test msg-re <error= expr)
(syntax/loc stx
(test-e (lambda () ((test-postprocess) expr)) 'expr msg-re))]))
(define-struct (exn:test exn) ())
(define (test-error fmt . args)
(parameterize ([current-inspector (test-inspector)]
[print-struct #t])
(let ([msg (string-append "Test failure: " (apply format fmt args))])
(case (test-mode)
[(report) (fprintf (current-error-port) "~a\n" msg)]
[(verbose error)
(raise (make-exn:test (string->immutable-string msg)
(current-continuation-marks)))]
[else (error 'test "bad test-mode: ~e" (test-mode))]))))
(define (test-ok label)
(parameterize ([current-inspector (test-inspector)]
[print-struct #t])
(when (eq? 'verbose (test-mode))
(fprintf (current-error-port) "Test passed: ~e\n" label))
(void)))
(define (test-1 val expr)
(if ((test-postprocess) val)
(test-ok expr)
(test-error "~e failed" expr)))
(define (test-2 val1 expr1 val2 expr2)
(parameterize ([current-inspector (test-inspector)])
(let ([val1 ((test-postprocess) val1)]
[val2 ((test-postprocess) val2)])
(if (equal? val1 val2)
(test-ok expr1)
(test-error "~e failed: got ~e, but expected ~e" expr1 val1 val2)))))
(define (test-e thunk expr msg-re)
(let ([r (with-handlers ([exn:fail? (lambda (e) e)]) (thunk))])
;; assume normal code does not return an exception
(cond
[(not (exn? r)) (test-error "~e did not signal an error" expr)]
[(not (regexp-match-positions (simple-glob->regexp msg-re)
(exn-message r)))
(test-error "mismatched error message in ~e (expecting \"~a\"): ~a"
expr msg-re (exn-message r))]
[else (test-ok expr)])))
(define glob-item-re
(regexp (string-append "(?:"
"[\\]." ; escaped item
"|"
"[*?]" ; wildcards -- the only 1-character match
")")))
(define (simple-glob->regexp glob)
(let loop ([i 0] [ps (regexp-match-positions* glob-item-re glob)] [r '()])
(if (null? ps)
(regexp (apply string-append
(reverse (cons (regexp-quote (substring glob i)) r))))
(loop (cdar ps) (cdr ps)
;; length=1 is only for `*' or `?'
(cons (if (= 1 (- (cdar ps) (caar ps)))
(if (equal? #\* (string-ref glob (caar ps))) ".*" ".")
(substring glob (caar ps) (cdar ps)))
(if (= i (caar ps))
r (cons (regexp-quote (substring glob i (caar ps)))
r)))))))
(install-test-inspector)
;; ========== additional type stuff =========================================
(provide any? list-of sexp-of box-of union-of intersection-of false? true?)
(define (any? x) #t)
(define (list-of pred?)
(define (list-of-proc l) (and (*list? l) (andmap pred? l)))
list-of-proc)
(define (sexp-of pred?) ; restricted to proper lists
(define (sexp-of-proc s)
(let loop ([s s]) (or (pred? s) (and (*list? s) (andmap loop s)))))
sexp-of-proc)
(define (box-of pred?)
(define (box-of-proc x) (and (box? x) (pred? (unbox x))))
box-of-proc)
(define (union-of . preds)
(define (union-of-proc x) (ormap (lambda (p?) (p? x)) preds))
union-of-proc)
(define (intersection-of . preds)
(define (intersection-of-proc x) (andmap (lambda (p?) (p? x)) preds))
intersection-of-proc)
(define (false? x) (not x))
(define (true? x) (not (not x)))
)
| true |
79b1b274e77c8700bf81303300fbda650a8f47fa | ac2a3544b88444eabf12b68a9bce08941cd62581 | /lib/_prim-will-gambit#.scm | 29ff727576e2709d1c70119543738332b8d216ed | [
"Apache-2.0",
"LGPL-2.1-only"
]
| permissive | tomelam/gambit | 2fd664cf6ea68859d4549fdda62d31a25b2d6c6f | d60fdeb136b2ed89b75da5bfa8011aa334b29020 | refs/heads/master | 2020-11-27T06:39:26.718179 | 2019-12-15T16:56:31 | 2019-12-15T16:56:31 | 229,341,552 | 1 | 0 | Apache-2.0 | 2019-12-20T21:52:26 | 2019-12-20T21:52:26 | null | UTF-8 | Scheme | false | false | 445 | scm | _prim-will-gambit#.scm | ;;;============================================================================
;;; File: "_prim-will-gambit#.scm"
;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved.
;;;============================================================================
;;; Will operations in Gambit.
(##namespace ("##"
make-will
will-execute!
will-testator
will?
))
;;;============================================================================
| false |
b96090a9be35a888d62727814af39468a59c0791 | c42881403649d482457c3629e8473ca575e9b27b | /test/partcont.scm | 2911b066088c9d1de60315120f461d3aa3e04a7c | [
"BSD-2-Clause",
"BSD-3-Clause"
]
| permissive | kahua/Kahua | 9bb11e93effc5e3b6f696fff12079044239f5c26 | 7ed95a4f64d1b98564a6148d2ee1758dbfa4f309 | refs/heads/master | 2022-09-29T11:45:11.787420 | 2022-08-26T06:30:15 | 2022-08-26T06:30:15 | 4,110,786 | 19 | 5 | null | 2015-02-22T00:23:06 | 2012-04-23T08:02:03 | Scheme | UTF-8 | Scheme | false | false | 434 | scm | partcont.scm | ;; -*- coding: utf-8 ; mode: scheme -*-
;; test kahua.partcont
(use gauche.test)
(use kahua.partcont)
(test-module 'kahua.partcont)
(test-start "kahua.partcont")
(test* "reset" 4
(+ 1 (reset 3)))
(test* "reset, let/pc" 5
(+ 1 (reset (* 2 (let/pc k 4)))))
(test* "reset, let/pc" 9
(+ 1 (reset (* 2 (let/pc k (k 4))))))
(test* "reset, let/pc" 17
(+ 1 (reset (* 2 (let/pc k (k (k 4)))))))
(test-end)
| false |
b74a557e6bffd5dbdd4578a696763f6adc3340c6 | 11f8c62565512010ec8bd59d929a35063be7bb2a | /compiler/src/test/scheme/functional/HashMapSuite.scm | be0f118fce5ba641ac1890c6ec836ddf44e0ab3d | [
"Apache-2.0"
]
| permissive | etaoins/llambda | 97b986e40d8aa6871a5ab1946b53c2898313776b | a2a5c212ebb56701fa28649c377d0ddd8b67da0b | refs/heads/master | 2020-05-26T18:43:11.776115 | 2018-01-03T07:40:49 | 2018-01-03T07:40:49 | 9,960,891 | 71 | 7 | null | null | null | null | UTF-8 | Scheme | false | false | 8,505 | scm | HashMapSuite.scm | (define-test "(make-hash-map)" (expect-success
(import (llambda hash-map))
(define empty-hash-map (make-hash-map))
(assert-true (hash-map? empty-hash-map))
(assert-false (hash-map? 1))
(assert-false (hash-map? #f))
(assert-equal 0 (hash-map-size empty-hash-map))))
(define-test "(hash-map-assoc)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define empty-hash-map (make-hash-map))
(define one-value-hash-map (hash-map-assoc empty-hash-map 1 'one))
(ann one-value-hash-map (HashMap <integer> 'one))
(assert-true (hash-map-exists? one-value-hash-map 1))
(assert-equal 'one (ann (hash-map-ref/default one-value-hash-map 1 #f) (U #f 'one)))
(assert-false (hash-map-exists? one-value-hash-map 2.0))
(assert-equal #f (hash-map-ref/default one-value-hash-map 2.0 #f))
(assert-false (hash-map-exists? one-value-hash-map 'three))
(assert-equal #f (hash-map-ref/default one-value-hash-map 'three #f))
(assert-equal 1 (hash-map-size one-value-hash-map))
(define two-value-hash-map (hash-map-assoc one-value-hash-map 2.0 'two))
(ann two-value-hash-map (HashMap <number> <symbol>))
(assert-equal 2 (hash-map-size two-value-hash-map))
(assert-true (hash-map-exists? two-value-hash-map 1))
(assert-equal 'one (ann (hash-map-ref/default two-value-hash-map 1 #f) (U #f 'one 'two)))
(assert-true (hash-map-exists? two-value-hash-map 2.0))
(assert-equal 'two (hash-map-ref/default two-value-hash-map 2.0 #f))
(assert-false (hash-map-exists? two-value-hash-map 'three))
(assert-equal #f (hash-map-ref/default two-value-hash-map 'three #f))))
(define-test "(hash-map-delete)" (expect-success
(import (llambda hash-map))
(define hash-map (make-hash-map))
(set! hash-map (hash-map-assoc hash-map 'one 1))
(set! hash-map (hash-map-assoc hash-map 'two 2))
(set! hash-map (hash-map-assoc hash-map 'three 3))
(define hash-map-wo-one (hash-map-delete hash-map 'one))
(assert-equal 2 (hash-map-size hash-map-wo-one))
(assert-false (hash-map-exists? hash-map-wo-one 'one))
(assert-true (hash-map-exists? hash-map-wo-one 'two))
(assert-true (hash-map-exists? hash-map-wo-one 'three))
(define hash-map-wo-two (hash-map-delete hash-map-wo-one 'two))
(assert-equal 1 (hash-map-size hash-map-wo-two))
(assert-false (hash-map-exists? hash-map-wo-two 'one))
(assert-false (hash-map-exists? hash-map-wo-two 'two))
(assert-true (hash-map-exists? hash-map-wo-two 'three))
(define hash-map-wo-three (hash-map-delete hash-map-wo-two 'three))
(assert-equal 0 (hash-map-size hash-map-wo-three))
(assert-false (hash-map-exists? hash-map-wo-three 'one))
(assert-false (hash-map-exists? hash-map-wo-three 'two))
(assert-false (hash-map-exists? hash-map-wo-three 'three))))
(define-test "(alist->hash-map)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define empty-hash-map (alist->hash-map '()))
(assert-equal 0 (hash-map-size empty-hash-map))
(define number-hash-map (alist->hash-map '((1 . one) (2 . one) (3 . three) (2 . two))))
(ann number-hash-map (HashMap <integer> <symbol>))
(assert-equal 3 (hash-map-size number-hash-map))
(assert-equal 'one (hash-map-ref/default number-hash-map 1 #f))
(assert-equal 'two (hash-map-ref/default number-hash-map 2 #f))
(assert-equal 'three (hash-map-ref/default number-hash-map 3 #f))
(assert-equal #f (hash-map-ref/default number-hash-map 4 #f))))
(define-test "(hash-map-ref)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(import (llambda error))
(define number-hash-map (alist->hash-map '((1 . one) (2 . one) (3 . three) (2 . two))))
(ann number-hash-map (HashMap <integer> <symbol>))
(assert-equal 3 (hash-map-size number-hash-map))
(assert-equal 'one (hash-map-ref number-hash-map 1))
(assert-equal 'two (hash-map-ref number-hash-map 2))
(assert-equal 'three (hash-map-ref number-hash-map 3))
(assert-equal 'four (hash-map-ref number-hash-map 4 (lambda () 'four)))
(assert-raises invalid-argument-error?
(hash-map-ref number-hash-map 4))))
(define-test "(hash-map->alist)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define number-hash-map (alist->hash-map '((1 . one) (2 . one) (3 . three) (2 . two))))
(define number-assoc (hash-map->alist number-hash-map))
(ann number-assoc (Listof (Pairof <integer> <symbol>)))
(assert-equal 3 (length number-assoc))
(assert-equal 'one (cdr (assoc 1 number-assoc)))
(assert-equal 'two (cdr (assoc 2 number-assoc)))
(assert-equal 'three (cdr (assoc 3 number-assoc)))
(assert-equal #f (assoc 4 number-assoc))))
(define-test "(hash-map-keys)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define number-hash-map (alist->hash-map '((1 . one) (2 . one) (3 . three) (2 . two))))
(define number-keys (hash-map-keys number-hash-map))
(ann number-keys (Listof <integer>))
(assert-equal 3 (length number-keys))
(assert-false (not (member 1 number-keys)))
(assert-false (not (member 2 number-keys)))
(assert-false (not (member 3 number-keys)))
(assert-false (member 4 number-keys))))
(define-test "(hash-map-values)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define number-hash-map (alist->hash-map '((1 . one) (2 . one) (3 . three) (2 . two))))
(define number-values (hash-map-values number-hash-map))
(ann number-values (Listof <symbol>))
(assert-equal 3 (length number-values))
(assert-false (not (member 'one number-values)))
(assert-false (not (member 'two number-values)))
(assert-false (not (member 'three number-values)))
(assert-false (member 'four number-values))))
(define-test "(hash-map-for-each)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define number-hash-map (alist->hash-map '((1 . one) (2 . one) (3 . three) (2 . two))))
(define seen-1 #f)
(define seen-2 #f)
(define seen-3 #f)
(hash-map-for-each (lambda (key value)
(case key
((1)
(assert-false seen-1)
(set! seen-1 #t))
((2)
(assert-false seen-2)
(set! seen-2 #t))
((3)
(assert-false seen-3)
(set! seen-3 #t))
(else (error "Unexpected key" key)))) number-hash-map)
(assert-true seen-1)
(assert-true seen-2)
(assert-true seen-3)))
(define-test "(hash-map-fold)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define number-hash-map (alist->hash-map '((1 . "one") (2 . "one") (3 . "three") (2 . "two"))))
(define total (hash-map-fold (lambda (key value accum)
(+ accum key (* (string-length value) 10))
) 0 number-hash-map))
(assert-equal 116 total)))
(define-test "(hash-map-merge)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(define source-hash-map-1 (alist->hash-map '((1 . #f) (2 . #f) (3 . #f))))
(define source-hash-map-2 (alist->hash-map '((1 . #t) (3 . #t) (4 . #f))))
(define actual-hash-map (hash-map-merge source-hash-map-1 source-hash-map-2))
(define expected-hash-map (alist->hash-map '((1 . #t) (2 . #f) (3 . #t) (4 . #f))))
(ann actual-hash-map (HashMap <integer> <boolean>))
(assert-equal 4 (hash-map-size actual-hash-map))
(assert-equal actual-hash-map expected-hash-map)))
(define-test "(hash)" (expect-success
(import (llambda hash-map))
(import (llambda typed))
(assert-equal (hash "One") (hash "One"))
(assert-equal (hash 'One) (hash 'One))
(assert-equal (hash 1) (hash 1))
(assert-equal (hash #(1)) (hash #(1)))
(assert-equal (hash '(1)) (hash '(1)))
; Ensure the runtime and compile time hashes match
(assert-equal
(hash "Hello world! What's up?")
(hash (string-append (typeless-cell "Hello world! ") (typeless-cell "What's up?"))))
; Ensure strings and bytevectors use compatible hashing
(assert-equal
(hash "Hello world! What's up?")
(hash (utf8->string (typeless-cell
#u8(72 101 108 108 111 32 119 111 114 108 100 33 32 87 104 97 116 39 115 32 117 112 63)))))
(assert-true (< (hash "Japan" 1) 1))
(assert-true (< (hash "France" 2) 2))
(assert-true (< (hash "United Kingdom" 3) 3))
(assert-true (< (hash "Germany" 4) 4))))
| false |
d89c84b4a345a9c952ed76bbc25eeff6be1efa8e | 165a4ff581651cdad1bc512ec1c82cebc0ac575a | /src/SICP/4/4.3/ex.ss | 584cd8816984db98035ee0b72fb5f0e86866c4a6 | []
| no_license | haruyama/yami | 5028e416a2caa40a0193d46018fe4be81d7820dc | 32997caecc18d9d82a28b88fabe5b414a55e0e18 | refs/heads/master | 2020-12-25T09:47:04.240216 | 2018-06-16T08:28:41 | 2018-06-16T08:28:41 | 898,824 | 1 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 31,771 | ss | ex.ss | (load "./4.3.ss")
(driver-loop)
(list (amb 1 2 3) (amb 'a 'b))
try-again
try-again
try-again
try-again
try-again
try-again
end
(driver-loop)
(define (an-integer-starting-from n)
(amb n (an-integer-starting-from (+ n 1))))
(an-integer-starting-from 2)
try-again
try-again
try-again
end
(driver-loop)
(define (square n) (* n n))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
(define (require p)
(if (not p) (amb)))
(define (an-element-of items)
(require (not (null? items)))
(amb (car items) (an-element-of (cdr items))))
(define (an-integer-starting-from n)
(amb n (an-integer-starting-from (+ n 1))))
(define (prime-sum-pair list1 list2)
(let ((a (an-element-of list1))
(b (an-element-of list2)))
(require (prime? (+ a b)))
(list a b)))
(prime-sum-pair '(1 3 5 8) '(20 35 110))
try-again
try-again
try-again
(prime-sum-pair '(19 27 30) '(11 36 58))
try-again
try-again
end
(driver-loop)
(let ((a (an-integer-starting-from 10)))
(require (prime? a))
a)
try-again
try-again
end
;ex4.35-36
(driver-loop)
(define (an-integer-between low high)
(require (<= low high))
(amb low (an-integer-between (+ low 1) high)))
(an-integer-between 5 10)
try-again
(an-element-of '(5 6 7))
(define (a-pythagorean-triple-between low high)
(let ((i (an-integer-between low high)))
(let ((j (an-integer-between i high)))
(let ((k (an-integer-between j high)))
(require (= (+ (* i i) (* j j)) (* k k)))
(list i j k)))))
(a-pythagorean-triple-between 3 13)
try-again
try-again
try-again
;(define (a-pythagorean-triple-bad low)
; (let ((i (an-integer-starting-from low)))
; (let ((j (an-integer-starting-from i)))
; (let ((k (an-integer-starting-from j)))
; (require (= (+ (* i i) (* j j)) (* k k)))
; (list i j k)))))
;(a-pythagorean-triple-bad 3)
(define (a-pythagorean-triple)
(let ((k (an-integer-starting-from 5)))
(let ((j (an-integer-between 1 (- k 1))))
(let ((i (an-integer-between 1 j)))
(require (= (+ (* i i) (* j j)) (* k k)))
(list i j k)))))
(a-pythagorean-triple)
try-again
try-again
try-again
try-again
try-again
try-again
try-again
try-again
try-again
end
;ex4.37
;kについて探索しないでよい
(driver-loop)
(define (require p)
(if (not p) (amb)))
(define (distinct? items)
(cond ((null? items) true)
((null? (cdr items)) true)
((member (car items) (cdr items)) false)
(else (distinct? (cdr items)))))
(define (multiple-dwelling)
(let ((baker (amb 1 2 3 4 5))
(cooper (amb 1 2 3 4 5))
(fletcher (amb 1 2 3 4 5))
(miller (amb 1 2 3 4 5))
(smith (amb 1 2 3 4 5)))
(require
(distinct? (list baker cooper fletcher miller smith)))
(require (not (= baker 5)))
(require (not (= cooper 1)))
(require (not (= fletcher 5)))
(require (not (= fletcher 1)))
(require (> miller cooper))
(require (not (= (abs (- smith fletcher)) 1)))
(require (not (= (abs (- fletcher cooper)) 1)))
(list (list 'baker baker)
(list 'cooper cooper)
(list 'fletcher fletcher)
(list 'miller miller)
(list 'smith smith))))
(multiple-dwelling)
try-again
end
;ex4.38
(driver-loop)
(define (multiple-dwelling2)
(let ((baker (amb 1 2 3 4 5))
(cooper (amb 1 2 3 4 5))
(fletcher (amb 1 2 3 4 5))
(miller (amb 1 2 3 4 5))
(smith (amb 1 2 3 4 5)))
(require
(distinct? (list baker cooper fletcher miller smith)))
(require (not (= baker 5)))
(require (not (= cooper 1)))
(require (not (= fletcher 5)))
(require (not (= fletcher 1)))
(require (> miller cooper))
;(require (not (= (abs (- smith fletcher)) 1)))
(require (not (= (abs (- fletcher cooper)) 1)))
(list (list 'baker baker)
(list 'cooper cooper)
(list 'fletcher fletcher)
(list 'miller miller)
(list 'smith smith))))
(multiple-dwelling2)
try-again
try-again
try-again
try-again
try-again
end
;ex4.39
;https://wizardbook.wordpress.com/2011/01/12/exercise-4-39/
(driver-loop)
(define (multiple-dwelling3)
(let ((baker (amb 1 2 3 4 5))
(cooper (amb 1 2 3 4 5))
(fletcher (amb 1 2 3 4 5))
(miller (amb 1 2 3 4 5))
(smith (amb 1 2 3 4 5)))
(require (not (= fletcher 5)))
(require (not (= fletcher 1)))
(require (not (= (abs (- smith fletcher)) 1)))
(require (not (= (abs (- fletcher cooper)) 1)))
(require (> miller cooper))
(require (not (= cooper 1)))
(require (not (= baker 5)))
(require
(distinct? (list baker cooper fletcher miller smith)))
(list (list 'baker baker)
(list 'cooper cooper)
(list 'fletcher fletcher)
(list 'miller miller)
(list 'smith smith))))
(multiple-dwelling3)
try-again
end
;ex4.40
(driver-loop)
(define (multiple-dwelling4)
(let ((fletcher (amb 1 2 3 4 5)))
(require (not (= fletcher 5)))
(require (not (= fletcher 1)))
(let ((cooper (amb 1 2 3 4 5)))
(require (not (= cooper 1)))
(require (not (= (abs (- fletcher cooper)) 1)))
(let ((baker (amb 1 2 3 4 5)))
(require (not (= baker 5)))
(let ((miller (amb 1 2 3 4 5)))
(require (> miller cooper))
(let ( (smith (amb 1 2 3 4 5)))
(require (not (= (abs (- smith fletcher)) 1)))
(require
(distinct? (list baker cooper fletcher miller smith)))
(list (list 'baker baker)
(list 'cooper cooper)
(list 'fletcher fletcher)
(list 'miller miller)
(list 'smith smith))))))))
(multiple-dwelling4)
try-again
end
;ex4.41
(define (distinct? items)
(cond ((null? items) true)
((null? (cdr items)) true)
((member (car items) (cdr items)) false)
(else (distinct? (cdr items)))))
(define (multiple-dwelling5-condition items)
(let ((baker (car items))
(cooper (cadr items))
(fletcher (caddr items))
(miller (cadddr items))
(smith (car (cddddr items))))
(cond ((= fletcher 5) false)
((= fletcher 1) false)
((= cooper 1) false)
((= (abs (- fletcher cooper)) 1) false)
((= baker 5) false)
((< miller cooper) false)
((= (abs (- smith fletcher)) 1) false)
; ((not (distinct? items)) false)
(else true))))
(define (accumulate op initial sequence)
(if (null? sequence) initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
(define (flatmap proc seq)
(accumulate append '() (map proc seq)))
(define (permutations s)
(if (null? s) (list '())
(flatmap (lambda (x)
(map (lambda (p) (cons x p))
(permutations (remove x s))))
s)))
(define (filter predicate sequence)
(cond ((null? sequence) '())
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
(define (remove item sequence)
(filter (lambda (x) (not (= x item)))
sequence))
;(permutations (list 1 2 3))
(define (multiple-dwelling5)
(filter multiple-dwelling5-condition
(permutations (list 1 2 3 4 5))))
(multiple-dwelling5)
(driver-loop)
(and true true)
(and true false)
(and)
(or true false)
(or true true)
(or false true)
(or false false)
end
;ex4.42
(driver-loop)
;(define (require-ex4-42 cond1 cond2)
; (require (or (and cond1 (not cond2))
; (and (not cond1) cond2))))
(define (ex4-42)
(define (xor a b)
(if a (not b) b))
(let ((betty (amb 1 2 3 4 5))
(ethel (amb 1 2 3 4 5))
(joan (amb 1 2 3 4 5))
(kitty (amb 1 2 3 4 5))
(mary (amb 1 2 3 4 5)))
(require (xor (= kitty 2) (= betty 3)))
(require (xor (= ethel 1) (= joan 2)))
(require (xor (= joan 3) (= ethel 5)))
(require (xor (= kitty 2) (= mary 4)))
(require (xor (= mary 4) (= betty 1)))
(require
(distinct? (list betty ethel joan kitty mary)))
(list betty ethel joan kitty mary)))
(ex4-42)
try-again
end
;ex4.43
(driver-loop)
;(define (distinct? items)
; (cond ((null? items) true)
; ((null? (cdr items)) true)
; ((member (car items) (cdr items)) false)
; (else (distinct? (cdr items)))))
;(define (require p)
; (if (not p) (amb)))
;(define (filter pred lst)
; (if (null? lst)
; '()
; (if (pred (car lst))
; (cons (car lst) (filter pred (cdr lst)))
; (filter pred (cdr lst)))))
;(define (map proc items)
; (if (null? items)
; '()
; (cons (proc (car items))
; (map proc (cdr items)))))
;(define (ex4-43)
; (let (
; (moore (cons 'lorna 'mary-ann))
; (downing (cons 'melissa (amb 'lorna 'rosalind 'gabrielle 'mary-ann)))
; (hall (cons 'rosalind (amb 'lorna 'gabrielle 'mary-ann)))
; (barnacle (cons 'gabrielle 'melissa))
; (parker (cons 'mary-ann (amb 'lorna 'rosalind 'gabrielle)))
; )
; (let ((fathers (list moore downing hall barnacle parker))
; (fathers-without-parker (list moore downing hall barnacle)))
; (require
; (distinct? (map cdr fathers)))
; (require
; (eq? (cdr parker)
; (car (car (filter (lambda (x) (eq? (cdr x) 'gabrielle)) fathers)))))
; (list 'moore moore 'downing downing 'hall hall 'barnacle barnacle 'parker parker))))
;(ex4-43)
;try-again
;end
(driver-loop)
(define (distinct? items)
(cond ((null? items) true)
((null? (cdr items)) true)
((member (car items) (cdr items)) false)
(else (distinct? (cdr items)))))
(define (require p)
(if (not p) (amb)))
(define (filter pred lst)
(if (null? lst)
'()
(if (pred (car lst))
(cons (car lst) (filter pred (cdr lst)))
(filter pred (cdr lst)))))
(define (map proc items)
(if (null? items)
'()
(cons (proc (car items))
(map proc (cdr items)))))
(define make-yacht-daughter cons)
(define (yacht f) (car f))
(define (daughter f) (cdr f))
(define (ex4-43)
(let ((moore (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht moore) 'lorna))
(require (eq? (daughter moore) 'mary-ann))
(let ((barnacle (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht barnacle) 'gabrielle))
(require (eq? (daughter barnacle) 'melissa))
(let ((downing (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht downing) 'melissa))
(require (not (member (daughter downing) '(melissa mary-ann))))
(let ((hall (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht hall) 'rosalind))
(require (not (member (daughter hall) '(melissa mary-ann rosalind))))
(let ((parker (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (not (member (yacht parker) '(lorna gabrielle melissa rosalind))))
(require (not (member (daughter parker) '(melissa mary-ann))))
(let ((fathers-without-parker
(list moore downing hall barnacle))
(fathers
(list moore downing hall barnacle parker)))
(let ((gabrielle-fathers (filter (lambda (x) (eq? (daughter x) 'gabrielle)) fathers-without-parker)))
(require (not (null? gabrielle-fathers)))
(require (null? (cdr gabrielle-fathers)))
(require
(eq? (daughter parker)
(yacht (car gabrielle-fathers))))
(require (distinct? (map yacht fathers)))
(require (distinct? (map daughter fathers)))
(list 'moore moore 'downing downing 'hall hall 'barnacle barnacle 'parker parker)))))))))
(ex4-43)
try-again
(define (ex4-43-2)
(let ((moore (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht moore) 'lorna))
;(require (eq? (daughter moore) 'mary-ann))
(require (not (eq? (daughter moore) 'lorna)))
(let ((barnacle (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht barnacle) 'gabrielle))
(require (eq? (daughter barnacle) 'melissa))
(let ((downing (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht downing) 'melissa))
(require (not (eq? (daughter downing) 'melissa)))
(let ((hall (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (eq? (yacht hall) 'rosalind))
(require (not (member (daughter hall) '(melissa rosalind))))
(let ((parker (make-yacht-daughter (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa) (amb 'gabrielle 'lorna 'rosalind 'mary-ann 'melissa))))
(require (not (member (yacht parker) '(lorna gabrielle melissa rosalind))))
(require (not (eq? (daughter parker) 'melissa)))
(let ((fathers-without-parker
(list moore downing hall barnacle))
(fathers
(list moore downing hall barnacle parker)))
(let ((gabrielle-fathers (filter (lambda (x) (eq? (daughter x) 'gabrielle)) fathers-without-parker)))
(require (not (null? gabrielle-fathers)))
(require (null? (cdr gabrielle-fathers)))
(require
(eq? (daughter parker)
(yacht (car gabrielle-fathers))))
(require (distinct? (map yacht fathers)))
(require (distinct? (map daughter fathers)))
(list 'moore moore 'downing downing 'hall hall 'barnacle barnacle 'parker parker)))))))))
(ex4-43-2)
try-again
try-again
end
(driver-loop)
(define (eight-queen-diag row1 rest-rows)
(if (null? rest-rows) true
(if
(= (abs (- (car row1) (caar rest-rows)))
(abs (- (cdr row1) (cdar rest-rows)))) false
(eight-queen-diag row1 (cdr rest-rows)))))
(define (eight-queen-sub rows)
(if (null? rows) true
(let ((first-row (car rows))
(rest-rows (cdr rows)))
(if
(eight-queen-diag first-row rest-rows)
(eight-queen-sub rest-rows)
false))))
(define (four-queen)
(let (
(row1 (cons 1 (amb 1 2 3 4)))
(row2 (cons 2 (amb 1 2 3 4)))
(row3 (cons 3 (amb 1 2 3 4)))
(row4 (cons 4 (amb 1 2 3 4)))
)
(let ((rows (list row1 row2 row3 row4)))
(require
(distinct? (map cdr rows)))
(require
(eight-queen-sub rows))
rows)))
(four-queen)
try-again
try-again
;(define (eight-queen)
; (let (
; (row1 (cons 1 (amb 1 2 3 4 5 6 7 8)))
; (row2 (cons 2 (amb 1 2 3 4 5 6 7 8)))
; (row3 (cons 3 (amb 1 2 3 4 5 6 7 8)))
; (row4 (cons 4 (amb 1 2 3 4 5 6 7 8)))
; (row5 (cons 5 (amb 1 2 3 4 5 6 7 8)))
; (row6 (cons 6 (amb 1 2 3 4 5 6 7 8)))
; (row7 (cons 7 (amb 1 2 3 4 5 6 7 8)))
; (row8 (cons 8 (amb 1 2 3 4 5 6 7 8)))
; )
; (let ((rows (list row1 row2 row3 row4 row5 row6 row7 row8)))
; (require
; (distinct? (map cdr rows)))
; (require
; (eight-queen-sub rows))
; rows)))
;(eight-queen)
;try-again
(define (eight-queen-diag row1 rest-rows)
(if (null? rest-rows) true
(if
(= (abs (- (car row1) (caar rest-rows)))
(abs (- (cdr row1) (cdar rest-rows)))) false
(eight-queen-diag row1 (cdr rest-rows)))))
(define (eight-queen)
(let ((row1 (cons 1 (amb 1 2 3 4 5 6 7 8)))
(row2 (cons 2 (amb 1 2 3 4 5 6 7 8))))
(require (distinct? (map cdr (list row1 row2))))
(require (eight-queen-diag row2 (list row1)))
(let ((row3 (cons 3 (amb 1 2 3 4 5 6 7 8))))
(require (distinct? (map cdr (list row1 row2 row3))))
(require (eight-queen-diag row3 (list row2 row1)))
(let ((row4 (cons 4 (amb 1 2 3 4 5 6 7 8))))
(require (distinct? (map cdr (list row1 row2 row3 row4))))
(require (eight-queen-diag row4 (list row3 row2 row1)))
(let ((row5 (cons 5 (amb 1 2 3 4 5 6 7 8))))
(require (distinct? (map cdr (list row1 row2 row3 row4 row5))))
(require (eight-queen-diag row5 (list row4 row3 row2 row1)))
(let ((row6 (cons 6 (amb 1 2 3 4 5 6 7 8))))
(require (distinct? (map cdr (list row1 row2 row3 row4 row5 row6))))
(require (eight-queen-diag row6 (list row5 row4 row3 row2 row1)))
(let ((row7 (cons 7 (amb 1 2 3 4 5 6 7 8))))
(require (distinct? (map cdr (list row1 row2 row3 row4 row5 row6 row7))))
(require (eight-queen-diag row7 (list row6 row5 row4 row3 row2 row1)))
(let ((row8 (cons 8 (amb 1 2 3 4 5 6 7 8))))
(require (distinct? (map cdr (list row1 row2 row3 row4 row5 row6 row7 row8))))
(require (eight-queen-diag row8 (list row7 row6 row5 row4 row3 row2 row1)))
(list row1 row2 row3 row4 row5 row6 row7 row8)))))))))
(eight-queen)
try-again
end
(driver-loop)
(define (eight-queen-diag first-row rest-rows)
(if (null? rest-rows) true
(if
(= (abs (- (car first-row) (caar rest-rows)))
(abs (- (cdr first-row) (cdar rest-rows))))
false
(eight-queen-diag first-row (cdr rest-rows)))))
(define (n-queens n)
(define (iter k rows)
(if (> k n) rows
(let ((new-row (cons k (an-integer-between 1 n))))
(require (distinct? (map cdr (cons new-row rows))))
(require (eight-queen-diag new-row rows))
(iter (+ k 1) (cons new-row rows)))))
(iter 1 '()))
(n-queens 4)
try-again
try-again
(n-queens 6)
(n-queens 8)
end
(driver-loop)
(define nouns '(noun student professor cat class))
(define verbs '(verb studies lectures eats sleeps))
(define articles '(article the a))
(define (parse-sentence)
(list 'sentence
(parse-noun-phrase)
(parse-word verbs)))
(define (parse-noun-phrase)
(list 'noun-phrase
(parse-word articles)
(parse-word nouns)))
(define (parse-word word-list)
(require (not (null? *unparsed*)))
(require (memq (car *unparsed*) (cdr word-list)))
(let ((found-word (car *unparsed*)))
(set! *unparsed* (cdr *unparsed*))
(list (car word-list) found-word)))
(define *unparsed* '())
(define (parse input)
(set! *unparsed* input)
(let ((sent (parse-sentence)))
(require (null? *unparsed*))
sent))
(parse '(the cat eats))
end
(driver-loop)
(define prepositions '(prep for to in by with))
(define (parse-prepositional-phrase)
(list 'prep-phrase
(parse-word prepositions)
(parse-noun-phrase)))
(define (parse-sentence)
(list 'sentence
(parse-noun-phrase)
(parse-verb-phrase)))
(define (parse-verb-phrase)
(define (maybe-extend verb-phrase)
(amb verb-phrase
(maybe-extend (list 'verb-phrase
verb-phrase
(parse-prepositional-phrase)))))
(maybe-extend (parse-word verbs)))
(define (parse-simple-noun-phrase)
(list 'simple-noun-phrase
(parse-word articles)
(parse-word nouns)))
(define (parse-noun-phrase)
(define (maybe-extend noun-phrase)
(amb noun-phrase
(maybe-extend (list 'noun-phrase
noun-phrase
(parse-prepositional-phrase)))))
(maybe-extend (parse-simple-noun-phrase)))
(parse '(the student with the cat sleeps in the class))
(parse '(the professor lectures to the student with the cat))
try-again
try-again
end
(driver-loop)
(parse '(the professor lectures to the student in the class with the cat))
try-again
try-again
try-again
try-again
try-again
end
;ex4.46
; 先に動詞句をパースしようとしてしまう
;ex4.47
;http://wat-aro.hatenablog.com/entry/2016/01/13/011023
(parse '(the professor lectures to the student in the class with the cat))
(define (parse-verb-phrase)
(amb (parse-word verbs)
(list 'verb-phrase
(parse-verb-phrase) ; ここで無限ループが起きる
(parse-prepositional-phrase))))
(parse '(the professor lectures to the student in the class with the cat))
(parse '(the student with the cat sleeps in the class))
(driver-loop)
(define (parse-verb-phrase)
(define (maybe-extend verb-phrase)
(amb verb-phrase
(maybe-extend (list 'verb-phrase
verb-phrase
(parse-prepositional-phrase)))))
(maybe-extend (parse-word verbs)))
(parse '(the student with the cat sleeps in the class))
;; (driver-loop)
;; (define (parse-word word-list)
;; (display *unparsed*)
;; (newline)
;; (display word-list)
;; (newline)
;; (require (not (null? *unparsed*)))
;; (require (memq (car *unparsed*) (cdr word-list)))
;; (let ((found-word (car *unparsed*)))
;; (set! *unparsed* (cdr *unparsed*))
;; (list (car word-list) found-word)))
;; (parse '(the cat eats))
;; try-again
;; end
;; (driver-loop)
;; (define (parse-verb-phrase)
;; (amb (parse-word verbs)
;; (list 'verb-phrase
;; (parse-verb-phrase)
;; (parse-prepositional-phrase))))
;; (parse '(the cat eats))
;; try-again
;; end
;ex4.48
; http://www.serendip.ws/archives/2545
(driver-loop)
(define conjunctions '(conjunction and or then if))
(define (parse-complex-sentence-with-conjuction)
(list 'conjunction-sentence
(parse-word conjunctions)
(parse-complex-sentence)))
(define (parse-complex-sentence)
(define (maybe-extend sentence)
(amb sentence
(maybe-extend (list 'complex-sentence
sentence
(parse-complex-sentence-with-conjuction)))))
(maybe-extend (parse-sentence)))
(define (parse input)
(set! *unparsed* input)
(let ((sent (parse-complex-sentence)))
(require (null? *unparsed*))
sent))
(parse '(the cat eats))
(parse '(the cat eats and the cat sleeps))
end
;ex4.49
(driver-loop)
(define (parse-verb-phrase)
(define (maybe-extend verb-phrase)
(amb verb-phrase
(maybe-extend (list 'verb-phrase
verb-phrase
(parse-prepositional-phrase)))))
(maybe-extend (parse-word verbs)))
(define (parse-word word-list)
(require (not (null? (cdr word-list))))
(let ((found-word (an-element-of (cdr word-list))))
(list (car word-list) found-word)))
(parse-sentence)
try-again
try-again
try-again
try-again
try-again
end
;ex4.50
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((lambda? exp) (analyze-lambda exp))
((let? exp)
(analyze (let->combination exp)))
((begin? exp)
(analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((amb? exp) (analyze-amb exp))
((ramb? exp) (analyze-ramb exp))
((and? exp) (analyze-and exp))
((or? exp) (analyze-or exp))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
(define (ramb? exp) (tagged-list? exp 'ramb))
(use math.mt-random)
(define m (make <mersenne-twister> :seed (sys-time)))
(mt-random-integer m 10)
(define (random a) (mt-random-integer m a))
(use srfi-1)
(list-ref '(1 2) 1)
(take '(1 2) 1)
(drop '(1 2) 1)
(list-ref '(1 2 3) 2)
(mt-random-integer m 10)
(random 110)
(define (analyze-ramb exp)
(let ((cprocs (map analyze (amb-choices exp))))
(lambda (env succeed fail)
(define (try-next choices)
(if (null? choices)
(fail)
(let ((i (random (length choices))))
((list-ref choices i) env
succeed
(lambda ()
(try-next (append (take choices i) (drop choices (+ i 1)))
))))))
(try-next cprocs))))
(driver-loop)
(ramb 1 2 3 4 5)
try-again
try-again
try-again
try-again
try-again
end
(driver-loop)
(define (parse-verb-phrase)
(define (maybe-extend verb-phrase)
(ramb verb-phrase
(maybe-extend (list 'verb-phrase
verb-phrase
(parse-prepositional-phrase)))))
(maybe-extend (parse-word verbs)))
(define (parse-simple-noun-phrase)
(list 'simple-noun-phrase
(parse-word articles)
(parse-word nouns)))
(define (parse-noun-phrase)
(define (maybe-extend noun-phrase)
(ramb noun-phrase
(maybe-extend (list 'noun-phrase
noun-phrase
(parse-prepositional-phrase)))))
(maybe-extend (parse-simple-noun-phrase)))
(define (parse-verb-phrase)
(define (maybe-extend verb-phrase)
(ramb verb-phrase
(maybe-extend (list 'verb-phrase
verb-phrase
(parse-prepositional-phrase)))))
(maybe-extend (parse-word verbs)))
(define (random-word items)
(require (not (null? items)))
(ramb (car items) (an-element-of (cdr items))))
(define (parse-word word-list)
(require (not (null? (cdr word-list))))
(list (car word-list) (random-word (cdr word-list))))
(parse-sentence)
try-again
try-again
;try-again
;try-again
;try-again
end
;ex4.51
(define (permanent-set? exp)
(tagged-list? exp 'permanent-set!))
(define (analyze-permanent-set exp)
(let ((var (assignment-variable exp))
(vproc (analyze (assignment-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(set-variable-value! var val env)
(succeed 'ok fail2))
fail))))
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((permanent-set? exp) (analyze-permanent-set exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((lambda? exp) (analyze-lambda exp))
((let? exp)
(analyze (let->combination exp)))
((begin? exp)
(analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((amb? exp) (analyze-amb exp))
((ramb? exp) (analyze-ramb exp))
((and? exp) (analyze-and exp))
((or? exp) (analyze-or exp))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
(driver-loop)
(define count 0)
(define p-count 0)
(let ((x (an-element-of '(a b c)))
(y (an-element-of '(a b c))))
(set! count (+ count 1))
(permanent-set! p-count (+ p-count 1))
(require (not (eq? x y)))
(list x y count p-count))
try-again
end
(driver-loop)
(define count 0)
(let ((x (an-element-of '(a b c)))
(y (an-element-of '(a b c))))
(set! count (+ count 1))
(require (not (eq? x y)))
(list x y count))
try-again
end
;ex4.52
(define (if-fail? exp)
(tagged-list? exp 'if-fail))
(define (analyze-if-fail exp)
(let ((normal (analyze (cadr exp)))
(alternative (analyze (caddr exp))))
(lambda (env succeed fail)
(normal env
succeed
(lambda ()
(alternative env succeed fail))))))
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((permanent-set? exp) (analyze-permanent-set exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((if-fail? exp) (analyze-if-fail exp))
((lambda? exp) (analyze-lambda exp))
((let? exp)
(analyze (let->combination exp)))
((begin? exp)
(analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((amb? exp) (analyze-amb exp))
((ramb? exp) (analyze-ramb exp))
((and? exp) (analyze-and exp))
((or? exp) (analyze-or exp))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
(driver-loop)
(if-fail (let ((x (an-element-of '(1 3 5))))
(require (even? x))
x)
'all-odd)
(if-fail (let ((x (an-element-of '(1 3 5 8))))
(require (even? x))
x)
'all-odd)
try-again
end
;ex4.53
(driver-loop)
(define (square n) (* n n))
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
(define (prime-sum-pair list1 list2)
(let ((a (an-element-of list1))
(b (an-element-of list2)))
(require (prime? (+ a b)))
(list a b)))
(let ((pairs '()))
(if-fail (let ((p (prime-sum-pair '(1 3 5 8) '(20 35 110))))
(permanent-set! pairs (cons p pairs))
(amb))
pairs))
end
;ex4.54
(define (require? exp) (tagged-list? exp 'require))
(define (require-predicate exp) (cadr exp))
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((permanent-set? exp) (analyze-permanent-set exp))
((definition? exp) (analyze-definition exp))
((require? exp) (analyze-require exp))
((if? exp) (analyze-if exp))
((if-fail? exp) (analyze-if-fail exp))
((lambda? exp) (analyze-lambda exp))
((let? exp)
(analyze (let->combination exp)))
((begin? exp)
(analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((amb? exp) (analyze-amb exp))
((ramb? exp) (analyze-ramb exp))
((and? exp) (analyze-and exp))
((or? exp) (analyze-or exp))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
(define (analyze-require exp)
(let ((pproc (analyze (require-predicate exp))))
(lambda (env succeed fail)
(pproc env
(lambda (pred-value fail2)
(if (false? pred-value)
(fail2)
(succeed 'ok fail2)))
fail))))
(driver-loop)
(define (prime-sum-pair list1 list2)
(let ((a (an-element-of list1))
(b (an-element-of list2)))
(require (prime? (+ a b)))
(list a b)))
(prime-sum-pair '(1 3 5 8) '(20 35 110))
try-again
try-again
try-again
end
| false |
539dddccf9ea9012f1df0ee5265bc1c4c6440f4c | d074b9a2169d667227f0642c76d332c6d517f1ba | /sicp/ch_3/exercise.3.32.scm | 9f7db812662a624867717c9390b7aff49c841d59 | []
| no_license | zenspider/schemers | 4d0390553dda5f46bd486d146ad5eac0ba74cbb4 | 2939ca553ac79013a4c3aaaec812c1bad3933b16 | refs/heads/master | 2020-12-02T18:27:37.261206 | 2019-07-14T15:27:42 | 2019-07-14T15:27:42 | 26,163,837 | 7 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 592 | scm | exercise.3.32.scm | #lang racket/base
;;; Exercise 3.32
;; The procedures to be run during each time segment
;; of the agenda are kept in a queue. Thus, the procedures for each
;; segment are called in the order in which they were added to the
;; agenda (first in, first out). Explain why this order must be
;; used. In particular, trace the behavior of an and-gate whose
;; inputs change from 0,1 to 1,0 in the same segment and say how the
;; behavior would differ if we stored a segment's procedures in an
;; ordinary list, adding and removing procedures only at the front
;; (last in, first out).
;; no
| false |
961362112ba16e80df3ffa34825317189b6ee746 | 00466b7744f0fa2fb42e76658d04387f3aa839d8 | /sicp/chapter1/fib-iter.scm | fa3f134f97fc3d8d7590ebad4210873b5f072165 | [
"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 | 207 | scm | fib-iter.scm | #lang scheme
(define (fib n)
(fib-iter 0 1 n)
)
(define (fib-iter a b n)
(if (= n 0)
b
(fib-iter (+ a b) a (- n 1))
)
)
(define res (fib 6))
(print res) (newline) | false |
663be64c03770ae2d2cf91d113c43e45257eb2e7 | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /ext/ffi/win32/user.scm | 982a6550c472d60570adb6860f69a0128be7af42 | [
"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 | 68,073 | scm | user.scm | ;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; user.scm - Win32 API wrapper library
;;;
;;; 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.
;;;
;; based on Cygwin's winuser.h
#!nounbound
(library (win32 user)
(export WNDPROC
IDI_APPLICATION IDI_HAND IDI_QUESTION IDI_EXCLAMATION
IDI_ASTERISK IDI_WINLOGO IDI_SHIELD
IDC_ARROW IDC_IBEAM IDC_WAIT IDC_CROSS IDC_UPARROW
IDC_SIZE IDC_ICON IDC_SIZENWSE IDC_SIZENESW IDC_SIZEWE
IDC_SIZENS IDC_SIZEALL IDC_NO IDC_HAND IDC_APPSTARTING
IDC_HELP
WNDCLASSEX
PAINTSTRUCT
MSG
CREATESTRUCT
MENUITEMINFO
NMHDR
DRAWITEMSTRUCT
message-box
create-window-ex
create-window
load-icon
destroy-icon
load-cursor
load-image
register-class-ex
get-class-info-ex
post-quit-message
def-window-proc
call-window-proc
show-window
update-window
is-window-visible
get-parent
get-message
peek-message
translate-message
dispatch-message
get-message-pos
tabbed-text-out
get-dc
get-dc-ex
release-dc
begin-paint
end-paint
get-client-rect
get-update-rect
invalidate-rect
inflate-rect
is-rect-empty
fill-rect
set-rect
move-window
destroy-window
send-message
post-message
create-menu
create-popup-menu
destroy-menu
append-menu
delete-menu
get-system-menu
set-menu
draw-menu-bar
insert-menu-item
set-menu-item-info
draw-text
set-window-text
get-window-text
get-window-text-length
get-window-rect
set-window-pos
set-cursor
get-cusor-pos
set-capture
release-capture
set-focus
set-window-long-ptr
get-window-long-ptr
get-sys-color
get-sys-color-brush
set-sys-colors
SCROLLINFO
get-scroll-info
set-scroll-info
scroll-window-ex
system-parameters-info
create-caret
show-caret
hide-caret
destroy-caret
set-caret-pos
get-caret-pos
TIMERPROC
set-timer kill-timer
screen-to-client
get-key-state
;; for custom extension
(rename (user32 *windows-user32-module*))
)
(import (rnrs)
(rename (sagittarius) (define-constant defconst))
(sagittarius ffi)
(win32 defs))
(define user32 (open-win32-module "user32.dll"))
(define WNDPROC callback)
(define-syntax define-constant
(syntax-rules ()
((_ name value)
(begin
(export name)
(defconst name value)))))
(define-syntax define-export
(syntax-rules ()
((_ name value)
(begin
(export name)
(define name value)))))
;; windows messages
(define-constant WM_NULL #x0000)
(define-constant WM_CREATE #x0001)
(define-constant WM_DESTROY #x0002)
(define-constant WM_MOVE #x0003)
(define-constant WM_SIZE #x0005)
(define-constant WM_ACTIVATE #x0006)
(define-constant WA_INACTIVE 0)
(define-constant WA_ACTIVE 1)
(define-constant WA_CLICKACTIVE 2)
(define-constant WM_SETFOCUS #x0007)
(define-constant WM_KILLFOCUS #x0008)
(define-constant WM_ENABLE #x000A)
(define-constant WM_SETREDRAW #x000B)
(define-constant WM_SETTEXT #x000C)
(define-constant WM_GETTEXT #x000D)
(define-constant WM_GETTEXTLENGTH #x000E)
(define-constant WM_PAINT #x000F)
(define-constant WM_CLOSE #x0010)
(define-constant WM_QUERYENDSESSION #x0011)
(define-constant WM_QUERYOPEN #x0013)
(define-constant WM_ENDSESSION #x0016)
(define-constant WM_QUIT #x0012)
(define-constant WM_ERASEBKGND #x0014)
(define-constant WM_SYSCOLORCHANGE #x0015)
(define-constant WM_SHOWWINDOW #x0018)
(define-constant WM_WININICHANGE #x001A)
(define-constant WM_SETTINGCHANGE WM_WININICHANGE)
(define-constant WM_DEVMODECHANGE #x001B)
(define-constant WM_ACTIVATEAPP #x001C)
(define-constant WM_FONTCHANGE #x001D)
(define-constant WM_TIMECHANGE #x001E)
(define-constant WM_CANCELMODE #x001F)
(define-constant WM_SETCURSOR #x0020)
(define-constant WM_MOUSEACTIVATE #x0021)
(define-constant WM_CHILDACTIVATE #x0022)
(define-constant WM_QUEUESYNC #x0023)
(define-constant WM_GETMINMAXINFO #x0024)
(define-constant WM_PAINTICON #x0026)
(define-constant WM_ICONERASEBKGND #x0027)
(define-constant WM_NEXTDLGCTL #x0028)
(define-constant WM_SPOOLERSTATUS #x002A)
(define-constant WM_DRAWITEM #x002B)
(define-c-struct DRAWITEMSTRUCT
(UINT CtlType)
(UINT CtlID)
(UINT itemID)
(UINT itemAction)
(UINT itemState)
(HWND hwndItem)
(HDC hDC)
(struct RECT rcItem)
(ULONG_PTR itemData))
(define-constant WM_MEASUREITEM #x002C)
(define-constant WM_DELETEITEM #x002D)
(define-constant WM_VKEYTOITEM #x002E)
(define-constant WM_CHARTOITEM #x002F)
(define-constant WM_SETFONT #x0030)
(define-constant WM_GETFONT #x0031)
(define-constant WM_SETHOTKEY #x0032)
(define-constant WM_GETHOTKEY #x0033)
(define-constant WM_QUERYDRAGICON #x0037)
(define-constant WM_COMPAREITEM #x0039)
(define-constant WM_GETOBJECT #x003D)
(define-constant WM_COMPACTING #x0041)
(define-constant WM_COMMNOTIFY #x0044)
(define-constant WM_WINDOWPOSCHANGING #x0046)
(define-constant WM_WINDOWPOSCHANGED #x0047)
(define-constant WM_POWER #x0048)
(define-constant WM_COPYDATA #x004A)
(define-constant WM_CANCELJOURNAL #x004B)
(define-constant WM_NOTIFY #x004E)
(define-constant WM_INPUTLANGCHANGEREQUEST #x0050)
(define-constant WM_INPUTLANGCHANGE #x0051)
(define-constant WM_TCARD #x0052)
(define-constant WM_HELP #x0053)
(define-constant WM_USERCHANGED #x0054)
(define-constant WM_NOTIFYFORMAT #x0055)
(define-constant WM_CONTEXTMENU #x007B)
(define-constant WM_STYLECHANGING #x007C)
(define-constant WM_STYLECHANGED #x007D)
(define-constant WM_DISPLAYCHANGE #x007E)
(define-constant WM_GETICON #x007F)
(define-constant WM_SETICON #x0080)
(define-constant WM_NCCREATE #x0081)
(define-constant WM_NCDESTROY #x0082)
(define-constant WM_NCCALCSIZE #x0083)
(define-constant WM_NCHITTEST #x0084)
(define-constant WM_NCPAINT #x0085)
(define-constant WM_NCACTIVATE #x0086)
(define-constant WM_GETDLGCODE #x0087)
(define-constant WM_SYNCPAINT #x0088)
(define-constant WM_NCMOUSEMOVE #x00A0)
(define-constant WM_NCLBUTTONDOWN #x00A1)
(define-constant WM_NCLBUTTONUP #x00A2)
(define-constant WM_NCLBUTTONDBLCLK #x00A3)
(define-constant WM_NCRBUTTONDOWN #x00A4)
(define-constant WM_NCRBUTTONUP #x00A5)
(define-constant WM_NCRBUTTONDBLCLK #x00A6)
(define-constant WM_NCMBUTTONDOWN #x00A7)
(define-constant WM_NCMBUTTONUP #x00A8)
(define-constant WM_NCMBUTTONDBLCLK #x00A9)
(define-constant WM_NCXBUTTONDOWN #x00AB)
(define-constant WM_NCXBUTTONUP #x00AC)
(define-constant WM_NCXBUTTONDBLCLK #x00AD)
(define-constant WM_INPUT #x00FF)
(define-constant WM_KEYFIRST #x0100)
(define-constant WM_KEYDOWN #x0100)
(define-constant WM_KEYUP #x0101)
(define-constant WM_CHAR #x0102)
(define-constant WM_DEADCHAR #x0103)
(define-constant WM_SYSKEYDOWN #x0104)
(define-constant WM_SYSKEYUP #x0105)
(define-constant WM_SYSCHAR #x0106)
(define-constant WM_SYSDEADCHAR #x0107)
(define-constant WM_UNICHAR #x0109)
(define-constant WM_KEYLAST #x0109)
(define-constant WM_IME_STARTCOMPOSITION #x010D)
(define-constant WM_IME_ENDCOMPOSITION #x010E)
(define-constant WM_IME_COMPOSITION #x010F)
(define-constant WM_IME_KEYLAST #x010F)
(define-constant WM_INITDIALOG #x0110)
(define-constant WM_COMMAND #x0111)
(define-constant WM_SYSCOMMAND #x0112)
(define-constant WM_TIMER #x0113)
(define-constant WM_HSCROLL #x0114)
(define-constant WM_VSCROLL #x0115)
(define-constant WM_INITMENU #x0116)
(define-constant WM_INITMENUPOPUP #x0117)
(define-constant WM_MENUSELECT #x011F)
(define-constant WM_MENUCHAR #x0120)
(define-constant WM_ENTERIDLE #x0121)
(define-constant WM_MENURBUTTONUP #x0122)
(define-constant WM_MENUDRAG #x0123)
(define-constant WM_MENUGETOBJECT #x0124)
(define-constant WM_UNINITMENUPOPUP #x0125)
(define-constant WM_MENUCOMMAND #x0126)
(define-constant WM_CHANGEUISTATE #x0127)
(define-constant WM_UPDATEUISTATE #x0128)
(define-constant WM_QUERYUISTATE #x0129)
(define-constant WM_CTLCOLORMSGBOX #x0132)
(define-constant WM_CTLCOLOREDIT #x0133)
(define-constant WM_CTLCOLORLISTBOX #x0134)
(define-constant WM_CTLCOLORBTN #x0135)
(define-constant WM_CTLCOLORDLG #x0136)
(define-constant WM_CTLCOLORSCROLLBAR #x0137)
(define-constant WM_CTLCOLORSTATIC #x0138)
(define-constant WM_MOUSEFIRST #x0200)
(define-constant WM_MOUSEMOVE #x0200)
(define-constant WM_LBUTTONDOWN #x0201)
(define-constant WM_LBUTTONUP #x0202)
(define-constant WM_LBUTTONDBLCLK #x0203)
(define-constant WM_RBUTTONDOWN #x0204)
(define-constant WM_RBUTTONUP #x0205)
(define-constant WM_RBUTTONDBLCLK #x0206)
(define-constant WM_MBUTTONDOWN #x0207)
(define-constant WM_MBUTTONUP #x0208)
(define-constant WM_MBUTTONDBLCLK #x0209)
(define-constant WM_MOUSEWHEEL #x020A)
(define-constant WM_XBUTTONDOWN #x020B)
(define-constant WM_XBUTTONUP #x020C)
(define-constant WM_XBUTTONDBLCLK #x020D)
(define-constant WM_MOUSELAST #x020D)
(define-constant WM_PARENTNOTIFY #x0210)
(define-constant WM_ENTERMENULOOP #x0211)
(define-constant WM_EXITMENULOOP #x0212)
(define-constant WM_NEXTMENU #x0213)
(define-constant WM_SIZING #x0214)
(define-constant WM_CAPTURECHANGED #x0215)
(define-constant WM_MOVING #x0216)
(define-constant WM_POWERBROADCAST #x0218)
(define-constant WM_DEVICECHANGE #x0219)
(define-constant WM_MDICREATE #x0220)
(define-constant WM_MDIDESTROY #x0221)
(define-constant WM_MDIACTIVATE #x0222)
(define-constant WM_MDIRESTORE #x0223)
(define-constant WM_MDINEXT #x0224)
(define-constant WM_MDIMAXIMIZE #x0225)
(define-constant WM_MDITILE #x0226)
(define-constant WM_MDICASCADE #x0227)
(define-constant WM_MDIICONARRANGE #x0228)
(define-constant WM_MDIGETACTIVE #x0229)
(define-constant WM_MDISETMENU #x0230)
(define-constant WM_ENTERSIZEMOVE #x0231)
(define-constant WM_EXITSIZEMOVE #x0232)
(define-constant WM_DROPFILES #x0233)
(define-constant WM_MDIREFRESHMENU #x0234)
;; #if WINVER >= #x0602)
(define-constant WM_POINTERDEVICECHANGE #x238)
(define-constant WM_POINTERDEVICEINRANGE #x239)
(define-constant WM_POINTERDEVICEOUTOFRANGE #x23a)
;; #endif
;; #if WINVER >= #x0601)
(define-constant WM_TOUCH #x0240)
;; #endif
;; #if WINVER >= #x0602)
(define-constant WM_NCPOINTERUPDATE #x0241)
(define-constant WM_NCPOINTERDOWN #x0242)
(define-constant WM_NCPOINTERUP #x0243)
(define-constant WM_POINTERUPDATE #x0245)
(define-constant WM_POINTERDOWN #x0246)
(define-constant WM_POINTERUP #x0247)
(define-constant WM_POINTERENTER #x0249)
(define-constant WM_POINTERLEAVE #x024a)
(define-constant WM_POINTERACTIVATE #x024b)
(define-constant WM_POINTERCAPTURECHANGED #x024c)
(define-constant WM_TOUCHHITTESTING #x024d)
(define-constant WM_POINTERWHEEL #x024e)
(define-constant WM_POINTERHWHEEL #x024f)
;; #endif
(define-constant WM_IME_SETCONTEXT #x0281)
(define-constant WM_IME_NOTIFY #x0282)
(define-constant WM_IME_CONTROL #x0283)
(define-constant WM_IME_COMPOSITIONFULL #x0284)
(define-constant WM_IME_SELECT #x0285)
(define-constant WM_IME_CHAR #x0286)
(define-constant WM_IME_REQUEST #x0288)
(define-constant WM_IME_KEYDOWN #x0290)
(define-constant WM_IME_KEYUP #x0291)
(define-constant WM_MOUSEHOVER #x02A1)
(define-constant WM_MOUSELEAVE #x02A3)
(define-constant WM_NCMOUSEHOVER #x02A0)
(define-constant WM_NCMOUSELEAVE #x02A2)
(define-constant WM_WTSSESSION_CHANGE #x02B1)
(define-constant WM_TABLET_FIRST #x02c0)
(define-constant WM_TABLET_LAST #x02df)
(define-constant WM_CUT #x0300)
(define-constant WM_COPY #x0301)
(define-constant WM_PASTE #x0302)
(define-constant WM_CLEAR #x0303)
(define-constant WM_UNDO #x0304)
(define-constant WM_RENDERFORMAT #x0305)
(define-constant WM_RENDERALLFORMATS #x0306)
(define-constant WM_DESTROYCLIPBOARD #x0307)
(define-constant WM_DRAWCLIPBOARD #x0308)
(define-constant WM_PAINTCLIPBOARD #x0309)
(define-constant WM_VSCROLLCLIPBOARD #x030A)
(define-constant WM_SIZECLIPBOARD #x030B)
(define-constant WM_ASKCBFORMATNAME #x030C)
(define-constant WM_CHANGECBCHAIN #x030D)
(define-constant WM_HSCROLLCLIPBOARD #x030E)
(define-constant WM_QUERYNEWPALETTE #x030F)
(define-constant WM_PALETTEISCHANGING #x0310)
(define-constant WM_PALETTECHANGED #x0311)
(define-constant WM_HOTKEY #x0312)
(define-constant WM_PRINT #x0317)
(define-constant WM_PRINTCLIENT #x0318)
(define-constant WM_APPCOMMAND #x0319)
(define-constant WM_THEMECHANGED #x031A)
(define-constant WM_CLIPBOARDUPDATE #x031d)
;; #if _WIN32_WINNT >= #x0600)
(define-constant WM_DWMCOMPOSITIONCHANGED #x031e)
(define-constant WM_DWMNCRENDERINGCHANGED #x031f)
(define-constant WM_DWMCOLORIZATIONCOLORCHANGED #x0320)
(define-constant WM_DWMWINDOWMAXIMIZEDCHANGE #x0321)
;; #endif
;; #if _WIN32_WINNT >= #x0601)
(define-constant WM_DWMSENDICONICTHUMBNAIL #x0323)
(define-constant WM_DWMSENDICONICLIVEPREVIEWBITMAP #x0326)
;; #endif
;; #if WINVER >= #x0600)
(define-constant WM_GETTITLEBARINFOEX #x033f)
;; #endif
(define-constant WM_HANDHELDFIRST #x0358)
(define-constant WM_HANDHELDLAST #x035F)
(define-constant WM_AFXFIRST #x0360)
(define-constant WM_AFXLAST #x037F)
(define-constant WM_PENWINFIRST #x0380)
(define-constant WM_PENWINLAST #x038F)
(define-constant WM_APP #x8000)
(define-constant WM_USER #x0400)
;; EM
(define-constant EM_GETSEL #x00B0)
(define-constant EM_SETSEL #x00B1)
(define-constant EM_GETRECT #x00B2)
(define-constant EM_SETRECT #x00B3)
(define-constant EM_SETRECTNP #x00B4)
(define-constant EM_SCROLL #x00B5)
(define-constant EM_LINESCROLL #x00B6)
(define-constant EM_SCROLLCARET #x00B7)
(define-constant EM_GETMODIFY #x00B8)
(define-constant EM_SETMODIFY #x00B9)
(define-constant EM_GETLINECOUNT #x00BA)
(define-constant EM_LINEINDEX #x00BB)
(define-constant EM_SETHANDLE #x00BC)
(define-constant EM_GETHANDLE #x00BD)
(define-constant EM_GETTHUMB #x00BE)
(define-constant EM_LINELENGTH #x00C1)
(define-constant EM_REPLACESEL #x00C2)
(define-constant EM_GETLINE #x00C4)
(define-constant EM_LIMITTEXT #x00C5)
(define-constant EM_CANUNDO #x00C6)
(define-constant EM_UNDO #x00C7)
(define-constant EM_FMTLINES #x00C8)
(define-constant EM_LINEFROMCHAR #x00C9)
(define-constant EM_SETTABSTOPS #x00CB)
(define-constant EM_SETPASSWORDCHAR #x00CC)
(define-constant EM_EMPTYUNDOBUFFER #x00CD)
(define-constant EM_GETFIRSTVISIBLELINE #x00CE)
(define-constant EM_SETREADONLY #x00CF)
(define-constant EM_SETWORDBREAKPROC #x00D0)
(define-constant EM_GETWORDBREAKPROC #x00D1)
(define-constant EM_GETPASSWORDCHAR #x00D2)
(define-constant EM_SETMARGINS #x00D3)
(define-constant EM_GETMARGINS #x00D4)
(define-constant EM_SETLIMITTEXT EM_LIMITTEXT)
(define-constant EM_GETLIMITTEXT #x00D5)
(define-constant EM_POSFROMCHAR #x00D6)
(define-constant EM_CHARFROMPOS #x00D7)
(define-constant EM_SETIMESTATUS #x00D8)
(define-constant EM_GETIMESTATUS #x00D9)
(define-constant MF_ENABLED 0)
(define-constant MF_GRAYED 1)
(define-constant MF_DISABLED 2)
(define-constant MF_BITMAP 4)
(define-constant MF_CHECKED 8)
(define-constant MF_POPUP 16)
(define-constant MF_MENUBARBREAK 32)
(define-constant MF_MENUBREAK 64)
(define-constant MF_OWNERDRAW 256)
(define-constant MF_STRING 0)
;; window style
(define-constant CS_VREDRAW 1)
(define-constant CS_HREDRAW 2)
(define-constant CW_USEDEFAULT #x80000000)
(define-constant WS_OVERLAPPED #x00000000)
(define-constant WS_POPUP #x80000000)
(define-constant WS_CHILD #x40000000)
(define-constant WS_MINIMIZE #x20000000)
(define-constant WS_VISIBLE #x10000000)
(define-constant WS_DISABLED #x08000000)
(define-constant WS_CLIPSIBLINGS #x04000000)
(define-constant WS_CLIPCHILDREN #x02000000)
(define-constant WS_MAXIMIZE #x01000000)
(define-constant WS_CAPTION #x00C00000)
(define-constant WS_BORDER #x00800000)
(define-constant WS_DLGFRAME #x00400000)
(define-constant WS_VSCROLL #x00200000)
(define-constant WS_HSCROLL #x00100000)
(define-constant WS_SYSMENU #x00080000)
(define-constant WS_THICKFRAME #x00040000)
(define-constant WS_GROUP #x00020000)
(define-constant WS_TABSTOP #x00010000)
(define-constant WS_MINIMIZEBOX #x00020000)
(define-constant WS_MAXIMIZEBOX #x00010000)
(define-constant WS_TILED WS_OVERLAPPED)
(define-constant WS_ICONIC WS_MINIMIZE)
(define-constant WS_SIZEBOX WS_THICKFRAME)
(define-constant WS_OVERLAPPEDWINDOW
(bitwise-ior WS_OVERLAPPED WS_CAPTION WS_SYSMENU
WS_THICKFRAME WS_MINIMIZEBOX WS_MAXIMIZEBOX))
(define-constant WS_TILEDWINDOW WS_OVERLAPPEDWINDOW)
(define-constant WS_POPUPWINDOW (bitwise-ior WS_POPUP WS_BORDER WS_SYSMENU))
(define-constant WS_CHILDWINDOW WS_CHILD)
(define-constant WS_EX_DLGMODALFRAME #x00000001)
(define-constant WS_EX_NOPARENTNOTIFY #x00000004)
(define-constant WS_EX_TOPMOST #x00000008)
(define-constant WS_EX_ACCEPTFILES #x00000010)
(define-constant WS_EX_TRANSPARENT #x00000020)
(define-constant WS_EX_MDICHILD #x00000040)
(define-constant WS_EX_TOOLWINDOW #x00000080)
(define-constant WS_EX_WINDOWEDGE #x00000100)
(define-constant WS_EX_CLIENTEDGE #x00000200)
(define-constant WS_EX_CONTEXTHELP #x00000400)
(define-constant WS_EX_RIGHT #x00001000)
(define-constant WS_EX_LEFT #x00000000)
(define-constant WS_EX_RTLREADING #x00002000)
(define-constant WS_EX_LTRREADING #x00000000)
(define-constant WS_EX_LEFTSCROLLBAR #x00004000)
(define-constant WS_EX_RIGHTSCROLLBAR #x00000000)
(define-constant WS_EX_CONTROLPARENT #x00010000)
(define-constant WS_EX_STATICEDGE #x00020000)
(define-constant WS_EX_APPWINDOW #x00040000)
(define-constant WS_EX_OVERLAPPEDWINDOW (bitwise-ior WS_EX_WINDOWEDGE WS_EX_CLIENTEDGE))
(define-constant WS_EX_PALETTEWINDOW (bitwise-ior WS_EX_WINDOWEDGE WS_EX_TOOLWINDOW WS_EX_TOPMOST))
(define-constant WS_EX_LAYERED #x00080000)
(define-constant WS_EX_NOINHERITLAYOUT #x00100000)
(define-constant WS_EX_LAYOUTRTL #x00400000)
(define-constant WS_EX_COMPOSITED #x02000000)
(define-constant WS_EX_NOACTIVATE #x08000000)
(define-constant ES_LEFT #x0000)
(define-constant ES_CENTER #x0001)
(define-constant ES_RIGHT #x0002)
(define-constant ES_MULTILINE #x0004)
(define-constant ES_UPPERCASE #x0008)
(define-constant ES_LOWERCASE #x0010)
(define-constant ES_PASSWORD #x0020)
(define-constant ES_AUTOVSCROLL #x0040)
(define-constant ES_AUTOHSCROLL #x0080)
(define-constant ES_NOHIDESEL #x0100)
(define-constant ES_OEMCONVERT #x0400)
(define-constant ES_READONLY #x0800)
(define-constant ES_WANTRETURN #x1000)
(define-constant ES_NUMBER #x2000)
(define-constant EM_GETSEL #x00B0)
(define-constant EM_SETSEL #x00B1)
(define-constant EM_GETRECT #x00B2)
(define-constant EM_SETRECT #x00B3)
(define-constant EM_SETRECTNP #x00B4)
(define-constant EM_SCROLL #x00B5)
(define-constant EM_LINESCROLL #x00B6)
(define-constant EM_SCROLLCARET #x00B7)
(define-constant EM_GETMODIFY #x00B8)
(define-constant EM_SETMODIFY #x00B9)
(define-constant EM_GETLINECOUNT #x00BA)
(define-constant EM_LINEINDEX #x00BB)
(define-constant EM_SETHANDLE #x00BC)
(define-constant EM_GETHANDLE #x00BD)
(define-constant EM_GETTHUMB #x00BE)
(define-constant EM_LINELENGTH #x00C1)
(define-constant EM_REPLACESEL #x00C2)
(define-constant EM_GETLINE #x00C4)
(define-constant EM_LIMITTEXT #x00C5)
(define-constant EM_CANUNDO #x00C6)
(define-constant EM_UNDO #x00C7)
(define-constant EM_FMTLINES #x00C8)
(define-constant EM_LINEFROMCHAR #x00C9)
(define-constant EM_SETTABSTOPS #x00CB)
(define-constant EM_SETPASSWORDCHAR #x00CC)
(define-constant EM_EMPTYUNDOBUFFER #x00CD)
(define-constant EM_GETFIRSTVISIBLELINE #x00CE)
(define-constant EM_SETREADONLY #x00CF)
(define-constant EM_SETWORDBREAKPROC #x00D0)
(define-constant EM_GETWORDBREAKPROC #x00D1)
(define-constant EM_GETPASSWORDCHAR #x00D2)
(define-constant EM_SETMARGINS #x00D3)
(define-constant EM_GETMARGINS #x00D4)
(define-constant EM_SETLIMITTEXT EM_LIMITTEXT) ;win40 Name change
(define-constant EM_GETLIMITTEXT #x00D5)
(define-constant EM_POSFROMCHAR #x00D6)
(define-constant EM_CHARFROMPOS #x00D7)
(define-constant EM_SETIMESTATUS #x00D8)
(define-constant EM_GETIMESTATUS #x00D9)
(define-constant EM_ENABLEFEATURE #x00DA)
(define-constant EN_SETFOCUS #x0100)
(define-constant EN_KILLFOCUS #x0200)
(define-constant EN_CHANGE #x0300)
(define-constant EN_UPDATE #x0400)
(define-constant EN_ERRSPACE #x0500)
(define-constant EN_MAXTEXT #x0501)
(define-constant EN_HSCROLL #x0601)
(define-constant EN_VSCROLL #x0602)
(define-constant EN_ALIGN_LTR_EC #x0700)
(define-constant EN_ALIGN_RTL_EC #x0701)
(define-constant SB_HORZ 0)
(define-constant SB_VERT 1)
(define-constant SB_CTL 2)
(define-constant SB_BOTH 3)
(define-constant SB_LINEUP 0)
(define-constant SB_LINELEFT 0)
(define-constant SB_LINEDOWN 1)
(define-constant SB_LINERIGHT 1)
(define-constant SB_PAGEUP 2)
(define-constant SB_PAGELEFT 2)
(define-constant SB_PAGEDOWN 3)
(define-constant SB_PAGERIGHT 3)
(define-constant SB_THUMBPOSITION 4)
(define-constant SB_THUMBTRACK 5)
(define-constant SB_TOP 6)
(define-constant SB_LEFT 6)
(define-constant SB_BOTTOM 7)
(define-constant SB_RIGHT 7)
(define-constant SB_ENDSCROLL 8)
(define-constant SW_HIDE 0)
(define-constant SW_SHOWNORMAL 1)
(define-constant SW_NORMAL 1)
(define-constant SW_SHOWMINIMIZED 2)
(define-constant SW_SHOWMAXIMIZED 3)
(define-constant SW_MAXIMIZE 3)
(define-constant SW_SHOWNOACTIVATE 4)
(define-constant SW_SHOW 5)
(define-constant SW_MINIMIZE 6)
(define-constant SW_SHOWMINNOACTIVE 7)
(define-constant SW_SHOWNA 8)
(define-constant SW_RESTORE 9)
(define-constant SW_SHOWDEFAULT 10)
(define-constant SW_FORCEMINIMIZE 11)
(define-constant SW_MAX 11)
(define-constant HIDE_WINDOW 0)
(define-constant SHOW_OPENWINDOW 1)
(define-constant SHOW_ICONWINDOW 2)
(define-constant SHOW_FULLSCREEN 3)
(define-constant SHOW_OPENNOACTIVATE 4)
(define-constant SW_PARENTCLOSING 1)
(define-constant SW_OTHERZOOM 2)
(define-constant SW_PARENTOPENING 3)
(define-constant SW_OTHERUNZOOM 4)
(define-constant MB_ICONQUESTION 32)
(define-constant MB_OK 0)
(define-constant MB_OKCANCEL 1)
(define-constant MB_YESNOCANCEL 3)
(define-constant MB_YESNO 4)
(define-constant IDOK 1)
(define-constant IDCANCEL 2)
(define-constant IDABORT 3)
(define-constant IDRETRY 4)
(define-constant IDIGNORE 5)
(define-constant IDYES 6)
(define-constant IDNO 7)
;; load option
(define-constant IMAGE_BITMAP 0)
(define-constant IMAGE_ICON 1)
(define-constant IMAGE_CURSOR 2)
(define-constant IMAGE_ENHMETAFILE 3)
;; OEM images
(define-export OBM_CLOSE (integer->pointer 32754))
(define-export OBM_UPARROW (integer->pointer 32753))
(define-export OBM_DNARROW (integer->pointer 32752))
(define-export OBM_RGARROW (integer->pointer 32751))
(define-export OBM_LFARROW (integer->pointer 32750))
(define-export OBM_REDUCE (integer->pointer 32749))
(define-export OBM_ZOOM (integer->pointer 32748))
(define-export OBM_RESTORE (integer->pointer 32747))
(define-export OBM_REDUCED (integer->pointer 32746))
(define-export OBM_ZOOMD (integer->pointer 32745))
(define-export OBM_RESTORED (integer->pointer 32744))
(define-export OBM_UPARROWD (integer->pointer 32743))
(define-export OBM_DNARROWD (integer->pointer 32742))
(define-export OBM_RGARROWD (integer->pointer 32741))
(define-export OBM_LFARROWD (integer->pointer 32740))
(define-export OBM_MNARROW (integer->pointer 32739))
(define-export OBM_COMBO (integer->pointer 32738))
(define-export OBM_UPARROWI (integer->pointer 32737))
(define-export OBM_DNARROWI (integer->pointer 32736))
(define-export OBM_RGARROWI (integer->pointer 32735))
(define-export OBM_LFARROWI (integer->pointer 32734))
(define-export OBM_OLD_CLOSE (integer->pointer 32767))
(define-export OBM_SIZE (integer->pointer 32766))
(define-export OBM_OLD_UPARROW (integer->pointer 32765))
(define-export OBM_OLD_DNARROW (integer->pointer 32764))
(define-export OBM_OLD_RGARROW (integer->pointer 32763))
(define-export OBM_OLD_LFARROW (integer->pointer 32762))
(define-export OBM_BTSIZE (integer->pointer 32761))
(define-export OBM_CHECK (integer->pointer 32760))
(define-export OBM_CHECKBOXES (integer->pointer 32759))
(define-export OBM_BTNCORNERS (integer->pointer 32758))
(define-export OBM_OLD_REDUCE (integer->pointer 32757))
(define-export OBM_OLD_ZOOM (integer->pointer 32756))
(define-export OBM_OLD_RESTORE (integer->pointer 32755))
(define-export OCR_NORMAL (integer->pointer 32512))
(define-export OCR_IBEAM (integer->pointer 32513))
(define-export OCR_WAIT (integer->pointer 32514))
(define-export OCR_CROSS (integer->pointer 32515))
(define-export OCR_UP (integer->pointer 32516))
(define-export OCR_SIZE (integer->pointer 32640)) ;/* OBSOLETE: use OCR_SIZEALL */
(define-export OCR_ICON (integer->pointer 32641)) ;/* OBSOLETE: use OCR_NORMAL */
(define-export OCR_SIZENWSE (integer->pointer 32642))
(define-export OCR_SIZENESW (integer->pointer 32643))
(define-export OCR_SIZEWE (integer->pointer 32644))
(define-export OCR_SIZENS (integer->pointer 32645))
(define-export OCR_SIZEALL (integer->pointer 32646))
(define-export OCR_ICOCUR (integer->pointer 32647)) ;/* OBSOLETE: use OIC_WINLOGO */
(define-export OCR_NO (integer->pointer 32648))
(define-export OCR_HAND (integer->pointer 32649))
(define-export OCR_APPSTARTING (integer->pointer 32650))
(define-export OIC_SAMPLE (integer->pointer 32512))
(define-export OIC_HAND (integer->pointer 32513))
(define-export OIC_QUES (integer->pointer 32514))
(define-export OIC_BANG (integer->pointer 32515))
(define-export OIC_NOTE (integer->pointer 32516))
(define-export OIC_WINLOGO (integer->pointer 32517))
(define-export OIC_WARNING OIC_BANG)
(define-export OIC_ERROR OIC_HAND)
(define-export OIC_INFORMATION OIC_NOTE)
(define-export OIC_SHIELD (integer->pointer 32518))
(define-constant LR_DEFAULTCOLOR #x00000000)
(define-constant LR_MONOCHROME #x00000001)
(define-constant LR_COLOR #x00000002)
(define-constant LR_COPYRETURNORG #x00000004)
(define-constant LR_COPYDELETEORG #x00000008)
(define-constant LR_LOADFROMFILE #x00000010)
(define-constant LR_LOADTRANSPARENT #x00000020)
(define-constant LR_DEFAULTSIZE #x00000040)
(define-constant LR_VGACOLOR #x00000080)
(define-constant LR_LOADMAP3DCOLORS #x00001000)
(define-constant LR_CREATEDIBSECTION #x00002000)
(define-constant LR_COPYFROMRESOURCE #x00004000)
(define-constant LR_SHARED #x00008000)
(define IDI_APPLICATION (integer->pointer 32512))
(define IDI_HAND (integer->pointer 32513))
(define IDI_QUESTION (integer->pointer 32514))
(define IDI_EXCLAMATION (integer->pointer 32515))
(define IDI_ASTERISK (integer->pointer 32516))
(define IDI_WINLOGO (integer->pointer 32517))
(define IDI_SHIELD (integer->pointer 32518))
(define-constant MIIM_STATE 1)
(define-constant MIIM_ID 2)
(define-constant MIIM_SUBMENU 4)
(define-constant MIIM_CHECKMARKS 8)
(define-constant MIIM_TYPE 16)
(define-constant MFT_STRING 0)
(define IDC_ARROW (integer->pointer 32512))
(define IDC_IBEAM (integer->pointer 32513))
(define IDC_WAIT (integer->pointer 32514))
(define IDC_CROSS (integer->pointer 32515))
(define IDC_UPARROW (integer->pointer 32516))
(define IDC_SIZE (integer->pointer 32640))
(define IDC_ICON (integer->pointer 32641))
(define IDC_SIZENWSE (integer->pointer 32642))
(define IDC_SIZENESW (integer->pointer 32643))
(define IDC_SIZEWE (integer->pointer 32644))
(define IDC_SIZENS (integer->pointer 32645))
(define IDC_SIZEALL (integer->pointer 32646))
(define IDC_NO (integer->pointer 32648))
(define IDC_HAND (integer->pointer 32649))
(define IDC_APPSTARTING (integer->pointer 32650))
(define IDC_HELP (integer->pointer 32651))
(define-c-struct WNDCLASSEX
(UINT cbSize)
(UINT style)
(WNDPROC lpfnWndProc)
(int cbClsExtra)
(int cbWndExtra)
(HINSTANCE hInstance)
(HICON hIcon)
(HCURSOR hCursor)
(HBRUSH hbrBackground)
(LPCWSTR lpszMenuName)
(LPCWSTR lpszClassName)
(HICON hIconSm))
(define-constant LPWNDCLASSEX void*)
(define-constant PWNDCLASSEX void*)
(define-c-struct PAINTSTRUCT
(HDC hdc)
(BOOL fErace)
(struct RECT rcPaint)
(BOOL fRestore)
(BOOL fIncUpdate)
(BYTE array 32 rgbReserved))
(define-constant LPPAINTSTRUCT void*)
(define-c-struct MSG
(HWND hwnd)
(UINT message)
(WPARAM wParam)
(LPARAM lParam)
(DWORD time)
(struct POINT pt))
(define-constant LPMSG void*)
(define-constant PMSG void*)
(define-c-struct CREATESTRUCT
(LPVOID lpCreateParams)
(HINSTANCE hInstance)
(HMENU hMenu)
(HWND hwndParent)
(int cy)
(int cx)
(int y)
(int x)
(LONG style)
(LPCSTR lpszName)
(LPCSTR lpszClass)
(DWORD dwExStyle))
(define-constant LPCREATESTRUCT void*)
(define-c-struct MENUITEMINFO
(UINT cbSize)
(UINT fMask)
(UINT fType)
(UINT fState)
(UINT wID)
(HMENU hSubMenu)
(HBITMAP hbmpChecked)
(HBITMAP hbmpUnchecked)
(ULONG_PTR dwItemData)
(LPWSTR dwTypeData)
(UINT cch)
(HBITMAP hbmpItem))
(define-c-typedef MENUITEMINFO (* LPMENUITEMINFO) (* LPCMENUITEMINFO))
(define-constant MIIM_STATE #x00000001)
(define-constant MIIM_ID #x00000002)
(define-constant MIIM_SUBMENU #x00000004)
(define-constant MIIM_CHECKMARKS #x00000008)
(define-constant MIIM_TYPE #x00000010)
(define-constant MIIM_DATA #x00000020)
(define-constant MIIM_STRING #x00000040)
(define-constant MIIM_BITMAP #x00000080)
(define-constant MIIM_FTYPE #x00000100)
(define-c-struct NMHDR
(HWND hwndFrom)
(UINT_PTR idFrom)
(UINT code))
(define-constant LPNMHDR void*)
(define message-box
(c-function user32
int MessageBoxW (HWND LPCWSTR LPCWSTR UINT)))
(define create-window-ex
(c-function user32
HWND CreateWindowExW
(DWORD LPCWSTR LPCWSTR DWORD UINT UINT UINT
UINT HWND HMENU HINSTANCE LPVOID)))
(define (create-window a b c d e f g h i j k)
(create-window-ex 0 a b c d e f g h i j k))
(define load-icon
(c-function user32
HICON LoadIconW (HINSTANCE LPCWSTR)))
(define destroy-icon
(c-function user32 BOOL DestroyIcon (HICON)))
(define load-cursor
(c-function user32
HCURSOR LoadCursorW (HINSTANCE LPCWSTR)))
(define load-image
(c-function user32
HANDLE LoadImageW (HINSTANCE LPCWSTR UINT int int UINT)))
(define register-class-ex
(c-function user32
ATOM RegisterClassExW (void*)))
(define get-class-info-ex
(c-function user32
BOOL GetClassInfoExW (void* LPCWSTR void*)))
(define post-quit-message (c-function user32 void PostQuitMessage (int)))
(define def-window-proc
(c-function user32 LRESULT DefWindowProcW (HWND UINT WPARAM LPARAM)))
(define call-window-proc
(c-function user32
LRESULT CallWindowProcW (WNDPROC HWND UINT WPARAM LPARAM)))
(define show-window (c-function user32 BOOL ShowWindow (HWND int)))
(define update-window (c-function user32 BOOL UpdateWindow (HWND)))
(define get-parent (c-function user32 HWND GetParent (HWND)))
(define is-window-visible (c-function user32 BOOL IsWindowVisible (HWND)))
(define get-message
(c-function user32 int GetMessageW (LPMSG HWND UINT UINT)))
(define peek-message
(c-function user32 BOOL GetMessageW (LPMSG HWND UINT UINT UINT)))
(define translate-message (c-function user32 BOOL TranslateMessage (void*)))
(define dispatch-message (c-function user32 LONG DispatchMessageW (void*)))
(define get-message-pos (c-function user32 DWORD GetMessagePos ()))
(define tabbed-text-out
(c-function user32 LONG TabbedTextOutW
(HDC int int LPCWSTR int int LPINT int)))
(define get-dc (c-function user32 HDC GetDC (HWND)))
(define get-dc-ex (c-function user32 HDC GetDCEx (HWND HRGN DWORD)))
(define release-dc (c-function user32 int ReleaseDC (HWND HDC)))
(define begin-paint (c-function user32 HDC BeginPaint (HWND LPPAINTSTRUCT)))
(define end-paint (c-function user32 BOOL EndPaint (HWND void*)))
(define get-client-rect
(c-function user32 BOOL GetClientRect (HWND LPRECT)))
(define get-update-rect
(c-function user32 BOOL GetUpdateRect (HWND LPRECT BOOL)))
(define invalidate-rect
(c-function user32 BOOL InvalidateRect (HWND LPRECT BOOL)))
(define inflate-rect
(c-function user32 BOOL InflateRect (LPRECT int int)))
(define is-rect-empty (c-function user32 BOOL IsRectEmpty (LPRECT)))
(define fill-rect (c-function user32 int FillRect (HDC LPRECT HBRUSH)))
(define set-rect (c-function user32 BOOL SetRect (LPRECT int int int int)))
(define move-window
(c-function user32 BOOL MoveWindow (HWND int int int int BOOL)))
(define destroy-window (c-function user32 BOOL DestroyWindow (HWND)))
(define send-message
(c-function user32 LRESULT SendMessageW (HWND UINT WPARAM LPARAM)))
(define post-message
(c-function user32 LRESULT PostMessageW (HWND UINT WPARAM LPARAM)))
(define create-menu (c-function user32 HMENU CreateMenu ()))
(define create-popup-menu (c-function user32 HMENU CreateMenu ()))
(define destroy-menu (c-function user32 BOOL DestroyMenu (HMENU)))
(define append-menu
(c-function user32 BOOL AppendMenuW (HMENU UINT UINT_PTR LPCWSTR)))
(define delete-menu (c-function user32 BOOL DeleteMenu (HMENU UINT UINT)))
(define get-system-menu (c-function user32 HMENU GetSystemMenu (HWND BOOL)))
(define set-menu (c-function user32 BOOL SetMenu (HWND HMENU)))
(define draw-menu-bar (c-function user32 BOOL DrawMenuBar (HWND)))
(define insert-menu-item
(c-function user32 BOOL InsertMenuItemW (HMENU UINT BOOL LPMENUITEMINFO)))
(define set-menu-item-info
(c-function user32 BOOL SetMenuItemInfoW (HMENU UINT BOOL LPCMENUITEMINFO)))
(define draw-text
(c-function user32 int DrawTextW (HDC LPCWSTR int LPRECT UINT)))
(define-constant DT_TOP #x00000000)
(define-constant DT_LEFT #x00000000)
(define-constant DT_CENTER #x00000001)
(define-constant DT_RIGHT #x00000002)
(define-constant DT_VCENTER #x00000004)
(define-constant DT_BOTTOM #x00000008)
(define-constant DT_WORDBREAK #x00000010)
(define-constant DT_SINGLELINE #x00000020)
(define-constant DT_EXPANDTABS #x00000040)
(define-constant DT_TABSTOP #x00000080)
(define-constant DT_NOCLIP #x00000100)
(define-constant DT_EXTERNALLEADING #x00000200)
(define-constant DT_CALCRECT #x00000400)
(define-constant DT_NOPREFIX #x00000800)
(define-constant DT_INTERNAL #x00001000)
(define-constant DT_EDITCONTROL #x00002000)
(define-constant DT_PATH_ELLIPSIS #x00004000)
(define-constant DT_END_ELLIPSIS #x00008000)
(define-constant DT_MODIFYSTRING #x00010000)
(define-constant DT_RTLREADING #x00020000)
(define-constant DT_WORD_ELLIPSIS #x00040000)
(define-constant DT_NOFULLWIDTHCHARBREAK #x00080000)
(define-constant DT_HIDEPREFIX #x00100000)
(define-constant DT_PREFIXONLY #x00200000)
(define set-window-text
(c-function user32 BOOL SetWindowTextW (HWND LPCWSTR)))
(define get-window-text
(c-function user32 int GetWindowTextW (HWND LPWSTR int)))
(define get-window-text-length
(c-function user32 int GetWindowTextLengthW (HWND)))
(define get-window-rect
(c-function user32 BOOL GetWindowRect (HWND LPRECT)))
(define set-window-pos
(c-function user32 BOOL SetWindowPos (HWND HWND int int int int UINT)))
(define set-cursor (c-function user32 HCURSOR SetCursor (HCURSOR)))
(define get-cusor-pos (c-function user32 BOOL GetCursorPos (LPPOINT)))
(define set-capture (c-function user32 HWND SetCapture (HWND)))
(define release-capture (c-function user32 BOOL ReleaseCapture ()))
(define set-focus (c-function user32 HWND SetFocus (HWND)))
;; button style
(define-constant BS_PUSHBUTTON #x00000000)
(define-constant BS_DEFPUSHBUTTON #x00000001)
(define-constant BS_CHECKBOX #x00000002)
(define-constant BS_AUTOCHECKBOX #x00000003)
(define-constant BS_RADIOBUTTON #x00000004)
(define-constant BS_3STATE #x00000005)
(define-constant BS_AUTO3STATE #x00000006)
(define-constant BS_GROUPBOX #x00000007)
(define-constant BS_USERBUTTON #x00000008)
(define-constant BS_AUTORADIOBUTTON #x00000009)
(define-constant BS_PUSHBOX #x0000000A)
(define-constant BS_OWNERDRAW #x0000000B)
(define-constant BS_TYPEMASK #x0000000F)
(define-constant BS_LEFTTEXT #x00000020)
(define-constant BS_TEXT #x00000000)
(define-constant BS_ICON #x00000040)
(define-constant BS_BITMAP #x00000080)
(define-constant BS_LEFT #x00000100)
(define-constant BS_RIGHT #x00000200)
(define-constant BS_CENTER #x00000300)
(define-constant BS_TOP #x00000400)
(define-constant BS_BOTTOM #x00000800)
(define-constant BS_VCENTER #x00000C00)
(define-constant BS_PUSHLIKE #x00001000)
(define-constant BS_MULTILINE #x00002000)
(define-constant BS_NOTIFY #x00004000)
(define-constant BS_FLAT #x00008000)
(define-constant BS_RIGHTBUTTON BS_LEFTTEXT)
(define-constant BN_CLICKED 0)
(define-constant BN_PAINT 1)
(define-constant BN_HILITE 2)
(define-constant BN_UNHILITE 3)
(define-constant BN_DISABLE 4)
(define-constant BN_DOUBLECLICKED 5)
(define-constant BN_PUSHED BN_HILITE)
(define-constant BN_UNPUSHED BN_UNHILITE)
(define-constant BN_DBLCLK BN_DOUBLECLICKED)
(define-constant BN_SETFOCUS 6)
(define-constant BN_KILLFOCUS 7)
(define-constant BM_GETCHECK #x00F0)
(define-constant BM_SETCHECK #x00F1)
(define-constant BM_GETSTATE #x00F2)
(define-constant BM_SETSTATE #x00F3)
(define-constant BM_SETSTYLE #x00F4)
(define-constant BM_CLICK #x00F5)
(define-constant BM_GETIMAGE #x00F6)
(define-constant BM_SETIMAGE #x00F7)
(define-constant BST_UNCHECKED #x0000)
(define-constant BST_CHECKED #x0001)
(define-constant BST_INDETERMINATE #x0002)
(define-constant BST_PUSHED #x0004)
(define-constant BST_FOCUS #x0008)
(cond-expand
(64bit
(define set-window-long-ptr
(c-function user32 LONG SetWindowLongPtrW (HWND int LONG_PTR)))
(define get-window-long-ptr
(c-function user32 LONG_PTR GetWindowLongPtrW (HWND int))))
(32bit
;; I want the signature the same like we can pass the pointer object
(define set-window-long-ptr
(c-function user32 LONG SetWindowLongW (HWND int LONG_PTR)))
(define get-window-long-ptr
(c-function user32 LONG_PTR GetWindowLongW (HWND int)))))
(define-constant GWL_STYLE -16)
(define-constant GWL_EXSTYLE -20)
(define-constant GWLP_WNDPROC -4)
(define-constant GWLP_HINSTANCE -6)
(define-constant GWLP_HWNDPARENT -8)
(define-constant GWLP_USERDATA -21)
(define-constant GWLP_ID -12)
;; list box
(define-constant LBS_NOTIFY #x0001)
(define-constant LBS_SORT #x0002)
(define-constant LBS_NOREDRAW #x0004)
(define-constant LBS_MULTIPLESEL #x0008)
(define-constant LBS_OWNERDRAWFIXED #x0010)
(define-constant LBS_OWNERDRAWVARIABLE #x0020)
(define-constant LBS_HASSTRINGS #x0040)
(define-constant LBS_USETABSTOPS #x0080)
(define-constant LBS_NOINTEGRALHEIGHT #x0100)
(define-constant LBS_MULTICOLUMN #x0200)
(define-constant LBS_WANTKEYBOARDINPUT #x0400)
(define-constant LBS_EXTENDEDSEL #x0800)
(define-constant LBS_DISABLENOSCROLL #x1000)
(define-constant LBS_NODATA #x2000)
(define-constant LBS_NOSEL #x4000)
(define-constant LBS_COMBOBOX #x8000)
(define-constant LBS_STANDARD (bitwise-ior LBS_NOTIFY
LBS_SORT WS_VSCROLL
WS_BORDER))
(define-constant LB_ADDSTRING #x0180)
(define-constant LB_INSERTSTRING #x0181)
(define-constant LB_DELETESTRING #x0182)
(define-constant LB_SELITEMRANGEEX #x0183)
(define-constant LB_RESETCONTENT #x0184)
(define-constant LB_SETSEL #x0185)
(define-constant LB_SETCURSEL #x0186)
(define-constant LB_GETSEL #x0187)
(define-constant LB_GETCURSEL #x0188)
(define-constant LB_GETTEXT #x0189)
(define-constant LB_GETTEXTLEN #x018A)
(define-constant LB_GETCOUNT #x018B)
(define-constant LB_SELECTSTRING #x018C)
(define-constant LB_DIR #x018D)
(define-constant LB_GETTOPINDEX #x018E)
(define-constant LB_FINDSTRING #x018F)
(define-constant LB_GETSELCOUNT #x0190)
(define-constant LB_GETSELITEMS #x0191)
(define-constant LB_SETTABSTOPS #x0192)
(define-constant LB_GETHORIZONTALEXTENT #x0193)
(define-constant LB_SETHORIZONTALEXTENT #x0194)
(define-constant LB_SETCOLUMNWIDTH #x0195)
(define-constant LB_ADDFILE #x0196)
(define-constant LB_SETTOPINDEX #x0197)
(define-constant LB_GETITEMRECT #x0198)
(define-constant LB_GETITEMDATA #x0199)
(define-constant LB_SETITEMDATA #x019A)
(define-constant LB_SELITEMRANGE #x019B)
(define-constant LB_SETANCHORINDEX #x019C)
(define-constant LB_GETANCHORINDEX #x019D)
(define-constant LB_SETCARETINDEX #x019E)
(define-constant LB_GETCARETINDEX #x019F)
(define-constant LB_SETITEMHEIGHT #x01A0)
(define-constant LB_GETITEMHEIGHT #x01A1)
(define-constant LB_FINDSTRINGEXACT #x01A2)
(define-constant LB_SETLOCALE #x01A5)
(define-constant LB_GETLOCALE #x01A6)
(define-constant LB_SETCOUNT #x01A7)
(define-constant LB_INITSTORAGE #x01A8)
(define-constant LB_ITEMFROMPOINT #x01A9)
(define-constant LB_GETLISTBOXINFO #x01B2)
(define-constant LB_MSGMAX #x01B3)
(define-constant LBN_ERRSPACE -2)
(define-constant LBN_SELCHANGE 1)
(define-constant LBN_DBLCLK 2)
(define-constant LBN_SELCANCEL 3)
(define-constant LBN_SETFOCUS 4)
(define-constant LBN_KILLFOCUS 5)
;; size
(define-constant SIZE_RESTORED 0)
(define-constant SIZE_MINIMIZED 1)
(define-constant SIZE_MAXIMIZED 2)
(define-constant SIZE_MAXSHOW 3)
(define-constant SIZE_MAXHIDE 4)
;; key state
(define-constant MK_LBUTTON #x0001)
(define-constant MK_RBUTTON #x0002)
(define-constant MK_SHIFT #x0004)
(define-constant MK_CONTROL #x0008)
(define-constant MK_MBUTTON #x0010)
(define-constant MK_XBUTTON1 #x0020)
(define-constant MK_XBUTTON2 #x0040)
;; virtual keycodes
(define-constant VK_LBUTTON #x01)
(define-constant VK_RBUTTON #x02)
(define-constant VK_CANCEL #x03)
(define-constant VK_MBUTTON #x04)
(define-constant VK_XBUTTON1 #x05)
(define-constant VK_XBUTTON2 #x06)
(define-constant VK_BACK #x08)
(define-constant VK_TAB #x09)
(define-constant VK_CLEAR #x0C)
(define-constant VK_RETURN #x0D)
(define-constant VK_SHIFT #x10)
(define-constant VK_CONTROL #x11)
(define-constant VK_MENU #x12)
(define-constant VK_PAUSE #x13)
(define-constant VK_CAPITAL #x14)
(define-constant VK_KANA #x15)
(define-constant VK_HANGEUL #x15)
(define-constant VK_HANGUL #x15)
(define-constant VK_JUNJA #x17)
(define-constant VK_FINAL #x18)
(define-constant VK_HANJA #x19)
(define-constant VK_KANJI #x19)
(define-constant VK_ESCAPE #x1B)
(define-constant VK_CONVERT #x1C)
(define-constant VK_NONCONVERT #x1D)
(define-constant VK_ACCEPT #x1E)
(define-constant VK_MODECHANGE #x1F)
(define-constant VK_SPACE #x20)
(define-constant VK_PRIOR #x21)
(define-constant VK_NEXT #x22)
(define-constant VK_END #x23)
(define-constant VK_HOME #x24)
(define-constant VK_LEFT #x25)
(define-constant VK_UP #x26)
(define-constant VK_RIGHT #x27)
(define-constant VK_DOWN #x28)
(define-constant VK_SELECT #x29)
(define-constant VK_PRINT #x2A)
(define-constant VK_EXECUTE #x2B)
(define-constant VK_SNAPSHOT #x2C)
(define-constant VK_INSERT #x2D)
(define-constant VK_DELETE #x2E)
(define-constant VK_HELP #x2F)
(define-constant VK_LWIN #x5B)
(define-constant VK_RWIN #x5C)
(define-constant VK_APPS #x5D)
(define-constant VK_SLEEP #x5F)
(define-constant VK_NUMPAD0 #x60)
(define-constant VK_NUMPAD1 #x61)
(define-constant VK_NUMPAD2 #x62)
(define-constant VK_NUMPAD3 #x63)
(define-constant VK_NUMPAD4 #x64)
(define-constant VK_NUMPAD5 #x65)
(define-constant VK_NUMPAD6 #x66)
(define-constant VK_NUMPAD7 #x67)
(define-constant VK_NUMPAD8 #x68)
(define-constant VK_NUMPAD9 #x69)
(define-constant VK_MULTIPLY #x6A)
(define-constant VK_ADD #x6B)
(define-constant VK_SEPARATOR #x6C)
(define-constant VK_SUBTRACT #x6D)
(define-constant VK_DECIMAL #x6E)
(define-constant VK_DIVIDE #x6F)
(define-constant VK_F1 #x70)
(define-constant VK_F2 #x71)
(define-constant VK_F3 #x72)
(define-constant VK_F4 #x73)
(define-constant VK_F5 #x74)
(define-constant VK_F6 #x75)
(define-constant VK_F7 #x76)
(define-constant VK_F8 #x77)
(define-constant VK_F9 #x78)
(define-constant VK_F10 #x79)
(define-constant VK_F11 #x7A)
(define-constant VK_F12 #x7B)
(define-constant VK_F13 #x7C)
(define-constant VK_F14 #x7D)
(define-constant VK_F15 #x7E)
(define-constant VK_F16 #x7F)
(define-constant VK_F17 #x80)
(define-constant VK_F18 #x81)
(define-constant VK_F19 #x82)
(define-constant VK_F20 #x83)
(define-constant VK_F21 #x84)
(define-constant VK_F22 #x85)
(define-constant VK_F23 #x86)
(define-constant VK_F24 #x87)
(define-constant VK_NUMLOCK #x90)
(define-constant VK_SCROLL #x91)
(define-constant VK_OEM_NEC_EQUAL #x92)
(define-constant VK_OEM_FJ_JISHO #x92)
(define-constant VK_OEM_FJ_MASSHOU #x93)
(define-constant VK_OEM_FJ_TOUROKU #x94)
(define-constant VK_OEM_FJ_LOYA #x95)
(define-constant VK_OEM_FJ_ROYA #x96)
(define-constant VK_LSHIFT #xA0)
(define-constant VK_RSHIFT #xA1)
(define-constant VK_LCONTROL #xA2)
(define-constant VK_RCONTROL #xA3)
(define-constant VK_LMENU #xA4)
(define-constant VK_RMENU #xA5)
(define-constant VK_BROWSER_BACK #xA6)
(define-constant VK_BROWSER_FORWARD #xA7)
(define-constant VK_BROWSER_REFRESH #xA8)
(define-constant VK_BROWSER_STOP #xA9)
(define-constant VK_BROWSER_SEARCH #xAA)
(define-constant VK_BROWSER_FAVORITES #xAB)
(define-constant VK_BROWSER_HOME #xAC)
(define-constant VK_VOLUME_MUTE #xAD)
(define-constant VK_VOLUME_DOWN #xAE)
(define-constant VK_VOLUME_UP #xAF)
(define-constant VK_MEDIA_NEXT_TRACK #xB0)
(define-constant VK_MEDIA_PREV_TRACK #xB1)
(define-constant VK_MEDIA_STOP #xB2)
(define-constant VK_MEDIA_PLAY_PAUSE #xB3)
(define-constant VK_LAUNCH_MAIL #xB4)
(define-constant VK_LAUNCH_MEDIA_SELECT #xB5)
(define-constant VK_LAUNCH_APP1 #xB6)
(define-constant VK_LAUNCH_APP2 #xB7)
(define-constant VK_OEM_1 #xBA)
(define-constant VK_OEM_PLUS #xBB)
(define-constant VK_OEM_COMMA #xBC)
(define-constant VK_OEM_MINUS #xBD)
(define-constant VK_OEM_PERIOD #xBE)
(define-constant VK_OEM_2 #xBF)
(define-constant VK_OEM_3 #xC0)
(define-constant VK_OEM_4 #xDB)
(define-constant VK_OEM_5 #xDC)
(define-constant VK_OEM_6 #xDD)
(define-constant VK_OEM_7 #xDE)
(define-constant VK_OEM_8 #xDF)
(define-constant VK_OEM_AX #xE1)
(define-constant VK_OEM_102 #xE2)
(define-constant VK_ICO_HELP #xE3)
(define-constant VK_ICO_00 #xE4)
(define-constant VK_PROCESSKEY #xE5)
(define-constant VK_ICO_CLEAR #xE6)
(define-constant VK_PACKET #xE7)
(define-constant VK_OEM_RESET #xE9)
(define-constant VK_OEM_JUMP #xEA)
(define-constant VK_OEM_PA1 #xEB)
(define-constant VK_OEM_PA2 #xEC)
(define-constant VK_OEM_PA3 #xED)
(define-constant VK_OEM_WSCTRL #xEE)
(define-constant VK_OEM_CUSEL #xEF)
(define-constant VK_OEM_ATTN #xF0)
(define-constant VK_OEM_FINISH #xF1)
(define-constant VK_OEM_COPY #xF2)
(define-constant VK_OEM_AUTO #xF3)
(define-constant VK_OEM_ENLW #xF4)
(define-constant VK_OEM_BACKTAB #xF5)
(define-constant VK_ATTN #xF6)
(define-constant VK_CRSEL #xF7)
(define-constant VK_EXSEL #xF8)
(define-constant VK_EREOF #xF9)
(define-constant VK_PLAY #xFA)
(define-constant VK_ZOOM #xFB)
(define-constant VK_NONAME #xFC)
(define-constant VK_PA1 #xFD)
(define-constant VK_OEM_CLEAR #xFE)
(define-constant COLOR_SCROLLBAR 0)
(define-constant COLOR_BACKGROUND 1)
(define-constant COLOR_ACTIVECAPTION 2)
(define-constant COLOR_INACTIVECAPTION 3)
(define-constant COLOR_MENU 4)
(define-constant COLOR_WINDOW 5)
(define-constant COLOR_WINDOWFRAME 6)
(define-constant COLOR_MENUTEXT 7)
(define-constant COLOR_WINDOWTEXT 8)
(define-constant COLOR_CAPTIONTEXT 9)
(define-constant COLOR_ACTIVEBORDER 10)
(define-constant COLOR_INACTIVEBORDER 11)
(define-constant COLOR_APPWORKSPACE 12)
(define-constant COLOR_HIGHLIGHT 13)
(define-constant COLOR_HIGHLIGHTTEXT 14)
(define-constant COLOR_BTNFACE 15)
(define-constant COLOR_BTNSHADOW 16)
(define-constant COLOR_GRAYTEXT 17)
(define-constant COLOR_BTNTEXT 18)
(define-constant COLOR_INACTIVECAPTIONTEXT 19)
(define-constant COLOR_BTNHIGHLIGHT 20)
(define-constant COLOR_3DDKSHADOW 21)
(define-constant COLOR_3DLIGHT 22)
(define-constant COLOR_INFOTEXT 23)
(define-constant COLOR_INFOBK 24)
(define-constant COLOR_HOTLIGHT 26)
(define-constant COLOR_GRADIENTACTIVECAPTION 27)
(define-constant COLOR_GRADIENTINACTIVECAPTION 28)
(define-constant COLOR_MENUHILIGHT 29)
(define-constant COLOR_MENUBAR 30)
(define-constant COLOR_DESKTOP COLOR_BACKGROUND)
(define-constant COLOR_3DFACE COLOR_BTNFACE)
(define-constant COLOR_3DSHADOW COLOR_BTNSHADOW)
(define-constant COLOR_3DHIGHLIGHT COLOR_BTNHIGHLIGHT)
(define-constant COLOR_3DHILIGHT COLOR_BTNHIGHLIGHT)
(define-constant COLOR_BTNHILIGHT COLOR_BTNHIGHLIGHT)
(define get-sys-color (c-function user32 DWORD GetSysColor (int)))
(define get-sys-color-brush
(c-function user32 HBRUSH GetSysColorBrush (int)))
(define set-sys-colors
;; int, CONST INT *, CONST COLORREF *
(c-function user32 BOOL SetSysColors (int void* void*)))
;; scroll bar
(define-c-struct SCROLLINFO
(UINT cbSize)
(UINT fMask)
(int nMin)
(int nMax)
(UINT nPage)
(int nPos)
(int nTrackPos))
(define-constant LPCSCROLLINFO void*)
(define-constant SIF_RANGE #x0001)
(define-constant SIF_PAGE #x0002)
(define-constant SIF_POS #x0004)
(define-constant SIF_DISABLENOSCROLL #x0008)
(define-constant SIF_TRACKPOS #x0010)
(define-constant SIF_ALL (bitwise-ior SIF_RANGE
SIF_PAGE
SIF_POS
SIF_TRACKPOS))
(define-constant SW_SCROLLCHILDREN #x0001)
(define-constant SW_INVALIDATE #x0002)
(define-constant SW_ERASE #x0004)
(define-constant SW_SMOOTHSCROLL #x0010)
(define get-scroll-info
(c-function user32 BOOL GetScrollInfo (HWND int LPCSCROLLINFO)))
(define set-scroll-info
(c-function user32 int SetScrollInfo (HWND int LPCSCROLLINFO BOOL)))
(define scroll-window-ex
(c-function user32 int ScrollWindowEx
(HWND int int LPRECT LPRECT HRGN LPRECT UINT)))
(define system-parameters-info
(c-function user32 BOOL SystemParametersInfoW (UINT UINT PVOID UINT)))
(define-constant SPI_GETBEEP #x0001)
(define-constant SPI_SETBEEP #x0002)
(define-constant SPI_GETMOUSE #x0003)
(define-constant SPI_SETMOUSE #x0004)
(define-constant SPI_GETBORDER #x0005)
(define-constant SPI_SETBORDER #x0006)
(define-constant SPI_GETKEYBOARDSPEED #x000A)
(define-constant SPI_SETKEYBOARDSPEED #x000B)
(define-constant SPI_LANGDRIVER #x000C)
(define-constant SPI_ICONHORIZONTALSPACING #x000D)
(define-constant SPI_GETSCREENSAVETIMEOUT #x000E)
(define-constant SPI_SETSCREENSAVETIMEOUT #x000F)
(define-constant SPI_GETSCREENSAVEACTIVE #x0010)
(define-constant SPI_SETSCREENSAVEACTIVE #x0011)
(define-constant SPI_GETGRIDGRANULARITY #x0012)
(define-constant SPI_SETGRIDGRANULARITY #x0013)
(define-constant SPI_SETDESKWALLPAPER #x0014)
(define-constant SPI_SETDESKPATTERN #x0015)
(define-constant SPI_GETKEYBOARDDELAY #x0016)
(define-constant SPI_SETKEYBOARDDELAY #x0017)
(define-constant SPI_ICONVERTICALSPACING #x0018)
(define-constant SPI_GETICONTITLEWRAP #x0019)
(define-constant SPI_SETICONTITLEWRAP #x001A)
(define-constant SPI_GETMENUDROPALIGNMENT #x001B)
(define-constant SPI_SETMENUDROPALIGNMENT #x001C)
(define-constant SPI_SETDOUBLECLKWIDTH #x001D)
(define-constant SPI_SETDOUBLECLKHEIGHT #x001E)
(define-constant SPI_GETICONTITLELOGFONT #x001F)
(define-constant SPI_SETDOUBLECLICKTIME #x0020)
(define-constant SPI_SETMOUSEBUTTONSWAP #x0021)
(define-constant SPI_SETICONTITLELOGFONT #x0022)
(define-constant SPI_GETFASTTASKSWITCH #x0023)
(define-constant SPI_SETFASTTASKSWITCH #x0024)
(define-constant SPI_SETDRAGFULLWINDOWS #x0025)
(define-constant SPI_GETDRAGFULLWINDOWS #x0026)
(define-constant SPI_GETNONCLIENTMETRICS #x0029)
(define-constant SPI_SETNONCLIENTMETRICS #x002A)
(define-constant SPI_GETMINIMIZEDMETRICS #x002B)
(define-constant SPI_SETMINIMIZEDMETRICS #x002C)
(define-constant SPI_GETICONMETRICS #x002D)
(define-constant SPI_SETICONMETRICS #x002E)
(define-constant SPI_SETWORKAREA #x002F)
(define-constant SPI_GETWORKAREA #x0030)
(define-constant SPI_SETPENWINDOWS #x0031)
(define-constant SPI_GETHIGHCONTRAST #x0042)
(define-constant SPI_SETHIGHCONTRAST #x0043)
(define-constant SPI_GETKEYBOARDPREF #x0044)
(define-constant SPI_SETKEYBOARDPREF #x0045)
(define-constant SPI_GETSCREENREADER #x0046)
(define-constant SPI_SETSCREENREADER #x0047)
(define-constant SPI_GETANIMATION #x0048)
(define-constant SPI_SETANIMATION #x0049)
(define-constant SPI_GETFONTSMOOTHING #x004A)
(define-constant SPI_SETFONTSMOOTHING #x004B)
(define-constant SPI_SETDRAGWIDTH #x004C)
(define-constant SPI_SETDRAGHEIGHT #x004D)
(define-constant SPI_SETHANDHELD #x004E)
(define-constant SPI_GETLOWPOWERTIMEOUT #x004F)
(define-constant SPI_GETPOWEROFFTIMEOUT #x0050)
(define-constant SPI_SETLOWPOWERTIMEOUT #x0051)
(define-constant SPI_SETPOWEROFFTIMEOUT #x0052)
(define-constant SPI_GETLOWPOWERACTIVE #x0053)
(define-constant SPI_GETPOWEROFFACTIVE #x0054)
(define-constant SPI_SETLOWPOWERACTIVE #x0055)
(define-constant SPI_SETPOWEROFFACTIVE #x0056)
(define-constant SPI_SETCURSORS #x0057)
(define-constant SPI_SETICONS #x0058)
(define-constant SPI_GETDEFAULTINPUTLANG #x0059)
(define-constant SPI_SETDEFAULTINPUTLANG #x005A)
(define-constant SPI_SETLANGTOGGLE #x005B)
(define-constant SPI_GETWINDOWSEXTENSION #x005C)
(define-constant SPI_SETMOUSETRAILS #x005D)
(define-constant SPI_GETMOUSETRAILS #x005E)
(define-constant SPI_SETSCREENSAVERRUNNING #x0061)
;; #define SPI_SCREENSAVERRUNNING SPI_SETSCREENSAVERRUNNING
(define-constant SPI_GETFILTERKEYS #x0032)
(define-constant SPI_SETFILTERKEYS #x0033)
(define-constant SPI_GETTOGGLEKEYS #x0034)
(define-constant SPI_SETTOGGLEKEYS #x0035)
(define-constant SPI_GETMOUSEKEYS #x0036)
(define-constant SPI_SETMOUSEKEYS #x0037)
(define-constant SPI_GETSHOWSOUNDS #x0038)
(define-constant SPI_SETSHOWSOUNDS #x0039)
(define-constant SPI_GETSTICKYKEYS #x003A)
(define-constant SPI_SETSTICKYKEYS #x003B)
(define-constant SPI_GETACCESSTIMEOUT #x003C)
(define-constant SPI_SETACCESSTIMEOUT #x003D)
(define-constant SPI_GETSERIALKEYS #x003E)
(define-constant SPI_SETSERIALKEYS #x003F)
(define-constant SPI_GETSOUNDSENTRY #x0040)
(define-constant SPI_SETSOUNDSENTRY #x0041)
(define-constant SPI_GETSNAPTODEFBUTTON #x005F)
(define-constant SPI_SETSNAPTODEFBUTTON #x0060)
(define-constant SPI_GETMOUSEHOVERWIDTH #x0062)
(define-constant SPI_SETMOUSEHOVERWIDTH #x0063)
(define-constant SPI_GETMOUSEHOVERHEIGHT #x0064)
(define-constant SPI_SETMOUSEHOVERHEIGHT #x0065)
(define-constant SPI_GETMOUSEHOVERTIME #x0066)
(define-constant SPI_SETMOUSEHOVERTIME #x0067)
(define-constant SPI_GETWHEELSCROLLLINES #x0068)
(define-constant SPI_SETWHEELSCROLLLINES #x0069)
(define-constant SPI_GETMENUSHOWDELAY #x006A)
(define-constant SPI_SETMENUSHOWDELAY #x006B)
;; #if _WIN32_WINNT >= 0x0600
(define-constant SPI_GETWHEELSCROLLCHARS #x006C)
(define-constant SPI_SETWHEELSCROLLCHARS #x006D)
;; #endif
(define-constant SPI_GETSHOWIMEUI #x006E)
(define-constant SPI_SETSHOWIMEUI #x006F)
(define-constant SPI_GETMOUSESPEED #x0070)
(define-constant SPI_SETMOUSESPEED #x0071)
(define-constant SPI_GETSCREENSAVERRUNNING #x0072)
(define-constant SPI_GETDESKWALLPAPER #x0073)
;; #if WINVER >= 0x0600
(define-constant SPI_GETAUDIODESCRIPTION #x0074)
(define-constant SPI_SETAUDIODESCRIPTION #x0075)
(define-constant SPI_GETSCREENSAVESECURE #x0076)
(define-constant SPI_SETSCREENSAVESECURE #x0077)
;; #endif
;; #if _WIN32_WINNT >= 0x0601
(define-constant SPI_GETHUNGAPPTIMEOUT #x0078)
(define-constant SPI_SETHUNGAPPTIMEOUT #x0079)
(define-constant SPI_GETWAITTOKILLTIMEOUT #x007a)
(define-constant SPI_SETWAITTOKILLTIMEOUT #x007b)
(define-constant SPI_GETWAITTOKILLSERVICETIMEOUT #x007c)
(define-constant SPI_SETWAITTOKILLSERVICETIMEOUT #x007d)
(define-constant SPI_GETMOUSEDOCKTHRESHOLD #x007e)
(define-constant SPI_SETMOUSEDOCKTHRESHOLD #x007f)
(define-constant SPI_GETPENDOCKTHRESHOLD #x0080)
(define-constant SPI_SETPENDOCKTHRESHOLD #x0081)
(define-constant SPI_GETWINARRANGING #x0082)
(define-constant SPI_SETWINARRANGING #x0083)
(define-constant SPI_GETMOUSEDRAGOUTTHRESHOLD #x0084)
(define-constant SPI_SETMOUSEDRAGOUTTHRESHOLD #x0085)
(define-constant SPI_GETPENDRAGOUTTHRESHOLD #x0086)
(define-constant SPI_SETPENDRAGOUTTHRESHOLD #x0087)
(define-constant SPI_GETMOUSESIDEMOVETHRESHOLD #x0088)
(define-constant SPI_SETMOUSESIDEMOVETHRESHOLD #x0089)
(define-constant SPI_GETPENSIDEMOVETHRESHOLD #x008a)
(define-constant SPI_SETPENSIDEMOVETHRESHOLD #x008b)
(define-constant SPI_GETDRAGFROMMAXIMIZE #x008c)
(define-constant SPI_SETDRAGFROMMAXIMIZE #x008d)
(define-constant SPI_GETSNAPSIZING #x008e)
(define-constant SPI_SETSNAPSIZING #x008f)
(define-constant SPI_GETDOCKMOVING #x0090)
(define-constant SPI_SETDOCKMOVING #x0091)
;; #endif
;; #if WINVER >= 0x0602
(define-constant SPI_GETTOUCHPREDICTIONPARAMETERS #x009c)
(define-constant SPI_SETTOUCHPREDICTIONPARAMETERS #x009d)
(define-constant SPI_GETLOGICALDPIOVERRIDE #x009e)
(define-constant SPI_SETLOGICALDPIOVERRIDE #x009f)
(define-constant SPI_GETMOUSECORNERCLIPLENGTH #x00a0)
(define-constant SPI_SETMOUSECORNERCLIPLENGTH #x00a1)
(define-constant SPI_GETMENURECT #x00a2)
(define-constant SPI_SETMENURECT #x00a3)
;; #endif
(define-constant SPI_GETACTIVEWINDOWTRACKING #x1000)
(define-constant SPI_SETACTIVEWINDOWTRACKING #x1001)
(define-constant SPI_GETMENUANIMATION #x1002)
(define-constant SPI_SETMENUANIMATION #x1003)
(define-constant SPI_GETCOMBOBOXANIMATION #x1004)
(define-constant SPI_SETCOMBOBOXANIMATION #x1005)
(define-constant SPI_GETLISTBOXSMOOTHSCROLLING #x1006)
(define-constant SPI_SETLISTBOXSMOOTHSCROLLING #x1007)
(define-constant SPI_GETGRADIENTCAPTIONS #x1008)
(define-constant SPI_SETGRADIENTCAPTIONS #x1009)
(define-constant SPI_GETKEYBOARDCUES #x100A)
(define-constant SPI_SETKEYBOARDCUES #x100B)
;; #define SPI_GETMENUUNDERLINES SPI_GETKEYBOARDCUES
;; #define SPI_SETMENUUNDERLINES SPI_SETKEYBOARDCUES
(define-constant SPI_GETACTIVEWNDTRKZORDER #x100C)
(define-constant SPI_SETACTIVEWNDTRKZORDER #x100D)
(define-constant SPI_GETHOTTRACKING #x100E)
(define-constant SPI_SETHOTTRACKING #x100F)
(define-constant SPI_GETMENUFADE #x1012)
(define-constant SPI_SETMENUFADE #x1013)
(define-constant SPI_GETSELECTIONFADE #x1014)
(define-constant SPI_SETSELECTIONFADE #x1015)
(define-constant SPI_GETTOOLTIPANIMATION #x1016)
(define-constant SPI_SETTOOLTIPANIMATION #x1017)
(define-constant SPI_GETTOOLTIPFADE #x1018)
(define-constant SPI_SETTOOLTIPFADE #x1019)
(define-constant SPI_GETCURSORSHADOW #x101A)
(define-constant SPI_SETCURSORSHADOW #x101B)
(define-constant SPI_GETMOUSESONAR #x101C)
(define-constant SPI_SETMOUSESONAR #x101D)
(define-constant SPI_GETMOUSECLICKLOCK #x101E)
(define-constant SPI_SETMOUSECLICKLOCK #x101F)
(define-constant SPI_GETMOUSEVANISH #x1020)
(define-constant SPI_SETMOUSEVANISH #x1021)
(define-constant SPI_GETFLATMENU #x1022)
(define-constant SPI_SETFLATMENU #x1023)
(define-constant SPI_GETDROPSHADOW #x1024)
(define-constant SPI_SETDROPSHADOW #x1025)
(define-constant SPI_GETBLOCKSENDINPUTRESETS #x1026)
(define-constant SPI_SETBLOCKSENDINPUTRESETS #x1027)
(define-constant SPI_GETUIEFFECTS #x103E)
(define-constant SPI_SETUIEFFECTS #x103F)
;; #if _WIN32_WINNT >= 0x0600
(define-constant SPI_GETDISABLEOVERLAPPEDCONTENT #x1040)
(define-constant SPI_SETDISABLEOVERLAPPEDCONTENT #x1041)
(define-constant SPI_GETCLIENTAREAANIMATION #x1042)
(define-constant SPI_SETCLIENTAREAANIMATION #x1043)
(define-constant SPI_GETCLEARTYPE #x1048)
(define-constant SPI_SETCLEARTYPE #x1049)
(define-constant SPI_GETSPEECHRECOGNITION #x104a)
(define-constant SPI_SETSPEECHRECOGNITION #x104b)
;; #endif
;; #if WINVER >= 0x0601
(define-constant SPI_GETCARETBROWSING #x104c)
(define-constant SPI_SETCARETBROWSING #x104d)
(define-constant SPI_GETTHREADLOCALINPUTSETTINGS #x104e)
(define-constant SPI_SETTHREADLOCALINPUTSETTINGS #x104f)
(define-constant SPI_GETSYSTEMLANGUAGEBAR #x1050)
(define-constant SPI_SETSYSTEMLANGUAGEBAR #x1051)
;; #endif
(define-constant SPI_GETFOREGROUNDLOCKTIMEOUT #x2000)
(define-constant SPI_SETFOREGROUNDLOCKTIMEOUT #x2001)
(define-constant SPI_GETACTIVEWNDTRKTIMEOUT #x2002)
(define-constant SPI_SETACTIVEWNDTRKTIMEOUT #x2003)
(define-constant SPI_GETFOREGROUNDFLASHCOUNT #x2004)
(define-constant SPI_SETFOREGROUNDFLASHCOUNT #x2005)
(define-constant SPI_GETCARETWIDTH #x2006)
(define-constant SPI_SETCARETWIDTH #x2007)
(define-constant SPI_GETMOUSECLICKLOCKTIME #x2008)
(define-constant SPI_SETMOUSECLICKLOCKTIME #x2009)
(define-constant SPI_GETFONTSMOOTHINGTYPE #x200A)
(define-constant SPI_SETFONTSMOOTHINGTYPE #x200B)
(define-constant FE_FONTSMOOTHINGSTANDARD #x0001)
(define-constant FE_FONTSMOOTHINGCLEARTYPE #x0002)
(define-constant FE_FONTSMOOTHINGDOCKING #x8000)
(define-constant SPI_GETFONTSMOOTHINGCONTRAST #x200C)
(define-constant SPI_SETFONTSMOOTHINGCONTRAST #x200D)
(define-constant SPI_GETFOCUSBORDERWIDTH #x200E)
(define-constant SPI_SETFOCUSBORDERWIDTH #x200F)
(define-constant SPI_GETFOCUSBORDERHEIGHT #x2010)
(define-constant SPI_SETFOCUSBORDERHEIGHT #x2011)
(define-constant SPI_GETFONTSMOOTHINGORIENTATION #x2012)
(define-constant SPI_SETFONTSMOOTHINGORIENTATION #x2013)
;; #if _WIN32_WINNT >= 0x0600
(define-constant SPI_GETMINIMUMHITRADIUS #x2014)
(define-constant SPI_SETMINIMUMHITRADIUS #x2015)
(define-constant SPI_GETMESSAGEDURATION #x2016)
(define-constant SPI_SETMESSAGEDURATION #x2017)
;; #endif
;; #if WINVER >= 0x0602
(define-constant SPI_GETCONTACTVISUALIZATION #x2018)
(define-constant SPI_SETCONTACTVISUALIZATION #x2019)
(define-constant SPI_GETGESTUREVISUALIZATION #x201a)
(define-constant SPI_SETGESTUREVISUALIZATION #x201b)
;; #endif
(define-constant MA_ACTIVATE 1)
(define-constant MA_ACTIVATEANDEAT 2)
(define-constant MA_NOACTIVATE 3)
(define-constant MA_NOACTIVATEANDEAT 4)
(define-constant SWP_ASYNCWINDOWPOS #x4000)
(define-constant SWP_DEFERERASE #x2000)
(define-constant SWP_DRAWFRAME #x0020)
(define-constant SWP_FRAMECHANGED #x0020)
(define-constant SWP_HIDEWINDOW #x0080)
(define-constant SWP_NOACTIVATE #x0010)
(define-constant SWP_NOCOPYBITS #x0100)
(define-constant SWP_NOMOVE #x0002)
(define-constant SWP_NOOWNERZORDER #x0200)
(define-constant SWP_NOREDRAW #x0008)
(define-constant SWP_NOREPOSITION #x0200)
(define-constant SWP_NOSENDCHANGING #x0400)
(define-constant SWP_NOSIZE #x0001)
(define-constant SWP_NOZORDER #x0004)
(define-constant SWP_SHOWWINDOW #x0040)
(define create-caret
(c-function user32 BOOL CreateCaret (HWND HBITMAP int int)))
(define show-caret
(c-function user32 BOOL ShowCaret (HWND)))
(define hide-caret
(c-function user32 BOOL HideCaret (HWND)))
(define destroy-caret
(c-function user32 BOOL DestroyCaret()))
(define set-caret-pos
(c-function user32 BOOL SetCaretPos (int int)))
(define get-caret-pos
(c-function user32 BOOL GetCaretPos (LPPOINT)))
(define TIMERPROC callback)
(define set-timer
(c-function user32 HWND SetTimer (HWND UINT_PTR UINT TIMERPROC)))
(define kill-timer
(c-function user32 BOOL KillTimer (HWND UINT_PTR)))
(define screen-to-client
(c-function user32 BOOL ScreenToClient (HWND LPPOINT)))
(define get-key-state
(c-function user32 SHORT GetKeyState (int)))
)
| true |
078d6526dffc6b4d72c8de02279febea182e8d4b | 37c751fc27e790303b84730013217d1c8cbb60cc | /s48/binary-parse/binary-parse.scm | b2a78a11948d5aca52b025c2138547d3faeceff8 | [
"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 | 15,562 | scm | binary-parse.scm | ;;; This file and the accompanying README were derived from
;;; Oleg's code for Gambit available from
;;;
;;; http://okmij.org/ftp/Scheme/index.html#binio
;;;
; Binary parsing
;----------------------------------------
; Apologia
;
; Binary parsing and unparsing are transformations between primitive or
; composite Scheme values and their external binary representations.
;
; Examples include reading and writing JPEG, TIFF, MP3, ELF file
; formats, communicating with DNS, Kerberos, LDAP, SLP internet
; services, participating in Sun RPC and CORBA/IIOP distributed systems,
; storing and retrieving (arrays of) floating-point numbers in a
; portable and efficient way. This project will propose a set of low- and
; intermediate- level procedures that make binary parsing possible.
; Scheme is a good language to do research in text compression. Text
; compression involves a great deal of building and traversing
; dictionaries, trees and similar data structures, where Scheme
; excels. Performance doesn't matter in research, but the size of
; compressed files does (to figure out the bpc for the common
; benchmarks). Variable-bit i/o is a necessity. It is implemented
; in the present file.
; ASN.1 corresponds to a higher-level parsing (LR parser
; vs. lexer). Information in LDAP responses and X.509 certificates is
; structural and recursive, and so lends itself to be processed in
; Scheme. Variable bit i/o is necessary, and so is a binary lexer for
; a LR parser. Parsing of ASN.1 is a highly profitable enterprise
;----------------------------------------
; The outline of the project
;
; Primitives and streams
;
; - read-byte
; - read-u8vector (cf. read-string)
; - with-input-from-u8vector, with-input-from-encoded-u8vector 'base64,...
; building binary i/o streams from a sequence of bytes. Streams over
; u8vector, u16vector, etc. provide a serial access to memory. See SRFI-4
;
; - read-bit, read-bits via overlayed streams given read-byte
; implemented in the present file.
;
; - mmap-u8vector, munmap-u8vector
;
; Conversions
; - u8vector->integer u8vector endianness,
; u8vector->sinteger u8vector endianness
; These conversion procedures turn a sequence of bytes to an unsigned or
; signed integer, minding the byte order. The u8vector in question can
; have size 1,2,4,8, 3 etc. bytes. These two functions therefore can be
; used to read shorts, longs, extra longs, etc. numbers.
; - u8vector-reverse and other useful u8vector operations
;
; - modf, frexp, ldexp
; The above primitives can be emulated in R5RS, yet they are quite handy
; (for portable FP manipulation) and can be executed very efficiently by
; an FPU.
;
; Higher-level parsing and combinators
; These are combinators that can compose primitives above for more
; complex (possibly iterative) actions.
;
; - skip-bits, next-u8token,...
; - IIOP, RPC/XDR, RMI
; - binary lexer for existing LR/LL-parsers
;
; The composition of primitives and combinators will represent binary
; parsing language in a _full_ notation. This is similar to XPath
; expressions in full notation. Later we need to find out the
; most-frequently used patterns of the binary parsing language and
; design an abbreviated notation. The latter will need a special
; "interpreter". The abbreviated notation may turn out to look like
; Olin's regular expressions.
; $Id: binary-parse.scm,v 1.2 2003/04/14 06:45:20 mainzelM Exp $
;----------------------------------------
; Test harness
;
; The following macro runs built-in test cases -- or does not run,
; depending on which of the two lines below you commented out
;(define-syntax run-test
; (syntax-rules ()
; ((run-test body ...)
; (begin (newline)
; (display "-->Test")
; (newline)
; body ...))))
(define-syntax run-test
(syntax-rules ()
((run-test body ...)
(begin #f))))
;(define-macro (run-test . body) '(begin #f))
;(defmacro run-test body `(begin (display "\n-->Test\n") ,@body))
;;========================================================================
;; Configuration section
;;
; Performance is very important for binary parsing. We have to get all
; help from a particular Scheme system we can get. If a Scheme function
; can support the following primitives faster, we should take
; advantage of that fact.
;---
; Configuration for Gambit. See below for other systems, as well as R5RS
; implementations
;(define-macro (logior x y) `(##fixnum.logior ,x ,y))
;(define-macro (logand x y) `(##fixnum.logand ,x ,y))
;(define-macro (lsh-left x n) `(##fixnum.shl ,x ,n))
;(define-macro (lsh-right x n) `(##fixnum.lshr ,x ,n))
;(define-macro (lsh-left-one x) `(##fixnum.shl ,x 1))
;(define-macro (lsh-right-one x) `(##fixnum.lshr ,x 1))
;(define-macro (-- x) `(##fixnum.- ,x 1))
;(define-macro (++ x) `(##fixnum.+ ,x 1))
;(define-macro (bit-set? x mask) ; return x & mask != 0
; `(##not (##fixnum.zero? (logand ,x ,mask)))
;)
; End of the Gambit-specific configuration section
;---
; ---
; Configuration for S48/scsh
(define logior bitwise-ior)
(define logand bitwise-and)
(define (lsh-right x n) (arithmetic-shift x (- n)))
(define lsh-left arithmetic-shift)
(define (lsh-left-one x) (arithmetic-shift x 1))
(define (lsh-right-one x) (arithmetic-shift x -1))
(define (bit-set? x mask)
(not (zero? (bitwise-and x mask))))
; -- and ++ are not valid R5RS names:
; ++ is not used in this file anyway
; -- is replaced by decrement-one:
(define (decrement-one n)
(- n 1))
(define-syntax time
(syntax-rules ()
((time expr)
expr)))
; End of S48/scsh configuration
; ---
; combine bytes in the MSB order. A byte may be #f
(define (combine-two b1 b2) ; The result is for sure a fixnum
(and b1 b2 (logior (lsh-left b1 8) b2)))
(define (combine-three b1 b2 b3) ; The result is for sure a fixnum
(and b1 b2 b3 (logior (lsh-left (logior (lsh-left b1 8) b2) 8) b3)))
; Here the result may be a BIGNUM
(define (combine-bytes . bytes)
(cond
((null? bytes) 0)
((not (car bytes)) #f)
(else
(let loop ((bytes (cdr bytes)) (result (car bytes)))
(cond
((null? bytes) result)
((not (car bytes)) #f)
(else (loop (cdr bytes) (+ (car bytes) (* 256 result)))))))))
;---
; R5RS implementations of the primitives
; This is the most portable -- and the slowest implementation
; See also logical.scm from SLIB
; (define (logior x y)
; (cond ((= x y) x)
; ((zero? x) y)
; ((zero? y) x)
; (else
; (+ (* (logior (quotient x 2) (quotient y 2)) 2)
; (if (and (even? x) (even? y)) 0 1)))))
; (define (logand x y)
; (cond ((= x y) x)
; ((zero? x) 0)
; ((zero? y) 0)
; (else
; (+ (* (logand (quotient x 2) (quotient y 2)) 2)
; (if (or (even? x) (even? y)) 0 1)))))
; (define (lsh-left x n) (* x (expt 2 n)))
; (define (lsh-right x n) (quotient x (expt 2 n)))
; (define (lsh-left-one x) (* x 2))
; (define (lsh-right-one x) (quotient x 2))
; (define (-- x) (- x 1))
; (define (++ x) (+ x 1))
;(define (bit-set? x mask) ; return x & mask != 0
; (odd? (quotient x mask)) ; mask is an exact power of two
;)
;========================================================================
; Reading a byte
; Read-byte is a fundamental primitive; it needs to be
; added to the standard. Most of the other functions are library
; procedures. The following is an approximation, which clearly doesn't
; hold if the port is a Unicode (especially UTF-8) character stream.
; Return a byte as an exact integer [0,255], or the EOF object
(define (read-byte port)
(let ((c (read-char port)))
(if (eof-object? c) c (char->ascii c))))
; The same as above, but returns #f on EOF.
(define (read-byte-f port)
(let ((c (read-char port)))
(and (not (eof-object? c)) (char->ascii c))))
;========================================================================
; Bit stream
; -- Function: make-bit-reader BYTE-READER
; Given a BYTE-READER (a thunk), construct and return a function
; bit-reader N
;
; that reads N bits from a byte-stream represented by the BYTE-READER.
; The BYTE-READER is a function that takes no arguments and returns
; the current byte as an exact integer [0-255]. The byte reader
; should return #f on EOF.
; The bit reader returns N bits as an exact unsigned integer,
; 0 -... (no limit). N must be a positive integer, otherwise the bit reader
; returns #f. There is no upper limit on N -- other than the size of the
; input stream itself and the amount of (virtual) memory an OS is willing
; to give to your process. If you want to read 1M of _bits_, go ahead.
;
; It is assumed that the bit order is the most-significant bit first.
;
; Note the bit reader keeps the following condition true at all times:
; (= current-inport-pos (ceiling (/ no-bits-read 8)))
; That is, no byte is read until the very moment we really need (some of)
; its bits. The bit reader does _not_ "byte read ahead".
; Therefore, it can be used to handle a concatenation of different
; bit/byte streams *STRICTLY* sequentially, _without_ 'backing up a char',
; 'unreading-char' etc. tricks.
; For example, make-bit-reader has been used to read GRIB files of
; meteorological data, which made of several bitstreams with headers and
; tags.
; Thus careful attention to byte-buffering and optimization are the
; features of this bit reader.
;
; Usage example:
; (define bit-reader (make-bit-reader (lambda () #b11000101)))
; (bit-reader 3) ==> 6
; (bit-reader 4) ==> 2
; The test driver below is another example.
;
; Notes on the algorithm.
; The function recognizes and handles the following special cases:
; - the buffer is empty and 8, 16, 24 bits are to be read
; - reading all bits which are currently in the byte-buffer
; (and then maybe more)
; - reading only one bit
; Since the bit reader is going to be called many times, optimization is
; critical. We need all the help from the compiler/interpreter
; we can get.
(define (make-bit-reader byte-reader)
(let ((buffer 0) (mask 0) ; mask = 128 means that the buffer is full and
; the msb bit is the current (yet unread) bit
(bits-in-buffer 0))
; read the byte into the buffer and set up the counters.
; return #f on eof
(define (set-buffer)
(set! buffer (byte-reader))
(and buffer
(begin
(set! bits-in-buffer 8)
(set! mask 128)
#t)))
; Read fewer bits than there are in the buffer
(define (read-few-bits n)
(let ((value (logand buffer ; all bits in buffer
(decrement-one (lsh-left-one mask)))))
(set! bits-in-buffer (- bits-in-buffer n))
(set! mask (lsh-right mask n))
(lsh-right value bits-in-buffer))) ; remove extra bits
; read n bits given an empty buffer, and append them to value, n>=8
(define (add-more-bits value n)
(let loop ((value value) (n n))
(cond
((zero? n) value)
((< n 8)
(let ((rest (read-n-bits n)))
(and rest (+ (* value (lsh-left 1 n)) rest))))
(else
(let ((b (byte-reader)))
(and b (loop (+ (* value 256) b) (- n 8))))))))
; The main module
(define (read-n-bits n)
; Check the most common cases first
(cond
((not (positive? n)) #f)
((zero? bits-in-buffer) ; the bit-buffer is empty
(case n
((8) (byte-reader))
((16)
(let ((b (byte-reader)))
(combine-two b (byte-reader))))
((24)
(let* ((b1 (byte-reader)) (b2 (byte-reader)))
(combine-three b1 b2 (byte-reader))))
(else
(cond
((< n 8)
(and (set-buffer) (read-few-bits n)))
((< n 16)
(let ((b (byte-reader)))
(and (set-buffer)
(logior (lsh-left b (- n 8))
(read-few-bits (- n 8))))))
(else
(let ((b (byte-reader)))
(and b (add-more-bits b (- n 8)))))))))
((= n 1) ; read one bit
(let ((value (if (bit-set? buffer mask) 1 0)))
(set! mask (lsh-right-one mask))
(set! bits-in-buffer (decrement-one bits-in-buffer))
value))
((>= n bits-in-buffer) ; will empty the buffer
(let ((n-rem (- n bits-in-buffer))
(value (logand buffer ; for mask=64, it'll be &63
(decrement-one (lsh-left-one mask)))))
(set! bits-in-buffer 0)
(cond
((zero? n-rem) value)
((<= n-rem 16)
(let ((rest (read-n-bits n-rem)))
(and rest (logior (lsh-left value n-rem) rest))))
(else (add-more-bits value n-rem)))))
(else (read-few-bits n))
))
read-n-bits)
)
; Validation tests
(run-test
(define (read-bits numbers nbits)
(let* ((left-numbers numbers)
(bit-reader
(make-bit-reader
(lambda ()
(and (pair? left-numbers)
(let ((byte (car left-numbers)))
(set! left-numbers (cdr left-numbers))
byte))))))
(let loop ((result '()))
(let ((num (bit-reader nbits)))
(if num (loop (cons num result)) (reverse result))))))
(define (do-test numbers nbits expected)
(let ((result (read-bits numbers nbits)))
(for-each display
(list "Reading " numbers " by " nbits " bits" ;newline
"The result is: " result ))
(or (equal? result expected)
(error "the result differs from the expected: " expected))))
(do-test '(1 2 3 4 5 6 7) 8 '(1 2 3 4 5 6 7))
(do-test '(193 5 131 4) 1
'(1 1 0 0 0 0 0 1 0 0 0 0 0 1 0 1 1 0 0 0 0 0 1 1
0 0 0 0 0 1 0 0))
(do-test '(193 5 131 4 5) 2
'(3 0 0 1 0 0 1 1 2 0 0 3 0 0 1 0 0 0 1 1))
(do-test '(193 5 131 4) 3
'(6 0 2 0 2 6 0 3 0 1))
(do-test '(193 5 131 4 5 6 7) 4
'(12 1 0 5 8 3 0 4 0 5 0 6 0 7))
(do-test '(193 5 131 4 5 6 7) 5
'(24 4 2 24 6 1 0 5 0 24 3))
(do-test '(193 5 131 4 5 6 7 8 17 24) 8
'(193 5 131 4 5 6 7 8 17 24))
(do-test '(193 5 131 4 5 6 7 8 17 24) 9
'(386 22 24 64 160 385 388 17))
(do-test '(193 5 131 4 5 6 7 8 17) 16
'(49413 33540 1286 1800))
(do-test '(193 5 131 4 5 6 104) 17
'(98827 3088 10291))
(do-test '(193 5 131 4 5 6 104) 19
'(395308 49409))
(do-test '(193 5 131 4 5 6 104) 55
'(27165365385724724))
(do-test '(193 5 131 4 5 6 104) 56
'(54330730771449448))
)
; Timing test
; This test relies on a Gambit special form 'time' to clock
; evaluation of an expression.
; R5RS does not provide any timing facilities. So the test below
; might not run on your particular system, and probably needs
; adjustment anyway.
(run-test
(let ((fname "/tmp/a") (size 10240)
(pattern (ascii->char #x55)))
(define (read-by-bits n)
(for-each display
(list "Reading the file by " n " bits "))
(call-with-input-file fname
(lambda (port)
(let ((bit-reader (make-bit-reader
(lambda () (read-byte-f port)))))
(time
(do ((c (bit-reader n) (bit-reader n))) ((not c))))))))
(for-each display
(list "Creating a file " fname " of size " size " filled with "
pattern ;"\n"
))
(with-output-to-file fname
(lambda () (do ((i 0 (+ 1 i))) ((>= i size)) (write-char pattern))))
(newline)
(display "Reading the file by characters: the baseline ")
(call-with-input-file fname
(lambda (port)
(time
(do ((c (read-char port) (read-char port))) ((eof-object? c))))))
(newline)
(display "Reading the file by bytes: ")
(call-with-input-file fname
(lambda (port)
(time
(do ((c (read-byte-f port) (read-byte-f port))) ((not c))))))
(for-each read-by-bits
(list 1 2 3 4 5 6 7 8 9 10 11 15 16 17 23 24 25 30 32 65535
(* 8 size)))
))
| true |
e42bf09817f922e15a78a95e07da06c9c575dd2a | 000dbfe5d1df2f18e29a76ea7e2a9556cff5e866 | /lib/sagittarius/mop/allocation.scm | 9fca0617eae4460c15f4e95da70f55ca14cea232 | [
"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 | 5,227 | scm | allocation.scm | ;;; -*- mode:scheme; coding:utf-8 -*-
;;;
;;; allocation.scm: metaclass to support :allocation
;;;
;;; Copyright (c) 2010-2012 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(library (sagittarius mop allocation)
(export <allocation-meta> <allocation-mixin>
(rename (<allocation-mixin> <allocation>))
<cached-allocation-meta>
<cached-allocation-mixin>
(rename (<cached-allocation-mixin> <cached-allocation>))
)
(import (rnrs)
(sagittarius) ;; for gensym
(clos user)
(clos core))
(define-class <allocation-meta> (<class>) ())
#|
;; This also works but deprecated.
(define-method compute-getters-and-setters ((class <allocation-meta>) slots)
(let ((r (call-next-method)))
(for-each
(lambda (acc slot)
(cond ((slot-definition-option slot :allocation :instance)
=> (lambda (type)
(case type
((:instance))
((:class)
(let* ((init-value (slot-definition-option
slot :init-value #f))
(init-thunk (slot-definition-option
slot :init-thunk #f))
(def (if init-thunk (init-thunk) init-value)))
(slot-set! acc 'setter (lambda (o v) (set! def v)))
(slot-set! acc 'getter (lambda (o) def))))
(else
(assertion-violation '<allocation-meta>
"unknown :allocation type"
type)))))))
r slots)
r))
|#
(define-method compute-getter-and-setter ((class <allocation-meta>) slot)
(cond ((slot-definition-option slot :allocation :instance)
=> (lambda (type)
(case type
((:instance) (call-next-method))
((:class)
(let* ((init-value (slot-definition-option
slot :init-value #f))
(init-thunk (slot-definition-option
slot :init-thunk #f))
(def (if init-thunk (init-thunk) init-value)))
(list (lambda (o) def)
(lambda (o v) (set! def v))
#f)))
((:delegate)
(let ((to-slot (slot-definition-option slot :forwarding #f)))
(unless (symbol? to-slot)
(assertion-violation 'compute-getter-and-setter
":allocation :delegate requires :forwarding {slot}"))
(list (lambda (o) (slot-ref o to-slot))
(lambda (o v) (slot-set! o to-slot))
#f)))
;; Gauche's :virtual
((:virtual)
(let ((getter (slot-definition-option slot :slot-ref #f))
(setter (slot-definition-option slot :slot-set! #f))
(bound? (slot-definition-option slot :slot-bound? #f)))
(unless (procedure? getter)
(assertion-violation 'compute-getter-and-setter
":allocation :virtual requires at least :slot-ref {procedure}"))
(list getter setter bound?)))
(else
(assertion-violation '<allocation-meta>
"unknown :allocation type"
type)))))
(else (call-next-method))))
(define-class <allocation-mixin> () () :metaclass <allocation-meta>)
(define cached-slot (gensym))
(define (caching-slot? slot) (slot-definition-option slot :cached #f))
(define-class <cached-allocation-meta> (<allocation-meta>) ())
(define-method compute-slots ((class <cached-allocation-meta>))
(let ((slots (call-next-method)))
(if (exists caching-slot? slots)
(cons `(,cached-slot :init-thunk ,make-eq-hashtable) slots)
slots)))
(define-method compute-getter-and-setter ((class <cached-allocation-meta>) slot)
(let ((acc (call-next-method)))
(if (caching-slot? slot)
(let-values (((getter setter bound?) (apply values acc)))
(let ((name (slot-definition-name slot)))
(list (lambda (o)
(cond ((hashtable-ref (slot-ref o cached-slot) name #f))
(else
(let ((v (getter o)))
(hashtable-set! (slot-ref o cached-slot) name v)
v))))
(and setter
(lambda (o v)
(setter o v)
(hashtable-set! (slot-ref o cached-slot) name v)))
bound?)))
acc)))
(define-class <cached-allocation-mixin> () ()
:metaclass <cached-allocation-meta>)
)
| false |
ebc26369093e36ffb4bfea6d21ed6faedb807018 | a6a1c8eb973242fd2345878e5a871a89468d4080 | /2.01.scm | a5b040724bba203ff55f2aa383e70440086c6f80 | []
| 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,049 | scm | 2.01.scm | (use slib)
(require 'trace)
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y))
(* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (equal-rat? x y)
(= (* (numer x) (denom y))
(* (numer y) (denom x))))
(define (make-rat n d) (cons n d))
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (print-rat x)
(newline)
(display (numer x))
(display "/")
(display (denom x)))
; 2.1
(define (make-rat n d)
(let ((g (gcd n d)))
(if (< d 0)
(cons (* -1 (/ n g)) (* -1 (/ d g)))
(cons (/ n g) (/ d g))
)))
(print-rat (make-rat 3 6))
(print-rat (make-rat -3 6))
(print-rat (make-rat 3 -6))
(print-rat (make-rat -3 -6))
| false |
e31c7d012b2de0754e494f4488339e39d3070972 | e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6 | /ch4/4.52.scm | dd96a627a67511f9ef7f780b7c8af695899d228a | []
| no_license | lythesia/sicp-sol | e30918e1ebd799e479bae7e2a9bd4b4ed32ac075 | 169394cf3c3996d1865242a2a2773682f6f00a14 | refs/heads/master | 2021-01-18T14:31:34.469130 | 2019-10-08T03:34:36 | 2019-10-08T03:34:36 | 27,224,763 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 628 | scm | 4.52.scm | (define dont-run-amb 1)
(include "4.03.03.amb.scm")
(define old-analyze analyze)
(define (if-fail? exp) (tagged-list? exp 'if-fail))
(define (analyze exp)
(if (if-fail? exp)
(analyze-if-fail exp)
(old-analyze exp)
)
)
(define (analyze-if-fail exp)
(let ((first (analyze (cadr exp))) (second (analyze (caddr exp))))
(lambda (env succeed fail)
(first
env
(lambda (value fail2)
(succeed value fail2)
)
(lambda ()
(second env succeed fail) ; <- if 1st try fail, continue try(via succeed) in the fail branch
)
)
)
)
)
(driver-loop)
| false |
0b3f674f4632481c8852f9e15e6719d2fb3f2a63 | bd71f5bba1e6482f76962c2bdc01e10d18fac0aa | /examples/state.scm | 651b319891d05ca229f5559aad2cc06f7f90ebce | []
| no_license | Hamayama/Gauche-effects | 089fe0388bff1756c7b9845c4ce8d4723381f315 | 637ca0e86288a7a048577b4f1b0f949333c2eefa | refs/heads/master | 2020-07-06T00:54:37.674086 | 2019-12-19T02:36:21 | 2019-12-19T02:41:28 | 202,837,835 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,628 | scm | state.scm | (add-load-path ".." :relative)
(use gauche.record)
(use effects)
;; Racket's definition
(define null '())
;;
;; effect Get: int
;; effect Set: int -> unit
;;
(define-record-type <get> get get?)
(define-record-type <set> set set? (value set-value))
;;
;; let monad_state = handler
;; | y -> (fun _ -> y)
;; | effect Get k -> (fun s -> (continue k s) s)
;; | effect (Set s') k -> (fun _ -> (continue k ()) s')
;;
(define-handler monad-state
[value y (lambda (_) y)]
[effect e k
[(get? e) (lambda (s) ((k s) s))]
[(set? e) (lambda (_) ((k null) (set-value e)))]])
;;
;; let f = with monad_state handle
;; let x = perform Get in
;; perform (Set (2 * x));
;; perform Get + 10
;; in
;; f 30
;;
(test-handler
"monad-state"
70
(let ((f (handle-with monad-state
(let ((x (perform (get))))
(perform (set (* 2 x)))
(+ (perform (get)) 10)))))
(f 30)))
;;
;; let better_state initial = handler
;; | y -> (fun s -> (y, s))
;; | effect Get k -> (fun s -> (continue k s) s)
;; | effect (Set s') k -> (fun _ -> (continue k ()) s')
;; | finally f -> f initial
;;
(define (better-state initial)
(make-handler
[value y (lambda (s) (list y s))]
[effect e k
[(get? e) (lambda (s) ((k s) s))]
[(set? e) (lambda (_) ((k null) (set-value e)))]]
[finally f (f initial)]))
;;
;; with better_state 30 handle
;; let x = perform Get in
;; perform (Set (2 * x));
;; perform Get + 10
;;
(test-handler
"better-state"
'(70 60)
(handle-with (better-state 30)
(let ((x (perform (get))))
(perform (set (* 2 x)))
(+ (perform (get)) 10))))
| false |
8d1ee841a7e1808f0b4a743188029ea867d4bba2 | 636e10279a19e26c8060f1944259af5ecd06393c | /docs/krivine-memo.scm | 9b396d46c9f889b94cd09c1a7f0b5cbabafb892b | [
"MIT"
]
| permissive | ympbyc/Carrot | 675eab6c9d98523204db90f4a8a2cfc9996e979d | c5258a878864fa4c91727c99820d8348185c84e7 | refs/heads/master | 2022-12-21T04:03:34.327669 | 2022-12-16T10:59:04 | 2022-12-16T10:59:04 | 6,885,775 | 60 | 4 | null | 2017-03-21T12:48:51 | 2012-11-27T15:31:45 | Scheme | UTF-8 | Scheme | false | false | 2,346 | scm | krivine-memo.scm | ;;;
;; N[n] = ACCESS(n); CONTINUE
;; N[λa] = GRAB; N[a]
;; N[b a] = CLOSURE(N[a]); N[b]
;;
;; M := x | M_1 M_2 | λx.M
;; (M N, S, E) -> (M, (S,(N,E)), E)
;; (λM, (S,N), E) -> (M, S, (E,N))
;; (i+1, S, (E,N)) -> (i, S, E)
;; (0, S, (E_1 (M, E_2))) -> (M, S, E_2)
;;To evaluate an application M N, the K-machine builds a closure made of the argument N
;;and the current environment E in the stack and proceeds with the reduction of the function
;;M. This is the first characteristic of the K-machine: a closure is built in constant time and includes the complete current environment.
;;The evaluation of a λ-abstraction places the argument (the stack’s top element) in the environment and proceeds with the body of the function. This is the second and more important characteristic of the K-machine: it strives not to build closures for functions. Other
;;abstract machines return functions as closures before applying them.
;;The evaluation of a variable i amounts to following i links to find the corresponding closure in the environment. The closure’s components become the current code and environment.
;;;
;((-> (a b (** + a b))) 5 6)
(
(,CLOSURE ((,STOP)))
(,CLOSURE (
(,GRAB a)
(,GRAB b)
(,PMARK)
(,CLOSURE ((,PRIMITIVE +) (,CONTINUE)))
(,ACCESS a)
(,ACCESS b)
(,CONTINUE)))
(,DEFINE +)
(,CLOSURE ((,CONSTANT 5) (,CONTINUE)))
(,CLOSURE ((,CONSTANT 6) (,CONTINUE)))
(,ACCESS +)
(,CONTINUE)
)
;(
; (:= (+ a b) (** + a b))
; (:= (x) 7)
; (+ x 6)
;)
(
(,CLOSURE ((,STOP)))
(,CLOSURE (
(,GRAB a)
(,GRAB b)
(,PMARK)
(,CLOSURE ((,PRIMITIVE +) (,CONTINUE)))
(,ACCESS a)
(,ACCESS b)
(,CONTINUE)))
(,DEFINE +)
(,CLOSURE ((,CONSTANT 7) (,CONTINUE)))
(,DEFINE x)
(,CLOSURE ((,ACCESS x) (,CONTINUE)))
(,CLOSURE ((,CONSTANT 6) (,CONTINUE)))
(,ACCESS +)
(,CONTINUE)
)
x, y, z ∈ Var
M, N ∈ Exp
Exp := x | (M N) | λx.M
Krivine: State -> State
State = Clos * Stack
Env = Var -> Clos
Clos = Exp * Env
Stack = [Clos]
VAR Rule
--------
(defliteral (Clos x y)
{x y})
(define (Krivine closure stack)
(case (closure stack)
[({x Env}, Stack)
(Krivine (get Env x) Stack)]
[({(M N) Env}, Stack)
(Krivine {M Env} (cons {N Env} Stack))]
[({(^ x M) Env} (c . Stack))
(Krivine {M (cons (x . c) Env)} Stack)]))
| false |
766c54cfe12b1b4a8313d44c0170d9bee5ccf361 | 958488bc7f3c2044206e0358e56d7690b6ae696c | /scheme/call.scm | a4674e22231e3dd8bd021863c4ad02ab666f2dbb | []
| no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 | Coq | UTF-8 | Scheme | false | false | 252 | scm | call.scm | (define (serialize p)
(define (q . args)
(print "This procedure has been serialized")
(apply p args))
q)
(define (serial p)
(define q
(lambda (l)
(print "This procedure has been serialized even more")
(apply p l)))
q)
| false |
13deb92eccfd77236a87e37b4c7df488ecd0d1dd | 7053803109172ee3fe36594257fb9f323f860c9a | /chapters/1/1.44.scm | 1be35cc31e4f0fd027de37779dad60afe6c97d3d | []
| no_license | david-davidson/SICP | 0c7c38a11b11ef70146f4a511e4ac8d7c0651b82 | 393932a507afdc35cb99451ef53a059e72f71eb1 | refs/heads/main | 2021-06-14T00:36:59.503919 | 2021-05-28T01:54:39 | 2021-05-28T01:55:42 | 195,283,241 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,803 | scm | 1.44.scm | (load "chapters/1/1.43.scm") ; To import `repeated`
;---------------------------------------------------------------------------------------------------
; Smoothing, from signal processing, involves taking a function `f` and some small number `dx`, and
; building a smoothed function whose value at `x` is the average of `f(x - dx)`, `f(x)`, and
; `f(x + dx)`. Write a function `smooth` to implement this.
;---------------------------------------------------------------------------------------------------
(define dx 0.00001)
; Cheating a little and using variadic syntax...
(define (average . args)
(/ (apply + args)
(length args)))
(define (smooth fn)
(lambda (x)
(average (fn (- x dx))
(fn x)
(fn (+ x dx)))))
;---------------------------------------------------------------------------------------------------
; Sometimes it's necessary to repeatedly smooth a function, generating an *n-fold smoothed
; function*. Use `repeated` (from 1.43.scm) and `smooth` to do so.
;---------------------------------------------------------------------------------------------------
(define (n-fold-smoothed fn n)
((repeated smooth n) fn))
;---------------------------------------------------------------------------------------------------
; How does this work?
; * The return value of `(repeated smooth n)` is a unary function that'll call `smooth` `n` times
; * The return value of `((repeated smooth n) fn)` is _another_ unary function (just like that of
; `(smooth fn)`) that'll be called with an actual value `x`
;
; So, invoking `n-fold-smoothed` invokes two higher-order functions before we enter the familiar
; averaging logic!
;---------------------------------------------------------------------------------------------------
| false |
d75a6e8ecc66f99fb66c206647aba2ed8a59dc5b | defeada37d39bca09ef76f66f38683754c0a6aa0 | /System.Data/mono/data/sql-expressions/iif-function.sls | cf664376124ce680c16e7847e34b5daaa19267b8 | []
| 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 | 801 | sls | iif-function.sls | (library (mono data sql-expressions iif-function)
(export new is? iif-function? get-hash-code eval equals?)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new Mono.Data.SqlExpressions.IifFunction a ...)))))
(define (is? a) (clr-is Mono.Data.SqlExpressions.IifFunction a))
(define (iif-function? a)
(clr-is Mono.Data.SqlExpressions.IifFunction a))
(define-method-port
get-hash-code
Mono.Data.SqlExpressions.IifFunction
GetHashCode
(System.Int32))
(define-method-port
eval
Mono.Data.SqlExpressions.IifFunction
Eval
(System.Object System.Data.DataRow))
(define-method-port
equals?
Mono.Data.SqlExpressions.IifFunction
Equals
(System.Boolean System.Object)))
| true |
adb6956bc2ef720aab18c17ed190619cd5456960 | 0bb7631745a274104b084f6684671c3ee9a7b804 | /lib/gambit/unstable/unstable.sld | 1e6067f90f29b498a8a5bc7c711efd417a054046 | [
"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 | 511 | sld | unstable.sld | ;;;============================================================================
;;; File: "unstable.sld"
;;; Copyright (c) 1994-2021 by Marc Feeley, All Rights Reserved.
;;;============================================================================
;;; Experimental procedures. May be changed or removed at any time.
(define-library (unstable)
(namespace "")
(export
make-inexact-real
)
(include "unstable.scm"))
;;;============================================================================
| false |
f6a8022e2e5add942c36958bc1a25a83de4e606a | defeada37d39bca09ef76f66f38683754c0a6aa0 | /UnityEngine.Networking/unity-engine/networking/log-filter.sls | baeb31645ccf7f3c78f4debd2874da73262cf883 | []
| no_license | futsuki/ironscheme-port | 2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5 | 4e7a81b0fbeac9a47440464988e53fb118286c54 | refs/heads/master | 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,484 | sls | log-filter.sls | (library (unity-engine networking log-filter)
(export new
is?
log-filter?
debug
info
warn
error
fatal
current-get
current-set!
current-update!
current-log-level-get
current-log-level-set!
current-log-level-update!
log-debug?
log-info?
log-warn?
log-error?
log-fatal?)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new UnityEngine.Networking.LogFilter a ...)))))
(define (is? a) (clr-is UnityEngine.Networking.LogFilter a))
(define (log-filter? a) (clr-is UnityEngine.Networking.LogFilter a))
(define-field-port
debug
#f
#f
(static:)
UnityEngine.Networking.LogFilter
Debug
System.Int32)
(define-field-port
info
#f
#f
(static:)
UnityEngine.Networking.LogFilter
Info
System.Int32)
(define-field-port
warn
#f
#f
(static:)
UnityEngine.Networking.LogFilter
Warn
System.Int32)
(define-field-port
error
#f
#f
(static:)
UnityEngine.Networking.LogFilter
Error
System.Int32)
(define-field-port
fatal
#f
#f
(static:)
UnityEngine.Networking.LogFilter
Fatal
System.Int32)
(define-field-port
current-get
current-set!
current-update!
(static:)
UnityEngine.Networking.LogFilter
current
UnityEngine.Networking.LogFilter+FilterLevel)
(define-field-port
current-log-level-get
current-log-level-set!
current-log-level-update!
(static: property:)
UnityEngine.Networking.LogFilter
currentLogLevel
System.Int32)
(define-field-port
log-debug?
#f
#f
(static: property:)
UnityEngine.Networking.LogFilter
logDebug
System.Boolean)
(define-field-port
log-info?
#f
#f
(static: property:)
UnityEngine.Networking.LogFilter
logInfo
System.Boolean)
(define-field-port
log-warn?
#f
#f
(static: property:)
UnityEngine.Networking.LogFilter
logWarn
System.Boolean)
(define-field-port
log-error?
#f
#f
(static: property:)
UnityEngine.Networking.LogFilter
logError
System.Boolean)
(define-field-port
log-fatal?
#f
#f
(static: property:)
UnityEngine.Networking.LogFilter
logFatal
System.Boolean))
| true |
5943367c4a5a3e52605685d12fd5109ec35015d9 | 9dc73e4725583ae7af984b2e19f965bbdd023787 | /eopl-solutions/chap1/1-29.ss | 225ef2235d0d30d9e916fe8cfd2b3796ea623449 | []
| no_license | hidaris/thinking-dumps | 2c6f7798bf51208545a08c737a588a4c0cf81923 | 05b6093c3d1239f06f3657cd3bd15bf5cd622160 | refs/heads/master | 2022-12-06T17:43:47.335583 | 2022-11-26T14:29:18 | 2022-11-26T14:29:18 | 83,424,848 | 6 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 754 | ss | 1-29.ss | #lang eopl
(require "base.ss")
;;; sort : Listof(Int) -> Listof(Int)
;;; usage: (sort loi) returns a list of the elements of loi in
;;; ascending order.
(define sort
(lambda (loi)
(cond
[(null? loi) '()]
[else
(insert (car loi)
(sort (cdr loi)))])))
;;; insert : Int x Listof(Int) -> Listof(Int)
;;; to create a list of numbers from n and the numbers
;;; on loi that is sorted in descending order; loi is
;;; already sorted.
(define insert
(lambda (n loi)
(cond
[(null? loi) (cons n '())]
[else
(cond
[(< n (car loi)) (cons n loi)]
[else
(cons (car loi)
(insert n (cdr loi)))])])))
(equal?? (sort '(8 2 5 2 3))
'(2 2 3 5 8))
| false |
abb93a098f0d93eafc5e0752712eb34a114e284e | b389e2ae98c6a980ac889326e104fd366286c193 | /test/testfiles/lambda2.scm | 777d046552477f2d4142e43f4a3e9ef963cb9e57 | []
| no_license | adamrk/scheme2luac | 1a0fbba81b4c2c0e06808bf93137cf5e0f1e9db7 | 5e64008b57a574c0afce72513363a176c7dcf299 | refs/heads/master | 2020-05-24T10:51:48.673627 | 2017-04-21T13:55:49 | 2017-04-21T13:55:49 | 84,849,528 | 22 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 20 | scm | lambda2.scm | ((lambda (x) x) 100) | false |
5c7cab6732b662ca7a9c6a879d546d4e835b4fa3 | 408a2b292dcb010e67632e15aa9c6d6d76b9402d | /brain.scm | bb40055b1679e5d17be7cd21c85bcb821a5d11d5 | []
| no_license | shanecelis/mc-2013 | f0e4832bca1fcbb1cd1c9c79ffcef7872488d50b | 19fc6e42ca47a779ea1565148caa1ffa5febe129 | refs/heads/master | 2021-01-10T19:01:47.043317 | 2013-12-17T20:10:26 | 2013-12-17T20:10:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 7,307 | scm | brain.scm | (define-module (brain)
#:use-module (oop goops)
#:use-module (minimal-cognition ctrnn)
#:use-module ((minimal-cognition fode)
#:renamer (symbol-prefix-proc 'fode:))
#:use-module (beer-parameters)
#:use-module (guile-user)
#:use-module (unified-procedure)
#:use-module (system foreign)
#:use-module (optimize-transition)
#:use-module (vector-math)
#:use-module (phenotype)
#:export (<brain>
set-brain-input!
step-brain!
init-brain-from-genome!
init-brain-state!
make-brain-effector
<ctrnn-brain>
;;ctrnn
;;ctrnn-state
<procedure-brain>
go-left
go-left*
go-right
go-right*
go-nowhere
go-nowhere*
make-brain
brain-class
<matrix-sandwich>
array-duplicate
))
(define-class <brain> ())
;; (make-brain-state brain)
;(define-generic make-brain-state)
;; (set-brain-input! brain input)
(define-generic set-brain-input!)
(define-generic init-brain-state!)
;; (step-brain! brain time-step)
(define-generic step-brain!)
(define-generic init-brain-from-genome!)
;; (make-brain-effector brain)
(define-generic make-brain-effector)
(define-class <ctrnn-brain> (<brain> <phenotype>)
(ctrnn #:accessor ctrnn)
(ctrnn-state #:accessor ctrnn-state)
(ctrnn-state-init #:accessor ctrnn-state-init))
(define (array->vector array)
;; This is terrible!
(list->vector (array->list array)))
(define-method (display (brain <ctrnn-brain>) port)
(apply format port "#<ctrnn-brain n ~a w ~1,1f t ~1,1f b ~1,1f g ~1,1f s ~1,1f s_i ~1,1f>"
(n (ctrnn brain))
(map (lambda (v)
(vector-mean (array->vector v)))
(list
(weights (ctrnn brain))
(time-constant (ctrnn brain))
(bias (ctrnn brain))
(gain (ctrnn brain))
(ctrnn-state brain)
(ctrnn-state-init brain)))))
(define (array-duplicate array)
(let ((dup (apply make-typed-array
(array-type array)
*unspecified*
(array-dimensions array))))
(array-copy! array dup)
dup))
(define-method (initialize (brain <ctrnn-brain>) initargs)
(set! (ctrnn brain) (make-n-ctrnn node-count))
(set! (ctrnn-state brain) (make-ctrnn-state (ctrnn brain)))
(set! (ctrnn-state-init brain) (array-duplicate (ctrnn-state brain))))
(define-method (set-brain-input! (brain <ctrnn-brain>) input)
(set! (input-func (ctrnn brain)) input))
(define-method (step-brain! (brain <ctrnn-brain>) time-step)
(if (not (step-ctrnn (ctrnn-state brain) time-step (ctrnn brain)))
(throw 'step-ctrnn-error)))
(define-method (make-brain-effector (brain <ctrnn-brain>))
(make-effector-func-unified (ctrnn-state brain))
#;
(let ((effector (make-c-effector-func (ctrnn-state brain))))
(format #t "CREATING c effector ~a ~a~%" effector (unified-default-values effector))
;(throw 'blah)
effector))
(define-method (gene-count-required (brain <ctrnn-brain>))
(gene-count-for-n-ctrnn node-count))
;; We'll just call init-brain-from-genome! so as not to break old
;; code.
(define-method (init-from-genome! (brain <ctrnn-brain>) genome)
(init-brain-from-genome! brain genome))
(define-method (init-brain-from-genome! (brain <ctrnn-brain>) genome)
(genome->ctrnn genome (ctrnn brain))
(init-brain-state! brain))
(define-method (init-brain-state! (brain <ctrnn-brain>))
(array-copy! (ctrnn-state-init brain) (ctrnn-state brain)))
(define-class <procedure-brain> (<brain>)
(brain-input #:accessor brain-input)
(proc #:getter proc #:init-keyword #:procedure))
(define-method (set-brain-input! (brain <procedure-brain>) input)
(set! (brain-input brain) input))
(define-method (step-brain! (brain <procedure-brain>) time-step)
#f)
(define-method (init-brain-state! (brain <procedure-brain>))
#f)
(define-method (make-brain-effector (brain <procedure-brain>))
(make-unified-procedure
double
(proc brain)
(list double int '*)))
(define-method (init-brain-from-genome! (brain <procedure-brain>) genome)
(format #t "warning: not able to init a <procedure-brain> from genome.~%")
#f)
(define (go-right t i . rest)
#;(format #t "GO RIGHT ~a~%" i)
(if (= i 1)
1.0
0.0))
(define (go-right* t i . rest)
#;(format #t "GO RIGHT ~a~%" i)
(if (= i 1)
1.0
-1.0))
(define (go-left t i . rest)
#;(format #t "GO LEFT ~a~%" i)
(if (= i 1)
0.0 ;; or -1.0
1.0))
(define (go-left* t i . rest)
#;(format #t "GO LEFT ~a~%" i)
(if (= i 1)
-1.0 ;; or -1.0
1.0))
(define (go-nowhere t i . rest)
0.)
(define (go-nowhere* t i . rest)
(if (= i 1)
1.0 ;; or -1.0
1.0))
(define brain-class <ctrnn-brain>)
(define* (make-brain #:optional (brain-class brain-class))
;(format #t "Brain class is ~s.~%" brain-class)
(if (list? brain-class)
(apply make brain-class)
(make brain-class)))
(define-class <matrix-sandwich> (<brain>)
(old-brain #:accessor ms:old-brain #:init-keyword #:old-brain)
(matrix-sandwich #:accessor ms:matrix-sandwich
#:init-value
#f
;#f64(0. 0. 0. 0.)
#:init-keyword #:matrix-sandwich)
(transition-params #:accessor ms:transition-params #:init-keyword #:transition-params))
(define-method (initialize (brain <matrix-sandwich>) initargs)
(next-method)
;; Must set this up before it is used to create a brain effector.
(set! (ms:matrix-sandwich brain)
(make-random-genome (gene-count-required brain))))
;(define-class <affine-matrix-sandwich> (<matrix-sandwich>))
(define-method (set-brain-input! (brain <matrix-sandwich>) input)
(set-brain-input! (ms:old-brain brain) input))
(define-method (step-brain! (brain <matrix-sandwich>) time-step)
(step-brain! (ms:old-brain brain) time-step))
(define-method (init-brain-state! (brain <matrix-sandwich>))
(init-brain-state! (ms:old-brain brain)))
(define-method (make-brain-effector (brain <matrix-sandwich>))
(unless (ms:matrix-sandwich brain)
(scm-error 'invalid-matrix-sandwich "make-brain-effector" "error: no matrix-sandwich available in ~a" (list brain) #f))
;(format #t "Using matrix ~a~%" (matrix-sandwich brain))
(make-transition-params-effector
(ms:transition-params brain)
(make-brain-effector (ms:old-brain brain))
(ms:matrix-sandwich brain)))
(define-method (init-from-genome! (brain <matrix-sandwich>) genome)
(init-brain-from-genome! brain genome))
(define-method (gene-count-required (brain <matrix-sandwich>))
(tp:gene-count* (ms:transition-params brain)))
(define-method (init-brain-from-genome! (brain <matrix-sandwich>) genome)
(if (ms:matrix-sandwich brain)
(array-copy! genome (ms:matrix-sandwich brain))
(set! (ms:matrix-sandwich brain) (array-duplicate genome))))
(define-method (display (brain <matrix-sandwich>) port)
(format port "#<matrix-sandwich M ~a tp ~a old-brain ~a>"
(ms:matrix-sandwich brain)
(ms:transition-params brain)
(ms:old-brain brain)))
| false |
553fc2e6f459d60bea93cec2b5abaef99ad088d7 | 40f36bb0b41c6a27b2e4802ddb128f7354ea38a3 | /self/schemeR6RS/lib/char.sld | 611d0f34fc3a3960d6a21f26785a69d659df9a8f | []
| no_license | simalaia/modules | b5d2d4c015646b0ea9edc17576a31493f520197c | 45f58e17b1faab48c6f0c46cb17cc010f30872fe | refs/heads/main | 2023-04-05T19:42:12.407065 | 2021-04-22T22:05:04 | 2021-04-22T22:05:04 | 343,354,627 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 567 | sld | char.sld | ;; -*- mode:scheme -*-
;; Less annoying character whatsits
(library (lib char)
(export char->string char-control? char-lower->ctrl)
(import (rnrs))
;; Probably the nicest function here
(define (char->string c) (list->string `(,c)) )
;; I don't remember why I wrote these...
(define (char-control? c)
(if (char? c) (not (< 31 (char->integer c) 127))
(error 'meh "char-control? hates you")) )
(define (char-lower->ctrl c)
(if (and (char? c) (char-lower-case? c))
(integer->char (- (char->integer c) 96))
(error 'meh "ctrl-key hates you")) )
)
| false |
2ddfa470071541155e8fab49a9383506b08bea94 | 3daa81eba7991914c6273dd4fcdddc51f78e027d | /src/scm/tail-rec.scm | 5cefb63f4a4c72a038a763132ced6f0bc72237c8 | [
"MIT"
]
| permissive | baioc/seccom-scheme | ac26d59b21b23a373f0e3e2d1656fdc4fc9cd753 | c43b0539d1b484ba972d074fa63162b23e0b5636 | refs/heads/master | 2020-08-06T10:06:37.120898 | 2020-05-24T19:45:47 | 2020-05-24T19:45:47 | 212,937,301 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,441 | scm | tail-rec.scm | (define (factorial n)
(let iter ((n n) (prod 1))
(if (<= n 1) prod
(iter (- n 1) (* n prod)))))
(define (fibo n)
(let iter ((n n) (prev 1) (curr 0))
(if (= n 0) curr
(iter (- n 1) curr (+ prev curr)))))
; (define (^ b n)
; (if (= n 0) 1 (* b (^ b (- n 1)))))
; (define (^ b n)
; (let iter ((n n) (prod 1))
; (if (= n 0) prod
; (iter (- n 1) (* b prod)))))
; (define (^ b n)
; (cond ((= n 0) 1)
; ((even? n) (square (^ b (halve n))))
; (else (* b (^ b (- n 1))))))
(define (^ b n)
(define (iter b n prod)
(cond ((= n 0) prod)
((even? n) (iter (square b) (halve n) prod))
(else (iter b (- n 1) (* b prod)))))
(if (< n 0)
(iter (/ 1 b) (- n) 1)
(iter b n 1)))
(define (mul b n)
(define (iter b n acc)
(cond ((= n 0) acc)
((even? n) (iter (double b) (halve n) acc))
(else (iter b (- n 1) (+ b acc)))))
(if (< n 0)
(iter (- b) (- n) 0)
(iter b n 0)))
(define (sqrt x)
(define (try guess)
(if (good-enough? guess) guess
(try (improve guess))))
(define (improve guess)
(average guess (/ x guess)))
(define (good-enough? guess)
(< (abs (- (square guess) x)) tolerance))
(try 1.0))
(define (fixcos)
(define (retry old new)
(if (approx? new old) new
(retry new (cos new))))
(define (approx? a b)
(< (abs (- a b)) tolerance))
(retry 0.0 (cos 0.0)))
| false |
f72fe2fcf0838bc63ae7a5b3f8695c47abebb9aa | 86092887e6e28ebc92875339a38271319a87ea0d | /Ch3/3_81.scm | ac8c0dbd1816268c35d4b217d631db32acc94716 | []
| no_license | a2lin/sicp | 5637a172ae15cd1f27ffcfba79d460329ec52730 | eeb8df9188f2a32f49695074a81a2c684fe6e0a1 | refs/heads/master | 2021-01-16T23:55:38.885463 | 2016-12-25T07:52:07 | 2016-12-25T07:52:07 | 57,107,602 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,385 | scm | 3_81.scm | (load "stream_lib.scm")
(define (rand-update x)
(modulo (+ (* x 1103515245) 12345) 32768))
(define random-init 0)
(define random-numbers
(cons-stream
random-init
(stream-map rand-update random-numbers)))
(define (parse-command command)
(cond ((equal? (car command) "generate") (list))
(else (list (cdr command)))))
(define z (cons-stream
(cons "generate" '())
(cons-stream
(cons "generate" '())
(cons-stream
(cons "reset" 5)
(cons-stream
(cons "generate" '())
(cons-stream
(cons "generate" '())
the-empty-stream))))))
(define (rand-cmd cmd-stream init)
(define next
(if (equal? cmd-stream the-empty-stream)
the-empty-stream
(let ((test (parse-command (stream-car cmd-stream))))
(cond ((equal? test the-empty-stream)
(cons-stream
init
(rand-cmd (stream-cdr cmd-stream) (rand-update init))))
(else
(cons-stream
(car test)
(rand-cmd (stream-cdr cmd-stream) (rand-update (car test)))
)
)
)
)
)
)
next
)
(rand-update 5)
(rand-update (rand-update 5))
(rand-update 3)
(take (rand-cmd z 3) 5)
| false |
0c54b14cef87d3d6ff58bbf6aeed79b6b34bb8c6 | d57b9abc4b2154946042204ff901d56c9766cbd3 | /SICP/02/list-oper.scm | 7a031a285b6a1ac2ef3df77308916fcb262355a0 | []
| no_license | caesarii/Beginning-Scheme | 964b37b081af35c1cdc945832975d179a0047a10 | 3bbc5b069ffa9c8ad8fba78dc682ae399f1b0f92 | refs/heads/master | 2021-09-09T22:39:02.126707 | 2018-03-20T02:49:57 | 2018-03-20T02:49:57 | 103,353,999 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,276 | scm | list-oper.scm | ; 获取表中的第 n 项
(define (list-ref items n)
(if (= n 0)
(car items)
(list-ref (cdr items) (- n 1))
)
)
(define squares (list 1 4 9 16 25))
(list-ref squares 3)
; 获取表长度
(define (length items)
(if (null? items)
0
(+ 1 (length (cdr items)))
)
)
(define odds (list 1 3 5 7))
(length odds)
; 迭代获取长度
(define (length items)
(define (iter a count)
(if (null? a)
count
(iter (cdr a) (+ 1 count))
)
)
(iter items 0)
)
; 合并表
(define (append list1 list2)
(if (null? list1)
; list为空,则返回 list2
list2
; 递归和并 (cdr list1) 和 list2
; 将 (car list1) 添加到新列表
(cons (car list1) (append (cdr list1) list2))
)
)
(define list1 (list 1 2 3 4))
(define list2 (list 5 6 7 8))
(append list1 list2)
; 最后一个元素
; 迭代
(define (last-pair lst)
(define (iter curr prev)
(if (null? curr)
prev
(iter (cdr curr) curr)
)
)
(iter lst lst)
)
; 递归
(define (last-pair lst)
(if (null? (cdr lst))
lst
(last-pair (cdr lst))
)
)
(last-pair list2)
; 逆序
; 迭代
(define (reverse lst)
(define result (list))
(define (iter result lst)
(if (null? lst)
result
(iter (cons (car lst) result) (cdr lst))
)
)
(iter (list) lst)
)
; 递归
; 实现不出来 | false |
302f12fa4ec8b60a80b4a3f0e4436736dfb504e8 | a09ad3e3cf64bc87282dea3902770afac90568a7 | /3/17.scm | 343be204c815990d48b0925653ed11dce3adc1b8 | []
| no_license | lockie/sicp-exercises | aae07378034505bf2e825c96c56cf8eb2d8a06ae | 011b37387fddb02e59e05a70fa3946335a0b5b1d | refs/heads/master | 2021-01-01T10:35:59.759525 | 2018-11-30T09:35:35 | 2018-11-30T09:35:35 | 35,365,351 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,006 | scm | 17.scm | #lang sicp
(define (count-pairs x)
(define (visited-pair? p pairs)
(cond ((null? pairs) false)
((eq? p (car pairs)) true)
(else (visited-pair? p (cdr pairs)))))
(let ((visited-pairs '()))
(define (count-pairs-internal x)
(if (not (pair? x))
0
(let ((visited (visited-pair? x visited-pairs)))
(begin (set! visited-pairs (append visited-pairs (list x)))
(if visited
0
(+ (count-pairs-internal (car x))
(count-pairs-internal (cdr x))
1))))))
(count-pairs-internal x)))
(count-pairs (cons 1 (cons 2 (cons 3 nil)))) ; 3
(define q (cons 1 2))
(count-pairs (cons q (cons q 1))) ; 4
(define p '(1))
(define pp (cons q q))
(count-pairs (cons pp pp)) ; 7
(define r (list 1 2 3))
(set-cdr! (cddr r) r)
(count-pairs r) ; infty
| false |
57afb961bcdd5f37b068a70964001ec93c951147 | 3db754b51b009dc74ef2043fbfbf6189f30d453f | /tree-syntax.scm | 6d0df3230668eddbc5fa90fe9174a47b79870520 | [
"MIT"
]
| permissive | webyrd/tree-automata | b8013f610f03454e0c300c93677ef730bb3b4c9d | 77865d4c026b73c32c6d1d4fe3946b712f61466a | refs/heads/master | 2023-09-01T00:53:51.505622 | 2019-02-15T16:21:08 | 2019-02-15T16:21:08 | 27,839,591 | 7 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,805 | scm | tree-syntax.scm | #lang racket
;(define sym (new-automaton '("sym")))
;(define num (new-automaton '("num")))
;(define nil (new-automaton '("nil") ))
;(define term (new-automaton '("term")))
;(define binding (new-automaton '("binding")))
;(define env (new-automaton '("env")))
;(automaton-productions-set!
;sym
;(list (make-production 'symbol? '(()))))
;(automaton-productions-set!
;num
;(list (make-production 'number? '(()))))
;(automaton-productions-set!
;nil
;(list (make-production 'null? '(()))))
;(automaton-productions-set!
;term
;(list (make-production 'pair? (list (list term term)))
;(make-production 'symbol? '(()))
;(make-production 'number? '(()))))
;(automaton-productions-set!
;binding
;(list (make-production 'pair? (list (list sym term)))))
;(automaton-productions-set!
;env
;(list (make-production 'null? '(()))
;(make-production 'pair?
;(list (list binding env)))))
(define (alist-update alist key value)
(let ([p (assv key alist)])
(if p
(cons (cons key value)
(remq p alist))
(cons (cons key value) alist))))
(define (alist-lookup alist key default)
(let ([p (assv key alist)])
(if p
(cdr p)
default)))
(define (factor-productions prods)
(define factored
(reverse
(fold-left
(lambda (acc prod)
(let* ([ctor (car prod)]
[children (cadr prod)]
[set-of-lists-of-children (alist-lookup acc ctor '())])
(alist-update acc ctor (cons children set-of-lists-of-children))))
'()
prods)))
(map (lambda (p)
(let ([ctor (car p)]
[set-of-lists-of-children (cdr p)])
(make-production ctor set-of-lists-of-children)))
factored))
(define-syntax define-automata
(lambda (stx)
(syntax-case stx ()
[(_
[name (ctor args ...)
(ctor* args* ...)
...]
...)
(with-syntax
([(string* ...) (map symbol->string (syntax->datum #'(name ...)))])
#'(begin
(define name (new-automaton '(string*)))
...
(automaton-productions-set!
name
(factor-productions
(list
(list 'ctor (list args ...))
(list 'ctor* (list args* ...))
...)))
...))])))
(define-automata
[sym (symbol?)]
[nil (null?)]
[term (pair? [term term])
(symbol?)
(number?)]
[binding (pair? [sym term])]
[env (null?)
(pair? [binding env])])
| true |
cbc4716885512a7c9bc0132f188aa72073aedc38 | 6c6cf6e4b77640825c2457e54052a56d5de6f4d2 | /ch2/2_48-segment.scm | 489849a37ea7f3a89159c3876b760233f2cc555d | []
| 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 | 345 | scm | 2_48-segment.scm | ;ex 2.48
(load "2_46-vect.scm")
(define (make-segment start end)
(list start end))
(define (start-segment segment)
(car segment))
(define (end-segment segment)
(cadr segment))
(define (print-segment segment)
(display "[")
(print-vect (start-segment segment))
(display ",")
(print-vect (end-segment segment))
(display "]"))
| false |
75d5836ed4fa712f01042b09c29187311fcebefa | 37c751fc27e790303b84730013217d1c8cbb60cc | /scsh/CSAN/CSAN-util.scm | cd09ebc6aec60fa3d92ba29455c56f68b8801583 | [
"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 | 3,909 | scm | CSAN-util.scm | ;;; CSAN-util.scm - Compehensive Scheme Archive Network utilities
;;;
;;; Copyright (c) 2012 Johan Ceuppens
;;;
;;; All rights reserved.
;;;
;;; 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.
;;; 3. The name of the authors may not 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 (url-bite-off url)
(let ((s "")
(rets "")
(j 0))
(do ((i 0 (+ i 1)))
((or (string=? s "http://")(string=? s "ftp://")
(string=? s " http://")(string=? s " ftp://"))
(set! j i))
(set! s (string-append s (string (string-ref url i))))
)
(do ((i j (+ i 1)))
((or (>= i (string-length url))
(eq? (string-ref url i) #\/)
(eq? (string-ref url i) #\\)) ;; needs scheme URL parsing (e.g. with regexps or other perl things
rets)
(set! rets (string-append rets (string (string-ref url i))))
)))
;;test
;;(display (url-bite-off "http://soft/vub/"))
(define CSAN-generators (make-table))
(table-set! CSAN-generators "helpfile" (lambda ()
(display "Type in your helpfile : commands are 'get <filename-on-server>' and 'h'")
(let ((*out (open-outputfile (string-append "/help"))))
(do ((s (read)(read)))
((eof-object? s)0)
(write s)(write " ")))))
(define (CSAN-shell-spawn CSAN-dir mirror)
(newline)
(display "span> ")
(do ((s (read)(read)))
((null? s)0)
(newline)
(display "span> ")
(cond ((symbol? s)
(cond ((string<=? (symbol->string s)(string #\return))
0)
((string=? "h" (symbol->string s))
(display "Generating helpfile...")(newline)
(let ((*helpfilename (string-append CSAN-dir "/help")))
(let ((*in (if (file-exists? *helpfilename)
(open-input-file *helpfilename)
(begin
(display "no helpfile...")
((CSAN-generate "helpfile"))))))
(for-each write (read *in))))
0)
((string<=? "get" (symbol->string s))
(display "enter package to fetch : ")
(CSAN-ask-server (string-append "get " (symbol->string (read)))
(url-bite-off mirror) 6969))
))
))
(display "span> signing off."))
| false |
28dc6e3e033e3c3e2a72e77313a24b5837592f11 | 4f17c70ae149426a60a9278c132d5be187329422 | /compat/simple-struct.nmosh.sls | a6014df256b0f35aabe87efc3bec3548ca37a97f | []
| no_license | okuoku/yuni-core | 8da5e60b2538c79ae0f9d3836740c54d904e0da4 | c709d7967bcf856bdbfa637f771652feb1d92625 | refs/heads/master | 2020-04-05T23:41:09.435685 | 2011-01-12T15:54:23 | 2011-01-12T15:54:23 | 889,749 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 475 | sls | simple-struct.nmosh.sls | (library (yuni compat simple-struct)
(export make-simple-struct
simple-struct-name
simple-struct-ref
simple-struct-set!
simple-struct?)
(import (rnrs)
(primitives make-simple-struct
simple-struct-name
simple-struct?
simple-struct-set!
simple-struct-ref)))
| false |
49bcef4317ab1a6279a412497c7e3f89d378f935 | 951b7005abfe3026bf5b3bd755501443bddaae61 | /generic/2-5-1.scm | 7be0c9dd5c316c936e939b8f1af9b49514c9ec65 | []
| no_license | WingT/scheme-sicp | d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61 | a255f3e43b46f89976d8ca2ed871057cbcbb8eb9 | refs/heads/master | 2020-05-21T20:12:17.221412 | 2016-09-24T14:56:49 | 2016-09-24T14:56:49 | 63,522,759 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 796 | scm | 2-5-1.scm | ;2.77
(put 'real-part '(complex) real-part)
(put 'imag-part '(complex) imag-part)
(put 'magnitude '(complex) magnitude)
(put 'angle '(complex) angle)
(define z (make-complex-from-real-imag 3 4))
(magnitude z)
;2.78
(define (type-tag-1 datum)
(cond ((pair? datum) (car datum))
((symbol? datum) 'scheme-symbol)
((number? datum) 'scheme-number)
(else (error "Bad tagged datum -- TYPE-TAG" datum))))
(define (contents-1 datum)
(cond ((pair? datum) (cdr datum))
((or (symbol? datum) (number? datum)) datum)
(else (error "Bad tagged datum -- CONTENTS" datum))))
(define (attach-tag-1 type contents)
(if (or (eq? type 'scheme-symbol) (eq? type 'scheme-number))
contents
(cons type contents)))
;2.79
(define (equ? x y) (apply-generic 'equ? x y))
| false |
5294a4bcc23c8d45440856837172d8fe4ea101d4 | a66514d577470329b9f0bf39e5c3a32a6d01a70d | /sdl2/mutex-functions.ss | b10735c35c7786342818a617e7f96411a2ac9866 | [
"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 | 1,530 | ss | mutex-functions.ss | (define-sdl-func (* sdl-mutex-t) sdl-create-mutex () "SDL_CreateMutex")
(define-sdl-func int sdl-lock-mutex ((mutex (* sdl-mutex-t))) "SDL_LockMutex")
(define-sdl-func int sdl-try-lock-mutex ((mutex (* sdl-mutex-t))) "SDL_TryLockMutex")
(define-sdl-func int sdl-unlock-mutex ((mutex (* sdl-mutex-t))) "SDL_UnlockMutex")
(define-sdl-func void sdl-destroy-mutex ((mutex (* sdl-mutex-t))) "SDL_DestroyMutex")
(define-sdl-func (* sdl-sem-t) sdl-create-semaphore ((initial_value uint32)) "SDL_CreateSemaphore")
(define-sdl-func void sdl-destroy-semaphore ((sem (* sdl-sem-t))) "SDL_DestroySemaphore")
(define-sdl-func int sdl-sem-wait ((sem (* sdl-sem-t))) "SDL_SemWait")
(define-sdl-func int sdl-sem-try-wait ((sem (* sdl-sem-t))) "SDL_SemTryWait")
(define-sdl-func int sdl-sem-wait-timeout ((sem (* sdl-sem-t)) (ms uint32)) "SDL_SemWaitTimeout")
(define-sdl-func int sdl-sem-post ((sem (* sdl-sem-t))) "SDL_SemPost")
(define-sdl-func uint32 sdl-sem-value ((sem (* sdl-sem-t))) "SDL_SemValue")
(define-sdl-func (* sdl-cond-t) sdl-create-cond () "SDL_CreateCond")
(define-sdl-func void sdl-destroy-cond ((cond (* sdl-cond-t))) "SDL_DestroyCond")
(define-sdl-func int sdl-cond-signal ((cond (* sdl-cond-t))) "SDL_CondSignal")
(define-sdl-func int sdl-cond-broadcast ((cond (* sdl-cond-t))) "SDL_CondBroadcast")
(define-sdl-func int sdl-cond-wait ((cond (* sdl-cond-t)) (mutex (* sdl-mutex-t))) "SDL_CondWait")
(define-sdl-func int sdl-cond-wait-timeout ((cond (* sdl-cond-t)) (mutex (* sdl-mutex-t)) (ms uint32)) "SDL_CondWaitTimeout")
| false |
86d88271776ba2e0bfb90f1b5fc148edf129aa52 | 26aaec3506b19559a353c3d316eb68f32f29458e | /modules/csv/csv.scm | 6e8a0904ab8e1f94b8bdad9c48476dab5dfc0631 | [
"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 | 8,202 | scm | csv.scm | #|
LambdaNative - a cross-platform Scheme framework
Copyright (c) 2009-2014, University of British Columbia
All rights reserved.
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the following
disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials
provided with the distribution.
* Neither the name of the University of British Columbia nor
the names of its contributors may be used to endorse or
promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|#
;; Test input and output
(include "csv-test-input.scm")
;; Useful procedures for working with csv files.
(define (csv-read file)
(let ((raw (file->u8vector file)))
(let loop ((i (fx- (u8vector-length raw) 1)))
(if (fx>= i 0) (begin
(if (fx= (u8vector-ref raw i) 13) (u8vector-set! raw i 10))
(loop (- i 1)))))
(let* ((rows (string-split (u8vector->string raw) #\newline))
(qcount 0) (qrow "") (idx 0)
(finalrows (make-vector (length rows))))
(for-each (lambda (row)
(set! qcount (+ qcount (string-count row "\"")))
(set! qrow (string-append qrow (if (> (string-length qrow) 0) "\n" "") row))
(if (even? qcount) (begin
(vector-set! finalrows idx (csv:split qrow))
(set! idx (+ idx 1))
(set! qrow "") (set! qcount 0)
))) rows)
(if (> (string-length qrow) 0) (begin
(vector-set! finalrows idx (csv:split qrow))
(set! idx (+ idx 1))))
(vector->list (subvector finalrows 0 idx)))))
(define (csv:split str)
;; First, split the line normally on all commas
(let ((lst (call-with-input-string str (lambda (port) (read-all port (lambda (p) (read-line p #\,)))))))
;; If the line contains quotation marks
(if (string-contains str "\"")
;; If quotation marks, adjust spliting so that no quoted sections are broken up
(let commaloop ((linelst lst) (newlst '()) (leftover ""))
(if (fx> (length linelst) 0)
(let* ((current (car linelst))
(oddq (odd? (string-count current "\""))) ;; Is there an odd number of qoutes in the current string
(cont (fx> (string-length leftover) 0))) ;; Is there any leftover text from the previous strings
(if oddq
;; Odd number of quotes between two commas
(if cont
;; Combine the current string with the leftovers from between last commas
(commaloop (cdr linelst) (append newlst (list (string-append leftover "," current))) "")
;; OR Start new leftovers to be combined with later strings
(commaloop (cdr linelst) newlst current)
)
;; Even number of quotes between two commas
(if cont
;; Add to leftovers between last commas - still to combine with later strings
(commaloop (cdr linelst) newlst (string-append leftover "," current))
;; Normal - even number of quotes and no leftovers
(commaloop (cdr linelst) (append newlst (list current)) "")
)
)
)
;; Finished the line
(begin
;; If still some leftover - odd number of quotes on whole line - just add to end
(if (fx> (string-length leftover) 0)
(append newlst (list leftover))
newlst)
)
)
)
;; If no quotation marks on line - just return line as is
lst
)
)
)
(define (csv-write file output)
(let ((fh (open-output-file file)))
(let lineloop ((res output))
;; If more lines
(if (fx> (length res) 0) (begin
(let cellloop ((line (car res)))
;; If no more cells on line, add new line
(if (fx= (length line) 0) (display "\n" fh) (begin
;; Otherwise add current cell with comma following
(display (car line) fh) (display "," fh)
(cellloop (cdr line))
))
)
(lineloop (cdr res))
))
)
(close-output-port fh)
)
)
;; unit tests
;; -----------------
;; 1. csv-write the given list
;; 2. csv-read it
;; 3. compare
(define (csv-unit-test-list testlist)
(let ((f (string-append (system-directory) (system-pathseparator) "csvtest.csv")))
;; Remove file if it exists
(if (file-exists? f)
(delete-file f))
;; Write and then read
(csv-write f testlist)
(let ((output (csv-read f)))
(delete-file f)
(equal? testlist output)))
)
;; 1. write the given string to a file
;; 2. csv-read it
;; 3. csv-write it
;; 4. read from the file into a string
;; 5. compare
(define (csv-unit-test-string inputstring outputstring)
(let ((f (string-append (system-directory) (system-pathseparator) "csvtest.csv")))
;; Delete file if it already exists
(if (file-exists? f)
(delete-file f))
(let ((fh (open-output-file f))
(loadedlist #f)
(loadedstring ""))
;; Output to the file
(display inputstring fh)
(close-output-port fh)
;; Read, delete the file, and then write
(set! loadedlist (csv-read f))
(delete-file f)
(csv-write f loadedlist)
;; Read back as a string, should be no new lines in the file
(with-input-from-file f (lambda ()
(let loop ((line (read-line (current-input-port) #\newline)) (first #t))
(if (not (eof-object? line))
(begin
(set! loadedstring (if first line (string-append loadedstring "\n" line)))
(loop (read-line) #f))))))
;; Delete file after
(delete-file f)
;; Do comparison
(equal? loadedstring outputstring)))
)
;; 1. write the given string to a file
;; 2. csv-read it
;; 3. compare
(define (csv-unit-test-read teststring testlist)
(let ((f (string-append (system-directory) (system-pathseparator) "csvtest.csv")))
;; Remove file if it exists
(if (file-exists? f)
(delete-file f))
(let ((fh (open-output-file f)))
;; Output to the file
(display teststring fh)
(close-output-port fh)
;; Write and then read=
(let ((output (csv-read f)))
(delete-file f)
(equal? testlist output))))
)
(unit-test "csv-write-read" "Quotation marks and line feed"
(lambda ()
(csv-unit-test-list csv:test_line_feed))
)
(unit-test "csv-write-read" "Quotation marks and carriage return"
(lambda ()
(csv-unit-test-string csv:test_carriage_return_input csv:test_carriage_return_output))
)
(unit-test "csv-write-read" "Trend File 1"
(lambda ()
(csv-unit-test-string csv:test_trend_file1 csv:test_trend_file1))
)
(unit-test "csv-write-read" "Trend File 2 Write-Read"
(lambda ()
(csv-unit-test-list csv:test_trend_list))
)
(unit-test "csv-write-read" "Trend File 2 Read"
(lambda ()
(csv-unit-test-read csv:test_trend_file2 csv:test_trend_list))
)
;; eof
| false |
a99b271555bedd50ba36b58eb46e5907c35da86b | 8c44b6c3cc638a03f1ae4f1c3338396e6c777364 | /chicken-egg/apk/reapk.scm | 4f9e804a9f8d4c04167e169a0aa934a72eadf99d | []
| no_license | kristianlm/chicken-apk | abad750ac24f2d51a9437fcb98a98fc2c9874a79 | 1bd08038e9b6fd8fca8346314efba8163722a6ff | refs/heads/master | 2020-09-11T01:08:21.611491 | 2019-11-15T09:24:16 | 2019-11-15T11:29:09 | 221,889,587 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 4,022 | scm | reapk.scm | (import (chicken foreign)
(chicken memory)
(only (chicken string) conc substring-index)
(only (chicken process) system)
(only (chicken process-context) get-environment-variable)
(only (chicken file) file-exists?)
(only (chicken pathname) make-pathname)
matchable)
(define (pointer-pointer-ref x)
((foreign-lambda* c-pointer (((c-pointer (c-pointer void)) x)) "return(*x);")
x))
(define (pointer-pointer-set! x v)
((foreign-lambda* void ( ((c-pointer (c-pointer void)) x) (c-pointer v)) "*x = v;")
x v))
(foreign-declare "
// callback used by repackage.c
C_word edit_apk_file(C_word user, char* fname, char** data, uint64_t* size);
#define Z_SOLO
#define IOAPI_NO_64
#include \"minizip/ioapi.c\"
#include \"minizip/zip.c\"
#include \"minizip/unzip.c\"
#include \"apk/repackage.c\"
")
(define-external
(edit_apk_file (scheme-object user)
(c-string fname)
((c-pointer (c-pointer char)) &data)
((c-pointer unsigned-integer64) &size))
scheme-object ;; return type
(print "&data=" &data)
(define data (pointer-pointer-ref &data))
(print "data=" data)
(define size (pointer-u64-ref &size))
(define original (make-string size))
(move-memory! data original size)
(free data)
(define str (user fname original))
(pointer-pointer-set! &data #f) ;; mark as skipped
(when str
(let ((result (allocate (string-length str))))
(move-memory! str result)
(pointer-pointer-set! &data result)
(pointer-u64-set! &size (string-length str))))
(print "@ " " " size " bytes" )
user)
(define (rezip source.apk dest.apk process_fname_data)
(unless (procedure? process_fname_data) (error "expecting edit procedure" process_fname_data))
((foreign-safe-lambda int "rezip" c-string c-string scheme-object)
source.apk dest.apk process_fname_data))
(define (discard-meta+lib file)
(cond ((eq? 0 (substring-index "META-INF/" file)) #f)
((eq? 0 (substring-index "lib/" file)) #f)
(else #t)))
(define (apk-repackage) (error "TODO"))
;; (define (apk-repackage src dst renaming #!optional (keep-file? discard-meta+lib))
;; (rezip src dst
;; (if (procedure? renaming) renaming
;; (lambda (fname data)
;; (and (keep-file? fname)
;; (cond ((assoc fname renaming) =>
;; (lambda (renames*)
;; (define renames (cdr renames*))
;; (unparse-xml
;; (string-pool-replace
;; (parse-xml data)
;; (lambda (str)
;; (print "*****" renames)
;; (cond ((assoc str renames) =>
;; (lambda (old+new)
;; (cadr old+new)))
;; (else str)))))))
;; (else data)))))))
(define (apk-sign filename #!optional
(keystore (make-pathname (list (get-environment-variable "HOME")
".android")
"debug.keystore"))
(storepass "android")
(alias "androiddebugkey"))
(if (file-exists? keystore)
(system (conc "jarsigner -digestalg SHA-256 -sigalg SHA256withRSA"
" -keystore \"" keystore "\""
" -storepass \"" storepass "\""
" " filename
" " alias))
(error (conc "cannot find keystore " keystore "\ncreate one with:\n keytool -genkey -v"
" -keystore \"" keystore "\""
" -alias \"" alias "\""
" -keyalg RSA -keysize 2048 -validity 10000\n default password is 'android'\n"))))
(define apk-align (foreign-lambda void "apk_align" c-string c-string))
| false |
0473228e8110070d24242167943709af50dfe986 | 4e2bb57118132e64e450671470c132205457d937 | /programs/secsh-client | 713c734b28d5753e066056e879ad7af13faae736 | [
"MIT"
]
| permissive | theschemer/industria | 8c4d01d018c885c0437e2575787ec987d800514f | 9c9e8c2b44280d3b6bda72154a5b48461aa2aba5 | refs/heads/master | 2021-08-31T23:32:29.440167 | 2017-12-01T23:24:01 | 2017-12-01T23:24:01 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 13,100 | secsh-client | #!/usr/bin/env scheme-script
;; -*- mode: scheme; coding: utf-8 -*- !#
;; Semi-interactive demonstration SSH client
;; Copyright © 2010, 2011, 2017 Göran Weinholt <[email protected]>
;; Permission is hereby granted, free of charge, to any person obtaining a
;; copy of this software and associated documentation files (the "Software"),
;; to deal in the Software without restriction, including without limitation
;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;; and/or sell copies of the Software, and to permit persons to whom the
;; Software is furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;; DEALINGS IN THE SOFTWARE.
#!r6rs
(import (rnrs)
(only (srfi :13 strings) string-index)
(srfi :39 parameters)
(weinholt crypto dsa)
(weinholt crypto ec dsa)
(weinholt crypto rsa)
(weinholt crypto sha-1)
(weinholt crypto ssh-public-key)
;; (weinholt net dns numbers)
;; (weinholt net dns types)
(weinholt net ssh)
(weinholt net ssh connection)
(weinholt net ssh transport)
(weinholt net ssh userauth)
(weinholt net tcp)
(weinholt text base64))
(define (print . x) (for-each display x) (newline))
(define (open-connection hostname portname)
(let-values (((in out) (tcp-connect hostname portname)))
(print "Connecting to " hostname " port " portname "...")
(let ((conn (make-ssh-client in out)))
(print "Running key exchange...")
(ssh-key-exchange conn)
conn)))
(define (reexchange conn algorithm)
;; Key re-exchange.
(let ((local
(parameterize ((preferred-server-host-key-algorithms (list algorithm)))
(build-kexinit-packet conn))))
(put-ssh conn local)
(let lp ()
(let ((pkt (get-ssh conn)))
(cond ((kexinit? pkt)
(ssh-key-re-exchange conn pkt local)
(lp))
((key-exchange-packet? pkt)
(unless (eq? (process-key-exchange-packet conn pkt) 'finished)
(lp)))
(else
;; XXX: pkt was probably something important, and now it's lost
(lp)))))))
(define (print-key hostname key)
(print (ssh-public-key-fingerprint key))
(print (ssh-public-key-random-art key))
;; (print key)
(let ((key-bv (ssh-public-key->bytevector key)))
(print hostname " "
(ssh-public-key-algorithm key) " "
(base64-encode key-bv))
;; RFC4255
#;
(let ((algo (cond ((rsa-public-key? key) (dns-sshfp-algorithm RSA))
((dsa-public-key? key) (dns-sshfp-algorithm DSA))
(else #f))))
(when algo
(display "\tSSHFP\t")
(dns-resource-print (current-output-port) 80
(make-dns-resource/SSHFP
'() 0 (dns-class IN)
algo
(dns-sshfp-type SHA-1)
(sha-1->bytevector (sha-1 key-bv))))
(newline)))))
;; Prints all of the server's host keys. It uses one new connection
;; per host key.
(define (scan-keys hostname portname)
(let ((conn (open-connection hostname portname)))
(let lp ((conn conn)
(algos (remove
(ssh-public-key-algorithm (ssh-conn-host-key conn))
(kexinit-server-host-key-algorithms
(ssh-conn-peer-kexinit conn)))))
(print-key hostname (ssh-conn-host-key conn))
(close-ssh conn)
(unless (null? algos)
(lp (parameterize ((preferred-server-host-key-algorithms (list (car algos))))
(open-connection hostname portname))
(cdr algos))))))
;; Prints all of the server's host keys. It uses one connection, but
;; requires userauth.
(define (getkeys hostname conn)
(for-each (lambda (algo)
(print "Switching to host key algorithm " algo)
(reexchange conn algo)
(print-key hostname (ssh-conn-host-key conn)))
(kexinit-server-host-key-algorithms
(ssh-conn-peer-kexinit conn))))
(define (main hostname portname)
(define username #f)
(define sessions '())
(define authenticated #f)
(define (get-send-id rec-id)
(let ((s (assv rec-id sessions)))
(and s (vector-ref (cdr s) 0))))
(define (get-auth-result conn)
(let ((x (get-ssh conn)))
(cond ((userauth-failure? x)
(print "You may try these authentication methods: "
(userauth-failure-can-continue x)))
((userauth-success? x)
(print "You've succesfully authenticated.")
(let ((r (ssh-conn-registrar conn)))
(deregister-userauth r)
(print "You now have access to the SSH connection protocol.")
(set! authenticated #t)
(register-connection r)))
(else
(error 'print-auth-result "Unexpected message" x)))))
(print "Industria SSH demo client.\n")
(let ((conn (open-connection hostname portname)))
(print-key hostname (ssh-conn-host-key conn))
(print "Please verify the above key.")
(print "SSH session established.\nType help for a list of commands.\n")
(let loop ()
(display hostname)
(display "=> ")
(flush-output-port (current-output-port))
(guard (exn
(else
(print "There was an error: " exn)))
(case (read)
((help)
(print "Command reference:")
(print "d Toggle protocol debug messages")
(print "help This helpful help text")
(print "q Exit the program")
(print "g Get all host keys")
(print "u \"username\" Start user authentication")
(print "p \"password\" User authentication with a password")
(print "s Open a new session channel")
(print "t <channel id> Request a pseudo-terminal and shell")
(print "w <channel id> Send a line to a channel")
(print "r Read a packet (might block)"))
((d)
(ssh-debugging (fxxor (ssh-debugging) #b111))
(print "ssh-debugging set to #b" (number->string #b111 2)))
((g)
(if authenticated
(getkeys hostname conn)
(scan-keys hostname portname)))
((u)
(when username
(error 'main "Once a username has been sent it can't be changed."))
(set! username (read))
;; Ask nicely that we may use the userauth protocol
(put-ssh conn (make-service-request "ssh-userauth"))
(let ((x (get-ssh conn)))
(if (and (service-accept? x)
(string=? (service-accept-name x)
"ssh-userauth"))
(print "Your request to use ssh-userauth was accepted.")
(error 'main "Couldn't request ssh-userauth" x)))
(register-userauth (ssh-conn-registrar conn))
;; Ask what authentication methods are available. Also
;; indicates that we want to use the ssh-connection
;; protocol later.
(put-ssh conn (make-userauth-request username "ssh-connection" "none"))
(get-auth-result conn))
((p)
;; Try password authentication. Passwords are of course
;; visible on the terminal.
(let ((password (read)))
(put-ssh conn (make-userauth-request/password username "ssh-connection"
password))
(get-auth-result conn)))
;; Open a new session
((s)
(let ((rec-id (length sessions))
(rec-w 4096)
(rec-max 32768))
(put-ssh conn (make-channel-open/session rec-id rec-w rec-max))
(let ((x (let lp ()
(let ((x (get-ssh conn)))
(if (channel-open-confirmation? x)
x
(lp))))))
(let ((send-id (channel-open-confirmation-sender x))
(send-w (channel-open-confirmation-initial-window-size x))
(send-max (channel-open-confirmation-maximum-packet-size x)))
(set! sessions (cons (cons rec-id
(vector send-id rec-w send-w
rec-max send-max))
sessions))
(print "New session opened.")
(print "Receive side parameters:")
(print "ID: " rec-id " window size: " rec-w
" maximum packet size: " rec-max)
(print "Send side parameters:")
(print "ID: " send-id " window size: " send-w
" maximum packet size: " send-max)))))
;; Request a pseudo-terminal and a shell
((t)
;; These parameters here are mostly useless, because this
;; program doesn't put the user's terminal into raw mode.
(let ((modes
(terminal-modes->bytevector
'((TTY_OP_OSPEED . 38400) (TTY_OP_ISPEED . 38400) (VINTR . 3)
(VQUIT . 28) (VERASE . 127) (VKILL . 21) (VEOF . 4)
(VEOL . 0) (VEOL2 . 0) (VSTART . 17) (VSTOP . 19)
(VSUSP . 26) (VREPRINT . 18) (VWERASE . 23) (VLNEXT . 22)
(VDISCARD . 15) (IGNPAR . 1) (PARMRK . 0) (INPCK . 0)
(ISTRIP . 0) (INLCR . 0) (IGNCR . 0) (ICRNL . 1)
(IUCLC . 0) (IXON . 1) (IXANY . 0) (IXOFF . 0)
(IMAXBEL . 1) (ISIG . 1) (ICANON . 1) (XCASE . 0)
(ECHO . 1) (ECHOE . 1) (ECHOK . 1) (ECHONL . 0)
(NOFLSH . 0) (TOSTOP . 0) (IEXTEN . 1) (ECHOCTL . 1)
(ECHOKE . 1) (PENDIN . 0) (OPOST . 1) (OLCUC . 0)
(ONLCR . 1) (OCRNL . 0) (ONOCR . 0) (ONLRET . 0) (CS7 . 1)
(CS8 . 1) (PARENB . 0) (PARODD . 0)))))
(cond ((assv (read) sessions) =>
(lambda (s)
(let ((send-id (vector-ref (cdr s) 0)))
(put-ssh conn (make-channel-request/pty-req
send-id #f "vt100" 24 80 1032 325 modes))
(put-ssh conn (make-channel-request/shell send-id #f))
(flush-ssh-output conn))))
(else
(print "No such session. Use the receive ID.")))))
((w)
(cond ((get-send-id (read)) =>
(lambda (send-id)
(print "Type a line:")
(get-line (current-input-port))
(let lp ((line (string->utf8
(string-append (get-line (current-input-port))
"\n"))))
(put-ssh conn (make-channel-data send-id line))
(flush-ssh-output conn))))
(else
(print "No such session. Use the receive ID."))))
((r)
(let ((x (get-ssh conn)))
(cond ((channel-data? x)
(display (utf8->string (channel-data-value x)))
(newline)
;; This is super-naive. These adjustments should
;; be based on some real buffer size and should
;; not be sent this often.
(let ((send-id (get-send-id (channel-packet-recipient x))))
(put-ssh conn (make-channel-window-adjust send-id
(bytevector-length
(channel-data-value x))))))
(else
(print x)))))
((q) (exit 0))
(else
(print "Unknown command."))))
(loop))))
(apply
(case-lambda
((who hostname portname)
(main hostname portname))
((who hostname)
(main hostname "22"))
((who . _)
(print "Usage: " who " hostname [port]")
(exit 1)))
(command-line))
| false |
|
1cc6b7356c4b80235946f4a75017145456bf3ea1 | 296dfef11631624a5b2f59601bc7656e499425a4 | /seth/seth/message-digest/update-item.sld | 449c210e876c095d32307dc4497f3d1b9865eec7 | []
| no_license | sethalves/snow2-packages | f4dc7d746cbf06eb22c69c8521ec38791ae32235 | 4cc1a33d994bfeeb26c49f8a02c76bc99dc5dcda | refs/heads/master | 2021-01-22T16:37:51.427423 | 2019-06-10T01:51:42 | 2019-06-10T01:51:42 | 17,272,935 | 1 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 4,229 | sld | update-item.sld | ;;;; message-digest-update-item.scm
;;;; Kon Lovett, Jan '06 (message-digest.scm)
;;;; Kon Lovett, May '10 (message-digest.scm)
;;;; Kon Lovett, Apr '12
;; Issues
(define-library (seth message-digest update-item)
(export message-digest-update-object
message-digest-update-procedure
message-digest-update-port
message-digest-update-file
)
(import
(scheme base)
(scheme file)
(seth message-digest parameters)
(seth message-digest primitive)
(seth message-digest type)
)
(begin
;;; Support
;;
(define (chunk-convert obj)
(let ((cnv (message-digest-chunk-converter)))
(cond ((cnv (cnv obj))))))
(define (get-chunk-reader in)
((message-digest-chunk-read-maker) in))
(define (get-update md)
(message-digest-primitive-update (message-digest-algorithm md)))
;;
;; (define (object->bytevector-like obj)
;; (or (packed-vector->blob/shared obj)
;; (chunk-convert obj)))
(define (object->bytevector-like obj)
(cond ((bytevector? obj)
(chunk-convert obj))
(else #f)))
(define (do-byte-source-update loc ctx src updt)
(cond
;; simple bytes
((bytevector? src)
(updt ctx src (bytevector-length src)))
((string? src)
(do-byte-source-update loc ctx (string->utf8 src) updt))
;; more complicated bytes
((object->bytevector-like src) =>
;; (cut do-byte-source-update loc ctx <> updt)
(lambda (x) (do-byte-source-update loc ctx x updt)))
;; too complicated bytes
(else
(error "indigestible object" loc src))))
(define (do-procedure-update loc md proc)
(let ((updt (get-update md))
(ctx (message-digest-context md)) )
;; (while* (proc) (do-byte-source-update loc ctx it updt))
(let loop ()
(let ((it (proc)))
(cond (it (do-byte-source-update loc ctx it updt)
(loop)))))))
(define (do-port-update loc md in)
(do-procedure-update loc md (get-chunk-reader in)) )
(define (do-bytes-update loc md src)
(let ((updt (get-update md))
(ctx (message-digest-context md)) )
(do-byte-source-update loc ctx src updt) ) )
(define (do-object-update loc md src)
(cond
((input-port? src) (do-port-update loc md src) )
((procedure? src) (do-procedure-update loc md src) )
(else (do-bytes-update loc md src) ) ) )
;;; Update Operation
;;
(define (message-digest-update-object md obj)
;; (check-message-digest 'message-digest-update-object md)
(do-object-update 'message-digest-update-object md obj) )
;;
(define (message-digest-update-procedure md proc)
;; (check-message-digest 'message-digest-update-procedure md)
;; (check-procedure 'message-digest-update-procedure proc)
(do-procedure-update 'message-digest-update-procedure md proc) )
;;
(define (message-digest-update-port md in)
;; (check-message-digest 'message-digest-update-port md)
;; (check-input-port 'message-digest-update-port in)
(do-port-update 'message-digest-update-port md in) )
;;
;; (define (message-digest-update-file md flnm)
;; ;; (check-message-digest 'message-digest-update-file md)
;; ;; (check-string 'message-digest-update-file flnm)
;; (let ((in (open-input-file flnm)))
;; (handle-exceptions exn
;; (begin (close-input-port in) (abort exn))
;; (do-port-update 'message-digest-update-file md in) )
;; (close-input-port in) ) )
;; (define (message-digest-update-file md flnm)
;; (check-message-digest 'message-digest-update-file md)
;; (check-string 'message-digest-update-file flnm)
;; (let ((in #f))
;; (dynamic-wind
;; (lambda () (set! in (open-input-file flnm)) )
;; (lambda () (do-port-update 'message-digest-update-file md in) )
;; (lambda () (close-input-port in) ) ) ) )
;; )
(define (message-digest-update-file md flnm)
;; (check-message-digest 'message-digest-update-file md)
;; (check-string 'message-digest-update-file flnm)
(let ((in (open-input-file flnm)))
(with-exception-handler
(lambda (exn)
(close-input-port in)
(error "message-digest-update-file" exn))
(lambda ()
(do-port-update 'message-digest-update-file md in)))
(close-input-port in) ) )
;;module message-digest-update-item
))
| false |
779efdf6ea6bf34d49fe0db98629970be9323477 | 2a8dc8faf0275eece40b2aa3a52cf8f5bc06babc | /src/scheme-prep.ss | 06842009ce2097a2f7272d2d5eef05e4d911747f | [
"MIT"
]
| permissive | dybvig/stex | 9da1a299329e9382e09d9f272268771a71fdd8e2 | afa607564a5662ffd748e824801277a6b5a3d11c | refs/heads/master | 2022-07-01T06:42:23.205482 | 2021-04-10T22:26:21 | 2021-04-10T22:28:36 | 55,739,382 | 95 | 25 | null | 2022-04-29T08:15:31 | 2016-04-08T01:12:34 | Scheme | UTF-8 | Scheme | false | false | 46,430 | ss | scheme-prep.ss | #! /usr/bin/scheme --program
;;; scheme-prep.ss
;;;
;;; Copyright (c) 1998-2016 R. Kent Dybvig and Oscar Waddell
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a
;;; copy of this software and associated documentation files (the "Software"),
;;; to deal in the Software without restriction, including without limitation
;;; the rights to use, copy, modify, merge, publish, distribute, sublicense,
;;; and/or sell copies of the Software, and to permit persons to whom the
;;; Software is furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
;;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;; primitive commands
;;; \genlab
;;; \generated ... \endgenerated ; inject and process string returned by enclosed Scheme code
;;; \hindex
;;; \index
;;; \raw
;;; \scheme
;;; \schemeinit ... \endschemeinit
;;; \schemedisplay ... \endschemedisplay
;;; \schemedisplay[number-lines] ... \endschemedisplay ; insert line numbers
;;; \schemeverbatim ... \endschemeverbatim
;;; \schlbrace
;;; \schrbrace
;;; \transcript ... \endtranscript
;;; \transcript[endtranscript] ... \endtranscript
;;; \var
;;; \xdef
;;; \xedef
;;; \schemeoutput[mode]{filename} ; divert schemedisplay code to file
;;; \schemeoutput{} ; closes the open scheme output file
;;; commands inserted into the output
;;; \$, \&, \%, \#, \\
;;; \dots
;;; \endschemedisplay
;;; \hindex
;;; \is
;;; \label
;;; \null
;;; \schemeindent
;;; \scheme
;;; \schemeblankline
;;; \schemedisplay
;;; \schemelinestart ; relies on defn of \schemeindent=
;;; \schatsign
;;; \schbackslash
;;; \schcarat
;;; \schdot
;;; \schlbrace
;;; \schrbrace
;;; \schtilde
;;; \schunderscore
;;; \si
;;; The transerr, etc. commands require an empty argument so that
;;; we can put them in a \raw{} in the schemedisplay we generate for
;;; the transcript and still keep both htmlprep and latex happy with
;;; the result. html-prep would also accept {\transin}, but latex
;;; was not happy with that.
;;; \transerr{} ... \endtranserr{} ; transcript error msg typesetting
;;; \transin{} ... \endtransin{} ; transcript user input typesetting
;;; \transout{} ... \endtransout{} ; transcript program output typesetting
;;; \var
;;; \vdots
;;; any undefined input command
;;; anything else inserted by \raw
;;; Valid within \scheme{...}
;;; \dots
;;; \raw{<text>}
;;; \var{<text>}
;;; \var{<text>_<subscript>}
;;; \
;;; all other characters besides } and newline
;;; Valid within \schemedisplay ... \endschemedisplay
;;; \dots
;;; \raw{<text>}
;;; \var{<text>}
;;; \var{<text>_<subscript>}
;;; \vdots
;;; \
;;; all other characters besides }
;;; \label{text} may appear immediately after \schemedisplay
;;; index and hindex entries follow makeindex 2.13 syntax except that
;;; the special characters !, @, |, ", and \ are freely allowed within
;;; embeded {, } pairs in the "actual entry" portion of a level (the
;;; portion following @, if any). a modified version of makeindex 2.13
;;; that supports this extension (with the -d [allow delimited special
;;; chars] flag) is available here as well.
;;;
;;; in \index input, we also allow \scheme{...} to appear, with embedded
;;; special characters.
;;; \index syntax
;;; \index{levels}
;;; \index{levels|pageformat}
;;; levels --> level
;;; --> level!levels
;;; level --> keyentry (key and entry same)
;;; level --> key@entry (separate key and entry)
;;;
;;; Valid within keyentry
;;; \scheme{...}
;;; If multiple filenames are supplied on the command line, each file is
;;; processed in the same runtime image. Thus an \xdef in an earlier file
;;; persists through the processing of subsequent files.
#!chezscheme
(import (except (chezscheme) open-input-file) (dsm) (preplib) (script))
(define use-interaction-window (make-parameter #f))
(define interaction-window-width (make-parameter 28))
(define copy-through-newline
(lambda (ip op)
(state-case (c (read-char ip))
[(#\newline) (write-char c op)]
[(eof) (void)]
[else (write-char c op) (copy-through-newline ip op)])))
(define dovar
(lambda (ip op)
(read-open-brace ip)
(display "\\var{" op)
(let f ()
(state-case (c (read-char ip))
[(#\}) (write-char c op)]
[(#\') (display "$'$" op) (f)]
[(#\_)
(display "$_" op)
(state-case (c (read-char ip))
[(eof) (input-error "unexpected eof in \\var{}")]
[(#\{) (fprintf op "{~a}" (read-bracketed-text ip 1))]
[else (write-char c op)])
(write-char #\$ op)
(f)]
[(eof) (input-error "unexpected eof in \\var{}")]
[else (write-char c op) (f)]))))
(define (sscheme ip op) ; within \scheme
; unlike schemedisplay, does not allow { or }. { and } must be expressed
; as \schlbrace and \schrbrace
(state-case (c (read-char ip))
[(#\{) (input-error "unexpected { within \\scheme{}")]
[(#\}) (void)]
[(#\\)
; use read-alpha-command instead of read-command to avoid
; improper handling of special characters that follow a slash,
; including }
(let ([cmd (read-alpha-command ip)])
(case cmd
[(dots)
(display "{\\dots}" op)
(sscheme ip op)]
[(raw)
(display (read-bracketed-text ip) op)
(sscheme ip op)]
[(var)
(dovar ip op)
(sscheme ip op)]
[(schlbrace)
(display "\\schlbrace" op)
(sscheme ip op)]
[(schrbrace)
(display "\\schrbrace" op)
(sscheme ip op)]
[else ; assume random \ possibly followed by alphabetic chars
(fprintf op "{\\schbackslash}~a" cmd)
(sscheme ip op)]))]
[(#\.) (display "{\\schdot}" op) (sscheme ip op)]
[(#\~) (display "{\\schtilde}" op) (sscheme ip op)]
[(#\^) (display "{\\schcarat}" op) (sscheme ip op)]
[(#\@) (display "{\\schatsign}" op) (sscheme ip op)]
[(#\_) (display "{\\schunderscore}" op) (sscheme ip op)]
[(#\space) (display "~" op) (sscheme ip op)]
[(#\$ #\& #\% #\#) (fprintf op "\\~c" c) (sscheme ip op)]
[(#\newline) (input-error "line ended within \\scheme{}")]
[(eof) (input-error "file ended within \\scheme{}")]
[else (write-char c op) (sscheme ip op)]))
(define sschemedisplay
(P lambda (number-lines? labels) ; within a schemedisplay
; number-lines?
; Flag is true if we want the lines numbered.
;
; labels
; A list of labels to be attached to this schemedisplay.
; We insert them after the first newline in the schemedisplay
; (or before the \endschemedisplay if no newline) so that the
; label is attached to something other than whitespace (this
; prevents labels from referring to the preceeding page when the
; start of a schemedisplay falls right on a page break).
(define print-line-start
(lambda (line op)
(if number-lines?
(fprintf op "\\schemelinestartnumbered{~s}~%" line)
(fprintf op "\\schemelinestart~%"))))
(fprintf op "\\schemelinestart~%")
(when sout (newline sout))
(let loop ([n? #f] [line 0] [labels labels])
; n? is true if we've just passed a new line within the display; we use
; it to determine whether to insert \\\schemelinestart. (We insert
; \schemelinestart after \\ to prevent \\ from sucking up ensuing
; whitespace---including spaces used for indentation on the following
; line.)
(state-case (c (read-char ip))
[(#\\)
; use read-alpha-command instead of read-alpha-command to avoid
; improper handling of special characters that follow a slash
(let ([cmd (read-alpha-command ip)])
(case cmd
[(endschemedisplay)
(unless (null? labels)
(for-each (lambda (l) (fprintf op "\\label{~a}" l)) labels))
(display "\\endschemedisplay" op)]
[else
(when n? (display "\\\\\n" op) (print-line-start line op))
(case cmd
[(dots)
(display "{\\dots}" op)
(loop #f line labels)]
[(var)
(dovar ip op)
(loop #f line labels)]
[(raw)
(fprintf op "~a" (read-bracketed-text ip))
(loop #f line labels)]
[(vdots)
(display "{\\vdots}" op)
(loop #f line labels)]
[else ; assume random \ possibly followed by alphabetic chars
(fprintf op "{\\schbackslash}~a" cmd)
(when sout (fprintf sout "\\~a" cmd))
(loop #f line labels)])]))]
[else
(when n? (display "\\\\\n" op) (print-line-start line op))
(when sout (write-char c sout))
(state-case (c c)
[(#\;)
; convert ;=> into \is and ;== into \si
(state-case (c (peek-char ip))
[(#\=)
(read-char ip)
(when sout (write-char c sout))
(state-case (c (peek-char ip))
[(#\>)
(when sout (write-char c sout))
(read-char ip)
(display "\\is" op)
(loop #f line labels)]
[(#\=)
(when sout (write-char c sout))
(read-char ip)
(display "\\si" op)
(loop #f line labels)]
[else
(when sout (write-char c sout))
(display ";=" op)
(loop #f line labels)])]
[(#\-) ; should abstract this
(read-char ip)
(when sout (write-char c sout))
(state-case (c (peek-char ip))
[(#\>)
(when sout (write-char c sout))
(read-char ip)
(display "\\becomes" op) ; would prefer something else here
(loop #f line labels)]
[else
(when sout (write-char c sout))
(display ";-" op)
(loop #f line labels)])]
[else
(write-char #\; op)
(loop #f line labels)])]
;; Convert space to ~ since \obeyspaces doesn't seem to work for us
;; when \schemedisplay appears within a macro (see f2002/quiz02.stex).
[(#\space) (display "~" op) (loop #f line labels)]
[(#\.)
(display "{\\schdot}" op)
(loop #f line labels)]
[(#\~)
(display "{\\schtilde}" op)
(loop #f line labels)]
[(#\^)
(display "{\\schcarat}" op)
(loop #f line labels)]
[(#\@)
(display "{\\schatsign}" op)
(loop #f line labels)]
[(#\_)
(display "{\\schunderscore}" op)
(loop #f line labels)]
[(#\{)
(display "{\\schlbrace}" op)
(loop #f line labels)]
[(#\})
(display "{\\schrbrace}" op)
(loop #f line labels)]
[(#\$ #\& #\% #\#)
(fprintf op "\\~c" c)
(loop #f line labels)]
[(#\newline)
(unless (null? labels)
(for-each (lambda (l) (fprintf op "\\label{~a}" l)) labels))
(state-case (c (peek-char ip))
[(#\newline)
(read-char ip)
(fprintf op "~%\\schemeblankline")
(print-line-start line op)
(when sout (newline sout))
(loop #f (fx+ line 2) '())]
[else
(loop #t (fx+ line 1) '())])]
[(eof) (errorf #f "file ended within schemedisplay")]
[else (write-char c op) (loop #f line labels)])]))))
(define (sindex ip op)
; 1. read entire contents of \index{} form, w/o intepreting \scheme{...}
; separate at !s into 1 or more levels plus page format
; after |, if present; separate levels at @ into sort key
; and text, if present
; 2. for each level,
; a. compute output sort key
; - if input sort key is given, use it
; - otherwise use stripped version of input text
; - insert quotes where needed
; b. preprocess input text to produce output text
; - expand \scheme{...}
; - insert quotes where needed
; 3. produce output
; a. print \index{
; b. for each level, if output text is same as output sort key,
; print <output text>.
; otherwise print <output text>@<output sort key>
; c. separate levels with !
; d. print |<page format> if present in input
; e. print }
(define strip-sort-key
; presently strips only \scheme{ and matching }
(let ([buf (open-output-string)])
(lambda (ip)
(state-case (c (read-char ip))
[(#\\)
(let ([cmd (read-command ip)])
(case cmd
[(scheme)
(read-open-brace ip)
(display (read-bracketed-text ip 1) buf)
(strip-sort-key ip)]
[else (unexpected-command cmd)]))]
[(eof) (get-output-string buf)]
[else (write-char c buf) (strip-sort-key ip)]))))
(call-with-values
(lambda () (parse-index ip #t))
(lambda (levels page-format)
(let ([keys (map (lambda (s) (insert-quotes (open-input-string s) #f))
(map (lambda (level)
(if (car level)
(car level)
; strip text to create sort key
(strip-sort-key
(open-input-string (cdr level)))))
levels))]
[texts (map (lambda (level)
(insert-quotes
(open-input-string
(expand-entry (open-input-string (cdr level))))
#f))
levels)])
(let f ([keys keys] [texts texts] [delim #\{])
(unless (null? keys)
(write-char delim op)
(let ([key (car keys)] [text (car texts)])
(if (string=? key text)
(display text op)
(fprintf op "~a@~a" key text)))
(f (cdr keys) (cdr texts) #\!)))
(unless (string=? page-format "") (fprintf op "|~a" page-format))
(write-char #\} op)))))
(define expand-entry
; expands \scheme{} forms
(let ([buf (open-output-string)])
(lambda (ip)
(state-case (c (read-char ip))
[(#\\)
(let ([cmd (read-command ip)])
(case cmd
[(scheme)
(read-open-brace ip)
(display "\\scheme{" buf)
(sscheme ip buf)
(write-char #\} buf)
(expand-entry ip)]
[else
(fprintf buf "\\~a" cmd)
(expand-entry ip)]))]
[(eof) (get-output-string buf)]
[else (write-char c buf) (expand-entry ip)]))))
(define insert-quotes
(let ([buf (open-output-string)])
; if proper-nesting? is true, the characters ", @, !, and | lose their
; special meaning within nested groups.
(lambda (ip proper-nesting?)
(let loop ()
(state-case (c (read-char ip))
[(#\" #\@ #\! #\|)
(write-char #\" buf)
(write-char c buf)
(loop)]
[(#\\)
(state-case (c (peek-char ip))
[(#\@ #\! #\|) (write-char #\" buf)]
[else (void)])
(write-char c buf)
(loop)]
[(#\{)
(if proper-nesting?
(fprintf buf "{~a}" (read-bracketed-text ip 1))
(write-char c buf))
(loop)]
[(eof) (get-output-string buf)]
[else (write-char c buf) (loop)])))))
(define-syntactic-monad P
ip ; current input port
op ; current output port
ips ; input port stack; does not include ip
ops ; output port stack; does not include op
ifiles ; stack of input files [(cons ip ips) w/o string ports]
eofconts ; stack of continuations to call on eof
sout ; output port for code within schemedisplay or #f
)
(define process-string
(P lambda (s k)
(P s0
([ip (open-input-string s)]
[ips (cons ip ips)]
[eofconts (cons (P lambda ()
(P k
([op (car ops)] [ops (cdr ops)])
(get-output-string op)))
eofconts)]
[op (open-output-string)]
[ops (cons op ops)]))))
(define s0
(P lambda ()
(state-case (c (read-char ip))
[(#\\)
(let ([cmd (read-command ip)])
(cond
[(get-def cmd '()) =>
(lambda (proc)
(unless (or (command-symbol? cmd)
(eq? cmd 'schemedisplay)
(eq? cmd 'schemeinit)
(eq? cmd 'transcript))
(suppress-white-space ip))
(P proc))]
[else (fprintf op "\\~a" cmd) (P s0)]))]
[(#\%)
(write-char #\% op)
(copy-through-newline ip op)
(P s0)]
[(eof)
(close-port ip)
(if (null? ips)
(when sout (close-port sout))
(P (car eofconts)
([ip (car ips)]
[ips (cdr ips)]
[ifiles (if (eq? ip (car ifiles)) (pop-ifile ifiles) ifiles)]
[eofconts (cdr eofconts)])))]
[else (write-char c op) (P s0)])))
;--------------------------------------------------------------------------
(define go
(lambda (fn)
(let ([ip (open-input-file (format "~a.stex" fn))])
(let ([op (open-output-file (format "~a.tex" fn) 'replace)])
(fprintf op "%%% DO NOT EDIT THIS FILE~%")
(fprintf op "%%% Edit the .stex version instead~%~%")
; preplib parameters
(parameterize ([current-ifile #f]
[genlab-prefix "s"]
[genlab-counters '()])
(P s0
([ip ip]
[op op]
[ips '()]
[ops '()]
[ifiles (push-ifile ip '())]
[eofconts (list s0)]
[sout #f]))
(close-port op))))))
(global-def genlab
(P lambda ()
(display (genlab) op)
(P s0)))
(global-def hindex
(P lambda ()
(P process-string () (read-bracketed-text ip)
(P lambda (lab)
(fprintf op "\\hindex{~a}" lab)
(read-open-brace ip)
(sindex ip op)
(P s0)))))
(global-def index
(P lambda ()
(let ([lab (genlab)])
(fprintf op "\\label{~a}\\hindex{~a}" lab lab))
(read-open-brace ip)
(sindex ip op)
(P s0)))
(global-def raw
(P lambda ()
(display (read-bracketed-text ip) op)
(P s0)))
(global-def scheme
(P lambda ()
(read-open-brace ip)
(display "\\scheme{" op)
(sscheme ip op)
(write-char #\} op)
(P s0)))
(global-def schemedisplay
(P lambda ()
(display "\\schemedisplay\n" op)
(let loop ([options '()] [labels '()])
; currently a bit sloppy on the grammar
(state-case (c (read-char ip))
[(#\\)
; use read-alpha-command instead of read-command to avoid
; improper handling of special characters that follow a slash
(let ([cmd (read-alpha-command ip)])
(case cmd
[(label)
(loop options (cons (read-bracketed-text ip) labels))]
[(raw)
(fprintf op "\\raw{~a}~%" (read-bracketed-text ip))
(loop options labels)]
[else
(input-error "invalid command \\~s following \\schemedisplay" cmd)]))]
[(#\newline)
(P sschemedisplay () (memq 'number-lines options) labels)]
[(#\[)
(unread-char c ip)
(let ([opt (read-optional-arg ip)])
(if (equal? opt "number-lines")
(loop (cons 'number-lines options) labels)
(input-error "unexpected optional argument ~a to \\schemedisplay" opt)))]
[else (input-error "expected newline after \\schemedisplay")]))
(P s0)))
(global-def schemeoutput
(P lambda ()
(let* ([mode (if (equal? (read-optional-arg ip) "append") 'append 'replace)]
[filename (read-bracketed-text ip)])
(when sout (close-port sout))
(if (eq? filename "")
(P s0 ([sout #f]))
(P s0 ([sout (open-output-file filename mode)]))))))
(global-def var
(P lambda ()
(display "\\scheme{" op)
(dovar ip op)
(write-char #\} op)
(P s0)))
(global-def def
(P lambda ()
(let* ([cmd (state-case (c (read-char ip))
[(#\\) (read-command ip)]
[else (input-error "invalid \\def syntax")])]
[pattern (read-def-pattern ip)]
[template (read-bracketed-text ip)])
(fprintf op "\\def\\~a" cmd)
(for-each
(lambda (x)
(cond
[(char? x) (write-char x op)]
[(number? x) (fprintf op "#~a" x)]
[else (errorf #f "unexpected parsed pattern element ~s" x)]))
pattern)
(fprintf op "{~a}" template)
(P s0))))
(global-def xdef
(P lambda ()
(let* ([cmd (state-case (c (read-char ip))
[(#\\) (read-command ip)]
[else (input-error "invalid \\xdef syntax")])]
[pattern (read-def-pattern ip)]
[template (read-bracketed-text ip)])
(set-def! cmd '() #f
(P lambda ()
(P s0
([ip (open-input-string
(expand-template template
(read-args ip pattern cmd) cmd))]
[ips (cons ip ips)]
[eofconts (cons s0 eofconts)]))))
(P s0))))
(global-def xedef
(P lambda ()
(let* ([cmd (state-case (c (read-char ip))
[(#\\) (read-command ip)]
[else (input-error "invalid \\xedef syntax")])]
[pattern (read-def-pattern ip)]
[template (read-bracketed-text ip)])
(P process-string () template
(P lambda (template)
(set-def! cmd '() #f
(P lambda ()
(P s0
([ip (open-input-string
(expand-template template
(read-args ip pattern cmd) cmd))]
[ips (cons ip ips)]
[eofconts (cons s0 eofconts)]))))
(P s0))))))
(global-def schemeverbatim
(P lambda ()
(display "\\begin{verbatim}\n" op)
(let f ()
(state-case (c (read-char ip))
[(#\\)
(let ([cmd (read-command ip)])
(case cmd
[(endschemeverbatim) (void)]
[else (write-char c op) (display cmd op) (f)]))]
[(eof) (unexpected-eof "after \\schemeverbatim")]
[else (write-char c op) (f)]))
(display "\\end{verbatim}\n" op)
(P s0)))
(global-def timestamp
(P lambda ()
(display (date-and-time) op)
(P s0)))
;--------------------------------------------------------------------------
(let ()
(define-syntax define-enumeration
(lambda (x)
(define iota
(case-lambda
[(n) (iota 0 n)]
[(i n) (if (= i n) '() (cons i (iota (+ i 1) n)))]))
(syntax-case x ()
[(_ name (enum ...))
(and (identifier? #'name) (andmap identifier? #'(enum ...)))
(with-syntax ([len (length #'(enum ...))])
(with-syntax ([(i ...) (iota #'len)])
#'(begin (define enum i) ... (define name len))))])))
(define-record tag (markup entity))
(define make-tag-port
(lambda (ip)
; To preserve the indentation of Scheme expressions in the .stex source,
; we have to add the leading whitespace the user would have entered to
; compensate for the indentation---due to the prompt---of the first line.
; We compute the current indentation level when writing non-echo output.
; We indent subsequent input lines after we read the first line that
; follows some output.
(define-enumeration num-modes (writing reading indenting))
(define mode writing)
(define indent 0)
(define adjust-indent ; called by output routine
(lambda (x)
(define do-char
(lambda (c)
(set! indent (if (char=? c #\newline) 0 (fx+ indent 1)))))
; shouldn't do this if we're printing on behalf of the repl
(begin ; unless (use-interaction-window)
(unless (fx= mode writing) (set! indent 0))
(set! mode writing)
(if (char? x)
(do-char x)
(let ([len (string-length x)])
(do ([i 0 (fx+ i 1)]) ((fx= i len))
(do-char (string-ref x i))))))))
(define whitespace?
(lambda (x)
(if (char? x)
(char-whitespace? x)
(let loop ([i (fx- (string-length x) 1)])
(or (fx< i 0)
(and (char-whitespace? (string-ref x i))
(loop (fx- i 1))))))))
(let ([line '()] [bline '()] [buffer '()] [ip ip])
(define (handler msg . args)
(record-case (cons msg args)
[char-ready? (p)
(critical-section
(or (not (null? line)) (char-ready? ip)))]
[peek-char (p)
(define read-line
(lambda ()
(when (fx= mode writing) (set! mode reading))
(when (fx= mode indenting)
(unless (fx= indent 0)
(set! buffer
(cons (make-tag #f (make-string indent #\space))
buffer))))
(let loop ()
(let ([c (read-char ip)])
(if (eof-object? c)
'()
(let ([x (make-tag #f c)])
(set! buffer (cons x buffer))
(if (eqv? c #\newline)
(begin (set! mode indenting) (list x))
(cons x (loop)))))))))
(critical-section
(if (null? line)
(let ([old bline])
(set! line (read-line))
(set! bline '())
(if (null? line)
(begin
; When the last expression in a transcript calls read
; and then prints something in the transcript window,
; we have to be sure that the newline character that
; sent the line of buffered text is properly tagged as
; having been read via the transcript input port since
; read simply peeks at the whitespace character and the
; subsequent repl read (returning #!eof) will usurp the
; newline unless we patch it up here.
(when (and (> (length old) 1)
(eqv? (tag-entity (car old)) #\newline)
(eq? (tag-markup (cadr old)) 'transin))
(set-tag-markup! (car old) 'transin))
#!eof)
(tag-entity (car line))))
(tag-entity (car line))))]
[unread-char (c p)
(critical-section
(when (null? bline)
(errorf 'unread-char "too many consecutive unreads from ~s" p))
(let ([x (car bline)])
(set! bline (cdr bline))
(set-tag-markup! x #f)
(set-tag-entity! x c)
(set! line (cons x line))))]
[clear-input-port (p)
(critical-section
(set! line '())
(set! bline '()))]
[clear-output-port (p) (void)]
[close-port (p) (mark-port-closed! p)]
[flush-output-port (p) (void)]
[file-position (p . pos)
(if (null? pos)
(most-negative-fixnum)
(errorf 'transcript-port "cannot reposition"))]
[port-name (p) "tag-port"]
; intentionally missing block-read and read-char
[tag-read-char (markup p)
(critical-section
(let ([c (peek-char p)])
(unless (null? line)
(let ([x (car line)])
(set! line (cdr line))
(set-tag-markup! x markup)
(set! bline (cons x bline))))
c))]
[tag-write-entity (markup x p)
(critical-section
(adjust-indent x)
(set! buffer (cons (make-tag markup x) buffer)))]
[tag-get-repl-interaction-strings ()
(let ([repl (open-output-string)] [intr (open-output-string)])
(define maxcols (interaction-window-width))
(define col 0)
(define col-display
(lambda (entity p)
(define col-write-char
(lambda (c p)
(cond
[(char=? c #\newline) (set! col 0)]
[(= col maxcols) (newline p) (set! col 0)])
(write-char c p)
(set! col (+ col 1))))
(if (char? entity)
(col-write-char entity p)
(for-each (lambda (c) (col-write-char c p)) (string->list entity)))))
(define choose-port
(lambda (mkup)
(case mkup
[(#f transerr traceout) repl]
[(transin transout) intr]
[else (errorf 'scheme-prep.ss "unexpected markup ~s" mkup)])))
(define reclaim-first-newline
; the newline that we entered after the expression in the repl window should
; be charged to the repl window, not the interaction window.
; (misattributed as being read by transin since the repl's read just peeks at
; the newline, and subsequent read during eval phase claims the newline)
(lambda (ls)
(let f ([ls ls])
(if (null? ls)
'()
(let ([x (car ls)])
(case (tag-markup x)
[(transin) (when (eqv? (tag-entity x) #\newline) (set-tag-markup! x #f))]
[(transout) (void)]
[else (f (cdr ls))]))))
ls))
(let loop ([ls (reclaim-first-newline (reverse buffer))] [markup #f])
(if (null? ls)
(begin
(set! buffer '())
(when markup (fprintf (choose-port markup) "\\raw{\\end~s{}}" markup))
(values
(get-output-string repl)
(let ([x (get-output-string intr)])
(if (eq? x "") #f x))))
(let ([x (car ls)])
(let ([new (tag-markup x)] [entity (tag-entity x)])
(unless (eq? new markup)
(when markup (fprintf (choose-port markup) "\\raw{\\end~s{}}" markup))
(when new (fprintf (choose-port new) "\\raw{\\~s{}}" new)))
(let ([p (choose-port new)])
(if (eq? p repl)
(display entity p)
(col-display entity p)))
(loop (cdr ls) new))))))]
[tag-get-output-string ()
(let ([op (open-output-string)])
(let loop ([ls (reverse buffer)] [markup #f])
(if (null? ls)
(begin
(set! buffer '())
(when markup (fprintf op "\\raw{\\end~s{}}" markup))
(get-output-string op))
(let ([x (car ls)])
(let ([new (tag-markup x)] [entity (tag-entity x)])
(unless (eq? new markup)
(when markup (fprintf op "\\raw{\\end~s{}}" markup))
(when new (fprintf op "\\raw{\\~s{}}" new)))
(display entity op)
(loop (cdr ls) new))))))]
[delete-last-line-if-unmarked ()
; clean up the "\n> \n" at the end of the transcript
; by deleting everything from the last newline upto, but
; not including the second newline.
(let trim ([ls buffer] [n? #f])
(if (or (null? ls) (tag-markup (car ls)))
(set! buffer ls)
(let foo ([first (tag-entity (car ls))])
(cond
[(string? first)
(let scan ([i (- (string-length first) 1)] [n? n?])
(cond
[(fx< i 0) (trim (cdr ls) n?)]
[(char=? (string-ref first i) #\newline)
(if (not n?)
(scan (fx- i 1) #t)
(begin
(set-tag-entity!
(car ls)
(substring first 0 i))
(set! buffer ls)))]
[else (scan (fx- i 1) n?)]))]
[(char=? first #\newline)
(if (not n?)
(trim (cdr ls) #t)
(set! buffer (cdr ls)))]
[else (trim (cdr ls) n?)]))))
; trim the last newline at the end of the transcript
; since transcript env will insert some vspace of its own
(unless (null? buffer)
(let ([first (car buffer)])
(when (eqv? (tag-entity first) #\newline)
(set! buffer (cdr buffer)))))]
[else (errorf 'tag-port "operation ~s not handled" msg)]))
(make-input/output-port handler "" ""))))
(define make-markup-port
(lambda (tag-p imarkup omarkup)
(define (handler msg . args)
(record-case (cons msg args)
[block-read (p str cnt)
(critical-section
(let ([c (peek-char p)])
(if (eof-object? c)
c
(if (= cnt 0)
0
(begin
(read-char p)
(string-set! str 0 c)
1)))))]
[char-ready? (p) (char-ready? tag-p)]
[clear-input-port (p) (clear-input-port tag-p)]
[clear-output-port (p) (clear-output-port tag-p)]
[close-port (p) (mark-port-closed! p) (close-port tag-p)]
[flush-output-port (p) (flush-output-port tag-p)]
[file-position (p . pos)
(if (null? pos)
(most-negative-fixnum)
(errorf 'transcript-port "cannot reposition"))]
[port-name (p) "markup"]
[peek-char (p) (peek-char tag-p)]
[read-char (p) ((port-handler tag-p) 'tag-read-char imarkup tag-p)]
[unread-char (c p) (unread-char c tag-p)]
[write-char (c p) ((port-handler tag-p) 'tag-write-entity omarkup c tag-p)]
[block-write (p str cnt)
((port-handler tag-p)
'tag-write-entity
omarkup
(substring str 0 cnt)
tag-p)
cnt]
[else (errorf 'markup-port "operation ~s not handled" msg)]))
(make-input/output-port handler "" "")))
(define scheme-transcript
(P lambda (console-input labels)
(let ([tp (make-tag-port (open-input-string console-input))])
(let ([normal (make-markup-port tp #f #f)]
[trace (make-markup-port tp #f 'traceout)]
[effect (make-markup-port tp 'transin 'transout)]
[errors (make-markup-port tp #f 'transerr)]
[handler (port-handler tp)])
(handler 'tag-write-entity #f "\\schemedisplay" tp)
(for-each
(lambda (l)
(handler 'tag-write-entity #f (format "\\label{~a}" l) tp))
labels)
(handler 'tag-write-entity #f "\n" tp)
(parameterize ([console-input-port normal]
[console-output-port normal]
[console-error-port normal]
[current-input-port effect]
[current-output-port effect]
[current-error-port effect]
[trace-output-port trace])
(new-cafe
(lambda (x)
(with-exception-handler default-exception-handler
(lambda ()
(eval x))))))
; We could do this with string bashing. I modified the port.
(handler 'delete-last-line-if-unmarked tp)
(handler 'tag-write-entity #f "\\endschemedisplay\n" tp)
(if (use-interaction-window)
(let-values ([(repl interaction) (handler 'tag-get-repl-interaction-strings tp)])
(P s0
([ip
(if (not interaction)
(open-input-string repl)
(open-input-string
(string-append
"\\startrepl{}" repl
"\\endrepl{}\\startinteraction{}\\schemedisplay\n"
interaction
"\\endschemedisplay\\endinteraction{}")))]
[ips (cons ip ips)]
[eofconts (cons s0 eofconts)])))
(let ([transcript (handler 'tag-get-output-string tp)])
(P s0
([ip (open-input-string transcript)]
[ips (cons ip ips)]
[eofconts (cons s0 eofconts)]))))))))
(define make-string-evaluator
(lambda (start-mark evaluator)
(P lambda ()
(define text-upto
(let ([op (open-output-string)])
(lambda (endmark)
(state-case (c (read-char ip))
[(#\\)
(let ([mk (read-alpha-command ip)])
(if (eq? mk endmark)
(get-output-string op)
(begin
(write-char #\\ op)
(display mk op)
(text-upto endmark))))]
[(eof) (unexpected-eof (format "after \\~a" start-mark))]
[else
(write-char c op)
(text-upto endmark)]))))
(let loop ([endmark #f] [labels '()])
(state-case (c (read-char ip))
[(#\[) ;]
(when endmark
(input-error "expected newline after \\~a[~a]" start-mark endmark))
(unread-char c ip)
(let ([ls (string->list (read-optional-arg ip))])
(when (null? ls)
(input-error "empty optional argument to \\~a" start-mark))
(when (not (char=? (car ls) #\\))
(input-error "\\~a terminator must begin with \\" start-mark))
(let ([rest (cdr ls)])
(when (or (null? rest) (not (andmap char-alphabetic? (cdr ls))))
(input-error
"\\~a terminator must be \\ followed by alphabetic character(s)" start-mark))
(loop (string->symbol (list->string rest)) labels)))]
[(#\\)
; currently a bit sloppy on the grammar
; could require all labels one after the other
; use read-alpha-command instead of read-command to avoid
; improper handling of special characters that follow a slash
(let ([cmd (read-alpha-command ip)])
(case cmd
[(label)
(loop endmark (cons (read-bracketed-text ip) labels))]
[else
(input-error "invalid command \\~s following \\~a" cmd start-mark)]))]
[(#\newline)
(let ([endmark
(or endmark
(string->symbol (string-append "end" start-mark)))])
(P evaluator () (text-upto endmark) endmark (reverse labels)))]
[(#\space #\tab) (loop endmark labels)]
[else
(let ([txt (format "expected newline after \\~a" start-mark)])
(input-error
(if endmark
(string-append txt (format "[~a]" endmark))
txt)))])))))
(global-def schemeinit
; whitespace has not suppressed when we are invoked
(make-string-evaluator "schemeinit"
(P lambda (s endmark labels)
(unless (null? labels) (input-error "what on earth do you mean putting \\label after \\schemeinit ???"))
; We could perhaps make this easier by not trying to share the
; make-string-evaluator code with \transcript and instead let
; the code simply read from the true ip instead, so that input-error
; does its job without our assistance. Unfortunately, I just thought
; of that and don't have the heart to do any more than document the
; possibility.
(let ([real-abort-handler (abort-handler)])
(let ([sip (open-input-string s)])
; nesting is not an issue.
(let f ()
; scan ahead to first non-whitespace character, if any
(let skip-whitespace ()
(let ([c (peek-char sip)])
(when (and (char? c) (char-whitespace? c))
(read-char sip)
(skip-whitespace))))
; record the current file position so we adjust the true
; file-position based on the string-input-port's file position
; if we run into an error
(let ([last-sip-pos (file-position sip)])
(define scout ; be prepared
(lambda (thunk)
(parameterize
([abort-handler
(lambda args
(let ([end (file-position ip)]
[endmark-len
(+ 1
(string-length (symbol->string endmark)))])
(file-position
ip
(- end
endmark-len
(- (string-length s) last-sip-pos))))
(parameterize ([abort-handler real-abort-handler])
(input-error
"previous error occurred within \\schemeinit")))])
(thunk))))
(let ([x (scout (lambda () (read sip)))])
(unless (eof-object? x)
(scout (lambda () (eval x)))
(f)))))))
(P s0 ()))))
(global-def generated
(P lambda ()
(let ([sop (open-output-string)])
(let loop ()
(state-case (c (peek-char ip))
[(#\space #\tab #\newline) (read-char ip) (loop)]
[(#\\)
(read-char ip)
(let ([cmd (read-alpha-command ip)])
(case cmd
[(endgenerated)
(P s0 ([ip (open-input-string (get-output-string sop))]
[ips (cons ip ips)]
[eofconts (cons s0 eofconts)]))]
[else (input-error "unexpected command \\~s following \\generated" cmd)]))]
[else
(parameterize ([current-output-port sop])
(eval (read ip))) ; should protect against errors
(loop)])))))
(global-def transcript
; whitespace has not suppressed when we are invoked
(make-string-evaluator "transcript"
(P lambda (s endmark labels)
(P scheme-transcript () s labels))))
(global-def useinteractionwindow
(P lambda ()
(use-interaction-window #t)
(P s0 ())))
(global-def enduseinteractionwindow
(P lambda ()
(use-interaction-window #f)
(P s0 ())))
(global-def interactionwindowwidth
(P lambda ()
(let ([s (read-bracketed-text ip)])
(let ([n (string->number s)])
(unless n (errorf #f "expected numeric argument to \\interactionwindowwidth"))
; should be more clever here to make it work in bgroup ... egroup fashion
(interaction-window-width n)
(P s0 ())))))
)
(populate-source-directories)
(command-line-case (command-line)
[((keyword --help)) (usage)]
[((keyword --version)) (version)]
[(filename* ...)
(for-each go
(let ([found (find-filename "scheme-prep.tex")])
(if found
(cons found filename*)
filename*)))])
| true |
6e134614558d58a1baff55f6966af809845572e7 | 91fc138a1cbcbeffaf6cf4eb0e3ae188b2ca257f | /Chapter 1 Exercises/1.46.scm | 721a04785520971524a65425c81f996d2bf21227 | []
| no_license | jlollis/sicp-solutions | 0bd8089aea5a85c7b34e43a0f34db87e4161bee0 | 7b03befcfe82e26a7fb28d94bc99292bc484f9dd | refs/heads/master | 2022-06-15T23:34:10.541201 | 2022-06-02T03:32:46 | 2022-06-02T03:32:46 | 130,729,626 | 9 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 858 | scm | 1.46.scm | #lang sicp
#|
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.
|#
[...] | false |
bf8b908e0cb72c3d5a704f0e9991808bc9d31ae7 | 120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193 | /packages/slib/sierpinski.scm | 1096bd5d50ddf11aa6aa0c9fa45b3f828685b3f2 | [
"MIT"
]
| permissive | evilbinary/scheme-lib | a6d42c7c4f37e684c123bff574816544132cb957 | 690352c118748413f9730838b001a03be9a6f18e | refs/heads/master | 2022-06-22T06:16:56.203827 | 2022-06-16T05:54:54 | 2022-06-16T05:54:54 | 76,329,726 | 609 | 71 | MIT | 2022-06-16T05:54:55 | 2016-12-13T06:27:36 | Scheme | UTF-8 | Scheme | false | false | 1,965 | scm | sierpinski.scm | ;"sierpinski.scm" Hash function for 2d data which preserves nearness.
;From: [email protected] (John Bartholdi)
;
; This code is in the public domain.
;Date: Fri, 6 May 94 13:22:34 -0500
;@
(define MAKE-SIERPINSKI-INDEXER
(lambda (max-coordinate)
(lambda (x y)
(if (not (and (<= 0 x max-coordinate)
(<= 0 y max-coordinate)))
(slib:error 'sierpinski-index
"Coordinate exceeds specified maximum.")
;
; The following two mutually recursive procedures
; correspond to to partitioning successive triangles
; into two sub-triangles, adjusting the index according
; to which sub-triangle (x,y) lies in, then rescaling
; and possibly rotating to continue the recursive
; decomposition:
;
(letrec ((loopA
(lambda (resolution x y index)
(cond ((zero? resolution) index)
(else
(let ((finer-index (+ index index)))
(if (> (+ x y) max-coordinate)
;
; In the upper sub-triangle:
(loopB resolution
(- max-coordinate y)
x
(+ 1 finer-index))
;
; In the lower sub-triangle:
(loopB resolution
x
y
finer-index)))))))
(loopB
(lambda (resolution x y index)
(let ((new-x (+ x x))
(new-y (+ y y))
(finer-index (+ index index)))
(if (> new-y max-coordinate)
;
; In the upper sub-triangle:
(loopA (quotient resolution 2)
(- new-y max-coordinate)
(- max-coordinate new-x)
(+ finer-index 1))
;
; In the lower sub-triangle:
(loopA (quotient resolution 2)
new-x
new-y
finer-index))))))
(if (<= x y)
;
; Point in NW triangle of initial square:
(loopA max-coordinate
x
y
0)
;
; Else point in SE triangle of initial square
; so translate point and increase index:
(loopA max-coordinate
(- max-coordinate x)
(- max-coordinate y) 1)))))))
| false |
44a4c1b653b77e6f5aa82e025021ed4a3ca51df3 | d921ed08d6d78aa2638da5521ec05ab603126602 | /scheme/hailstone-sequence.scm | dddd44a35a05374ed7d4b4c5eba42d754bb9e35d | []
| no_license | gowda/hailstone-sequence | fe12e683a961049a4225bd2e0e6499065fc2b188 | c4b8efaa7824142eac2279bdf988bf0d9cf1c27b | refs/heads/master | 2020-05-01T06:30:11.419978 | 2012-09-09T00:42:51 | 2012-09-09T00:42:51 | 2,642,012 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,177 | scm | hailstone-sequence.scm | #!/usr/bin/guile \
-e main -s
!#
(use-modules (ice-9 streams))
(use-modules (ice-9 getopt-long))
(define even?
(lambda (number)
(= (modulo number 2) 0)))
(define odd?
(lambda (number)
(not (even? number))))
(define (hailstone number)
(define (stone-it number)
(cond ((odd? number) (+ 1 (* 3 number)))
((even? number) (/ number 2))))
(if (= number 1)
(list number)
(append (list number) (hailstone (stone-it number)))))
(define (make-hailstone-sequence limit)
(let ((numbers (make-stream (lambda (state)
(if (>= state limit)
state
(cons state
(+ state 1)))) 1)))
(define (move-on!)
(let ((new-stream (stream-cdr numbers)))
(set! numbers new-stream)))
(define (dispatch op)
(cond ((eq? op 'hailstone) (let ((sequence (hailstone
(stream-car numbers))))
(move-on!)
sequence))
((eq? op 'longest) (stream-fold (lambda (sequence previous)
(cond ((or (null? previous)
(>= (length sequence)
(cadr previous)))
(list (car sequence)
(length sequence)))
(else previous)))
'()
(stream-map hailstone numbers)))))
dispatch))
(define (time-diff t1 t2)
(cons (- (car t1) (car t2))
(- (cdr t1) (cdr t2))))
(define-syntax measure-time
(syntax-rules ()
((_ exp)
(let ((past (gettimeofday)))
(let ((value exp))
(let ((now (gettimeofday)))
(list value (time-diff now past))))))))
(define (longest-hailstone-until limit)
(let ((hailstones (make-hailstone-sequence limit)))
(hailstone (car (hailstones 'longest)))))
(define (main args)
(let* ((option-spec '((version (single-char #\v) (value #f))
(help (single-char #\h) (value #f))
(longest (single-char #\l) (value #t))))
(options (getopt-long args option-spec))
(help-wanted (option-ref options 'help #f))
(version-wanted (option-ref options 'version #f))
(longest-limit (string->number (option-ref options 'longest "100"))))
(if (or version-wanted help-wanted)
(begin
(if version-wanted
(display "hailstone-sequence - version 0.5\n"))
(if help-wanted
(display "\
hailstone-sequence [options]
-v, --version Display version
-h, --help Display this help
-l, --longest N Display the longest hailstone sequence for any 'n' (< N)
")))
(begin
(display (longest-hailstone-until longest-limit))
(newline)))))
| true |
0f0278e7e164d4f94c3c379c7a8e055df32d1b83 | 2e4afc99b01124a1d69fa4f44126ef274f596777 | /apng/resources/dracula/lang/config-panel-sig.ss | f975d2d38c9d865da06905f50093939bb8914838 | []
| no_license | directrix1/se2 | 8fb8204707098404179c9e024384053e82674ab8 | 931e2e55dbcc55089d9728eb4194ebc29b44991f | refs/heads/master | 2020-06-04T03:10:30.843691 | 2011-05-05T03:32:54 | 2011-05-05T03:32:54 | 1,293,430 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 69 | ss | config-panel-sig.ss | (module config-panel-sig (lib "a-signature.ss") attach-config-panel!) | false |
2f0f104193af0496f2c57462f68f94c16a4a5b88 | eef5f68873f7d5658c7c500846ce7752a6f45f69 | /test/algorithm-hamming-distance.scm | e52ba44b07d4bb258b69cdac0044b08972b172da | [
"MIT"
]
| permissive | alvatar/spheres | c0601a157ddce270c06b7b58473b20b7417a08d9 | 568836f234a469ef70c69f4a2d9b56d41c3fc5bd | refs/heads/master | 2021-06-01T15:59:32.277602 | 2021-03-18T21:21:43 | 2021-03-18T21:21:43 | 25,094,121 | 13 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 1,224 | scm | algorithm-hamming-distance.scm | (%load-library '(spheres/util test))
(%load-library '(spheres/algorithm hamming-distance))
(test-begin "hamming-distance" 9)
(test-equal "hamming distance 1"
(hamming-distance '(a b c d) '(a b a d))
1)
(test-equal "hamming distance 2"
(hamming-distance '(a a c d) '(a b a d))
2)
(test-equal "hamming distance 3"
(hamming-distance '(a b c d) '(a b c d))
0)
(test-error "hamming distance 4"
(hamming-distance '(a a c d) '(a)))
(test-equal "hamming distance with all permutations 1"
(hamming-distance-all-permutations '(a b c d) '(a b c d))
0)
(test-equal "hamming distance with all permutations 2"
(hamming-distance-all-permutations '(a b c d) '(a d c b))
0)
(test-equal "hamming distance with all permutations 3"
(hamming-distance-all-permutations '(a b c d) '(d b z a))
1)
(test-equal "hamming distance with all permutations 4"
(hamming-distance-all-permutations '(a b c d) '(a b z a))
2)
(test-error "hamming distance with all permutations 5"
(hamming-distance-all-permutations '(a b c d) '(a)))
(test-end)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.