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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01560867274ae1e6b99ea50c654914a745fcd355
|
ece1c4300b543df96cd22f63f55c09143989549c
|
/Chapter4/Exercise4.26.scm
|
e1df14e10d5a863318fd600752883ae0e7535d45
|
[] |
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,294 |
scm
|
Exercise4.26.scm
|
; Exercise 4.26: Ben Bitdiddle and Alyssa P. Hacker disagree over the importance of lazy evaluation for implementing things such as unless. Ben points out that it’s possible to implement unless in applicative order as a special form. Alyssa counters that, if one did that, unless would be merely syntax, not a procedure that could be used in conjunction with higher-order procedures. Fill in the details on both sides of the argument. Show how to implement unless as a derived expression (like cond or let), and give an example of a situation where it might be useful to have unless available as a procedure, rather than as a special form.
; as a special form, it unless could be normal order using if.
; if we were to eval it as procedure, we have to use delay to do it
; when you try to use it with map, you have to use it as procedure not special form
(load "/Users/soulomoon/git/SICP/Chapter4/separating.scm")
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp)
(analyze-quoted exp))
((variable? exp)
(analyze-variable exp))
((unless? exp)
(display (unless->if exp))(newline )
(analyze (unless->if exp)))
((assignment? exp)
(analyze-assignment exp))
((definition? exp)
(analyze-definition exp))
((if? exp)
(analyze-if exp))
((lambda? exp)
(analyze-lambda exp))
((begin? exp)
(analyze-sequence
(begin-actions exp)))
((cond? exp)
(analyze (cond->if exp)))
((application? exp)
(analyze-application exp))
(else
(error "Unknown expression
type: ANALYZE"
exp))))
(define (unless-conditione exp)
(cadr exp))
(define (unless-normal exp)
(caddr exp))
(define (unless-exception exp)
(cadddr exp))
(define (unless->if exp)
(make-if (unless-conditione exp)
(unless-exception exp)
(unless-normal exp)))
(define (unless? exp)
(tagged-list? exp 'unless))
(interpret
'(unless (= 0 0)
(/ 1 0)
10
)
)
; Welcome to DrRacket, version 6.7 [3m].
; Language: SICP (PLaneT 1.18); memory limit: 128 MB.
; (if (= 0 0) 10 (/ 1 0))
; 10
; >
| false |
ead9db4697161caa763c108d45f750828268aa46
|
92b8d8f6274941543cf41c19bc40d0a41be44fe6
|
/testsuite/sva40077.scm
|
1d53eac14d23ed72b921e954cb18d4342499f815
|
[
"MIT"
] |
permissive
|
spurious/kawa-mirror
|
02a869242ae6a4379a3298f10a7a8e610cf78529
|
6abc1995da0a01f724b823a64c846088059cd82a
|
refs/heads/master
| 2020-04-04T06:23:40.471010 | 2017-01-16T16:54:58 | 2017-01-16T16:54:58 | 51,633,398 | 6 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 185 |
scm
|
sva40077.scm
|
(let ((a 0) (b 0.01))
(format #t "~a~%" (and (eqv? a 0) (not b))))
;; Output: #f
(define (repeat? a b)
(and (eqv? a 0) (not b)))
(format #t "~a~%" (repeat? 0 0.01))
;; Output: #f
| false |
8dc3a8c159053690a650e7ed8b4e2e71e553a58d
|
174072a16ff2cb2cd60a91153376eec6fe98e9d2
|
/Chap-Three/3-23.scm
|
992d7340081789ecea88aec7852ab34926246d04
|
[] |
no_license
|
Wang-Yann/sicp
|
0026d506ec192ac240c94a871e28ace7570b5196
|
245e48fc3ac7bfc00e586f4e928dd0d0c6c982ed
|
refs/heads/master
| 2021-01-01T03:50:36.708313 | 2016-10-11T10:46:37 | 2016-10-11T10:46:37 | 57,060,897 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,732 |
scm
|
3-23.scm
|
(define (front-ptr deque) (car deque))
(define (rear-ptr deque) (cdr deque))
(define (set-front-ptr! deque item) (set-car! deque item))
(define (set-rear-ptr! deque item) (set-cdr! deque item))
(define (empty-deque? deque) (null? (front-ptr deque)))
(define (make-deque) (cons '() '()))
(define (front-deque deque)
(if (empty-deque? deque) (error "Front called with an empty deque" deque)
(car (front-ptr deque))))
(define (rear-insert-deque! deque item)
(let ((new-pair (cons item '())))
(cond ((empty-deque? deque)
(set-front-ptr! deque new-pair) (set-rear-ptr! deque new-pair) deque)
(else
(set-cdr! (rear-ptr deque) new-pair) (set-rear-ptr! deque new-pair) deque))))
(define (front-delete-deque! deque)
(cond ((empty-deque? deque) (error "Delete called with an empty deque" deque))
(else(set-front-ptr! deque (cdr ( front-ptr deque )))deque )))
(define (front-insert-deque! deque item)
(let ((new-pair (cons item '())))
(cond ((empty-deque? deque)
(set-front-ptr! deque new-pair) (set-rear-ptr! deque new-pair) deque)
(else
(set-front-ptr! deque (cons item (front-ptr deque ))) deque))))
(define (rear-delete-deque! deque)
(define (iter deque lst)
(cond ((null? (cdr (cdr lst))) (set-cdr! lst '())(set-rear-ptr! deque lst) deque)
(else (iter deque (cdr lst)))))
(cond ((empty-deque? deque) (error "Delete called with an empty deque" deque))
((null? (cdr (front-ptr deque ))) (set-front-ptr! deque '()) deque)
(else (iter deque (front-ptr deque)))));;;;a不符合题意,此处O(n)
(define (print-deque deque) (car deque))
(define dq (make-deque))
(front-insert-deque! dq 'b)
(rear-insert-deque! dq 'qq)
(rear-insert-deque! dq 's)
(rear-insert-deque! dq 'e)
| false |
65fffdbcc82e18db16e674e4fea7f28de2446436
|
98dbcedc8c813a012dd91aa2b0760c0003000203
|
/framework/caching.scm
|
6d76d30fdbc65ff1b2129b37a0164c487dd46db2
|
[] |
no_license
|
nathanielrb/mu-graph-rewriter
|
4d229996ad5e0a9e238dbe76cbdd3d98a2457a5c
|
f03413978f7a204637b23ffad0883f2a0be437a5
|
refs/heads/master
| 2020-06-22T21:12:20.053161 | 2017-12-21T11:24:01 | 2017-12-21T11:24:01 | 94,225,065 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 15,877 |
scm
|
caching.scm
|
(use srfi-69 srfi-18 abnf lexgen)
(require-extension mailbox)
(define (debug-message str #!rest args)
(when (*debug-logging?*)
(apply format (current-error-port) str args)))
(define *query-forms* (make-hash-table))
(define *cache-mailbox* (make-mailbox))
(define-syntax timed-let
(syntax-rules ()
((_ label (let-exp (vars/vals ...) body ...))
(let-values (((ut1 st1) (cpu-time)))
(let ((t1 (current-milliseconds)))
(let-exp (vars/vals ...)
(let-values (((ut2 st2) (cpu-time)))
(let ((t2 (current-milliseconds)))
(debug-message "~%[~A] ~A Time: ~Ams / ~Ams / ~Ams~%" (logkey) label (- ut2 ut1) (- st2 st1) (- t2 t1))
body ...))))))))
(define-syntax timed
(syntax-rules ()
((_ label body ...)
(let-values (((ut1 st1) (cpu-time)))
(let ((t1 (current-milliseconds)))
(let ((result body ...))
(let-values (((ut2 st2) (cpu-time)))
(let ((t2 (current-milliseconds)))
(debug-message "~%[~A] ~A Time: ~Ams / ~Ams / ~Ams~%" (logkey) label (- ut2 ut1) (- st2 st1) (- t2 t1))
result))))))))
(define-syntax timed-limit
(syntax-rules ()
((_ limit label expression body ...)
(let-values (((ut1 st1) (cpu-time)))
(let ((t1 (current-milliseconds)))
(let ((result body ...))
(let-values (((ut2 st2) (cpu-time)))
(let ((t2 (current-milliseconds)))
(when (> (- ut2 ut1) limit)
(debug-message "~%[~A] Exceeded time limit for ~A: ~Ams / ~Ams / ~Ams~%~A~%~%"
(logkey) label (- ut2 ut1) (- st2 st1) (- t2 t1)
expression))
result))))))))
(define-syntax try-safely
(syntax-rules ()
((_ label exp body ...)
(handle-exceptions exn
(begin (log-message "~%[~A] ==Error ~A==~%~A~%~%"
(logkey) label exp)
#f)
body ...))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Quick Splitting of Prologue/Body by Parsing
(define ws*
(repetition
(alternatives char-list/wsp char-list/crlf char-list/lf char-list/cr)))
(define PrefixDecl*
(concatenation
ws* (char-list/:s "PREFIX") ws* PNAME_NS ws* IRIREF ws*))
(define BaseDecl*
(concatenation
ws* (char-list/:s "BASE") ws* IRIREF ws*))
(define Prologue*
(repetition
(alternatives BaseDecl* PrefixDecl*)))
(define split-query-prefix
(memoize
(lambda (q)
(match-let (((prefix body)
(map list->string
(lex Prologue* error q))))
(values prefix body)))))
(define get-query-prefix
(memoize
(lambda (q)
(let-values (((prefix body) (split-query-prefix q)))
prefix))))
(define get-query-body
(memoize
(lambda (q)
(let-values (((prefix body) (split-query-prefix q)))
body))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; REST
(define (regex-escape-string str)
(string-translate* str '(("\\" . "\\\\")
("$" . "\\$")
("." . "\\.")
("|" . "\\|")
("+" . "\\|")
("(" . "\\(")
(")" . "\\)")
("[" . "\\[")
("{" . "\\{")
("*" . "\\*")
("?" . "\\?")
("^" . "\\^")
)))
(define uri-pat "<[^> ]+>")
(define uri-regex (irregex uri-pat))
(define str-pat "\\\"[^\"]+\\\"")
(define str-regex (irregex str-pat))
(define form-regex (irregex (format "(~A)|(~A)" uri-pat str-pat)))
(define (match-to-replacement-keys pattern query from-index match substr key* key)
(conc pattern
(substring query from-index (irregex-match-start-index match))
(if (string=? key substr) substr
(conc "<" key ">"))))
(define (match-to-regex pattern query from-index match substr key* key)
(conc pattern
(regex-escape-string (substring query from-index (irregex-match-start-index match)))
(if key*
(conc "\\k<" key ">")
(conc "(?<" key ">"
(let ((c (substring substr 0 1)))
(cond ((equal? c "<") uri-pat)
((equal? c "\"") str-pat)))
")"))))
(define (split-matches query-body form? matches)
(irregex-fold form-regex
(lambda (from-index form-match seed)
(match seed
((pattern matches end-index n)
(let* ((substr (irregex-match-substring form-match))
(key* (cdr-when (assoc substr matches)))
(key (or key*
(if form? substr
(conc "uri" (number->string n))))))
(list ((if form?
match-to-replacement-keys
match-to-regex)
pattern query-body from-index form-match substr key* key)
(if (or key* form?)
matches
(alist-update substr key matches))
(irregex-match-end-index form-match)
(+ n 1))))))
`("" ,matches #f 0)
query-body))
(define (make-query-pattern/form query #!optional form? (matches '()))
(let ((query-body (get-query-body query)))
(match (split-matches query-body form? matches)
((pattern matches end-index _)
(if end-index
(values (conc pattern
(if form?
(substring query-body end-index)
(regex-escape-string (substring query-body end-index))))
matches)
(values (if form? query-body (regex-escape-string query-body))
'()))))))
(define (make-query-form query matches)
(make-query-pattern/form query #t matches))
(define make-query-pattern
(memoize
(lambda (query)
(make-query-pattern/form query))))
(define (query-cache-key query)
(list (get-query-prefix query)
;; (get-binding 'queried-functional-properties bindings)) ...
(make-query-pattern query)
(call-if (*read-constraint*))
(call-if (*write-constraint*))))
(define (populate-cached-form pattern form match query-string)
(let ((matches (map (lambda (name-pair)
(let ((name (car name-pair))
(index (cdr name-pair)))
(cons (conc "<" (symbol->string name) ">")
(irregex-match-substring match index))))
(irregex-match-names match))))
(string-translate* form matches)))
(define (query-form-lookup query-string)
(if (*cache-forms?*)
(let ((cached-forms (hash-table-ref/default *query-forms* (query-cache-key query-string) #f)))
(if cached-forms
(let ((pattern-regex (first cached-forms)))
(values (irregex-match pattern-regex (get-query-body query-string))
cached-forms))
(values #f #f)))
(values #f #f)))
(define (populate-cached-forms query-string form-match cached-forms)
(match cached-forms
((pattern form form-prefix annotations annotations-forms annotations-prefixes annotations-pairs
deltas-form deltas-prefix bindings update? cached-logkey)
(log-message "~%[~A] Using cached form of ~A~%" (logkey) cached-logkey)
(values (replace-headers
(conc form-prefix
(populate-cached-form pattern form form-match query-string)))
annotations
(and annotations-forms
(map (lambda (annotations-prefix annotations-form)
(replace-headers
(conc annotations-prefix
(populate-cached-form pattern annotations-form form-match query-string))))
annotations-prefixes annotations-forms))
annotations-pairs
(and deltas-form
(replace-headers
(conc deltas-prefix
(populate-cached-form pattern deltas-form form-match query-string))))
bindings
update?))))
(define cache-save-daemon
(make-thread
(lambda ()
(let loop ()
(let ((thunk (mailbox-receive! *cache-mailbox*)))
(handle-exceptions exn (begin
(log-message "[~A] Error saving cache forms~%" (logkey))
(print-exception exn))
(thunk)))
(loop)))))
(thread-start! cache-save-daemon)
(define (enqueue-cache-action! thunk)
(mailbox-send! *cache-mailbox* thunk))
(define (make-cached-forms query-string rewritten-query
annotations annotations-query-strings annotations-pairs
deltas-query-string bindings update? key)
(let-values (((pattern form-bindings) (make-query-pattern query-string)))
(let* ((make-form (lambda (q) (and q (make-query-form q form-bindings)))))
(list (irregex pattern)
(make-form rewritten-query)
(get-query-prefix rewritten-query)
annotations
(and annotations-query-strings (map make-form annotations-query-strings))
(and annotations-query-strings (map get-query-prefix annotations-query-strings))
annotations-pairs
(and deltas-query-string (make-form deltas-query-string))
(and deltas-query-string (get-query-prefix deltas-query-string))
bindings update? key))))
(define (query-form-save! query-string rewritten-query annotations annotations-query-strings annotations-pairs
deltas-query-string bindings update? key)
(hash-table-set! *query-forms*
(query-cache-key query-string)
;; (filter (lambda (pair) (not (sparql-variable? (cdr pair))))
;; (get-binding 'functional-properties bindings)))
(make-cached-forms query-string rewritten-query
annotations annotations-query-strings annotations-pairs
deltas-query-string bindings update? key)))
(define (enqueue-save-cache-form query-string rewritten-query-string
annotations annotations-query-strings annotations-pairs
deltas-query-string bindings update?)
(let ((key (logkey)) (rc (*read-constraint*)) (wc (*write-constraint*)))
(debug-message "[~A] Saving cache form...~%" (logkey))
(enqueue-cache-action!
(lambda ()
(parameterize ((logkey key)
(*read-constraint* rc)
(*write-constraint* wc))
(let-values (((form-match _) (query-form-lookup query-string)))
(if form-match
(begin (debug-message "[~A] Already cached~%" key)
#f)
(timed "Generate Cache Form"
(query-form-save! query-string
rewritten-query-string
annotations
annotations-query-strings annotations-pairs
deltas-query-string
bindings update? key)))))))))
(define (apply-constraints-with-form-cache query-string)
(apply-constraints-with-form-cache* query-string
(call-if (*read-constraint*))
(call-if (*write-constraint*))))
(define (apply-constraints-with-form-cache* query-string
read-constraint
write-constraint)
(timed-let "Lookup"
(let-values (((form-match cached-forms) (query-form-lookup query-string)))
(if form-match
(populate-cached-forms query-string form-match cached-forms)
(let ((query (parse-query query-string)))
(timed-let "Rewrite"
(let-values (((rewritten-query bindings) (apply-constraints query)))
(let* ((update? (update-query? query))
(annotations (and (*calculate-annotations?*)
(handle-exceptions exn #f
(get-annotations rewritten-query bindings)))))
(let-values (((aqueries annotations-pairs) (if annotations
(annotations-queries annotations rewritten-query)
(values #f #f))))
(let* (;;(queried-annotations (and aquery (try-safely "Getting Queried Annotations" aquery
(rewritten-query-string (write-sparql rewritten-query))
(annotations-query-strings (and aqueries (map write-sparql aqueries)))
(deltas-query (and (*send-deltas?*) (notify-deltas-query rewritten-query)))
(deltas-query-string (and deltas-query (write-sparql deltas-query))))
(log-message "~%[~A] ==Rewritten Query==~%~A~%" (logkey) rewritten-query-string)
(when (*cache-forms?*)
(enqueue-save-cache-form query-string rewritten-query-string
annotations annotations-query-strings annotations-pairs
deltas-query-string bindings update?))
(values (replace-headers rewritten-query-string)
annotations
(and annotations-query-strings (map replace-headers annotations-query-strings))
annotations-pairs
(and deltas-query-string (replace-headers deltas-query-string))
bindings
update?
)))))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; memoization
;; (define keys (memoize keys*))
;;(define renaming (memoize renaming*))
(define-syntax memoize-save
(syntax-rules ()
((_ proc)
(begin
(put! (quote proc) 'memoized proc)
(memoize proc)))))
(define-syntax rememoize
(syntax-rules ()
((_ proc)
(memoize (get (quote proc) 'memoized)))))
(define-syntax unmemoize
(syntax-rules ()
((_ proc)
(or (get (quote proc) 'memoized)
proc))))
(define unique-variable-substitutions (memoize-save unique-variable-substitutions))
(define parse-query (memoize-save parse-query))
(define rdf-equal? (memoize-save rdf-equal?)) ; needs to take namespaces as param as well
(define get-constraint-prefixes (memoize-save get-constraint-prefixes))
(define parse-constraint (memoize-save parse-constraint))
(define replace-headers (memoize-save replace-headers))
(define get-dependencies (memoize-save get-dependencies))
;; (define apply-constraints-with-form-cache* (memoize-save apply-constraints-with-form-cache*))
| true |
eba9ea9b5df30f6ce38d0a8c5003d387f5d2e4a6
|
58381f6c0b3def1720ca7a14a7c6f0f350f89537
|
/Chapter 1/1.3/Ex1.39.scm
|
8dd004bec34e5ea1b818264ef10b7f36b2a3c9a0
|
[] |
no_license
|
yaowenqiang/SICPBook
|
ef559bcd07301b40d92d8ad698d60923b868f992
|
c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a
|
refs/heads/master
| 2020-04-19T04:03:15.888492 | 2015-11-02T15:35:46 | 2015-11-02T15:35:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 437 |
scm
|
Ex1.39.scm
|
#lang planet neil/sicp
(define (cont-frac n d k)
(define (iter n d i)
(if (= k i)
(/ (n i) (d i))
(/ (n i) (+ (d i) (iter n d (+ i 1))))))
(iter n d 1))
(define (d i)
(- (* 2 i) 1))
(define (tan-cf x k)
(cont-frac (lambda (i)
(if (= i 1)
x
(- (* x x))))
d k))
(- (tan 1.0) (tan-cf 1.0 1200))
;; 2.220446049250313e-16 very small difference
| false |
8a1fb121f54b40ce87a99f1a26425ac73309269c
|
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
|
/boot/lib/enums.scm
|
8bc6579f20cf687007b378f3fc59324630b2b429
|
[
"BSD-2-Clause"
] |
permissive
|
david135/sagittarius-scheme
|
dbec76f6b227f79713169985fc16ce763c889472
|
2fbd9d153c82e2aa342bfddd59ed54d43c5a7506
|
refs/heads/master
| 2016-09-02T02:44:31.668025 | 2013-12-21T07:24:08 | 2013-12-21T07:24:08 | 32,497,456 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,769 |
scm
|
enums.scm
|
;; -*- scheme -*-
#!core
(library (core enums)
(export make-enumeration
enum-set-universe
enum-set-indexer
enum-set-constructor
enum-set->list
enum-set-member?
enum-set-subset?
enum-set=?
enum-set-union
enum-set-intersection
enum-set-difference
enum-set-complement
enum-set-projection
define-enumeration)
(import (core)
(core base)
;;(for (core struct) expand)
;;(for (core syntax-rules) expand)
(sagittarius))
;; use record api directory
(define <enum-type>
(let* ((rtd (make-record-type-descriptor '<enum-type> #f #f #f #f
(vector '(immutable universe)
'(immutable indexer))))
(rcd (make-record-constructor-descriptor rtd #f #f)))
(make-record-type '<enum-type> rtd rcd)))
(define make-enum-type (record-constructor (record-type-rcd <enum-type>)))
(define enum-type? (record-predicate (record-type-rtd <enum-type>)))
(define enum-type-universe (record-accessor (record-type-rtd <enum-type>) 0))
(define enum-type-indexer (record-accessor (record-type-rtd <enum-type>) 1))
(define <enum-set>
(let* ((rtd (make-record-type-descriptor '<enum-set> #f #f #f #f
(vector '(immutable type)
'(immutable members))))
(rcd (make-record-constructor-descriptor rtd #f #f)))
(make-record-type '<enum-set> rtd rcd)))
(define make-enum-set (record-constructor (record-type-rcd <enum-set>)))
(define enum-set? (record-predicate (record-type-rtd <enum-set>)))
(define enum-set-type (record-accessor (record-type-rtd <enum-set>) 0))
(define enum-set-members (record-accessor (record-type-rtd <enum-set>) 1))
#;(define-struct <enum-type>
(make-enum-type universe indexer)
enum-type?
(lambda (i p)
(format p "#<enum-type ~a>" (enum-type-members i)))
(universe enum-type-universe)
(indexer enum-type-indexer))
#;(define-struct <enum-set>
(make-enum-set type members)
enum-set?
(lambda (i p)
(format p "#<enum-set ~a>" (enum-set-members i)))
(type enum-set-type)
(members enum-set-members))
;; from mosh
(define (make-enumeration-type symbol-list)
(let ([ht (make-eq-hashtable)])
(let loop ([symbol-list symbol-list]
[i 0])
(if (null? symbol-list)
'()
(begin (hashtable-set! ht (car symbol-list) i)
(loop (cdr symbol-list) (+ i 1)))))
(make-enum-type symbol-list
(lambda (symbol)
(hashtable-ref ht symbol #f)))))
(define (make-enumeration symbol-list)
(cond
[(and (list? symbol-list) (for-all symbol? symbol-list))
(make-enum-set (make-enumeration-type symbol-list) symbol-list)]
[else
(assertion-violation 'make-enumeration "argument 1 must be a list of symbols")]))
(define (enum-set-universe enum-set)
(make-enum-set (enum-set-type enum-set)
(enum-type-universe (enum-set-type enum-set))))
(define (enum-set-indexer enum-set)
(enum-type-indexer (enum-set-type enum-set)))
(define (enum-set-constructor enum-set)
(lambda (symbol-list)
(let ([universe (enum-type-universe (enum-set-type enum-set))])
(if (for-all (lambda (x) (memq x universe)) symbol-list)
(make-enum-set (enum-set-type enum-set) symbol-list)
(assertion-violation 'enum-set-constructor "the symbol list must all belong to the universe." universe symbol-list)))))
(define (enum-set->list enum-set)
(let ([universe (enum-type-universe (enum-set-type enum-set))]
[members (enum-set-members enum-set)])
(let loop ([universe universe])
(cond
[(null? universe) '()]
[(memq (car universe) members)
(cons (car universe) (loop (cdr universe)))]
[else
(loop (cdr universe))]))))
(define (enum-set-member? symbol enum-set)
(and (memq symbol (enum-set-members enum-set)) #t))
(define (enum-set-subset? enum-set1 enum-set2)
(and
(let ([enum-set2-univese (enum-set->list (enum-set-universe enum-set2))])
(for-all
(lambda (symbol) (memq symbol enum-set2-univese))
(enum-set->list (enum-set-universe enum-set1))))
(for-all
(lambda (symbol) (enum-set-member? symbol enum-set2))
(enum-set-members enum-set1))))
(define (enum-set=? enum-set1 enum-set2)
(and (enum-set-subset? enum-set1 enum-set2)
(enum-set-subset? enum-set2 enum-set1)))
(define (enum-set-union enum-set1 enum-set2)
(define (union lst1 lst2)
(let loop ([ret lst1]
[lst lst2])
(cond
[(null? lst) ret]
[(memq (car lst) ret)
(loop ret (cdr lst))]
[else
(loop (cons (car lst) ret) (cdr lst))])))
(if (eq? (enum-set-type enum-set1) (enum-set-type enum-set2))
(make-enum-set (enum-set-type enum-set1)
(union (enum-set-members enum-set1) (enum-set-members enum-set2)))
(assertion-violation 'enum-set-union "enum-set1 and enum-set2 must be enumeration sets that have the same enumeration type.")))
(define (enum-set-intersection enum-set1 enum-set2)
(define (intersection lst1 lst2)
(let loop ([ret '()]
[lst lst1])
(if (null? lst)
ret
(cond
[(memq (car lst) lst2)
(loop (cons (car lst) ret) (cdr lst))]
[else
(loop ret (cdr lst))]))))
(if (eq? (enum-set-type enum-set1) (enum-set-type enum-set2))
(make-enum-set (enum-set-type enum-set1)
(intersection (enum-set-members enum-set1) (enum-set-members enum-set2)))
(assertion-violation 'enum-set-intersection "enum-set1 and enum-set2 must be enumeration sets that have the same enumeration type.")))
(define (enum-set-difference enum-set1 enum-set2)
(define (difference lst1 lst2)
(let loop ([ret '()]
[lst lst1])
(if (null? lst)
ret
(cond
[(memq (car lst) lst2)
(loop ret (cdr lst))]
[else
(loop (cons (car lst) ret) (cdr lst))]))))
(if (eq? (enum-set-type enum-set1) (enum-set-type enum-set2))
(make-enum-set (enum-set-type enum-set1)
(difference (enum-set-members enum-set1) (enum-set-members enum-set2)))
(assertion-violation 'enum-set-difference "enum-set1 and enum-set2 must be enumeration sets that have the same enumeration type.")))
(define (enum-set-complement enum-set)
(let ([members (enum-set-members enum-set)])
(make-enum-set (enum-set-type enum-set)
(filter (lambda (symbol) (not (memq symbol members))) (enum-type-universe (enum-set-type enum-set))))))
(define (enum-set-projection enum-set1 enum-set2)
(if (enum-set-subset? enum-set1 enum-set2)
enum-set1
(let ([universe2 (enum-type-universe (enum-set-type enum-set2))]
[members1 (enum-set-members enum-set1)])
(make-enum-set (enum-set-type enum-set2)
(filter (lambda (symbol) (memq symbol universe2)) members1)))))
) ; [end]
;; end of file
;; Local Variables:
;; coding: utf-8-unix
;; End:
| false |
2e448a3dda0701f088b16d0e55a2df6b666e28e6
|
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
|
/tests/yunife/fecore0.sps
|
14faaecfbdc90ff3a4cf0dd92224d79a8a038a07
|
[
"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 | 973 |
sps
|
fecore0.sps
|
;; FIXME: This test is not used for now
(import (yuni scheme)
(yunife core)
(yunitest mini))
(define cmd (member "ROOT" (command-line)))
(define root (cadr cmd))
(define fe (make-yunife))
(define (path! pth)
(yunife-add-path! fe (string-append root "/" pth)))
;; FIXME: Read config/config.scm ?
(yunife-add-alias-map! fe 'yuni 'yunife-yuni)
(yunife-add-alias-map! fe 'yunivm 'yunife-yunivm)
(for-each path!
(list
"lib"
"lib-compat"
"lib-r7c"
"lib-r6rs"
"external"))
(yunife-load-sexp-list! fe
'((import (yuni scheme)
(yunitest mini))
(define-syntax stx
(syntax-rules ()
((_ a b) (+ 1 a b))))
(display (stx 4 5))))
;(write (yunife-get-library-code fe #t)) (newline)
(check-finish)
| true |
cc7406d7d6fba2200dcdf121439978709efea34b
|
ea4e27735dd34917b1cf62dc6d8c887059dd95a9
|
/assignment.scm
|
a728ea1388dbdc28f7c9f7dc31390a6449c7bb80
|
[
"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 | 2,968 |
scm
|
assignment.scm
|
(define balance 100)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficiente funds"))
;(withdraw 25)
;(withdraw 25)
;(withdraw 60)
;(withdraw 15)
(define new-withdraw
(let ((balance 100))
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))))
;(new-withdraw 25)
;(new-withdraw 25)
;(new-withdraw 60)
;(new-withdraw 15)
(define (make-withdraw balance)
(lambda (amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds")))
;(define w1 (make-withdraw 100))
;(define w2 (make-withdraw 100))
;(w1 50)
;(w2 70)
;(w2 40)
;(w1 40)
(define (make-account balance)
(define (withdraw amount)
(if (>= balance amount)
(begin (set! balance (- balance amount))
balance)
"Insufficient funds"))
(define (deposit amount)
(set! balance (+ balance amount))
balance)
(define (dispatch m)
(cond ((eq? m 'withdraw) withdraw)
((eq? m 'deposit) deposit)
(else (error "Unknown request -- MAKE-ACCOUN"
m))))
dispatch)
;(define acc (make-account 100))
;((acc 'withdraw) 50)
;((acc 'withdraw) 60)
;((acc 'deposit) 40)
;((acc 'withdraw) 60)
(define random-init 13061981)
; From K&R - The C Programming Language
(define rand-update
(lambda (x)
(modulo (quotient (+ (* 1103515245 x)
12345)
65536)
32768)))
(define rand
(let ((x random-init))
(lambda ()
(set! x (rand-update x))
x)))
;(rand)
;(rand)
;(rand)
;(rand)
;(rand)
;(rand)
;(rand)
;(rand)
; Using assignment
(define (estimate-pi trials)
(sqrt (/ 6 (monte-carlo trials cesaro-test))))
(define (cesaro-test)
(= (gcd (rand) (rand)) 1))
(define (monte-carlo trials experiment)
(define (iter trials-remaining trials-passed)
(cond ((= trials-remaining 0)
(/ trials-passed trials))
((experiment)
(iter (- trials-remaining 1) (+ trials-passed 1)))
(else
(iter (- trials-remaining 1) trials-passed))))
(iter trials 0))
(estimate-pi 100)
; Without assignment (stateless)
; Need to keep track of random-update, losing modularity
(define (estimate-pi2 trials)
(sqrt (/ 6 (random-gcd-test trials cesaro-test random-init))))
(define (random-gcd-test trials experiment initial-x)
(define (iter trials-remaining trials-passed x)
(let ((x1 (rand-update x)))
(let ((x2 (rand-update x1)))
(cond ((= trials-remaining 0)
(/ trials-passed trials))
((= (gcd x1 x2) 1)
(iter (- trials-remaining 1) (+ trials-passed 1) x2))
(else
(iter (- trials-remaining 1) trials-passed x2))))))
(iter trials 0 initial-x))
(estimate-pi2 100)
| false |
ce64a26fc6efd5d8dc8ec47f837339ebd6634fbe
|
0011048749c119b688ec878ec47dad7cd8dd00ec
|
/src/spoilers/200/solution.scm
|
4fe27d35f76ac0c5de80afedbd672c8d57cafa10
|
[
"0BSD"
] |
permissive
|
turquoise-hexagon/euler
|
e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5
|
852ae494770d1c70cd2621d51d6f1b8bd249413c
|
refs/heads/master
| 2023-08-08T21:01:01.408876 | 2023-07-28T21:30:54 | 2023-07-28T21:30:54 | 240,263,031 | 8 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,881 |
scm
|
solution.scm
|
(import
(chicken fixnum)
(chicken sort)
(euler)
(srfi 1))
(define-constant limit #e2e5)
(define (subprime-proof? head tail digit order)
(let loop ((replacement 0))
(if (fx= replacement 10)
#t
(if (fx= replacement digit)
(loop (fx+ replacement 1))
(let ((_ (fx+? (fx+? head tail) (fx*? replacement order))))
(if (and _ (prime? _))
#f
(loop (fx+ replacement 1))))))))
(define (prime-proof? n)
(let loop ((i n) (order 1) (tail 0))
(if (fx= i 0)
#t
(let* ((digit (fxmod i 10)) (next (fx* order 10)) (head (fx* (fx/ n next) next)))
(if (subprime-proof? head tail digit order)
(loop (fx/ i 10) next (fx+ tail (fx* digit order)))
#f)))))
(define (submatch? a b)
(let loop ((a a) (b b))
(if (fx= b 0)
#t
(if (fx= (fxmod a 10)
(fxmod b 10))
(loop (fx/ a 10)
(fx/ b 10))
#f))))
(define (match? a b)
(let loop ((a a))
(if (fx> b a)
#f
(if (submatch? a b)
#t
(loop (fx/ a 10))))))
(define (combine a b)
(let loop ((a a) (b (cdr b)) (acc '()))
(if (null? b)
acc
(let subloop ((c b) (acc acc))
(if (null? c)
(loop (cdr a) (cdr b) acc)
(let ((_ (fx*? (car a) (car c))))
(if _
(subloop (cdr c) (cons _ acc))
acc)))))))
(define (solve index pattern)
(let* ((primes (primes limit))
(a (map (lambda (i) (fx* i i)) primes))
(b (map (lambda (i) (fx* i (fx* i i))) primes)))
(list-ref
(sort
(filter
(lambda (i)
(and (match? i pattern) (prime-proof? i)))
(append
(combine a b)
(combine b a)))
fx<)
(fx- index 1))))
(let ((_ (solve 200 200)))
(print _) (assert (= _ 229161792008)))
| false |
fe90026ce7faaecc3bb6c1c6498012114061933b
|
a189a23c6841ac05c4f729484bea5f33abe238ab
|
/in-class/13-number-cons.scm
|
26215585ddda64ec7df9e9729ecb68dc0ab63d9a
|
[] |
no_license
|
langmartin/hackrec
|
5129ede644b3eedd76f54350d9df87c241c1c0db
|
7ba3dd05bc54c42a9e3bdb6e86745c7b9f96a610
|
refs/heads/master
| 2020-05-21T13:10:03.274157 | 2012-04-05T15:14:38 | 2012-04-05T15:14:38 | 2,925,866 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 424 |
scm
|
13-number-cons.scm
|
;; Exercise 2.5
(define (cons a b)
(* (expt 2 a) (expt 3 b)))
(define z (cons 2 3))
(define (gcp n part)
(define (iter power)
(if (not (= 0 (remainder n (expt part power))))
(- power 1)
(iter (+ power 1))))
(iter 1))
(define (car cell)
(gcp cell 2))
(define (cdr cell)
(gcp cell 3))
(car (cons 16 7))
(cdr (cons 16 7))
;; Exercise 2.6
;; Church Numerals. See ../student/lang/church.scm
| false |
98b700c821212917274a443dcdcd11b4304bc3ee
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec4/q4.11-test.scm
|
e6ba95a0ad72cdaa025b21adb7aefc5a422aaa64
|
[] |
no_license
|
thash/sicp
|
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
|
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
|
refs/heads/master
| 2021-05-28T16:29:26.617617 | 2014-09-15T21:19:23 | 2014-09-15T21:19:23 | 3,238,591 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 329 |
scm
|
q4.11-test.scm
|
(load "./my_defs")
(prepare-test)
(define vars '(a b c))
(define vals '(1 2 3))
(eqr (make-frame vars vals) => '((a . 1) (b . 2) (c . 3)))
(define f (make-frame vars vals))
(eqr (frame-variables f) => '(a b c))
(eqr (frame-values f) => '(1 2 3))
(eqr (add-binding-to-frame! 'd 4 f) => '((a . 1) (b . 2) (c . 3) (d . 4)))
| false |
7fffd4fea3652f5a72ce881fcea09ad36c62c542
|
928e706795455cddbacba32cf039aa04e1576963
|
/compiler/src/p00_string2tokens.sld
|
7a3f1ebd60d984d521bca14864b3f3566c2cffd0
|
[
"MIT"
] |
permissive
|
zaoqi-clone/loki
|
a26931aa773df35601099e59695a145a8cacf66c
|
a0edd3933a1d845d712b977a47504c8751a6201f
|
refs/heads/master
| 2020-07-01T21:52:28.446404 | 2019-08-08T02:31:46 | 2019-08-08T02:31:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 17,346 |
sld
|
p00_string2tokens.sld
|
; string2tokens
; this pass converts a stream of characters (via an input port) into a list of scheme tokens.
; if the stream of characters is not a valid list of scheme tokens an error will be raised
; each token stores the original string from the input, the representative scheme value,
; and the original location in the source file
; TODO: implement string escapes and multi-line strings
(define-library
(p00_string2tokens)
(import (scheme base))
(import (scheme char))
(import (scheme complex))
(import (scheme write))
(import (srfi 115))
(import (srfi 159))
(import (util))
(import (shared))
(export p00_string2tokens)
(begin
(define *whitespace* '(#\tab #\return #\newline #\space))
(define (whitespace? c) (member c *whitespace*))
(define *left-paren* (car (string->list "(")))
(define *right-paren* (car (string->list ")")))
(define (left-paren? c) (equal? c *left-paren*))
(define (right-paren? c) (equal? c *right-paren*))
(define *left-vector* "#(")
(define *left-bytevector* "#u8(")
(define (left-vector? s) (equal? s *left-vector*))
(define (left-bytevector? s) (equal? s *left-bytevector*))
(define (newline? c) (equal? c #\newline))
(define (return? c) (equal? c #\return))
(define (semicolon? c) (equal? c #\;))
(define (doublequote? c) (equal? c #\"))
(define (hash? c) (equal? c #\#))
(define (quote? c) (equal? c #\'))
(define (quasiquote? c) (equal? c #\`))
(define (unquote? c) (equal? c #\,))
(define (unquote-splicing? s) (equal? s ",@"))
(define (dot? c) (equal? c #\.))
(define (vertical? c) (equal? c #\|))
(define (delimiter? c)
(or
(eof-object? c)
(left-paren? c)
(right-paren? c)
(whitespace? c)
(doublequote? c)
(semicolon? c)))
(define *char-literal-regexp* (rx (: bos #\# #\\ any eos)))
(define *char-name-regexp* (rx (: bos #\# #\\
(or "alarm" "backspace" "delete" "escape" "newline" "null" "return" "space" "tab") eos)))
(define *char-scalar-regexp* (rx (: bos #\# #\\ #\x (+ hex-digit) eos)))
(define (char-literal? str) (regexp-search *char-literal-regexp* str))
(define (char-name? str) (regexp-search *char-name-regexp* str))
(define (char-scalar? str) (regexp-search *char-scalar-regexp* str))
(define (char-literal->char str)
(car (string->list (string-copy str 2 3))))
(define (char-name->char str)
(cond
((equal? str "#\\alarm") #\alarm)
((equal? str "#\\backspace") #\backspace)
((equal? str "#\\delete") #\delete)
((equal? str "#\\escape") #\escape)
((equal? str "#\\newline") #\newline)
((equal? str "#\\null") #\null)
((equal? str "#\\return") #\return)
((equal? str "#\\space") #\space)
((equal? str "#\\tab") #\tab)
(else (raise "unknown character name"))))
(define (char-scalar->char str)
(let ((scalar (string-copy str 3 (string-length str))))
(integer->char (real-string->number scalar 16 #t))))
(define *num-infnan-sre* '(or "+inf.0" "-inf.0" "+nan.0" "-nan.0"))
(define *num-sign-sre* '(or #\+ #\-))
(define *num-exactness-sre* '(? (or "#i" "#e")))
(define *num-radix-02-sre* "#b")
(define *num-radix-08-sre* "#o")
(define *num-radix-10-sre* '(? "#d"))
(define *num-radix-16-sre* "#x")
(define *num-digit-02-sre* '(or #\0 #\1))
(define *num-digit-08-sre* '(or #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7))
(define *num-digit-10-sre* 'num)
(define *num-digit-16-sre* 'hex-digit)
(define (define-num-sre digit-sre radix-sre)
(define num-uinteger-sre `(+ ,digit-sre))
(define num-ureal-sre
`(or
,num-uinteger-sre
(: ,num-uinteger-sre #\/ ,num-uinteger-sre)))
(define num-real-sre
`(or
(: (? ,*num-sign-sre*) ,num-ureal-sre)
,*num-infnan-sre*))
(define num-complex-sre
`(or
(-> real ,num-real-sre)
(: (-> real ,num-real-sre) (-> imag (: ,*num-sign-sre* (? ,num-ureal-sre))) #\i)
(: (-> real ,num-real-sre) (-> imag ,*num-infnan-sre*) #\i)
(: (-> x ,num-real-sre) #\@ (-> y ,num-real-sre))
(: (-> imag ,*num-sign-sre* ,num-ureal-sre) #\i)
(: (-> imag ,*num-infnan-sre*) #\i)
(: (-> imag ,*num-sign-sre*) #\i)))
(define num-prefix-sre
`(or
(: (-> radix ,radix-sre) (-> exact ,*num-exactness-sre*))
(: (-> exact ,*num-exactness-sre*) (-> radix ,radix-sre))))
`(: ,num-prefix-sre ,num-complex-sre))
(define *num-02-sre* (define-num-sre *num-digit-02-sre* *num-radix-02-sre*))
(define *num-08-sre* (define-num-sre *num-digit-08-sre* *num-radix-08-sre*))
(define *num-10-sre* (define-num-sre *num-digit-10-sre* *num-radix-10-sre*))
(define *num-16-sre* (define-num-sre *num-digit-16-sre* *num-radix-16-sre*))
(define *num-02-regexp* (regexp *num-02-sre*))
(define *num-08-regexp* (regexp *num-08-sre*))
(define *num-10-regexp* (regexp *num-10-sre*))
(define *num-16-regexp* (regexp *num-16-sre*))
(define *num-regexp* (regexp
`(or
,*num-10-sre*
,*num-02-sre*
,*num-08-sre*
,*num-16-sre*
)))
(define (parse-num str)
(or
(regexp-matches *num-10-regexp* str)
(regexp-matches *num-16-regexp* str)
(regexp-matches *num-02-regexp* str)
(regexp-matches *num-08-regexp* str)))
(define (char-hex-letter? char)
(let ((int (char->integer char)))
(or
(and (>= int 65) (<= int 70))
(and (>= int 97) (<= int 102)))))
(define (char-hex-letter->number char)
(let ((int (char->integer char)))
(+ (if (and (>= int 65) (<= int 70))
(- int 65)
(- int 97)) 10)))
(define (radix->base radix)
(cond
((equal? radix "#b") 2)
((equal? radix "#o") 8)
((equal? radix "#d") 10)
((equal? radix "") 10)
((equal? radix "#x") 16)
(else (raise "unknown radix"))))
(define (real-string->number str base is-exact)
(if str
(cond
((equal? str "+inf.0") +inf.0)
((equal? str "-inf.0") -inf.0)
((equal? str "+nan.0") +nan.0)
((equal? str "-nan.0") -nan.0)
(else
(let* ((chars (string->list str))
(sign 1)
(num (fold-left (lambda (char num)
(cond
((char-numeric? char) (+ (* num base) (digit-value char)))
((char-hex-letter? char) (+ (* num base) (char-hex-letter->number char)))
((equal? char #\-) (set! sign -1) num)
((equal? char #\+) num)
((equal? char #\/) (raise "rational literals unimplemented"))
(else (raise "unhandled character in real number string")))) 0 chars)))
(* sign (if is-exact (exact num) (inexact num))))))
0))
(define (imag-string->number str base is-exact)
(cond
((equal? str "-") (if is-exact (exact -1) (inexact -1)))
((equal? str "+") (if is-exact (exact 1) (inexact 1)))
((equal? str "") (if is-exact (exact 1) (inexact 1)))
(else (real-string->number str base is-exact))))
(define (lexed-num->num str matches)
(let* ((real (regexp-match-submatch matches 'real))
(imag (regexp-match-submatch matches 'imag))
(x (regexp-match-submatch matches 'x))
(y (regexp-match-submatch matches 'y))
(radix (regexp-match-submatch matches 'radix))
(exactness (regexp-match-submatch matches 'exact))
(exact (if (equal? exactness "#i") #f #t))
(base (radix->base radix))
(realnum (real-string->number real base exact))
(imagnum (imag-string->number imag base exact))
(xnum (real-string->number x base exact))
(ynum (imag-string->number y base exact)))
(if (or x y)
(make-polar xnum ynum)
(make-rectangular realnum imagnum))))
(define *initial-id-sre* '(or alpha #\! #\$ #\% #\& #\* #\/ #\: #\< #\=
#\> #\? #\^ #\_ #\~))
(define *explicit-sign-sre* '(or #\+ #\-))
(define *special-subsequent-sre* `(or ,*explicit-sign-sre* #\. #\@))
(define *subsequent-id-sre* `(or ,*initial-id-sre* num ,*special-subsequent-sre*))
(define *sign-subsequent-id-sre* `(or ,*initial-id-sre* ,*explicit-sign-sre* #\@))
(define *dot-subsequent-id-sre* `(or ,*sign-subsequent-id-sre* #\.))
(define *symbol-element-id-sre*
'(or
(difference any ("|\\"))
(: #\\ #\x (+ hex-digit))
(or "\\a" "\\b" "\\t" "\\n" "\\r")
"\\|"))
(define *id-sre* `(: bos (or
(-> id (: ,*initial-id-sre* (* ,*subsequent-id-sre*)))
(: #\| (-> id (* ,*symbol-element-id-sre*)) #\|)
(-> id ,*explicit-sign-sre*)
(-> id (: ,*explicit-sign-sre* ,*sign-subsequent-id-sre* (* ,*subsequent-id-sre*)))
(-> id (: ,*explicit-sign-sre* #\. ,*dot-subsequent-id-sre* (* ,*subsequent-id-sre*)))
(-> id (: #\. ,*dot-subsequent-id-sre* (* ,*subsequent-id-sre*))) eos)))
(define *id-regexp* (regexp *id-sre*))
(define (parse-id string) (regexp-matches *id-regexp* string))
(define (lexed-id->symbol matches) (regexp-match-submatch matches 'id))
(define-record-type <tchar>
(make-tchar char location)
tchar?
(char tchar->char)
(location tchar->location))
(define (tchar->token tchar type value)
(make-token
(list->string (list (tchar->char tchar)))
type
value
(tchar->location tchar)))
(define (tchars->string tchars) (list->string (map tchar->char tchars)))
(define (tchars->token tchars type value)
(let ((chars (map tchar->char tchars)))
(make-token
(list->string chars)
type
value
(tchar->location (car tchars)))))
(define-record-type <reader>
(make-reader port saves line col offset)
reader?
(port reader->port)
(saves reader->saves set-reader-saves)
(line reader->line set-reader-line)
(col reader->col set-reader-col)
(offset reader->offset set-reader-offset))
(define (port->reader port)
(make-reader port '() 1 1 0))
(define (read-reader reader)
(let ((port (reader->port reader))
(saves (reader->saves reader))
(line (reader->line reader))
(col (reader->col reader))
(offset (reader->offset reader)))
(if (null? saves)
(let* ((char (read-char port))
(next (peek-char port))
(tchar (make-tchar char (make-source-location line col offset))))
(if (return? char)
(if (newline? next)
(begin
; will be crlf, but currently on cr, only increment col
(set-reader-col reader (+ col 1))
(set-reader-offset reader (+ offset 1))
tchar)
(begin
; only cr, increment as cr line ending
(set-reader-line reader (+ line 1))
(set-reader-col reader 1)
(set-reader-offset reader (+ offset 1))
tchar))
(if (newline? char)
(begin
; only lf, increment as lf line ending
(set-reader-line reader (+ line 1))
(set-reader-col reader 1)
(set-reader-offset reader (+ offset 1))
tchar)
(begin
; no line endings
(set-reader-col reader (+ col 1))
(set-reader-offset reader (+ offset 1))
tchar))))
(let ((save (car saves)))
(set-reader-saves reader (cdr saves))
save))))
(define (peek-reader reader)
(let ((tchar (read-reader reader)))
(roll-back-reader reader tchar)
tchar))
(define (roll-back-reader reader tchar)
(set-reader-saves reader (cons tchar (reader->saves reader))))
(define (add-token token tokens) (cons token tokens))
(define (p00_string2tokens port)
(let* ((raw-reader (port->reader port))
(tokens '())
(buffer '())
(should-roll-back #f))
(define (emit-tchar tchar type value)
(set! tokens (cons (tchar->token tchar type value) tokens)))
(define (emit-buffer type value)
(set! tokens (cons (tchars->token (reverse buffer) type value) tokens))
(set! buffer '()))
(define (push-buffer tchar)
(set! buffer (cons tchar buffer)))
(define (reader) (read-reader raw-reader))
(define (peek) (peek-reader raw-reader))
(define (roll-back tchar)
(roll-back-reader raw-reader tchar))
(define (buffer->string)
(tchars->string (reverse buffer)))
(define (error-with-value msg value)
(error (string-append
"error! "
msg
": "
value)))
(define (lex-ready)
(let* ((tchar (reader)) (char (tchar->char tchar)))
(cond
((eof-object? char) #f)
((whitespace? char) (lex-ready))
((dot? char) (emit-tchar tchar 'dot #f) (lex-ready))
((quote? char) (emit-tchar tchar 'quote #f) (lex-ready))
((quasiquote? char) (emit-tchar tchar 'quasiquote #f) (lex-ready))
((unquote? char)
(let* ((next (peek)) (next-char (tchar->char next)))
(if (equal? next-char #\@)
(begin
(push-buffer tchar)
(push-buffer (reader))
(emit-buffer 'unquote-splicing #f))
(emit-tchar tchar 'unquote #f))
(lex-ready)))
((doublequote? char)
(push-buffer tchar)
(lex-string))
((left-paren? char)
(emit-tchar tchar 'lparen #f)
(lex-ready))
((right-paren? char)
(emit-tchar tchar 'rparen #f)
(lex-ready))
(else
(push-buffer tchar)
(lex-reading)))))
(define (lex-reading)
(let* ((tchar (reader)) (char (tchar->char tchar)))
(if (delimiter? char)
(let* ((string (buffer->string)))
(cond
((and (left-paren? char) (equal? string "#"))
(push-buffer tchar)
(emit-buffer 'lvector #f))
((and (left-paren? char) (equal? string "#u8"))
(push-buffer tchar)
(emit-buffer 'lbytevector #f))
(else
(roll-back tchar)
(cond
((equal? string "#t") (emit-buffer 'boolean #t))
((equal? string "#true") (emit-buffer 'boolean #t))
((equal? string "#f") (emit-buffer 'boolean #f))
((equal? string "#false") (emit-buffer 'boolean #f))
((parse-num string) => (lambda (matches) (emit-buffer 'number (lexed-num->num string matches))))
((parse-id string) => (lambda (matches) (emit-buffer 'id (string->symbol (lexed-id->symbol matches)))))
((char-literal? string) (emit-buffer 'char (char-literal->char string)))
((char-name? string) (emit-buffer 'char (char-name->char string)))
((char-scalar? string) (emit-buffer 'char (char-scalar->char string)))
(else (error-with-value "unknown value" string)))))
(lex-ready))
(begin
(push-buffer tchar)
(lex-reading)))))
; escapes need to be re-handled
; as well as multi line strings with \
(define (lex-string)
(let* ((tchar (reader)) (char (tchar->char tchar)))
(cond
((eof-object? char) (error "unterminated string!!!"))
((doublequote? char)
(push-buffer tchar)
(let ((str (buffer->string)))
(emit-buffer 'string (string-copy str 1 (- (string-length str) 1)))
(lex-ready)))
(else
(push-buffer tchar)
(lex-string)))))
(lex-ready)
(reverse tokens)))
))
| false |
ecc7021c1515d62152409dda8c35df648bbc7d97
|
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
|
/scheme/swl1.3/apps/edit/edit.ss
|
0b7e0be1bdcc8b3fe846e86ea43429e8b39fc45e
|
[
"SWL",
"TCL"
] |
permissive
|
ktosiu/snippets
|
79c58416117fa646ae06a8fd590193c9dd89f414
|
08e0655361695ed90e1b901d75f184c52bb72f35
|
refs/heads/master
| 2021-01-17T08:13:34.067768 | 2016-01-29T15:42:14 | 2016-01-29T15:42:14 | 53,054,819 | 1 | 0 | null | 2016-03-03T14:06:53 | 2016-03-03T14:06:53 | null |
UTF-8
|
Scheme
| false | false | 28,651 |
ss
|
edit.ss
|
;;
;; Copyright (c) 1996-1998 John Zuckerman
;;
;; See the file "Notice" for information on usage and redistribution
;; of this file, and for a DISCLAIMER OF ALL WARRANTIES.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;
(require "../common/app.ss")
(require "../common/scrollframe.ss")
(require "../common/auxio.ss")
(require "edit-text.ss")
; new-repl should probably change editor's value of the repl key. But to
; do that correctly we need to wrap the begin-application in a
; thread-fork-group. But to do that, we need do change to logic for
; returning (via continuation) to the caller of new-repl.
; when/if we get modules set up for this file, abstract the port-opening code
; and make backup filename a preference
(define-swl-class (<edit-toplevel> iop filename notify-q app-token) (<app-toplevel>)
(ivars
(current-filename filename)
(file-port iop)
(backup? (and filename #t))
)
(inherited mini-buffer mini-search)
(inheritable mini-buffer mini-search)
(private
[set-current-filename! (name)
(set! current-filename name)
(set-title! self (if name (format "Editing ~s" name) "Editor"))]
[delegate (who handler)
(let ([txt (send self get-text-widget)])
(if txt (handler txt) (assertion-violationf who "no text widget installed")))])
(protected)
(public
[get-filename () current-filename]
[register-request (request)
(delegate 'register-request
(lambda (x) (send x register-request request)))]
[unregister-request (request)
(delegate 'unregister-request
(lambda (x) (send x unregister-request request)))]
[set-locked! (locked?)
(delegate 'set-locked!
(lambda (x) (send x set-enabled! (not locked?))))]
[get-buffer-content ()
(delegate 'get-buffer-content
(lambda (x) (send x get-string '(0 . 0) 'end)))]
[show-sexpression-at (pos bfp efp)
(delegate 'show-sexpression-at
(lambda (x) (send x show-sexpression-at pos bfp efp)))]
[show-explanation (str)
(delegate 'show-explanation
(lambda (x) (send x display-mini str)))]
[init (iop filename notify-q app-token)
(send-base self init)
(send self load-prefs 'edit)
(set-current-filename! filename)
(let () ;;; needed for defns
(define-syntax simple-menu-item
(syntax-rules ()
((_ (str1 str2) act (argname argval) ...)
(create <command-menu-item> with
(title: (cons str1 str2))
(action: act)
(argname argval) ...
))))
(define block-copy
(lambda (ip consumer)
(define bufsize 8192)
(let ([buf (make-string bufsize)])
(let loop ()
(let ([n (block-read ip buf bufsize)])
(unless (eof-object? n)
(consumer (if (< n bufsize) (substring buf 0 n) buf))
(loop)))))))
;;
;; widget bindings
;;
(let* ((scrolled-frame
(create <scrollframe> self with
(default-vscroll: #t)
(sticky-hscroll: #t)
))
(edit-wgt
(create <edit-text> scrolled-frame with
(background-color: 'white)
(foreground-color: 'black)
(wrap: 'none)
))
) ;;; widget bindings
(define open-new-file
(lambda (filename)
(on-error (with-message msg
(warning-dialog self
(format "Unable to open ~s.\n\n~a" filename msg)))
(let ([iop (on-error
(let ([p (open-input-file filename)])
(warning-dialog self
(format "Unable to open ~a for writing.\n\nYou can edit this file but must save it under a different filename." filename))
p)
(open-input-output-file filename))])
(set! file-port iop)
(set-current-filename! filename)
(load-the-file)))))
(define load-the-file
(lambda ()
(when (input-port? file-port)
(let ([end (send edit-wgt get-end-mk)])
(block-copy file-port
(lambda (string)
(send edit-wgt raw-insert-at end string))))
(send edit-wgt set-cursor-pos! '(0 . 0)))))
(define save-to-file
(lambda (filename iop backup?)
; get buffer content before trashing any files in case of error
(let ([buf (send edit-wgt get-string '(0 . 0) 'end)])
; write backup file
; might want an override dialog to allow save to continue
; even if backup fails
(when (and backup? (> (file-length iop) 0))
(file-position iop 0)
(let ([backup-filename (string-append filename ".backup")])
(let ([backup-port
(on-error
(assertion-violationf #f "cannot open backup file ~a for writing" backup-filename)
(open-output-file backup-filename 'truncate))])
(block-copy iop
(lambda (s)
(block-write backup-port s (string-length s))))
(close-output-port backup-port))))
; write buffer contents, buf contains 1 extra char at end
(truncate-file iop)
(block-write iop buf (- (string-length buf) 1))
(flush-output-port iop)
; clear buffer modified flag
(send edit-wgt set-buffer-to-safe!))))
(define save-the-file
(lambda ()
(on-error (with-message msg (warning-dialog self (format "Unable to save the file.\n\n~a" msg)))
(save-to-file current-filename file-port backup?)
; at most one backup per file
(set! backup? #f))))
(define save-as-file
(lambda ()
(let ([filename (swl:file-dialog "Save file as" 'save
(file-types: '(("Scheme source" ("*.ss"))
("All files" ("*"))))
(parent: self)
(default-dir: (current-directory)))])
(when filename
(on-error (with-message msg
(warning-dialog self
(format "Unable to save as ~s.\n\n~a" filename msg)))
(let ([iop (open-input-output-file filename)])
; wait to install until we're sure there were no errors saving
(on-error (with-message msg (warning-dialog self (format "Unable to save to ~a.\n\n~a" filename msg)))
(save-to-file filename iop #t)
; at most one backup per file
(set! backup? #f)
(when (port? file-port) (close-port file-port))
(set! file-port iop)
(set-current-filename! filename))))))))
(send edit-wgt set-font!
(send self get-pref 'base-font (create <font> 'courier 12 '())))
(send self notify-text edit-wgt)
(send self set-destroy-request-handler!
(let ([posted? #f])
(lambda (self)
(and (not posted?)
(or (not (send edit-wgt buffer-modified?))
(fluid-let ([posted? #t])
; make sure the <toplevel> window is visible
; and on top so we know which editor we're
; about to blow away.
(send self show)
(send self raise)
(swl:sync-display)
(let ([ans
(warning-dialog self
(format
"\n The ~a is not saved to disk.\n Do you really want to discard your changes?\n"
(if current-filename
(format "file ~s" current-filename)
"edit buffer"))
'(|discard changes| |keep editing|))])
(eq? ans '|discard changes|))))
(not (send edit-wgt reserved? '|close anyway|))
(begin
(when file-port (close-port file-port))
(swl:remove-editor self)
(swl:end-application app-token)
#t)))))
;;
;; action & menu-item bindings
;;
(letrec
((buffer-modified-menu-item (create <command-menu-item>))
(new-action (lambda (item) (new-edit)))
(open-action
(lambda (item)
(let ([filename
(swl:file-dialog "Select a file to edit" 'open
(file-types: '(("Scheme source" ("*.ss"))
("All files" ("*"))))
(parent: self))])
(when filename
; if already editing a file, open in a new window
(if (or current-filename (send edit-wgt buffer-modified?))
(new-edit filename)
(open-new-file filename))))))
(insert-file-action
(lambda (item)
(let ([filename
(swl:file-dialog "Insert file" 'open
(file-types: '(("Scheme source" ("*.ss"))
("All files" ("*"))))
(parent: self))])
(when filename
(on-error
(with-message msg
(warning-dialog self
(format "Unable to insert ~a.\n\n~a" filename msg)))
(let ([ip (open-input-file filename)]
[pos (send edit-wgt get-cursor-pos)]
[op (open-output-string)])
(block-copy ip
(lambda (s)
(block-write op s (string-length s))))
; use plain insert-at to record in undo history
(send edit-wgt insert-at pos (get-output-string op))
(send edit-wgt set-cursor-pos! pos)
(send edit-wgt set-buffer-to-modified!)))))))
(directory-action
(lambda (item)
(let ([dirname (swl:tcl-eval '|tk_chooseDirectory|
'-parent self
'-mustexist #t)])
(unless (equal? dirname "")
(let ([key (swl:repl-key)])
(let ([repl (swl:lookup-repl key)])
(if repl
(send repl insert-expression
(format "(cd ~s)\n" dirname))
(on-error (with-message msg (warning-dialog self (format "Unable to change directory to ~a.\n\n~a" dirname msg)))
(cd dirname)))))))))
(save-action
(lambda (item)
(if (and current-filename (output-port? file-port))
(save-the-file)
(save-as-file))))
(save-as-action
(lambda (item)
(save-as-file)))
(new-menu-item
(simple-menu-item ("_New file" "Alt+n")
(lambda (item) (new-action item))))
(open-menu-item
(simple-menu-item ("_Open file..." "Alt+o")
(lambda (item) (open-action item))))
(insert-file-menu-item
(simple-menu-item ("_Insert file..." "Alt+i")
(lambda (item) (insert-file-action item))))
(directory-menu-item
(simple-menu-item ("Change _Directory..." "Alt+d")
(lambda (item) (directory-action item))))
(save-menu-item
(simple-menu-item ("_Save" "Alt+s")
(lambda (item) (save-action item))))
(save-as-menu-item
(simple-menu-item ("Save _as..." "Alt+a")
(lambda (item) (save-as-action item))))
(quit-menu-item
(simple-menu-item ("_Close" "Alt+q")
(lambda (item) (send self destroy))))
(execute-menu-item
(simple-menu-item ("(Save and) _Load" "Alt+g")
(let ([doit
(lambda (repl)
(send repl insert-expression
(format "(load ~s)\n" current-filename)))])
(lambda (item)
(critical-section
(if current-filename
(when (send edit-wgt buffer-modified?)
(if (output-port? file-port)
(save-the-file)
(save-as-file)))
(save-as-file))
; proceed only if save was successful
(when (and current-filename (not (send edit-wgt buffer-modified?)))
(let ([key (swl:repl-key)])
(let ([repl (swl:lookup-repl key)])
(if repl
(doit repl)
(new-repl key doit void))))))))))
(undo-menu-item
(simple-menu-item ("_Undo" "Ctrl+z")
(lambda (item) (send edit-wgt undo))))
(redo-menu-item
(simple-menu-item ("_Redo" "Alt+z")
(lambda (item) (send edit-wgt redo))))
(copy-menu-item
(simple-menu-item ("_Copy" "Alt+c")
(lambda (item) (send edit-wgt action-copy))))
(cut-menu-item
(simple-menu-item ("Cu_t" "Alt+x")
(lambda (item) (send edit-wgt action-cut))))
(paste-menu-item
(simple-menu-item ("_Paste" "Alt+v")
(lambda (item) (send edit-wgt action-paste))))
(search-forward-menu-item
(simple-menu-item ("Search _Forward" "Ctrl+s")
(lambda (item) (send edit-wgt search-forward))))
(search-backward-menu-item
(simple-menu-item ("Search _Backward" "Ctrl+r")
(lambda (item) (send edit-wgt search-backward))))
) ;;; action & menu-item bindings
;;
;; menu bindings
;;
(let*
((menu-file
(create <cascade-menu-item> with
(title: "_File")
(menu:
(create <menu>
(list (simple-menu-item ("New _repl" "")
(lambda (item) (new-repl)))
new-menu-item
open-menu-item
insert-file-menu-item
execute-menu-item
save-menu-item
save-as-menu-item
directory-menu-item
quit-menu-item
(simple-menu-item ("E_xit SWL" "")
(lambda (item)
(swl:end-application 'exit-all))))))))
(menu-edit
(create <cascade-menu-item> with
(title: "_Edit")
(menu:
(create <menu>
(list
undo-menu-item
redo-menu-item
copy-menu-item
cut-menu-item
paste-menu-item
(simple-menu-item ("_Go to line..." "Ctrl+g")
(lambda (item)
(send edit-wgt ask-goto-line)))
(simple-menu-item ("Forward S-expression" "Ctrl+0")
(lambda (item)
(send edit-wgt move-to-match 'forward)))
(simple-menu-item ("Backward S-expression" "Ctrl+9")
(lambda (item)
(send edit-wgt move-to-match 'backward)))
(simple-menu-item ("Select S-expression Forward" "Ctrl+)")
(lambda (item)
(send edit-wgt select-to-match 'forward)))
(simple-menu-item ("Select S-expression Backward" "Ctrl+(")
(lambda (item)
(send edit-wgt select-to-match 'backward)))
(simple-menu-item ("Select All" "")
(lambda (item)
(send edit-wgt select-range '(0 . 0) 'end)))
search-forward-menu-item
search-backward-menu-item)))))
(menu-preferences
(create <cascade-menu-item> with
(title: "_Preferences")
(menu:
(make-menu
("_Font..."
(lambda (item)
(swl:font-dialog self "Select a font for editor text"
(swl:font-families 'fixed)
#;
'(-8 -10 -12 -14 -16 -18 -20 -22 -24
8 10 12 14 16 18 20 22 24)
'(6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 22 24 26 32)
'(bold normal)
(lambda () (send edit-wgt get-font))
(lambda (fnt)
(when fnt
(send edit-wgt set-font! fnt)
(send self set-pref! 'base-font fnt))))))
("_Toggles"
(create <menu>
(list (create <check-menu-item> with
(title: "The _Box")
(enabled: #f) ; existing box implement breaks UNDO/REDO
(prefs-key: 'use-the-box)
(action:
(lambda (item)
(send edit-wgt show-the-box (send item get-selected)))))
(create <check-menu-item> with
(title: "_Auto-indent")
(selected: (send edit-wgt get-auto-indent))
(prefs-key: 'auto-indent)
(action:
(lambda (item)
(send edit-wgt set-auto-indent!
(send item get-selected)))))
)))
("_Save preferences"
(lambda (ignore)
(send self save-prefs! 'edit)))))))
; Due to bug in Tk 8.0.4 on Unix, command-menu-items are never invoked
; if drawn in a menubar (ie. as menu: option of a <toplevel>).
; I have a patch to tk8.0.4/library/menu.tcl that fixes this, but instead
; plan to make Help a cascade.
; (create <command-menu-item> with
; (title: "Help")
; (action:
; (lambda (item)
; (let ([root (getenv "SWL_ROOT")])
; (if (not root)
; (warning-dialog self "Can't locate documentation. (SWL_ROOT environment variable not set)" 'oops)
; (swl:open-url (string-append "file:" root "/edit.html")))))))
) ;;; menu bindings
(send edit-wgt set-menu-items!
buffer-modified-menu-item
new-menu-item open-menu-item insert-file-menu-item
execute-menu-item
save-menu-item save-as-menu-item
directory-menu-item
quit-menu-item
undo-menu-item
redo-menu-item
copy-menu-item
cut-menu-item
paste-menu-item
#f
)
(send self set-menu!
(create <menu>
(list menu-file
menu-edit
menu-preferences
buffer-modified-menu-item
(swl:help-menu))))
; hack (until we fix menu.ss, menu configuration has to be done
; after the menu is installed via set-menu!)
(set-relief! (send self get-menu) 'flat)
(set-border-width! (send self get-menu) 0)
(pack scrolled-frame (expand: #t) (fill: 'both))
(thread-fork-group
(lambda ()
(load-the-file)
; Code that calls new-edit shouldn't get the editor instance
; until the specified file, if any, has been loaded. If we
; don't guarantee this, then methods like show-sexpression-at
; may show bogus source or no source at all.
; Once we've loaded the file, if any, send this instance back
; to the continuation waiting to receive it from the message
; queue in new-edit, below.
(thread-send-msg notify-q self)))
;; This makes the edit-wgt responsive to key bindings on startup
;; we should fix SWL so this isn't needed.
(send edit-wgt set-focus)
)))
(swl:add-editor self)
(void))]
)
)
(define new-edit
(rec new-edit
(case-lambda
[() (new-edit #f)]
[(current-filename) (new-edit current-filename (lambda (ed) (void)))]
[(current-filename k)
; Using #%$fixed-path? here isn't going to work because it considers
; relative paths fixed. The best plan is to open an input-output port
; right here and use truncate-file when it's time to rewrite it.
;
; We open the ports here in case we're being called via command-line
; arguments passed to a server that is running in a different current
; directory from the directory of the invoking client. The server
; parameterizes current directory to point to the directory of the
; client while we process the command-line arguments, so we open the
; ports while we have access to the files, lest someone change the
; current directory before we think to create our backup file, zB.
;
; Opening the backup file with 'append so that we don't modify the file
; in case they don't save the current file.
(define colon-path?
(lambda (filename i)
(and (memq (machine-type) '(i3nt ppcnt))
(fx= i 1)
(char=? (string-ref filename 1) #\:)
(char-alphabetic? (string-ref filename 0)))))
(define path-sep?
(lambda (filename i)
(let ([c (string-ref filename i)])
(or (char=? c #\/) (colon-path? filename i)))))
(define split-path
(lambda (filename)
(let ([len (string-length filename)])
(let loop ([i (fx- len 1)])
(if (fx< i 0)
(values "" filename)
(if (path-sep? filename i)
(values
(substring filename 0 (fx+ i 1))
(substring filename (fx+ i 1) len))
(loop (fx- i 1))))))))
(define absolute?
(lambda (path)
(let ([len (string-length path)])
(case (machine-type)
[(i3nt ppcnt)
(and (> len 2)
(let ([prefix (substring path 0 2)])
; not treating \foo or /foo as absolute since those paths
; are relative to the currently selected drive letter
(or (string=? prefix "//") ; //cfs.indiana.edu
(and (> len 3)
(colon-path? path 1)
(char=? (string-ref path 2) #\/)))))]
[else (> len 1) (char=? (string-ref path 0) #\/)]))))
(define join-paths
(lambda (p1 p2)
(if (and (>= (string-length p2) 2) (colon-path? p2 1))
p2
(let ([len (string-length p1)])
(if (and (> len 0) (path-sep? p1 (- len 1)))
(string-append p1 p2)
(string-append p1 "/" p2))))))
(define sanitize
(lambda (s)
(import scheme)
(case (machine-type)
[(i3nt ppcnt)
(list->string (subst #\/ #\\ (string->list s)))]
[else s])))
; Thanks to Windows for a few dozen special cases.
; We convert \ to / for political and religious reasons.
; Known "bug": on Windows, (new-edit "/foo") is relative to current
; directory rather than being root of current drive. Yawn.
(define absolute-path
; assume leading whitespace is intended part of filename
(lambda (filename bail-out)
(let ([filename (sanitize filename)])
(if (absolute? filename)
filename
(let-values ([(path file) (split-path filename)])
(on-error (begin
(warning-dialog #f
(format "Unable to determine absolute path for file ~a"
filename))
(or (swl:file-dialog "Select a file to edit" 'open
(file-types:
'(("Scheme source" ("*.ss"))
("All files" ("*"))))
(default-file: file))
(bail-out)))
(join-paths
; let the system normalize the path for us
(parameterize ([current-directory
(join-paths (current-directory) path)])
(sanitize (current-directory)))
file)))))))
(call/cc
(lambda (bail-out)
; swl:file-dialog gives us absolute paths, so we just have to
; ensure that we get an absolute path when started up via new-repl
(let ([current-filename
(and current-filename
(absolute-path current-filename bail-out))])
(let ([iop (and current-filename
(on-error
(let ([p (open-input-file current-filename)])
(warning-dialog 'noblock
(format "Unable to open ~a for writing.\n\nYou can edit this file but must save it under a different filename." current-filename))
p)
(open-input-output-file current-filename)))])
(let ([q (thread-make-msg-queue "new-edit")])
(swl:begin-application
(lambda (token)
(let ([editor (create <edit-toplevel> iop current-filename q token)])
(lambda () (send editor destroy)))))
; wait for the editor to initialize itself before returning
; maybe this would be better handled via lock method
(k (thread-receive-msg q)))))))])))
; (swl:register-application "New Editor" new-edit)
| true |
f75925465ff3c3e3e523d67f0209e96b60ffb407
|
7f3f185931818a0be4e256040704e2830d253b18
|
/examples/tui-menubar-demo.scm
|
651ace3044495e8d1bfddea0b568ad5574592a21
|
[] |
no_license
|
spk121/pip-tui
|
f405f240a5091ecab2f01ef145a1b3f5d38b65e3
|
7fafdadf80f5dcf867639af9fefa87fe1443fd78
|
refs/heads/master
| 2021-01-20T18:28:35.615714 | 2016-07-29T15:43:49 | 2016-07-29T15:43:49 | 60,352,270 | 7 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,532 |
scm
|
tui-menubar-demo.scm
|
(use-modules (srfi srfi-1)
(pip-tui tui-menubar)
(pip-tui action)
(pip-tui action-map)
(pip-tui event)
(pip-tui tui-action)
(pip-tui tui-progress-bar)
(pip-tui pip-color-names)
(pip-tui pip-colors)
(ncurses curses)
(ncurses panel))
(setlocale LC_ALL "")
(define mainwin (initscr))
(start-color!)
(cbreak!)
(keypad! mainwin #t)
(nodelay! mainwin #t)
(noecho!)
(mousemask (logior ALL_MOUSE_EVENTS REPORT_MOUSE_POSITION))
;; Make a menubar widget
(define menubar1 (tui-menubar-new 1 0 3 80
#:horizontal-padding 1
#:border-type 'border-light
#:border-color COLOR_INDEX_BLACK
#:text-color COLOR_INDEX_PIPGREEN1
#:bg-color COLOR_INDEX_PIPGREEN5
#:horizontal-alignment 'center
#:key-label-alist '((#\x . "SLEEP")
(#\y . "SNORE")
(#\z . "BLAMMO!"))))
(define menubar2 (tui-menubar-new 8 10 3 20
#:horizontal-padding 1
#:border-type 'border-light
#:border-color COLOR_INDEX_BLACK
#:text-color COLOR_INDEX_PIPGREEN1
#:bg-color COLOR_INDEX_PIPGREEN5
#:horizontal-alignment 'center
#:key-label-alist '((#\f . "FART")
(#\b . "BURP"))))
;; Make an action map
(define amap (action-map-new '()))
(action-map-add-action! amap (tui-menubar-action-handler) menubar1)
(action-map-add-action! amap (tui-menubar-action-handler) menubar2)
(define (finalize widget)
(enqueue-symbolic-action 'main-loop-detach widget)
(enqueue-symbolic-action 'main-loop-break widget))
(define LASTKEY #f)
(define LASTLABEL #f)
(define (menubar-keypress-action-activate mbar event state)
(when (symbolic-event? event)
(let ((data (event-get-data event)))
(when (eq? (first data) 'menubar-keypress)
(let ([key (second data)]
[label (third data)]
[source (fourth data)])
(when (eq? mbar source)
(finalize mbar)
;; (simple-tone 0 0 (list 0.001 0.01 (+ 5000 (random 1)) 0.5 0.4))
(set! LASTKEY key)
(set! LASTLABEL label)
#f
))))))
(action-map-add-action!
amap
(action-new "menubar-keypress" #t '() menubar-keypress-action-activate #f)
menubar1)
(action-map-add-action!
amap
(action-new "menubar-keypress" #t '() menubar-keypress-action-activate #f)
menubar2)
;; (action-map-add-action!
;; amap
;; (action-new "sound-terminal-glyph-new" #t '() sound-action-activate #f)
;; TT)
(main-loop amap)
(endwin)
(newline)
(newline)
(newline)
(newline)
(display LASTKEY) (newline)
(display LASTLABEL) (newline)
| false |
94e4c2658507336105fe8e1ef2f1e83293aae798
|
0575d30974d391752ad244b523dd0517cfa380d6
|
/nova.scm
|
1324c47f4db91ceabc46c3649f138e1e412557c4
|
[] |
no_license
|
cgswords/Fractals
|
bbb6c5411b036b8f92d47e83c9bf58d4f1b89f11
|
7557d73970f4673a9f61901aedabb6d47c93d3b2
|
refs/heads/master
| 2021-03-12T22:23:27.090530 | 2013-02-24T23:19:43 | 2013-02-24T23:19:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,225 |
scm
|
nova.scm
|
(load "pmatch.scm")
;; z = z - relax * ( z ^ power - 1 ) + pixel
;; / ( power * z ^ ( power - 1 ) )
;;
(define nova-recur
(lambda (z r p c icount imax)
(if (>= icount imax) icount
(let ((nz
(+ (- z (* r (sub1 (expt z p))
(/ 1 (* p (expt z (sub1 p)))))) c)))
(if (or (< (abs (- (cfl-real-part z) (cfl-real-part nz))) 0.001)
(< (abs (- (cfl-imag-part z) (cfl-imag-part nz))) 0.001))
icount
(nova-recur nz r p c (add1 icount) imax))))))
(define nova
(lambda (r p c imax)
(trace-lambda nova (y x)
(cond
[(and (fixnum? y) (fixnum? x))
(nova-recur
(fl-make-rectangular (fixnum->flonum x) (fixnum->flonum y))
r p c 0 imax)]
[(fixnum? x)
(nova-recur
(fl-make-rectangular (fixnum->flonum x) y)
r p c 0 imax)]
[(fixnum? y)
(nova-recur
(fl-make-rectangular x (fixnum->flonum y))
r p c 0 imax)]
[else
(nova-recur
(fl-make-rectangular x y)
r p c 0 imax)]))))
(define itercombstrf
(lambda (i j max f outport scale top left)
(cond
[(< max i)
(begin
(display "\n" outport)
(itercombstrf 0 (add1 j) max f outport scale top left))]
[(< max j) (void)]
[else
(begin
(display " " outport)
(display (f (+ top (* i scale)) (+ left (* j scale))) outport)
(display " " outport)
(itercombstrf (add1 i) j max f outport scale top left))])))
(define write-pgm-color
(lambda (file f size ceil top left)
(if (file-exists? file) (delete-file file))
(call-with-output-file file
(lambda (p)
(display "P3\n" p)
(display (number->string size) p)
(display " " p)
(display (number->string size) p)
(display "\n" p)
;;(display (number->string (add1 ceil)) p)
(display "255" p)
(display "\n" p)
(itercombstrf 0 0 size f p (/ 1.0 ceil) top left)))))
(define runnovacolor
(lambda (file f n m t l)
(write-pgm-color file f n m t l)))
(define color-lookup
(lambda (n env)
(cond
[(null? env) '(0 0 0)]
[(and (>= n (caaar env)) (<= n (cdaar env))) (cdar env)]
[else (color-lookup n (cdr env))])))
(define color-1
'(
(( 0 . 5) . (80 80 255))
(( 6 . 10) . (40 40 20))
(( 11 . 15) . (0 0 0))
(( 16 . 25) . (30 30 80))
(( 26 . 30) . (0 0 200))
(( 31 . 35) . (80 80 80))
(( 36 . 40) . (60 40 160))
(( 41 . 50) . (5 5 5))
(( 51 . 75) . (0 0 100))
(( 76 . 100) . (30 30 30))
((101 . 125) . (150 150 150))
((126 . 150) . (100 0 80))
((151 . 175) . (10 0 255))
((176 . 200) . (40 40 40))
((201 . 225) . (40 40 255))
((226 . 255) . (30 30 0))
))
(define gen-blue
(lambda (x)
`(0 0 ,(min 255 (* x 4)))))
(define gen-darkergray
(lambda (x)
(let ((v (max 0 (- 255 (* x 4)))))
(list v v v))))
(define gen-rainbow
(lambda (x)
(let ((v (min 255 (* x x))))
(cond
[(< 200 v) (list v (- v x) (- v x))]
[(< 175 v) (list v v v)]
[(< 150 v) (list v (- v x) 0)]
[(< 100 v) (list v 0 0)]
[(< 50 v) (list v v 0)]
[(< 25 v) (list v v v)]
[(< 10 v) (list 0 v 0)]
[else (list v 0 0)]))))
(define gen-darkgray
(lambda (x)
(let ((v (min 255 (* x 4))))
(list v v v))))
(define color-gen
(lambda (color-fun color-f)
(lambda (x y)
(let* ((v (color-fun x y))
(colors (color-f v)))
(pmatch colors
[(,red ,green ,blue)
(string-append
(number->string red) " "
(number->string green) " "
(number->string blue))])))))
(define color-set
(lambda (color-fun colorenv)
(lambda (x y)
(let* ((v (color-fun x y))
(colors (color-lookup v colorenv)))
(pmatch colors
[(,red ,green ,blue)
(string-append
(number->string red) " "
(number->string green) " "
(number->string blue))])))))
| false |
a549a635c6eff13e5c8bdb2558744fe1f3ea1127
|
4ffb53517febeb13281dc5daf05c93f988ea4815
|
/src/hello-world.scm
|
ddf1afc53276ac4544b20098507c292e19b74624
|
[
"MIT"
] |
permissive
|
massimo-nocentini/chicken-microhttpd
|
9806042d265b97a7fd92769510ae5f765ac3d458
|
6ef67a5da78638bb7f9c951de48b1b24da972940
|
refs/heads/master
| 2020-04-27T00:13:19.038235 | 2019-03-21T15:26:33 | 2019-03-21T15:26:33 | 173,927,497 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,186 |
scm
|
hello-world.scm
|
(import scheme (chicken base) (chicken io) (chicken foreign))
(import microhttpd)
(foreign-declare "#include <microhttpd.h>")
(define-external
(answer_to_connection
(c-pointer cls)
((c-pointer (struct "MHD_Connection")) connection)
((const c-string) url)
((const c-string) method)
((const c-string) version)
((const c-string) upload_data)
((c-pointer size_t) upload_data_size)
((c-pointer (c-pointer void)) con_cls))
int
(begin
(print* 'within)
(let* ((page "<html><body>Hello, browser!</body></html>")
(response (MHD_create_response_from_buffer
(string-length page) page MHD_RESPMEM_PERSISTENT))
(ret (MHD_queue_response connection MHD_HTTP_OK response)))
(MHD_destroy_response response)
ret)))
(define (main port)
(let ((daemon (MHD_start_daemon
MHD_USE_SELECT_INTERNALLY port NULL NULL
(location answer_to_connection)
NULL
MHD_OPTION_END
)))
(when (equal? NULL daemon) (print 'exiting) (exit 1))
(print `(started daemon ,daemon))
(read-line)
(MHD_stop_daemon daemon)
(print 'stopped)
(exit 0)))
(main 8080)
| false |
a5d3acb5a11944a5c234692544a247959c355492
|
434a6f6b2e788eae6f6609d02262f9c9819773a7
|
/day14/program-a.scm
|
3f46d28c59720c1d3cda049e5057e7390f3d5313
|
[] |
no_license
|
jakeleporte/advent-of-code-2020
|
978fc575d580c63386c53bb40fc14f24d5137be7
|
649292bf17feaccf572e02d4dad711d2c46d66cb
|
refs/heads/main
| 2023-02-07T22:29:08.479708 | 2021-01-03T01:16:22 | 2021-01-03T01:16:22 | 318,069,993 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,058 |
scm
|
program-a.scm
|
#!/usr/bin/env guile
!#
(use-modules (ice-9 rdelim) (ice-9 match))
(define (apply-mask mask int)
"Given a MASK as a string, ignore bits in INT corresponding
to 'X' in the MASK, and for each '0' or '1' in the MASK, replace
the corresponding bit in INT"
(let ((bits (string->list
(string-pad (number->string int 2) 36 #\0)))
(bitmask (string->list mask)))
(string->number
(list->string
(map (lambda (c1 c2) (match c1 (#\X c2) (bit bit)))
bitmask bits))
2)))
(define (run-docking-program)
(define memory (make-hash-table))
(let loop ((line (read-line)) (mask ""))
(if (eof-object? line) memory
(let ((inst (string-tokenize line char-set:letter+digit)))
(match (car inst)
("mask" (loop (read-line) (cadr inst)))
(_ (hash-set! memory (cadr inst)
(apply-mask mask (string->number (caddr inst))))
(loop (read-line) mask)))))))
(define (main)
(let ((memory (run-docking-program)))
(display
(hash-fold (lambda (key value prev) (+ value prev))
0 memory))
(newline)))
(main)
| false |
b7fa8539cc28ea53b3eae4a19788238bc73044b7
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/runtime/serialization/object-manager.sls
|
4ddeb5f16a718172363bb51d77ed566988509195
|
[] |
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,524 |
sls
|
object-manager.sls
|
(library (system runtime serialization object-manager)
(export new
is?
object-manager?
get-object
record-delayed-fixup
record-fixup
register-object
raise-on-deserializing-event
raise-deserialization-event
do-fixups
record-array-element-fixup)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Runtime.Serialization.ObjectManager
a
...)))))
(define (is? a) (clr-is System.Runtime.Serialization.ObjectManager a))
(define (object-manager? a)
(clr-is System.Runtime.Serialization.ObjectManager a))
(define-method-port
get-object
System.Runtime.Serialization.ObjectManager
GetObject
(System.Object System.Int64))
(define-method-port
record-delayed-fixup
System.Runtime.Serialization.ObjectManager
RecordDelayedFixup
(System.Void System.Int64 System.String System.Int64))
(define-method-port
record-fixup
System.Runtime.Serialization.ObjectManager
RecordFixup
(System.Void
System.Int64
System.Reflection.MemberInfo
System.Int64))
(define-method-port
register-object
System.Runtime.Serialization.ObjectManager
RegisterObject
(System.Void
System.Object
System.Int64
System.Runtime.Serialization.SerializationInfo
System.Int64
System.Reflection.MemberInfo
System.Int32[])
(System.Void
System.Object
System.Int64
System.Runtime.Serialization.SerializationInfo
System.Int64
System.Reflection.MemberInfo)
(System.Void
System.Object
System.Int64
System.Runtime.Serialization.SerializationInfo)
(System.Void System.Object System.Int64))
(define-method-port
raise-on-deserializing-event
System.Runtime.Serialization.ObjectManager
RaiseOnDeserializingEvent
(System.Void System.Object))
(define-method-port
raise-deserialization-event
System.Runtime.Serialization.ObjectManager
RaiseDeserializationEvent
(System.Void))
(define-method-port
do-fixups
System.Runtime.Serialization.ObjectManager
DoFixups
(System.Void))
(define-method-port
record-array-element-fixup
System.Runtime.Serialization.ObjectManager
RecordArrayElementFixup
(System.Void System.Int64 System.Int32[] System.Int64)
(System.Void System.Int64 System.Int32 System.Int64)))
| true |
2c7e0d58374761b638d6106563672f54fd91e990
|
f6ebd0a442b29e3d8d57f0c0935fd3e104d4e867
|
/ch02/2.4/ex-2-4-iamslash.ss
|
1e28f3b5e9a39981cb95149cdd9678f10aba3c06
|
[] |
no_license
|
waytai/sicp-2
|
a8e375d43888f316a063d280eb16f4975b583bbf
|
4cdc1b1d858c6da7c9f4ec925ff4a724f36041cc
|
refs/heads/master
| 2021-01-15T14:36:22.995162 | 2012-01-24T12:21:30 | 2012-01-24T12:21:30 | 23,816,705 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 16,813 |
ss
|
ex-2-4-iamslash.ss
|
;; -*- coding: utf-8 -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2.4.1 복소수표현
(make-from-real-imag (real-part z) (imag-part z))
(make-from-mag-ang (magnitude z) (angle z))
(define (add-complex z1 z2)
(make-from-real-imag (+ (real-part z1) (real-part z2))
(+ (imag-part z1) (imag-part z2))))
(define (sub-complex z1 z2)
(make-from-real-imag (- (real-part z1) (real-part z2))
(- (imag-part z1) (imag-part z2))))
(define (mul-complex z1 z2)
(make-from-mag-ang (* (magnitude z1) (magnitude z2))
(+ (angle z1) (angle z2))))
(define (div-complex z1 z2)
(make-from-mag-ang (/ (magnitude z1) (magnitude z2))
(- (angle z1) (angle z2))))
;; Ben의 표현방식을 정의하는 짜뭊추개와 고르개 (직각좌표방식)
(define (real-part z) (car z))
(define (imag-part z) (cdr z))
(define (magnitude z)
(sqrt (+ (square (real-part z)) (square (imag-part z)))))
(define (angle z)
(atan (imag-part z) (real-part z)))
(define (make-from-real-imag x y) (cons x y))
(define (make-from-mag-ang r a)
(cons (* r (cos a)) (* r (sin a))))
;; Alissa의 표현방식을 정의하는 짜뭊추개와 고르개 (극좌표방식)
(define (real-part z)
(* (magnitude z) (cos (angle z))))
(define (imag-part z)
(* (magnitude z) (sin (angle z))))
(define (magnitude z) (car z))
(define (angle z) (cdr z))
(define (make-from-real-imag x y)
(cons (sqrt (+ (square x) (square y)))
(atan y x)))
(define (make-from-mag-ang r a) (cons r a))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2.4.2 타입을 표시한 데이터
(define (attach-tag type-tag contents)
(cons type-tag contents))
(define (type-tag datum)
(if (pair? datum)
(car datum)
(error "Bad tagged datum -- TYPE-TAG" datum)))
(define (contents datum)
(if (pair? datum)
(cdr datum)
(error "Bad tagged datum -- CONTENTS" datum)))
(define (rectangular? z)
(eq? (type-tag z) 'rectangular))
(define (polar? z)
(eq? (type-tag z) 'polar))
;; Ben의 표현방식을 정의하는 짜뭊추개와 고르개 (직각좌표방식)
(define (real-part-rectangular z) (car z))
(define (imag-part-rectangular z) (cdr z))
(define (magnitude-rectangular z)
(sqrt (+ (square (real-part-rectangular z)) (square (imag-part z)))))
(define (angle-rectangular z)
(atan (imag-part-rectangular z) (real-part-rectangular z)))
(define (make-from-real-imag-rectangular x y)
(attach-tag 'rectangular
(cons x y)))
(define (make-from-mag-ang-rectangular r a)
(attach-tag 'rectangular
(cons (* r (cos a)) (* r (sin a)))))
;; Alissa의 표현방식을 정의하는 짜뭊추개와 고르개 (극좌표방식)
(define (real-part-polar z)
(* (magnitude-polar z) (cos (angle-polar z))))
(define (imag-part-polar z)
(* (magnitude-polar z) (sin (angle-polar z))))
(define (magnitude-polar z) (car z))
(define (angle-polar z) (cdr z))
(define (make-from-real-imag-polar x y)
(attach-tag 'polar
(cons (sqrt (+ (square x) (square y)))
(atan y x))))
(define (make-from-mag-ang r a)
(attach-tag 'polar
(cons r a)))
;; 일반화된 고르개 연산
(define (real-part z)
(cond ((rectangular? z)
(real-part-rectangular (contents z)))
((polar? z)
(real-part-polar (contents z)))
(else (error "Unknown type -- REAL-PART" z))))
(define (imag-part z)
(cond ((rectangular? z)
(imag-part-rectangular (contents z)))
((polar? z)
(imag-part-rectangular (contents z)))
(else (error "Unknown type -- IMAG-PART" z))))
(define (magnitude z)
(cond ((rectangular? z)
(magnitude-polar (contents z)))
((polar? z)
(magnitude-polar (contents z)))
(else (error "Unknown type -- MAGNITUDE" z))))
(define (angle z)
(cond ((rectangular? z)
(angle-rectangular (contents z)))
((polar? z)
(angle-polar (contents z)))
(else (error "Unknown type -- ANGLE" z))))
(define (add-complex z1 z2)
(make-from-real-imag (+ (real-part z1) (real-part z2))
(+ (imag-part z1) (imag-part z2))))
(define (make-from-real-imag x y)
(make-from-real-imag-rectangular x y))
(define (make-from-mag-ang r a)
(make-from-mag-ang-polar r a))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 2.4.3 데이터 중심 프로그래밍과 덧붙임 성질
(define (install-rectangular-package)
;; 갇힌 프로시저
(define (real-part z) (car z))
(define (imag-part z) (cdr z))
(define (make-from-real-imag x y) (cons x y))
(define (magnitude z)
(sqrt (+ (square (real-part z))
(square (imag-part z)))))
(define (angle z)
(atan (imag-part z) (real-part z)))
(define (make-from-mag-ang r a)
(cons (* r (cos a)) (* r (sin a))))
;; 이꾸러미의 인터페이스
(define (tag x) (attatch-tag 'rectangular x))
(put 'real-part '(rectangular) real-part)
(put 'imag-part '(rectangular) imag-part)
(put 'magnitude '(rectangular) magnitude)
(put 'angle '(rectangular) angle)
(put 'make-from-real-imag 'rectangular
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'rectangular
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (install-polar-package)
;; 갇힌 프로시저
(define (magnitude z) (car z))
(define (angle z) (cdr z))
(define (make-from-mag-ang r a) (cons r a))
(define (real-part z)
(* (magnitude z) (cos (angle z))))
(define (imag-part z)
(* (magnitude z) (sin (angle z))))
(define (make-from-real-imag x y)
(cons (sqrt (+ (square x) (square y)))
(atan y x)))
;; 이꾸러미의 인터페이스
(define (tag x) (attatch-tag 'polar x))
(put 'real-part '(polar) real-part)
(put 'imag-part '(polar) imag-part)
(put 'magnitude '(polar) magnitude)
(put 'angle '(polar) angle)
(put 'make-from-real-imag 'polar
(lambda (x y) (tag (make-from-real-imag x y))))
(put 'make-from-mag-ang 'polar
(lambda (r a) (tag (make-from-mag-ang r a))))
'done)
(define (apply-generic op . args)
(let ((type-tags (map type-tag args)))
(let ((proc (get op type-tags)))
(if proc
(apply proc (map contents args))
(error
"No method for these types -- APPLY-GENERIC"
(list op type-tags))))))
(define (real-part z) (apply-generic 'real-part z))
(define (imag-part z) (apply-generic 'imag-part z))
(define (magnitude z) (apply-generic 'magnitude z))
(define (angle z) (apply-generic 'angle z))
(define (make-from-real-imag x y)
((get 'make-from-real-imag 'rectangular) x y))
(define (make-from-mag-ang r a)
((get 'make-from-mag-ang 'polar) r a))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.73
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp) (if (same-variable? exp var) 1 0))
((sum? exp)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
((product? exp)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
<추가된 규칙들은 여기에 붙여진다.>
(else (error "unknown expresssion type -- DERIVE" exp))))
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp) (if (same-variable? exp var) 1 0))
(else ((get 'deriv (operator exp))
(operands exp) var))))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.73.a.
;; 위에서 한일이 무엇인지 설명해 보라. number?나 variable?같은 술어 프로시저를 모조리
;; 데이터 중심방식으로 다루지 못하는 까닭은 무엇인가?
;;
;; 0) exp의 operator에 따라 적절한 deriv를 리턴한다.
;; 1) number? variable?다음에 operator가 없다. 모델링의 요구사항에 맞지 않는다.
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.73.b. 덧셈과 곱셈식을 미분하는 프로시절들을 짜라. 그런다음, 그
;; 프로시저들을 위 프로그램에서 쓰는 표에 집어넣는데 필요한 코드를 덧붙여라.
;;
;; 해쉬테이블관련코드
(define *op-table* (make-hash))
(define (put op type proc)
(hash-set! *op-table* (list op type) proc))
(define (get op type)
(hash-ref *op-table* (list op type) #f))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (=number? exp num)
(and (number? exp) (= exp num)))
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp) (if (same-variable? exp var) 1 0))
(else ((get 'deriv (operator exp)) (operands exp)
var))))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (install-deriv-package)
(define (make-sum a1 a2)
(cond ((=number? a1 0) a2)
((=number? a2 0) a1)
((and (number? a1) (number? a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
(define (addend s) (car s))
(define (augend s) (cadr s))
(define (multiplier p) (car p))
(define (multiplicand p) (cadr p))
(define (deriv-sum exp var)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
(define (deriv-product exp var)
(make-sum
(make-product (multiplier exp)
(deriv (multiplicand exp) var))
(make-product (deriv (multiplier exp) var)
(multiplicand exp))))
(put 'deriv '+ deriv-sum)
(put 'deriv '* deriv-product))
(install-deriv-package)
(deriv '(+ x 3) 'x)
(deriv '(* x y) 'x)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.73.c. 지수식을 미분하는 것과 같이, 새로 모태고 싶은 규칙을 하나
;; 골라 여기서 만든 데이터 중심 시스템에 집어넣어라.
;;
(define (install-deriv-exponentiation-package)
(define (base s) (car s))
(define (exponent s) (cadr s))
(define (make-exponentiation b e)
(cond ((=number? b 0) 0)
((=number? e 1) b)
(else (list '** b e))))
(define (make-product m1 m2)
(cond ((or (=number? m1 0) (=number? m2 0)) 0)
((=number? m1 1) m2)
((=number? m2 1) m1)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
(define (deriv-exponentiation exp var)
(make-product
(exponent exp)
(make-product
(make-exponentiation (base exp) (- (exponent exp) 1))
(deriv (base exp) var))))
(put 'deriv '** deriv-exponentiation))
(install-deriv-exponentiation-package)
(deriv '(** x 3) 'x)
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.73.d. 이런 단순한 대수 처리방식에서는, 식에 붙은 연산자가 그
;; 식의 타입을 나타낸다. 이때 '연산자와 타입'이 아니라 '타입과
;; 연산자'로 프로시저 인덱스가 붙어 있다면, deriv속에서 알맞은
;; 프로시저를 꺼내 쓰는 코드가 다음과 같이 바뀐다.
;; ((get (operator exp) 'deriv) (operands exp) var)
;; 이경우, 이분 시스템에는 어떤 변화가 필요한가?
;;
;; put의 인자 순서를 get과 같이 (operator exp) 'deriv순서로 변경해준다.
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.74
;; 부서파일은 부서이름+이것저것 의 형식이라고 가정한다.
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.74.a
;; rec_part 부서이름
;; rec_name 직원이름
(define (get-record rec_part rec_name)
((get 'get-record rec_part) rec_name))
(put 'get-record rec_part get-record-custom)
;; 각 부서 파일의 레코드는 get-record-custom이 제대로 동작 하도록 자치적이면 된다.
;; 이문제는 부서이름과 직원이름을 꼭 알아야 풀 수 있다.
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.74.b
;; rec_part 부서이름
;; rec_name 직원이름
(define (get-salary rec_part rec_name)
((get 'get-salary rec_part) rec_name))
(put 'get-salary rec_part get-salary-custom)
;; 각 부서 파일의 레코드는 get-salary-custom이 제대로 동작 하도록 자치적이면 된다.
;; 이문제는 부서이름과 직원이름을 꼭 알아야 풀 수 있다.
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.74.c
;; 문제를 간단히 하기위해 부서이름은 부서파일의 앞에 위치한다.
(define (find-employee-record rec_name l_rec_files)
(define (get-part file) (car file))
(map (lambda (file) get-record (get-part file) rec_name)
l_rec_files))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.74.d
;;
;; ex.2.74.a, ex.2.74.b와 같이 자치적인 get-record, get-salary를 제작하여
;; 해시맵에 put합니다.
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 메시지 패싱
(define (square x) (* x x))
(define (make-from-real-imag x y)
(define (dispatch op)
(cond ((eq? op 'real-part) x)
((eq? op 'imag-part) y)
((eq? op 'magnitude)
(sqrt (+ (square x) (square y))))
((eq? op 'angle) (atan y x))
(else
(error "Unknown op -- MAKE-FROM-REAL-IMAG" op))))
dispatch)
(define (apply-generic op arg) (arg op))
(apply-generic 'real-part (make-from-real-imag 1 2))
(apply-generic 'imag-part (make-from-real-imag 1 2))
(apply-generic 'magnitude (make-from-real-imag 1 2))
(apply-generic 'angle (make-from-real-imag 1 2))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.75
;;
(define (make-from-mag-ang r a)
(define (dispatch op)
(cond ((eq? op 'real-part)
(* r (cos a)))
((eq? op 'imag-part)
(* r (sin a)))
((eq? op 'magnitude) r)
((eq? op 'angle) a)
(else
(error "Unknown op -- MAKE-FROM-MAG-ANG" op))))
dispatch)
(define (apply-generic op arg) (arg op))
(apply-generic 'real-part (make-from-mag-ang 1 2))
(apply-generic 'imag-part (make-from-mag-ang 1 2))
(apply-generic 'magnitude (make-from-mag-ang 1 2))
(apply-generic 'angle (make-from-mag-ang 1 2))
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ex.2.76 일화된 연산을 갖춘 커다란 시스템이 오랜 시간에 걸쳐 진화를
;; 거듭하면, 그 에 따라 새로운 데이터 타입이나 연산이 필요 할 수 있다.
;; 지금까지 살펴본 세방식, 즉 일을 집적 나눠맡기는 방식(explicit
;; dispatch), 데이터 중식방식, 메시지패싱방식에 따라 새로운 연산을
;; 집어넣거나 새로운 타입을 보탠다고 하면, 시스템에 어떤 변화가
;; 일어나는가? 새로운 데이터 타입을 집어 넣어야 할일이 많다면, 어떤
;; 방식으로 시스템을 짜맞추는게 가장 좋은가? 새로운 연산을 덧붙이는
;; 경우가 많을때에는 어떤 방식이 가장 적당한가?
;; 0) i) 일을직접나눠맡기는방식
;; - 새로운 이름의 프러시저가 늘어난다.
;; - 사용시 새로운 이름의 프러시저를 직접 사용한다.
;; ii) 데이터중심방식
;; - 새로운 이름의 프러시저가 늘어난다. 이 프러시저를 해시테이블에 등록한다.
;; - 사용시 이전과 같은 이름의 프러시저를 사용한다. 데이터에 따라 등록된 프러시저가 사용된다.
;; iii)메시지패싱방식
;; - 기존의 프러시저에
;;
;; 1) 새로운 데이터 타입을 집어 넣어야 할일이 많다면 데이터중심방식이 좋다.
;; 2) 새로운 연산을 덧붙이는 일이 많다면 메시지패싱방식이 좋다.
| false |
4a2a06c8747456fcfdfadaa855d9333456c63345
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/runtime/serialization/formatters/binary/object-writer.sls
|
f7f0403c3b14a05ed5ed18186f47a397eb717166
|
[] |
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,636 |
sls
|
object-writer.sls
|
(library (system runtime serialization formatters binary object-writer)
(export new
is?
object-writer?
get-assembly-name-id
get-assembly-id
write-object-graph
write-value
write-type-spec
write-queued-objects
write-object-instance
write-primitive-value
write-assembly
queue-object
get-type-tag
write-assembly-name
write-type-code
write-serialization-end)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
a
...)))))
(define (is? a)
(clr-is
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
a))
(define (object-writer? a)
(clr-is
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
a))
(define-method-port
get-assembly-name-id
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
GetAssemblyNameId
(System.Int32 System.String))
(define-method-port
get-assembly-id
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
GetAssemblyId
(System.Int32 System.Reflection.Assembly))
(define-method-port
write-object-graph
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteObjectGraph
(System.Void
System.IO.BinaryWriter
System.Object
System.Runtime.Remoting.Messaging.Header[]))
(define-method-port
write-value
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteValue
(System.Void System.IO.BinaryWriter System.Type System.Object))
(define-method-port
write-type-spec
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteTypeSpec
(System.Void System.IO.BinaryWriter System.Type))
(define-method-port
write-queued-objects
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteQueuedObjects
(System.Void System.IO.BinaryWriter))
(define-method-port
write-object-instance
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteObjectInstance
(System.Void System.IO.BinaryWriter System.Object System.Boolean))
(define-method-port
write-primitive-value
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WritePrimitiveValue
(static: System.Void System.IO.BinaryWriter System.Object))
(define-method-port
write-assembly
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteAssembly
(System.Int32 System.IO.BinaryWriter System.Reflection.Assembly))
(define-method-port
queue-object
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
QueueObject
(System.Void System.Object))
(define-method-port
get-type-tag
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
GetTypeTag
(static:
System.Runtime.Serialization.Formatters.Binary.TypeTag
System.Type))
(define-method-port
write-assembly-name
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteAssemblyName
(System.Int32 System.IO.BinaryWriter System.String))
(define-method-port
write-type-code
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteTypeCode
(static: System.Void System.IO.BinaryWriter System.Type))
(define-method-port
write-serialization-end
System.Runtime.Serialization.Formatters.Binary.ObjectWriter
WriteSerializationEnd
(static: System.Void System.IO.BinaryWriter)))
| true |
5d11b39695ada5e9882ffddd877e2dbcfbed545a
|
378e5f5664461f1cc3031c54d243576300925b40
|
/rsauex/script/utils.scm
|
3568f579f795e67fca768a9449320c7a607667b8
|
[] |
no_license
|
rsauex/dotfiles
|
7a787f003a768699048ffd068f7d2b53ff673e39
|
77e405cda4277e282725108528874b6d9ebee968
|
refs/heads/master
| 2023-08-07T17:07:40.074456 | 2023-07-30T12:59:48 | 2023-07-30T12:59:48 | 97,400,340 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,089 |
scm
|
utils.scm
|
(define-module (rsauex script utils)
#:use-module ((ice-9 popen))
#:use-module ((ice-9 ports))
#:use-module ((ice-9 textual-ports))
#:export (invoke/capture-string-all
invoke/capture-strings
get-lines
ask
with-input-from-tty))
(define (invoke/capture-string-all program . args)
(let* ((pipe (apply open-pipe* OPEN_READ program args))
(output (get-string-all pipe)))
(close-pipe pipe)
output))
(define (invoke/capture-strings program . args)
(let* ((pipe (apply open-pipe* OPEN_READ program args))
(lines (get-lines pipe)))
(close-pipe pipe)
lines))
(define (get-lines port)
(let ((lines (list))
(line (get-line port)))
(while (not (eof-object? line))
(set! lines (cons line lines))
(set! line (get-line port)))
(reverse! lines)))
(define (ask question)
(display question)
(force-output)
(get-line (current-input-port)))
(define (with-input-from-tty thunk)
(call-with-input-file "/dev/tty"
(lambda (port)
(with-input-from-port port thunk))))
| false |
31d2ad8b50a99c763698baab993c5e5b63685496
|
c38f6404e86123560ae8c9b38f7de6b66e30f1c4
|
/slatex/callsla.scm
|
fdae7a1d7260141210a1d5d3f790a06d8f882789
|
[
"LicenseRef-scancode-warranty-disclaimer",
"CC-BY-4.0"
] |
permissive
|
webyrd/dissertation-single-spaced
|
efeff4346d0c0e506e671c07bfc54820ed95a307
|
577b8d925b4216a23837547c47fb4d695fcd5a55
|
refs/heads/master
| 2023-08-05T22:58:25.105388 | 2018-12-30T02:11:58 | 2018-12-30T02:11:58 | 26,194,521 | 57 | 4 | null | 2018-08-09T09:21:03 | 2014-11-05T00:00:40 |
TeX
|
UTF-8
|
Scheme
| false | false | 261 |
scm
|
callsla.scm
|
(define call-slatex (let ((already-loaded? #f)) (lambda (f) (if (not already-loaded?) (begin (load "~/latex/slatex/slatex.scm") (set! already-loaded? #t))) (slatex::process-main-tex-file f) (display "Call (La)TeX on ") (display f) (display " now") (newline))))
| false |
b0d0a5472679b663d8b7b0a63e0115c8e84072a2
|
1dcae2ac82bd47eac29d8f938ec51c9b724bede0
|
/examples/my-let.scm
|
acb2cf6b5acbed092f8ce8d7711c389e6f439b66
|
[
"BSD-3-Clause"
] |
permissive
|
stjordanis/bsdscheme
|
9730afab326c818daaea4ad96886ca0826320297
|
ffdc0ab5e8a2cadabcc1ca394ae06072972b75de
|
refs/heads/master
| 2021-09-21T23:30:57.615938 | 2018-09-03T02:48:41 | 2018-09-03T02:48:41 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 302 |
scm
|
my-let.scm
|
(define-syntax my-let*
(syntax-rules ()
((_ ((p v)) b ...)
(let ((p v)) b ...))
((_ ((p1 v1) (p2 v2) ...) b ...)
(let ((p1 v1))
(my-let* ((p2 v2) ...)
b ...)))))
(define (main)
(my-let* ((a 1)
(b (+ a 2)))
(display (+ a b))
(newline)))
| true |
8ac50d877ff77197c5cdcf8b36a90d0140a833cd
|
0b31088d2c5267dc646ab9e05400fbf58fbf4dc2
|
/irrlicht-example/irrlicht-method-advice.scm
|
1cd36bd10dd31d2aa3bece14a26dfb5dbf235546
|
[] |
no_license
|
braxtonrivers/swig2bmx
|
322a0cd966fbfa28a98340e4c34a0a9256208d7a
|
d3172aff86b052baf4454403c6caf34ca61f96b6
|
refs/heads/master
| 2021-01-25T09:20:24.890362 | 2016-04-03T22:48:07 | 2016-04-03T22:48:07 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,820 |
scm
|
irrlicht-method-advice.scm
|
(set! interface-typemap
(lambda (tag)
(if (pair? tag)
(cond ((eq? (cadr tag) ':irrstring) (make-max-type ":String" tag 'special 'irrstring))
(else #f) )
(case tag
((:w-string) (make-max-type ":String" tag 'special 'w-string))
(else #f) ))))
(set! before-method-advice
(lambda (class name args)
(do ((args args (cdr args))
(c 0 (fx+ c 1)) )
((null? args) #t)
(let ((a (car args)))
(when (is-special? a)
(pr "\t\tLocal cs" c ":Byte Ptr = " (car a) ".ToCString(), ")
(case (max-type-extra (cdr a))
((irrstring) (pr "is" c ":Byte Ptr = new_fromCString_OVERLOAD_1(cs" c ")\n"))
((w-string) (pr "ws" c ":Byte Ptr = _CStrToWStr(cs" c ", " (car a) ".Length)\n")) ))))))
(set! var-call-advice
(lambda (arg n)
(case (max-type-extra (cdr arg))
((irrstring) (string-append "is" (number->string n)))
((w-string) (string-append "ws" (number->string n))) )))
(set! after-method-advice
(lambda (class name args)
(do ((args args (cdr args))
(c 0 (fx+ c 1)) )
((null? args) #t)
(let ((a (car args)))
(when (is-special? a)
(pr "\t\tMemFree cs" c " ; ")
(case (max-type-extra (cdr a))
((irrstring) (pr "delete_path is" c "\n"))
((w-string) (pr "_CStdFree ws" c "\n")) ))))))
(set! return-special-advice
(lambda (class name rt)
(string-append "String.FromCString(ret)") ))
(set! return-object-advice
(lambda (class name rv)
(if (and (fx>= (string-length name) 6)
(string-ci=? "create" (substring name 0 6)) )
(string-append (substring rv 0 (fx- (string-length rv) 1)) "._withDel(IReferenceCounted_drop))")
rv) ))
(set! additional-imports
(lambda ()
(string-append "?MacOS\n"
"Import \"-framework OpenGL\"\n"
"?Win32\n"
"Import \"-lopengl32\"\n"
"?Linux\n"
"Import \"-lGL\"\n"
"?\n") ))
| false |
d1a40b74b78662357d500b7e75636843e48aeff9
|
2d868c9428b8f4772d2ede375a3492b3b6885e1d
|
/Henderson Escher Example/2.39.scm
|
8efbd5660e86095ebb94490d0643e7cf298ee289
|
[] |
no_license
|
transducer/sicp
|
2428223945da87836fa2a82c02d965061717ae95
|
2cec377aa7805edfd7760c643c14127e344ee962
|
refs/heads/master
| 2021-06-06T20:06:47.156461 | 2016-09-16T22:05:02 | 2016-09-16T22:05:02 | 25,219,798 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,080 |
scm
|
2.39.scm
|
#lang scheme
;; Complete the following definitions of reverse (exercise 2.18)
;; in terms of fold-right and fold-left from exercise 2.38:
;; (define (reverse sequence)
;; (fold-right (lambda (x y) <??>) nil sequence))
;; (define (reverse sequence)
;; (fold-left (lambda (x y) <??>) nil sequence))
;; Define fold-left and fold-right
(define (fold-left op initial sequence)
(define (iter result rest)
(if (null? rest)
result
(iter (op result (car rest))
(cdr rest))))
(iter initial sequence))
(define (fold-right op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(fold-right op initial (cdr sequence)))))
(define nil '())
(define (reverse-with-fold-right sequence)
(fold-right (lambda (x y) (append y (if (pair? x) (car x) (cons x '())))) nil sequence))
(define (reverse-with-fold-left sequence)
(fold-left (lambda (x y) (cons y x)) nil sequence))
;; Testing:
(reverse-with-fold-right (list 1 2 3 4 5)) ;; => (5 4 3 2 1)
(reverse-with-fold-left (list 1 2 3 4 5)) ;; => (5 4 3 2 1)
| false |
bc0b9ce05bbae294f02c8ed4f89c41b9c70b3f81
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec4/sec4.4.4-study.scm
|
6805689536cf9237591502e6acecd00fc8e827ce
|
[] |
no_license
|
thash/sicp
|
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
|
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
|
refs/heads/master
| 2021-05-28T16:29:26.617617 | 2014-09-15T21:19:23 | 2014-09-15T21:19:23 | 3,238,591 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 7,639 |
scm
|
sec4.4.4-study.scm
|
(define (query-driver-loop)
;...
(qeval q (singleton-stream '())))
x: hoge
y: futa
; という束縛があったとして, これをもとに
(foo ?x ?y)
;を
(foo hoge fuga)
; に置き換えるのがinstantiate.
;; (and (foo ?x ?y) (bar ?z))
(define (conjoin conjuncts frame-stream)
(if (empty-conjunction? conjuncts)
frame-stream
(conjoin (rest-conjuncts conjuncts)
(qeval (first-conjunct conjuncts)
frame-stream))))
;; まず最初の(foo ?x ?y)を満たす可能性を列挙して,
;; その中からさらに (bar ?z) を満たすものを探す
;; これを
(put 'and 'qeval conjoin)
;; こんな感じに格納するんだけど第二の'qevalってなんだっけ. 二次元テーブルの2個目軸.
;; or = disjoin.
(define (disjoin disjuncts frame-stream)
(if (empty-disjunction? disjuncts)
the-empty-stream
(interleave-delayed
(qeval (first-disjunct disjuncts) frame-stream)
(delay (disjoin (rest-disjuncts disjuncts)
frame-stream)))))
;; interleave は「第一引数のstreamが無限だったらそこの可能性を探して永遠に終わらない」可能性を回避するため交互に取っていく手続き. そのdelay版
;; lisp-value
(define (lisp-value call frame-stream)
(stream-flatmap
(lambda (frame)
;; その時点で確定しているものを当てはめていってexecute = lispとして評価する.
(if (execute
(instantiate ;; qevalでも出てきたinstantiate
call
frame
(lambda (v f)
(error "Unknown pat var -- LISP-VALUE" v))))
(singleton-stream frame) ;; 与えられたframeをsingleton繰り返ししたstream?
the-empty-stream))
frame-stream))
;; evalじゃなくexecuteである理由は?
(define (execute exp)
(apply (eval (predicate exp) (interaction-environment))
(args exp)))
;; 評価するときに与える環境, Gaucheではinteraction-environmentにしないと動かないよと
;;; 4.4.4.3 パターンマッチ
(define (find-assertions pattern frame)
(stream-flatmap (lambda (datum)
(check-an-assertion datum pattern frame))
(fetch-assertions pattern frame)))
(define (check-an-assertion assertion query-pat query-frame)
(let ((match-result
(pattern-match query-pat assertion query-frame)))
(if (eq? match-result 'failed) ;; failedをemptyに変換してる
the-empty-stream
(singleton-stream match-result))))
(define (pattern-match pat dat frame)
(cond ((eq? frame 'failed) 'failed)
((equal? pat dat) frame) ;; patternとdataが一致すれば(これがpatternmatchの本体(?)) frameを返す.
((var? pat) (extend-if-consistent pat dat frame))
;; extend-if-consistentは整合性があるかどうかチェックして, 整合性が取れてたらフレームを拡張する.
((and (pair? pat) (pair? dat))
(pattern-match (cdr pat)
(cdr dat)
(pattern-match (car pat)
(car dat)
frame)))
(else 'failed))) ;; 最後までなければ'failedを返す(で, check-an-assertionにてthe-empty-streamに置き換えられる.)
;; pattern-matchをそのままで使いたい!
;; query-driver-loopでassertした後エラー起こして(適当な数値を出す)goshに戻ってきて以下を評価すればいい. そんな方法が.
(pattern-match '(job (? x) (? y)) '(job foo bar) the-empty-stream)
(((? y) . bar) ((? x) . foo))
(define (extend-if-possible var val frame)
(let ((binding (binding-in-frame var frame)))
(cond (binding
(unify-match
(binding-value binding) val frame))
((var? val) ; ***
(let ((binding (binding-in-frame val frame)))
(if binding
(unify-match
var (binding-value binding) frame)
(extend var val frame))))
((depends-on? val var frame) ; ***
'failed)
(else (extend var val frame)))))
;; extendはgaucheに既にあるので(ゆえにsyntax highlight)
;; シンプルなprologならここまででok, とのこと.
;;;; 4.4.4.4 規則とユニフィケーション
;; uniqueなidを作る
;; (? x) 1回目
(? 1 x)
;; (? x) 2回目
(? 2 x)
(define (apply-a-rule rule query-pattern query-frame)
(let ((clean-rule (rename-variables-in rule)))
(let ((unify-result
(unify-match query-pattern
(conclusion clean-rule)
query-frame)))
(if (eq? unify-result 'failed)
the-empty-stream
(qeval (rule-body clean-rule)
(singleton-stream unify-result))))))
;; ここがいよいよunifyの本体
;; pattern-matchと似てるがp1,p2とふたつ変数入る可能性があるのが大きな違い.
(define (unify-match p1 p2 frame)
(cond ((eq? frame 'failed) 'failed)
((equal? p1 p2) frame)
((var? p1) (extend-if-possible p1 p2 frame))
((var? p2) (extend-if-possible p2 p1 frame)) ; ***
((and (pair? p1) (pair? p2))
(unify-match (cdr p1)
(cdr p2)
(unify-match (car p1)
(car p2)
frame)))
(else 'failed)))
;; extend-if-possibleとは?
(define (extend-if-possible var val frame)
(let ((binding (binding-in-frame var frame)))
(cond (binding
(unify-match
(binding-value binding) val frame))
((var? val) ; ***
(let ((binding (binding-in-frame val frame)))
(if binding
(unify-match
var (binding-value binding) frame)
(extend var val frame))))
((depends-on? val var frame) ; ***
'failed)
(else (extend var val frame)))))
;; "y"と"yを含む式"はマッチできない, それを判定するのがdepends-on?
(unify-match '(job (? x) (? y)) '(job (? z) (computer (? y))) the-empty-stream)
;; うまくうごかん
;; 4.4.4.6 ストリーム演算
(define (stream-flatmap proc s)
(flatten-stream (stream-map proc s)))
; ----------------------------------------------------------------------------------
;;;; 疑問
;; ? (quit!) はなにしてる?
;; ? prologなの?
;; ? idを付与する的なところ, uniqueじゃないと困る理由聞き逃した
;; ? (quit!) はなにしてる?
;; => 発表者が独自に定義してた. THE-ASSERTIONSとかTHE-RULESをthe-empty-streamにいれたうえで'quit. で脱出
; delayしておけば何かしら印字されるけどdelaysしてなければぜんぶ
; 単純なるーぷであればstackに積んでおいてもっかいきたときに覚えておいて判定すれば良いよ
;; flatten-streamはflatにしようとしてる.
;; flatten-stream は
((stream1) (stream1) ...)
;; となっているものを
(stream1 stream1 ...)
;; にしてやる.
;;
;; で, streamに無限があればいつまでもflatできないので差し込みします. interleave.
;; で, そもそも
((stream1) (stream1) .. "ココ" .)
;; が無限に続いているかもしれないのでdelayを入れないといけない.
| false |
1994b46dc22230e6ec38fe8264fd04a1bfb5d5c8
|
0855447c3321a493efa9861b3713209e37c03a4c
|
/sdf/chapter2_wrapper.ss
|
ea0510fdaead2426d2369d955abfd34ee16d9578
|
[] |
no_license
|
dasheng523/sicp
|
d04f30c50076f36928728ad2fe0da392dd0ae414
|
1c40c01e16853ad83b8b82130c2c95a5533875fe
|
refs/heads/master
| 2021-06-16T20:15:08.281249 | 2021-04-02T04:09:01 | 2021-04-02T04:09:01 | 190,505,284 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,743 |
ss
|
chapter2_wrapper.ss
|
;;;; 2.3 Wrappers
;; 临时心得
;; 当需要扩展的时候,我一般在某个函数上多加一个参数,然后修改其内部实现。是的这样看来会非常快。但这会隐藏程序背后的逻辑。
;; 应该换成什么样的思维呢?我想要的目的是把背后的逻辑抽离出来。但一般来说背后的逻辑不会非常清晰。应怎么做呢?
;; 背后的逻辑就是不变的逻辑。就拿这个程序,不管单位如何变化,不变的是gas-law-volume的逻辑。
;; 找到背后的逻辑,也就是找到不变的逻辑。
;; 找到之后,就封装变化的逻辑了。变化的逻辑就可借助于领域语言。
;; 关注点分离就是将某段逻辑分成不同的部分。一般来说就是把主逻辑和从逻辑分开来。
(load "../g-point/startup.ss")
(import (common combinator))
(define (gas-law-volume pressure temperature amount)
(/ (* amount gas-constant temperature) pressure))
(define gas-constant 8.3144621)
(define (sphere-radius volume)
(expt (/ volume (* 4/3 pi)) 1/3))
(define pi (* 4 (atan 1 1)))
(define (make-unit-conversion f1 f2)
(case-lambda
[() (cons f1 f2)]
[args (apply f1 args)]))
(define (unit:* u1 u2)
(make-unit-conversion
(compose u2 u1)
(compose (unit:invert u1) (unit:invert u2))))
(define (units:* . units)
(let ([n (length units)])
(cond
[(= n 1) (car units)]
[(= n 2) (unit:* (car units) (cadr units))]
[(> n 2) (apply units:* (unit:* (car units) (cadr units))
(cddr units))]
[else (error "入参数量错误")])))
(define (unit:invert u)
(let ([fs (u)])
(make-unit-conversion
(cdr fs)
(car fs))))
(define (unit:/ u1 u2)
(unit:* u1 (unit:invert u2)))
(define (unit:expt u n)
(assert (exact-nonnegative-integer? n))
(if (= n 1)
u
(unit:* u (unit:expt u (- n 1)))))
;; (sphere-radius (conventional-gas-law-volume 14.7 68 1))
(define (unit-specializer procedure implicit-output-unit . implicit-input-units)
(define (specializer specific-output-unit . specific-input-units)
(let ((output-converter (make-converter implicit-output-unit specific-output-unit))
(input-converters (map make-converter specific-input-units implicit-input-units)))
(define (specialized-procedure . arguments)
(output-converter
(apply procedure
(map (lambda (converter argument) (converter argument))
input-converters arguments))))
specialized-procedure))
specializer)
;; 创建一个单位节点
(define (create-unit-node u)
(list u))
;; 在一个节点上挂载一个叶子
(define (unit-node-mount node leaf conversion)
(append node (list (cons leaf conversion))))
;; 获取节点的(叶子和转换器)的pair组成的List
(define (unit-node-leafs node)
(cdr node))
;; 获取pair的单位
(define (leaf-unit p)
(car p))
;; 获取pair的转换器
(define (leaf-conver p)
(cdr p))
;; 节点table
(define unit-node-table (make-eqv-hashtable))
;; 获取单位节点
(define (get-unit-node u)
(hashtable-ref unit-node-table u #f))
(define (register-unit-conversion u1 u2 conversion)
(define (register u1 u2 conversion)
(let ([node (or (get-unit-node u1)
(create-unit-node u1))])
(hashtable-set! unit-node-table
u1
(unit-node-mount node u2 conversion))))
(register u1 u2 conversion)
(register u2 u1 (unit:invert conversion)))
;; (make-converter 'fahrenheit 'celsius)
(define (make-converter u1 u2)
(cond
[(and (simple-unit? u1) (simple-unit? u2))
(let ([conversions (find-unit-path-conversion u1 u2)])
(if conversions
(apply units:* conversions)
(error 'make-converter (list "找不到单位换算路径" u1 u2))))]
[(and (compound-unit? u1) (compound-unit? u2))
(let ([op1 (compound-unit-operator u1)]
[op2 (compound-unit-operator u2)])
(assert (eq? op1 op2))
(let ([composer (find-operator-composer op)])
(assert composer)
(composer (make-converter (compound-unit-fst u1) (compound-unit-fst u2))
(make-converter (compound-unit-sec u1) (compound-unit-sec u2)))))]))
;; 判断是否是简单单位
;; (simple-unit? 'fahrenheit)
(define (simple-unit? u)
(symbol? u))
(define (simple-unit-eq? u1 u2)
(eq? u1 u2))
;; 寻找两个简单单位之间的转换器
;; ((car (find-unit-path-conversion 'fahrenheit 'celsius)) 66)
;; ((car (find-unit-path-conversion 'celsius 'kelvin)) 66) TODO 这里死循环了
(define (find-unit-path-conversion u1 u2)
(let loop ([plist (unit-node-leafs (get-unit-node u1))])
(if (null? plist)
#f
(let ([item (car plist)])
(if (simple-unit-eq? u2 (leaf-unit item))
(list (leaf-conver item))
(let ([conver-path (find-unit-path-conversion (leaf-unit item) u2)])
(if conver-path
(cons (leaf-conver item) conver-path)
(loop (cdr plist)))))))))
;; 创建一个复合单位
(define (make-compound-unit op u1 u2)
(list op u1 u2))
;; 判断是否是复合单位
(define (compound-unit? u)
(and (pair? u) (symbol? (car u))))
;; 获取复合单位的操作符
(define (compound-unit-operator u)
(car u))
;; 获取复合单位的第一个单位
(define (compound-unit-fst u)
(cadr u))
;; 获取复合单位的第二个单位
(define (compound-unit-sec u)
(caddr u))
;; 寻找操作符对应的单位转换器的组合器
(define (find-operator-composer op)
(cond
[(eq? op '/) unit:/]
[(eq? op 'expt) unit:expt]
[(eq? op 'invert) unit:invert]
[else 'none-operator-composer]))
;; 华氏度和摄氏度的关系
(register-unit-conversion 'fahrenheit 'celsius
(make-unit-conversion (lambda (f) (* 5/9 (- f 32)))
(lambda (c) (+ (* c 9/5) 32))))
;; 摄氏度与绝对度的关系
(register-unit-conversion 'celsius 'kelvin
(let ((zero-celsius 273.15)) ;kelvins
(make-unit-conversion
(lambda (c) (+ c zero-celsius))
(lambda (k) (- k zero-celsius)))))
(define make-specialized-gas-law-volume
(unit-specializer gas-law-volume
'(expt meter 3) ; output (volume)
'(/ newton (expt meter 2)) ; pressure
'kelvin ; temperature
'mole)) ; amount
(define conventional-gas-law-volume
(make-specialized-gas-law-volume
'(expt inch 3) ; output (volume)
'(/ pound (expt inch 2)) ; pressure
'fahrenheit ; temperature
'mole)) ; amount
| false |
bfbd88ed0472408994af2e2c7ca47957ca20b076
|
bcb10d60b55af6af2f5217b6338f9f2c99af8a14
|
/test/syntax.swat
|
2acebb35414af19dbd64420438e47533849dfe82
|
[
"Apache-2.0"
] |
permissive
|
lars-t-hansen/swat
|
e3aaffdca6fe74208b51a1ffed6fc380a91296d7
|
f6c30bee2ceaa47a4fe0e6f7ac4e7c3257921c3a
|
refs/heads/master
| 2020-03-18T08:45:41.600093 | 2018-06-20T05:49:47 | 2018-06-20T05:49:47 | 134,526,524 | 8 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,837 |
swat
|
syntax.swat
|
;;; -*- mode: scheme; fill-column: 80 -*-
(defmodule Misc
(defun+ (t_begin (n i32) -> i32)
(begin
(+ n 1)
(+ n 2)
(+ n 3)))
(defun+ (t_if (n i32) -> i32)
(if (> n 3)
(begin
(+ n 4)
(+ n 8))
(begin
(+ n 1))))
(defun+ (t_cond (n i32) -> i32)
(cond ((= n 1) -1)
((= n 2) -2)
(else -3)))
(defun (f (n i32)))
(defun+ (t_cond2 (n i32))
(cond ((= n 1) (f 1))
((= n 2) (f 2))
((= n 3))))
(defun+ (t_cond3 (n i32))
(cond))
(defun+ (t_cond4 (n i32))
(cond (else)))
(defun+ (t_and0 -> i32)
(and))
(defun+ (t_and1 (n i32) -> i32)
(and (= n 1)))
(defun+ (t_and2 (n i32) (m i32) -> i32)
(and (= n 1) (= m 1)))
(defun+ (t_and3 (n i32) (m i32) (o i32) -> i32)
(and (= n 1) (= m 1) (= o 1)))
(defun+ (t_and3v (n i32) (m i32) (o i32) -> i32)
(and n m o))
(defun+ (t_or0 -> i32)
(or))
(defun+ (t_or1 (n i32) -> i32)
(or (= n 1)))
(defun+ (t_or2 (n i32) (m i32) -> i32)
(or (= n 1) (= m 1)))
(defun+ (t_or3 (n i32) (m i32) (o i32) -> i32)
(or (= n 1) (= m 1) (= o 1)))
(defun+ (t_or3v (n i32) (m i32) (o i32) -> i32)
(or n m o))
(defun+ (t_trap (n i32) -> i32)
(if (= n 0)
n
(trap i32)))
)
(js "
Misc.compile().then(function(module) {
let i = new WebAssembly.Instance(module, {lib:Misc.lib}).exports;
assertEq(i.t_begin(5), 8);
assertEq(i.t_if(8), 16);
assertEq(i.t_if(3), 4);
assertEq(i.t_cond(0), -3);
assertEq(i.t_cond(1), -1);
assertEq(i.t_cond(2), -2);
assertEq(i.t_cond(3), -3);
assertEq(i.t_and0(), 1);
assertEq(i.t_and1(0), 0);
assertEq(i.t_and1(1), 1);
assertEq(i.t_and2(0, 0), 0);
assertEq(i.t_and2(1, 0), 0);
assertEq(i.t_and2(0, 1), 0);
assertEq(i.t_and2(1, 1), 1);
assertEq(i.t_and3(1, 1, 0), 0);
assertEq(i.t_and3(0, 1, 1), 0);
assertEq(i.t_and3(1, 1, 1), 1);
assertEq(i.t_and3v(1, 1, 2), 2);
assertEq(i.t_and3v(1, 1, 0), 0);
assertEq(i.t_or0(), 0);
assertEq(i.t_or1(0), 0);
assertEq(i.t_or1(1), 1);
assertEq(i.t_or2(0, 0), 0);
assertEq(i.t_or2(1, 0), 1);
assertEq(i.t_or2(0, 1), 1);
assertEq(i.t_or2(1, 1), 1);
assertEq(i.t_or3(1, 1, 0), 1);
assertEq(i.t_or3(0, 1, 1), 1);
assertEq(i.t_or3(1, 1, 1), 1);
assertEq(i.t_or3(0, 0, 0), 0);
assertEq(i.t_or3v(0, 0, 0), 0);
assertEq(i.t_or3v(0, 2, 0), 2);
assertEq(i.t_or3v(0, 3, 2), 3);
assertEq(i.t_trap(0), 0);
let thrown = false; try { i.t_trap(1) } catch (e) { thrown = true }; assertEq(thrown, true);
},
function(err) { throw err }).catch(function (e) {
print('FAILURE: ' + e);
quit(1);
})
")
(defmodule Case
(defconst g i32 5)
(defun+ (t_case_1 (n i32) -> i32)
(case n
((0) 1)
((1 2 g) 2)
((-1) 4)
(else 3)))
(defun- (getchar -> i32))
(defun+ (t_case2 (cur i32) -> i32)
(loop LEX
(case cur
((0)
(break LEX -1))
((1)
(set! cur (getchar)))
((2)
(comment))
((3)
(set! cur (getchar))
(break LEX 0))
((4)
(break LEX (sharp)))
(else
(cond ((pred? cur)
(break LEX (symbol)))
(else
(badchar cur)))))))
(defun (comment))
(defun (sharp -> i32) 0)
(defun (pred? (n i32) -> i32) 0)
(defun (symbol -> i32) 0)
(defun (badchar (n i32)))
)
(js "
Case.compile().then(function(module) {
let i = new WebAssembly.Instance(module, {lib:Case.lib, '':{getchar:() => 0}}).exports;
assertEq(i.t_case_1(0), 1);
assertEq(i.t_case_1(1), 2);
assertEq(i.t_case_1(2), 2);
assertEq(i.t_case_1(3), 3);
assertEq(i.t_case_1(4), 3);
assertEq(i.t_case_1(5), 2);
assertEq(i.t_case_1(6), 3);
assertEq(i.t_case_1(-1), 4);
assertEq(i.t_case_1(-2), 3);
},
function(err) { throw err }).catch(function (e) {
print('FAILURE: ' + e);
quit(1);
})
")
(defmodule Let
(defun (g1 (v i32)) v)
(defun (g2 (v i64)) v)
(defun (g3 (v f64)) v)
(defun+ (t1 (n i32))
(let ((k 1)
(j 3.14)
(h L.0))
(g1 k)
(g3 j)
(g2 h))
(let ((k L.1)
(h 3)
(v 0.0))
(g1 h)
(g2 k)
(g3 v)))
(defun+ (t2 (n i32) (m i32) -> i32)
(let ((n m)
(m n))
(+ (* n 1000) m)))
)
(js "
Let.compile().then(function(module) {
let ins = new WebAssembly.Instance(module, {lib:Let.lib}).exports;
assertEq(ins.t1(10), undefined);
assertEq(ins.t2(1,2), 2001);
},
function(err) { throw err }).catch(function (e) {
print('FAILURE: ' + e);
quit(1);
})
")
(defmodule LetStar
(defun+ (f (n i32) -> i32)
(let* ((n (+ n 1))
(n (+ n 2))
(n (+ n 3)))
n)))
(js "
LetStar.compile().then(function(module) {
let ins = new WebAssembly.Instance(module, {lib:LetStar.lib}).exports;
assertEq(ins.f(0), 6);
},
function(err) { throw err }).catch(function (e) {
print('FAILURE: ' + e);
quit(1);
})
")
;; test inc! and dec! on both locals and globals and fields
(defmodule IncDec
(defclass Box
(v1 i32)
(v2 i32))
(defun+ (test (key i32) -> i32)
(let ((b (new Box 0 0)))
(inc! (*v1 b))
(dec! (*v2 b))
(case key
((0) (*v1 b))
((1) (*v2 b))
(else -10)))))
(js "
IncDec.compile().then(function(module) {
let ins = new WebAssembly.Instance(module, {lib:IncDec.lib}).exports;
assertEq(ins.test(0), 1)
assertEq(ins.test(1), -1)
},
function(err) { throw err }).catch(function (e) {
print('FAILURE: ' + e);
quit(1);
})
")
(defmodule Do
(defvar+ v i32 0)
(defvar+ k i32 0)
(defun+ (test -> i32)
(do ((i 0 (+ i 1))
(j 0 (- j 1)))
((= i 3) j)
(set! v (+ v i))
(set! k (+ k j)))))
(js "
Do.compile().then(function(module) {
let ins = new WebAssembly.Instance(module, {lib:Do.lib}).exports;
assertEq(ins.test(), -3);
assertEq(ins.v.value, 3);
assertEq(ins.k.value, -3);
},
function(err) { throw err }).catch(function (e) {
print('FAILURE: ' + e);
quit(1);
})
")
| false |
c95a28d3d99bd7f6f07282e30b55e948104028e0
|
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
|
/10.1/10.1-7.scm
|
aa2cff3cea45b5e5af72fdb316c7dda9a43da8eb
|
[] |
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 | 571 |
scm
|
10.1-7.scm
|
(require-extension syntax-case check)
(require '../10.1/section)
(import* section-10.1
make-queue
queue-data
queue-push!
queue-pop!)
;;; queue-push! is Theta(2n), where n is the length of the stack;
;;; while queue-pop! is Theta(3n) because of the extra vector-fill!
(let ((queue (make-queue (make-vector 6 #f) 0 0)))
(queue-push! queue 4)
(queue-push! queue 1)
(queue-push! queue 3)
(check (queue-pop! queue) => 3)
(queue-push! queue 8)
(check (queue-pop! queue) => 8)
(check (queue-data queue) => '#(4 #f #f #f #f 1)))
| false |
6257a6de826d723a0808daddc2f4a03d948c13a8
|
be32518c6f54b0ab1eaf33f53405ac1d2e1023c2
|
/np/lang/macros/test/codegen/test-codegen-terminals.ss
|
672215ddcaa1c5ee0c761a336666b43ca01a00cf
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
ilammy/np
|
7990302bc30fe7802a7f4fc33d8fa7449ef8b011
|
0e3cbdea0eb2583f9b272d97bc408011af6a7947
|
refs/heads/master
| 2016-09-05T17:11:03.893011 | 2015-06-13T16:37:39 | 2015-06-13T16:37:39 | 23,740,287 | 1 | 0 | null | 2015-06-13T16:39:43 | 2014-09-06T17:19:46 |
Scheme
|
UTF-8
|
Scheme
| false | false | 5,899 |
ss
|
test-codegen-terminals.ss
|
(import (scheme base)
(only (srfi 1) every first second)
(np lang macros codegen)
(np lang descriptions definitions)
(sr ck)
(sr ck kernel)
(te base)
(te conditions assertions)
(te utils verify-test-case))
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
(define-test-case (terminals:standalone "Code generation for standalone terminal forms")
(define-syntax for
(syntax-rules ()
((_ defs normalized-forms . body)
(let ((defs ($ ($generate-standalone-terminal-definitions normalized-forms))))
. body )) ) )
(define (assert-list-of n list)
(assert-true (list? list))
(assert-= n (length list))
(assert-true (every terminal-definition? list)) )
(define (assert-def def name predicate meta-variables)
(assert-eq name (terminal-name def))
(assert-eqv predicate (terminal-predicate def))
(assert-equal meta-variables (terminal-meta-variables def)) )
(define-test ("Empty list")
(for defs '()
(assert-list-of 0 defs) ) )
(define-test ("Smoke test")
(for defs '((number number? (n)))
(assert-list-of 1 defs)
(assert-def (first defs) 'number number? '(n)) ) )
(define-test ("Does not change meta-variable order")
(for defs '((number number? (a b c)))
(assert-list-of 1 defs)
(assert-def (first defs) 'number number? '(a b c)) ) )
(define-test ("Can handle several terminals and does not change their order")
(for defs '((number number? (a b c)) (pair? pair? (p)))
(assert-list-of 2 defs)
(assert-def (first defs) 'number number? '(a b c))
(assert-def (second defs) 'pair? pair? '(p)) ) )
)
(verify-test-case! terminals:standalone)
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
(define-test-case (terminals:extension-addition "Code generation for extension addition terminal forms")
(define-syntax for
(syntax-rules ()
((_ defs normalized-forms . body)
(let ((defs ($ ($generate-extension-terminal-additions normalized-forms))))
. body )) ) )
(define (assert-list-of n list)
(assert-true (list? list))
(assert-= n (length list))
(assert-true (every terminal-definition? list)) )
(define (assert-def def name predicate meta-variables)
(assert-eq name (terminal-name def))
(assert-eqv predicate (terminal-predicate def))
(assert-equal meta-variables (terminal-meta-variables def)) )
(define-test ("Empty list")
(for defs '()
(assert-list-of 0 defs) ) )
(define-test ("Smoke test")
(for defs '((number number? (n)))
(assert-list-of 1 defs)
(assert-def (first defs) 'number number? '(n)) ) )
(define-test ("Does not change meta-variable order")
(for defs '((number number? (a b c)))
(assert-list-of 1 defs)
(assert-def (first defs) 'number number? '(a b c)) ) )
(define-test ("Can handle several terminals and does not change their order")
(for defs '((number number? (a b c)) (pair? pair? (p)))
(assert-list-of 2 defs)
(assert-def (first defs) 'number number? '(a b c))
(assert-def (second defs) 'pair? pair? '(p)) ) )
)
(verify-test-case! terminals:extension-addition)
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
(define-test-case (terminals:extension-removal "Code generation for extension removal terminal forms")
(define-syntax for
(syntax-rules ()
((_ rems normalized-forms . body)
(let ((rems ($ ($generate-extension-terminal-removals normalized-forms))))
. body )) ) )
(define (assert-list-of n list)
(assert-true (list? list))
(assert-= n (length list))
(assert-true (every symbol? list)) )
(define (assert-rem removed name)
(assert-eq name removed) )
(define-test ("Empty list")
(for rems '()
(assert-list-of 0 rems) ) )
(define-test ("Smoke test")
(for rems '(number)
(assert-list-of 1 rems)
(assert-rem (first rems) 'number) ) )
(define-test ("Does not change removed terminal order")
(for rems '(number pair)
(assert-list-of 2 rems)
(assert-rem (first rems) 'number)
(assert-rem (second rems) 'pair) ) )
)
(verify-test-case! terminals:extension-removal)
; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ;
(define-test-case (terminals:extension-modification "Code generation for extension modification terminal forms")
(define-syntax for
(syntax-rules ()
((_ mods normalized-forms . body)
(let ((mods ($ ($generate-extension-terminal-modifications normalized-forms))))
. body )) ) )
(define (assert-list-of n list)
(assert-true (list? list))
(assert-= n (length list))
(assert-true (every terminal-modification? list)) )
(define (assert-mod modified name added-meta-vars removed-meta-vars)
(assert-eq name (modified-terminal-name modified))
(assert-equal added-meta-vars (modified-terminal-added-meta-variables modified))
(assert-equal removed-meta-vars (modified-terminal-removed-meta-variables modified)) )
(define-test ("Empty list")
(for mods '()
(assert-list-of 0 mods) ) )
(define-test ("Smoke test")
(for mods '((number () ()))
(assert-list-of 1 mods)
(assert-mod (first mods) 'number '() '()) ) )
(define-test ("Does not change meta-variable order")
(for mods '((number (a b) (c d)))
(assert-list-of 1 mods)
(assert-mod (first mods) 'number '(a b) '(c d)) ) )
(define-test ("Does not change terminal order")
(for mods '((number (a) ()) (pair () (p)))
(assert-list-of 2 mods)
(assert-mod (first mods) 'number '(a) '())
(assert-mod (second mods) 'pair '() '(p)) ) )
)
(verify-test-case! terminals:extension-modification)
| true |
c3b1400b3023a33fa851b117feeb1f654179051e
|
b9eb119317d72a6742dce6db5be8c1f78c7275ad
|
/guile/my-fluidlet2.scm
|
26e4d834b8b1887fe4bb5cbaf2f17aaedfd95fa5
|
[] |
no_license
|
offby1/doodles
|
be811b1004b262f69365d645a9ae837d87d7f707
|
316c4a0dedb8e4fde2da351a8de98a5725367901
|
refs/heads/master
| 2023-02-21T05:07:52.295903 | 2022-05-15T18:08:58 | 2022-05-15T18:08:58 | 512,608 | 2 | 1 | null | 2023-02-14T22:19:40 | 2010-02-11T04:24:52 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,836 |
scm
|
my-fluidlet2.scm
|
;; 15 Oct 1998
(use-modules (ice-9 syncase))
(defmacro save (symbol)
`(internal-save ',symbol ,symbol))
(defmacro restore! (symbol)
`(set! ,symbol (internal-lookup ',symbol)))
(define-syntax fluid-let
(syntax-rules ()
((fluid-let ((name val) ...) body1 body2 ...)
(begin
(define internal-save #f)
(define internal-lookup #f)
(let ((saved-stuff '()))
(set! internal-save
(lambda (symbol new-value)
(let ((old-value (assq symbol saved-stuff)))
(if old-value
(set-cdr! old-value new-value)
(set! saved-stuff (cons (cons symbol new-value)
saved-stuff))))))
(set! internal-lookup
(lambda (symbol)
(let ((saved-value (assq symbol saved-stuff)))
(or saved-value (error "can't restore" symbol))
(cdr saved-value)))))
(save name) ...
(dynamic-wind
(lambda ()
(set! name val)
...)
(lambda ()
body1 body2 ...)
(lambda ()
(restore! name)
...))))))
;; a simple test
(let ((a #f)
(b #f))
(for-each display (list "A is " a "; b is " b #\newline))
(fluid-let ((a 3)
(b 4))
(for-each display (list "Sum of fluid values is " (+ a b) #\newline))
(internal-lookup a))
(for-each display (list "A is " a "; b is " b #\newline)))
| true |
41eea1dba8444f98f7995c798ae5d2f69c1bd394
|
84c9e7520891b609bff23c6fa3267a0f7f2b6c2e
|
/2.3-rectangle.scm
|
be98d476ec6679ddb53b49485d910c3d2745e3c4
|
[] |
no_license
|
masaedw/sicp
|
047a4577cd137ec973dd9a7bb0d4f58d29ef9cb0
|
11a8adf49897465c4d8bddb7e1afef04876a805d
|
refs/heads/master
| 2020-12-24T18:04:01.909864 | 2014-01-23T11:10:11 | 2014-01-23T11:17:38 | 6,839,863 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 957 |
scm
|
2.3-rectangle.scm
|
(load "./2.2-segment.scm")
(define (square x) (* x x))
(define (length-segment s)
(let ((start (start-segment s))
(end (end-segment s)))
(sqrt (+ (square (- (x-point start) (x-point end)))
(square (- (y-point start) (y-point end)))))))
;; 底辺と高さバージョン
(define (make-rectangle bl h) (cons bl h))
(define (width-rectangle r)
(length-segment (car r)))
(define (height-rectangle r) (cdr r))
;; 対角線と底辺のx軸からの角度バージョン
(define (make-rectangle bl h)
(define (perimeter-rectangle r)
(* 2 (+ (width-rectangle r)
(height-rectangle r))))
(define (area-rectangle r)
(* (width-rectangle r)
(height-rectangle r)))
(define (main args)
(define rect (make-rectangle (make-segment (make-point 0 0)
(make-point 0 5))
5))
(print (perimeter-rectangle rect))
(print (area-rectangle rect)))
| false |
0ee6d6d3b2ef59fc08266580725bac901cc64535
|
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
|
/lib/yuniapp/util/openlibfile.sls
|
3a7f360336b6bfb704e84e886eccc41d655fb711
|
[
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
okuoku/yuni
|
8be584a574c0597375f023c70b17a5a689fd6918
|
1859077a3c855f3a3912a71a5283e08488e76661
|
refs/heads/master
| 2023-07-21T11:30:14.824239 | 2023-06-11T13:16:01 | 2023-07-18T16:25:22 | 17,772,480 | 36 | 6 |
CC0-1.0
| 2020-03-29T08:16:00 | 2014-03-15T09:53:13 |
Scheme
|
UTF-8
|
Scheme
| false | false | 1,070 |
sls
|
openlibfile.sls
|
(library (yuniapp util openlibfile)
(export openlibfile)
(import (yuni scheme)
(yuni compat file-ops))
;;
(define (libname->filename libname)
(define (itr acc cur)
(if (pair? cur)
(let ((a (car cur)))
(itr (string-append acc "/" (symbol->string a)) (cdr cur)))
acc) )
(itr "" libname))
(define (mkdirp-1! prefix libname)
(unless (= 1 (length libname))
(let* ((dirname (car libname))
(pth (string-append prefix "/" (symbol->string dirname))))
(unless (file-directory? pth)
(create-directory pth))
(mkdirp-1! pth (cdr libname)))))
(define (openlibfile output? libname prefix suffix) ;; => port / #f
(when output?
(mkdirp-1! prefix libname))
(let* ((f (libname->filename libname))
(fn (string-append prefix "/" f suffix)))
(cond
(output?
(when (file-exists? fn)
(delete-file fn))
(open-output-file fn))
(else
(and (file-exists? fn)
(open-input-file fn))))))
)
| false |
0ca4622a5c42ac27fe4de75122b3e38fdba752b1
|
f4f3fa828c89a435dfde7f814964e79926850e23
|
/iset-test.scm
|
9982ed086b532507f580f87039cd2f3053be45d5
|
[
"BSD-2-Clause"
] |
permissive
|
kevinwortman/Scheme-immutable-data-structures
|
36ab692912bed18616b132420fa49e1503d85e8f
|
861327ef70638508a9f2024949e7ef2dba9c081e
|
refs/heads/master
| 2021-01-23T21:42:43.876475 | 2020-09-14T17:12:53 | 2020-09-14T17:12:53 | 11,671,684 | 12 | 2 |
BSD-2-Clause
| 2020-09-14T17:12:54 | 2013-07-25T21:39:26 |
Scheme
|
UTF-8
|
Scheme
| false | false | 5,090 |
scm
|
iset-test.scm
|
(import
(chibi test)
(scheme comparator)
(scheme generator)
(immutable set)
(scheme base)
(scheme write)
(srfi 1)
(srfi 26))
(define number-comparator
(make-comparator real? = < (lambda (x . o) (exact (abs (round x))))))
(let* ((cmp number-comparator)
(s0 (iset cmp))
(l3 '(2 4 6))
(s3 (iset cmp 6 4 2))
(always-false (lambda () #f))
(at-least-3 (cute >= <> 3))
(add1 (cute + 1 <>)))
;; iset
(test '() (iset->list s0))
(test '(2 4 6) (iset->list s3))
;; iset-tabulate
(test '(1 4 9)
(iset->list
(iset-tabulate cmp
3
(lambda (i)
(expt (+ 1 i) 2)))))
;; iset-unfold
(test '(-2 -1 0)
(iset->list
(iset-unfold cmp
(cute = 3 <>)
(cute - <>)
(cute + <> 1)
0)))
;; iset?
(test #t (iset? s0))
(test #t (iset? s3))
(test #f (iset? '()))
;; iset-empty?
(test #t (iset-empty? s0))
(test #f (iset-empty? s3))
;; iset-member?
(test #f (iset-member? s0 1))
(test #f (iset-member? s3 1))
(test #t (iset-member? s3 2))
(test #f (iset-member? s3 3))
(test #t (iset-member? s3 4))
(test #f (iset-member? s3 5))
(test #t (iset-member? s3 6))
(test #f (iset-member? s3 7))
;; iset-min
(test-error (iset-min s0))
(test 2 (iset-min s3))
;; iset-max
(test-error (iset-max s0))
(test 6 (iset-max s3))
;; iset-comparator
(test-assert (eqv? number-comparator (iset-comparator s3)))
;; iset-predecessor
;; iset-successor
;; TODO
;; iset-adjoin
(let ((s (iset-adjoin s0 7)))
(test '(7) (iset->list s))
(test 1 (iset-size s)))
(let ((s (iset-adjoin s3 1)))
(test '(1 2 4 6) (iset->list s))
(test 4 (iset-size s)))
(let ((s (iset-adjoin s3 2)))
(test '(2 4 6) (iset->list s))
(test 3 (iset-size s)))
;; iset-adjoin-all
(let ((s (iset-adjoin-all s3 '(8 -4 4))))
(test '(-4 2 4 6 8) (iset->list s))
(test 5 (iset-size s)))
;; iset-replace
;; effectual
(let ((s (iset-replace s3 1)))
(test '(1 2 4 6) (iset->list s))
(test 4 (iset-size s)))
;; ineffectual
(let ((s (iset-replace s3 4)))
(test '(2 4 6) (iset->list s))
(test 3 (iset-size s)))
;; iset-delete
;; effectual
(let ((s (iset-delete s3 4)))
(test '(2 6) (iset->list s))
(test 2 (iset-size s)))
;; ineffectual
(let ((s (iset-delete s3 5)))
(test '(2 4 6) (iset->list s3))
(test 3 (iset-size s)))
;; iset-delete-elements
;; effectual
(let ((s (iset-delete-elements s3 '(5 4))))
(test '(2 6) (iset->list s))
(test 2 (iset-size s)))
;; ineffectual
(let ((s (iset-delete-elements s3 '(5 1 3))))
(test '(2 4 6) (iset->list s))
(test 3 (iset-size s)))
;; iset-find
;; success
(test 2 (iset-find s3 2 always-false))
(test 4 (iset-find s3 4 always-false))
(test 6 (iset-find s3 6 always-false))
;; failure
(test #f (iset-find s3 1 always-false))
(test #f (iset-find s3 3 always-false))
(test #f (iset-find s3 5 always-false))
(test #f (iset-find s3 7 always-false))
;; iset-count
(test 3 (iset-count even? s3))
(test 0 (iset-count odd? s3))
;; iset-any
(test #t (iset-any even? s3))
(test #f (iset-any odd? s3))
;; iset-every
(test #t (iset-every even? s3))
(test #f (iset-every odd? s3))
;; iset-range=
;; iset-range<
;; iset-range>
;; iset-range<=
;; iset-range>=
;; TODO
;; iset-filter
(test '(4 6)
(iset->list (iset-filter at-least-3 s3)))
;; iset-remove
(test '(2)
(iset->list (iset-remove at-least-3 s3)))
;; iset-partition
(let-values (((yay nay) (iset-partition at-least-3 s3)))
(test '(4 6) (iset->list yay))
(test '(2) (iset->list nay)))
;; iset-fold
(test (fold + 0 l3)
(iset-fold + 0 s3))
;; iset-fold-right
(test (fold-right cons '() l3)
(iset-fold-right cons '() s3))
;; iset-map/monotone
;; same comparator
(test '(3 5 7)
(iset->list (iset-map/monotone add1 s3)))
;; new comparator
(test '(2.0 4.0 6.0)
(iset->list (iset-map/monotone inexact s3 real-comparator)))
;; iset-map
;; monotone tests work
(test '(3 5 7)
(iset->list (iset-map add1 s3)))
(test '(2.0 4.0 6.0)
(iset->list (iset-map inexact s3 real-comparator)))
;; non-monotone
(test '(-6 -4 -2)
(iset->list (iset-map - s3)))
;; iset-for-each
(let ((sum 0))
(iset-for-each (lambda (x)
(set! sum (+ sum x)))
s3)
(test 12 sum))
;; iset=?
;; iset<?
;; iset>?
;; iset<=?
;; iset>=?
;; iset-union
;; iset-intersection
;; iset-difference
;; iset-xor
;; TODO
;; iset->list
(test '() (iset->list s0))
(test '(2 4 6) (iset->list s3))
;; increasing-list->iset
(test '(1 2 3)
(iset->list (increasing-list->iset cmp '(1 2 3))))
;; list->iset
(test '(1 2 3)
(iset->list (list->iset cmp '(3 2 1))))
;; iset->generator
(test '(2 4 6)
(generator->list (iset->generator s3)))
;; increasing-generator->iset
(test '(1 2 3)
(iset->list (increasing-generator->iset cmp (list->generator '(1 2 3)))))
;; generator->iset
(test '(1 2 3)
(iset->list (generator->iset cmp (list->generator '(3 2 1)))))
) ; let
| false |
191d8e0791346d3ca90d1a51ca5ab4745c03e15f
|
6be443e2def01b1f9a5285f1287983e10e167515
|
/ch2/2-14.scm
|
eaf0ba1c34409c4dbbbea6d7aa9aa208061bffb7
|
[
"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 | 1,763 |
scm
|
2-14.scm
|
(define (make-interval a b)
(cons a b))
(define (center i)
(/ (+ (lower-bound i) (upper-bound i)) 2))
(define (make-center-percent center percentage)
(make-interval (- center (* center percentage))
(+ center (* center percentage))))
(define (upper-bound interval)
(max (car interval) (cdr interval)))
(define (lower-bound interval)
(min (car interval) (cdr interval)))
(define (percent interval)
(/ (- (upper-bound interval) (center interval)) (center interval)))
(define (add-interval x y)
(make-interval (+ (lower-bound x) (lower-bound y))
(+ (upper-bound x) (lower-bound y))))
(define (mul-interval x y)
(let ((p1 (* (lower-bound x) (lower-bound y)))
(p2 (* (lower-bound x) (upper-bound y)))
(p3 (* (upper-bound x) (lower-bound y)))
(p4 (* (upper-bound x) (upper-bound y))))
(make-interval (min p1 p2 p3 p4)
(max p1 p2 p3 p4))))
(define (div-interval x y)
(mul-interval x (make-interval (/ 1.0 (upper-bound y))
(/ 1.0 (lower-bound y)))))
(define (par1 r1 r2)
(div-interval (mul-interval r1 r2)
(add-interval r1 r2)))
(define (par2 r1 r2)
(let ((one (make-interval 1 1)))
(div-interval one (add-interval (div-interval one r1)
(div-interval one r2)))))
(print (par1 (make-center-percent 10 0.1) (make-center-percent 50 0.1)))
(print (par2 (make-center-percent 10 0.1) (make-center-percent 50 0.1)))
(print (par1 (make-interval 5 15) (make-center-percent 5 15)))
(print (par2 (make-center-percent 5 15) (make-center-percent 5 15)))
(print (div-interval (make-interval 5 15) (make-interval 5 15)))
(print (div-interval (make-interval 1 1) (make-interval 5 15)))
| false |
bf2e843067ce75b8ce417c65a14b25dce5726a44
|
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
|
/packages/slib/dft.scm
|
690095c7f77685e3ac23d90cac0d5c253c38c148
|
[
"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 | 6,699 |
scm
|
dft.scm
|
;;;"dft.scm" Discrete Fourier Transform
;Copyright (C) 1999, 2003, 2006 Aubrey Jaffer
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
;;;; For one-dimensional power-of-two length see:
;;; Introduction to Algorithms (MIT Electrical
;;; Engineering and Computer Science Series)
;;; by Thomas H. Cormen, Charles E. Leiserson (Contributor),
;;; Ronald L. Rivest (Contributor)
;;; MIT Press; ISBN: 0-262-03141-8 (July 1990)
;;; Flipped polarity of exponent to agree with
;;; http://en.wikipedia.org/wiki/Discrete_Fourier_transform
(require 'array)
(require 'logical)
(require 'subarray)
(require 'multiarg-apply)
;;@code{(require 'dft)} or
;;@code{(require 'Fourier-transform)}
;;@ftindex dft, Fourier-transform
;;
;;@code{fft} and @code{fft-1} compute the Fast-Fourier-Transforms
;;(O(n*log(n))) of arrays whose dimensions are all powers of 2.
;;
;;@code{sft} and @code{sft-1} compute the Discrete-Fourier-Transforms
;;for all combinations of dimensions (O(n^2)).
(define (dft:sft1d! new ara n dir)
(define scl (if (negative? dir) (/ 1.0 n) 1))
(define pi2i/n (/ (* 0-8i (atan 1) dir) n))
(do ((k (+ -1 n) (+ -1 k)))
((negative? k) new)
(let ((sum 0))
(do ((j (+ -1 n) (+ -1 j)))
((negative? j) (array-set! new sum k))
(set! sum (+ sum (* (exp (* pi2i/n j k))
(array-ref ara j)
scl)))))))
(define (dft:fft1d! new ara n dir)
(define scl (if (negative? dir) (/ 1.0 n) 1))
(define lgn (integer-length (+ -1 n)))
(define pi2i (* 0-8i (atan 1) dir))
(do ((k 0 (+ 1 k)))
((>= k n))
(array-set! new (* (array-ref ara k) scl) (reverse-bit-field k 0 lgn)))
(do ((s 1 (+ 1 s))
(m (expt 2 1) (expt 2 (+ 1 s))))
((> s lgn) new)
(let ((w_m (exp (/ pi2i m)))
(m/2-1 (+ (quotient m 2) -1)))
(do ((j 0 (+ 1 j))
(w 1 (* w w_m)))
((> j m/2-1))
(do ((k j (+ m k))
(k+m/2 (+ j m/2-1 1) (+ m k m/2-1 1)))
((>= k n))
(let ((t (* w (array-ref new k+m/2)))
(u (array-ref new k)))
(array-set! new (+ u t) k)
(array-set! new (- u t) k+m/2)))))))
;;; Row-major order is suboptimal for Scheme.
;;; N are copied into and operated on in place
;;; A[a, *, c] --> N1[c, a, *]
;;; N1[c, *, b] --> N2[b, c, *]
;;; N2[b, *, a] --> N3[a, b, *]
(define (dft:rotate-indexes idxs)
(define ridxs (reverse idxs))
(cons (car ridxs) (reverse (cdr ridxs))))
(define (dft:dft prot ara dir transform-1d)
(define (ranker ara rdx dims)
(define ndims (dft:rotate-indexes dims))
(if (negative? rdx)
ara
(let ((new (apply make-array prot ndims))
(rdxlen (car (last-pair ndims))))
(define x1d
(cond (transform-1d)
((eqv? rdxlen (expt 2 (integer-length (+ -1 rdxlen))))
dft:fft1d!)
(else dft:sft1d!)))
(define (ramap rdims inds)
(cond ((null? rdims)
(x1d (apply subarray new (dft:rotate-indexes inds))
(apply subarray ara inds)
rdxlen dir))
((null? inds)
(do ((i (+ -1 (car rdims)) (+ -1 i)))
((negative? i))
(ramap (cddr rdims)
(cons #f (cons i inds)))))
(else
(do ((i (+ -1 (car rdims)) (+ -1 i)))
((negative? i))
(ramap (cdr rdims) (cons i inds))))))
(if (= 1 (length dims))
(x1d new ara rdxlen dir)
(ramap (reverse dims) '()))
(ranker new (+ -1 rdx) ndims))))
(ranker ara (+ -1 (array-rank ara)) (array-dimensions ara)))
;;@args array prot
;;@args array
;;@var{array} is an array of positive rank. @code{sft} returns an
;;array of type @2 (defaulting to @1) of complex numbers comprising
;;the @dfn{Discrete Fourier Transform} of @var{array}.
(define (sft ara . prot)
(dft:dft (if (null? prot) ara (car prot)) ara 1 dft:sft1d!))
;;@args array prot
;;@args array
;;@var{array} is an array of positive rank. @code{sft-1} returns an
;;array of type @2 (defaulting to @1) of complex numbers comprising
;;the inverse Discrete Fourier Transform of @var{array}.
(define (sft-1 ara . prot)
(dft:dft (if (null? prot) ara (car prot)) ara -1 dft:sft1d!))
(define (dft:check-dimensions ara name)
(for-each (lambda (n)
(if (not (eqv? n (expt 2 (integer-length (+ -1 n)))))
(slib:error name "array length not power of 2" n)))
(array-dimensions ara)))
;;@args array prot
;;@args array
;;@var{array} is an array of positive rank whose dimensions are all
;;powers of 2. @code{fft} returns an array of type @2 (defaulting to
;;@1) of complex numbers comprising the Discrete Fourier Transform of
;;@var{array}.
(define (fft ara . prot)
(dft:check-dimensions ara 'fft)
(dft:dft (if (null? prot) ara (car prot)) ara 1 dft:fft1d!))
;;@args array prot
;;@args array
;;@var{array} is an array of positive rank whose dimensions are all
;;powers of 2. @code{fft-1} returns an array of type @2 (defaulting
;;to @1) of complex numbers comprising the inverse Discrete Fourier
;;Transform of @var{array}.
(define (fft-1 ara . prot)
(dft:check-dimensions ara 'fft-1)
(dft:dft (if (null? prot) ara (car prot)) ara -1 dft:fft1d!))
;;@code{dft} and @code{dft-1} compute the discrete Fourier transforms
;;using the best method for decimating each dimension.
;;@args array prot
;;@args array
;;@0 returns an array of type @2 (defaulting to @1) of complex
;;numbers comprising the Discrete Fourier Transform of @var{array}.
(define (dft ara . prot)
(dft:dft (if (null? prot) ara (car prot)) ara 1 #f))
;;@args array prot
;;@args array
;;@0 returns an array of type @2 (defaulting to @1) of
;;complex numbers comprising the inverse Discrete Fourier Transform of
;;@var{array}.
(define (dft-1 ara . prot)
(dft:dft (if (null? prot) ara (car prot)) ara -1 #f))
;;@noindent
;;@code{(fft-1 (fft @var{array}))} will return an array of values close to
;;@var{array}.
;;
;;@example
;;(fft '#(1 0+i -1 0-i 1 0+i -1 0-i)) @result{}
;;
;;#(0.0 0.0 0.0+628.0783185208527e-18i 0.0
;; 0.0 0.0 8.0-628.0783185208527e-18i 0.0)
;;
;;(fft-1 '#(0 0 0 0 0 0 8 0)) @result{}
;;
;;#(1.0 -61.23031769111886e-18+1.0i -1.0 61.23031769111886e-18-1.0i
;; 1.0 -61.23031769111886e-18+1.0i -1.0 61.23031769111886e-18-1.0i)
;;@end example
| false |
34fb0fe8c610193698108ed89dd08bdbf44f5e85
|
5dfe2cdb9e9b80915a878154093bf073df904bf0
|
/chap33.scm
|
005662159111f804bde44ff4ac9f573a6caa7a88
|
[] |
no_license
|
Acedio/sicp-exercises
|
6f4b964f0d7a4795b0ec584a84c9ea5471677829
|
38844977bf41c23c5dde42d84583429439344da9
|
refs/heads/master
| 2020-04-16T00:20:47.251218 | 2018-03-31T03:40:42 | 2018-03-31T03:40:42 | 39,810,760 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,910 |
scm
|
chap33.scm
|
; ex 3.17
(define (bad-count-pairs x)
(if (not (pair? x))
0
(+ (bad-count-pairs (car x))
(bad-count-pairs (cdr x))
1)))
(define (count-pairs x)
(define (contains col item)
(if (not (pair? col))
#f
(if (eq? (car col)
item)
#t
(contains (cdr col) item))))
(let ((seen '()))
(define (iter cur)
(if (and (pair? cur)
(not (contains seen cur)))
(begin (set! seen (cons cur seen))
(+ (iter (car cur))
(iter (cdr cur))
1))
0))
(iter x)))
(define c (cons '() (cons 1 2)))
(set-car! c (cons (cdr c) (cdr c)))
(define d3 (cons 1 2))
(define d2 (cons d3 d3))
(define d1 (cons d2 d2))
; ex 3.23
(define (make-node prev next data)
(list prev next data))
(define (get-node-prev node)
(car node))
(define (set-node-prev! node prev)
(set-car! node prev))
(define (get-node-next node)
(cadr node))
(define (set-node-next! node next)
(set-car! (cdr node) next))
(define (get-node-data node)
(caddr node))
(define (set-node-data! node data)
(set-car! (cddr node) data))
(define (make-deque)
(cons '() '()))
(define (empty-deque? deque)
(null? (car deque)))
(define (front-deque deque)
(if (empty-deque? deque)
(error "front-deque on empty deque!")
(get-node-data (car deque))))
(define (rear-deque deque)
(if (empty-deque? deque)
(error "rear-deque on empty deque!")
(get-node-data (cdr deque))))
(define (print-deque deque)
(define (iter node)
(if (null? node)
'()
(begin
(display (get-node-data node))
(display " ")
(iter (get-node-next node)))))
(if (empty-deque? deque)
(display "empty!")
(iter (car deque))))
(define (front-insert-deque! deque data)
(if (empty-deque? deque)
(begin
(set-car! deque (make-node '() '() data))
(set-cdr! deque (car deque)))
(let ((next (car deque)))
(set-car! deque (make-node '() next data))
(set-node-prev! next (car deque)))))
(define (front-delete-deque! deque)
(if (empty-deque? deque)
(error "front-delete-deque! on empty deque!")
(let ((next (get-node-next (car deque))))
(set-car! deque next)
(if (empty-deque? deque)
'()
(set-node-prev! next '())))))
(define (rear-insert-deque! deque data)
(if (empty-deque? deque)
(begin
(set-car! deque (make-node '() '() data))
(set-cdr! deque (car deque)))
(let ((prev (cdr deque)))
(set-cdr! deque (make-node prev '() data))
(set-node-next! prev (cdr deque)))))
(define (rear-delete-deque! deque)
(if (empty-deque? deque)
(error "rear-delete-deque! on empty deque!")
(let ((prev (get-node-prev (cdr deque))))
(if (null? prev)
(set-car! deque '())
(begin
(set-cdr! deque prev)
(set-node-next! prev '()))))))
| false |
ba3babef60d73739e30758678ff3af4347df8936
|
852ee43ffa97f0240b508b268a73dc168064f4fb
|
/day2/day2.scm
|
b88a72a423b232daaca54c7cfb8a53701afaa7be
|
[] |
no_license
|
lilactown/advent-2020
|
1b5c0f92f03996124fc42f9abc343b10114154a8
|
1dc983332de098ecb0aeb83a0999a29ac36bb924
|
refs/heads/main
| 2023-01-28T14:29:25.375709 | 2020-12-09T17:00:37 | 2020-12-09T17:00:37 | 317,655,853 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,337 |
scm
|
day2.scm
|
#!/usr/local/bin/guile -L .. -s
!#
(use-modules
;; for list operation find
(srfi srfi-1)
;; for format ~d
(ice-9 format)
(common))
(define (first-policy policy)
(car policy))
(define (second-policy policy)
(car (cdr policy)))
(define (policy-char policy)
(car (cdr (cdr policy))))
(define (parse-passwords+policys input)
(map
(lambda (line)
(let ((split-line (string-split line #\:)))
(let ((split-policy (string-split (car split-line) #\space))
(password (string-trim (car (cdr split-line)))))
(let ((occurences (string-split (car split-policy) #\-)))
(list (list
(string->number (car occurences)) ;; min
(string->number (car (cdr occurences))) ;; max
(car (string->list (car (cdr split-policy))))) ;; character
(string->list password))))))
input))
(define test-passwords
(parse-passwords+policys
(string-split "1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc" #\newline)))
(define (policy-match? policy password occurence-count)
(let ((policy-min (first-policy policy))
(policy-max (second-policy policy))
(char (policy-char policy)))
(cond
((< policy-max occurence-count) #f)
((null? password) (<= policy-min occurence-count))
(else (policy-match?
policy
(cdr password)
(if (eq? char (car password))
(+ 1 occurence-count)
occurence-count))))))
(define (part-1 input)
(count (lambda (policy+pw)
(policy-match? (car policy+pw) (car (cdr policy+pw)) 0))
input))
(assert "Test password policy"
(= 2 (part-1 test-passwords)))
(define passwords+policies
(parse-passwords+policys (read-file "day2-input")))
(format #t "Part 1: ~d\n" (part-1 passwords+policies))
(define (policy-match2? policy password)
(let ((char (policy-char policy)))
(not (eq? (eq? char (list-ref password (- (first-policy policy) 1)))
(eq? char (list-ref password (- (second-policy policy) 1)))))))
(define (part-2 input)
(count (lambda (policy+pw)
(policy-match2? (car policy+pw) (car (cdr policy+pw))))
input))
(assert "Test part 2 policy"
(= 1 (part-2 test-passwords)))
(format #t "Part 2: ~d\n" (part-2 passwords+policies))
| false |
8ffc4e37cb7762f9a3f25e9f32ea9d2d4f2920d5
|
080465977523100c18e7e8a052e67cc44d6bd176
|
/xmonad/.xmonad/bin/status.scm
|
849e45c7f16a935ee8e576710277262f6638bda6
|
[] |
no_license
|
mytoh/dotfiles
|
af4c40c090c17b20ccad1c02eb3b0a632fc0803a
|
4756f8976c9f8aa21b450759d65a460e56d6591b
|
refs/heads/master
| 2020-04-06T07:04:30.243973 | 2018-07-02T22:32:53 | 2018-07-02T22:32:53 | 909,274 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,950 |
scm
|
status.scm
|
#!/usr/bin/env gosh
;; -*- coding: utf-8 -*-
(use gauche.process)
(use gauche.parseopt)
(use gauche.sequence)
(use util.match)
(use text.tree)
(use file.util)
(use srfi-1)
(use srfi-13)
(use srfi-19)
(use kirjasto.grafiikka)
(define-syntax forever
;;macro for endless loop
(syntax-rules ()
((_ e1 e2 ...)
(let loop () e1 e2 ...
(sys-sleep 3) ; sleep 5 minutes
(loop)))))
;; dzen helper
(define fg
(lambda (colour)
(tree->string
`("^fg(" ,colour ")"))))
(define bg
(lambda (colour)
(cond
(colour
(string-concatenate
`("^bg(" ,colour ")")))
(else
"^bg()")
)))
(define fn
(lambda (font)
(tree->string
`("^fn(" ,font ")"))))
;; xpm from powerline.el www.emacswiki.org/emacs/powerline.el
(define make-temp-dir
(lambda ()
(make-directory*
(build-path (temporary-directory)
"dzen"))
(build-path (temporary-directory)
"dzen")))
(define arrow-left
"/* XPM */
static char * arrow_left[] = {
/* <width/cols> <height/rows> <colors> <char on pixel>*/
\"10 12 2 1\",
\". c ~a\",
\" c ~a\",
\" .\",
\" ..\",
\" ...\",
\" ....\",
\" .....\",
\" ......\",
\" ......\",
\" .....\",
\" ....\",
\" ...\",
\" ..\",
\" .\",
};
"
)
(define arrow-left-xpm
(lambda (c1 c2)
(let ((icon-name
(build-path (make-temp-dir)
(string-append
"arrow-left"
"_"
(string-trim c1 #\#) "_"
(string-trim c2 #\#)
".xpm"))))
(make-xpm icon-name arrow-left c1 c2))))
(define icon
(lambda (name)
(string-concatenate
`("^i("
,name
")"))))
;; printers
(define (date)
(string-concatenate
`(,(fg "#303633")
,(date->string (current-date)))))
(define (memory)
(fifth
(take-right
(string-split
(process-output->string "vmstat -h")
" ")
19)))
(define (fs)
(let* ((fs-lst (map (lambda (s) (string-split s #/\s+/))
(cdr (process-output->string-list "df -h"))))
(find-fs (lambda (lst fs-name)
(find (lambda (l)
(cond ((string=? (sixth l) fs-name)
l)
(else
#f)))
lst)))
(root (find-fs fs-lst "/"))
(quatre (find-fs fs-lst "/nfs/quatre"))
(mypassport (find-fs fs-lst "/nfs/mypassport"))
(deskstar (find-fs fs-lst "/nfs/deskstar"))
(fs-remain (lambda (n)
(- (string->number (subseq (second n) 0 3))
(string->number (subseq (third n) 0 3))))))
(list
(cond ((list? root)
(list
(string-append
(fg "#b8b843")
"/ "
(fg "#acacac" )
(subseq (third root) 0 3) "/" (second root))))
(else
""))
(if (list? quatre)
(list
" "
(fg "#f2a2a2")
"q "
(fg "#acacac" )
(fs-remain quatre)
"G" )
"")
(if (list? mypassport)
(list
" " (fg "#f282a2")
"m "
(fg "#ffffff" )
(fs-remain mypassport)
"G" )
"")
(if (list? deskstar)
(list
" "
(fg "#f282a2")
"d "
(fg "#ffffff" )
(fs-remain deskstar)
"G")
""))))
(define (volume)
(let ((vol (string-split (process-output->string "mixer -S vol") ":"))
(pcm (string-split (process-output->string "mixer -S pcm") ":")))
(list
(fg "#43be93")
(car vol)
" "
(cadr vol)
" "
(car pcm)
" "
(cadr pcm))))
(define (mpd)
(let ((current-song (and (find-file-in-paths "mpc")
(process-output->string "mpc current"))))
(cond
(current-song
(list
(fg "#baafa9")
current-song))
(else
(list
"Not playng")))))
(define ip
(lambda ()
(process-output->string "curl --silent --ssl -x http://127.0.0.1:8118 ifconfig.me/ip")))
(define (dzen)
(tree->string
(list
(icon (arrow-left-xpm "#292929" "None"))
(bg "#292929")
(mpd)
(icon (arrow-left-xpm "#303633" "#292929"))
(bg "#303633")
(memory)
(icon (arrow-left-xpm "#444444" "#303633"))
(bg "#444444")
(fs)
(icon (arrow-left-xpm "#555555" "#444444"))
(bg "#555555")
(volume)
(icon (arrow-left-xpm "#858180" "#555555"))
(bg "#858080")
(date) " ")))
(define (main args)
(let loop ()
(print
(dzen))
(loop)))
| true |
23039979588576bea90719cad99b8aea7dbed31a
|
2bcf33718a53f5a938fd82bd0d484a423ff308d3
|
/programming/sicp/ch1/ex-1.44.scm
|
c97f4c80688d9f99692f5d26e616deaa8f59f994
|
[] |
no_license
|
prurph/teach-yourself-cs
|
50e598a0c781d79ff294434db0430f7f2c12ff53
|
4ce98ebab5a905ea1808b8785949ecb52eee0736
|
refs/heads/main
| 2023-08-30T06:28:22.247659 | 2021-10-17T18:27:26 | 2021-10-17T18:27:26 | 345,412,092 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 322 |
scm
|
ex-1.44.scm
|
;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-12.html#%_thm_1.44
(define (smooth f dx)
(define dx 0.001)
(lambda (x)
(/ (+ (f x) (f (- x dx)) (f (+ x dx)))
3)))
;; n-fold smoothed function using repeated from ex-1.43
(define (n-fold-smoothed f n)
((repeated smooth n) f))
| false |
26f9af70d19dedabf263651ab49505cd913a39ed
|
bf6fad8f5227d0b0ef78598065c83b89b8f74bbc
|
/chapter02/scheme/ex2_9_7.ss
|
628179e835afb6193d0ce9a6f186194cd390fbbd
|
[] |
no_license
|
e5pe0n/tspl
|
931d1245611280457094bd000e20b1790c3e2499
|
bc76cac2307fe9c5a3be2cea36ead986ca94be43
|
refs/heads/main
| 2023-08-18T08:21:29.222335 | 2021-09-28T11:04:54 | 2021-09-28T11:04:54 | 393,668,056 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 626 |
ss
|
ex2_9_7.ss
|
(define print
(lambda (x)
(for-each display `(,x "\n"))
)
)
(define ls
(let ([ls (cons 'a '())])
(set-cdr! ls ls)
ls
)
)
(print (length ls))
; Error: (length) bad argument type - not a non-cyclic list: (a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a...
| false |
6aed957a958d5d93b0a79013e60f035fc8bee39c
|
def26f110cf94581c6e0523383cec8c56c779d51
|
/test-all.scm
|
e19c07e4bad336a9dd459cf8b21df08cb238e6cc
|
[
"MIT"
] |
permissive
|
TaylanUB/scheme-srfis
|
f86649e4a71e8af59d2afd71bd33e96aaae4760f
|
7c4ba635c9829a35ce7134fa12db9959e4d1982a
|
refs/heads/master
| 2021-07-06T00:29:53.807790 | 2021-06-01T00:41:31 | 2021-06-01T00:41:31 | 37,764,520 | 39 | 4 | null | 2015-08-25T10:09:16 | 2015-06-20T09:20:04 |
Scheme
|
UTF-8
|
Scheme
| false | false | 597 |
scm
|
test-all.scm
|
(import (scheme base)
(scheme eval)
(scheme file)
(srfi 1)
(srfi 48)
(srfi 64))
(test-runner-current (test-runner-simple "tests.log"))
(test-begin "SRFI")
(for-each
(lambda (n)
(let ((srfi-n (string->symbol (format #f "srfi-~s" n)))
(file-name (format #f "srfi-tests/srfi-~s.sld" n))
(test-name (format #f "SRFI-~s" n)))
(when (file-exists? file-name)
(test-assert test-name
(guard (err (else #f))
(eval '(run-tests) (environment `(srfi-tests ,srfi-n))))))))
(iota 200))
(test-end "SRFI")
(test-exit)
| false |
ac00a6d711bdfeb5cbed05f380e4022e698b7df8
|
54819d742ff4fa8055a335a674640992f8c166d8
|
/main.scm
|
01528887f9bfca172731ed57309985c77603e541
|
[] |
no_license
|
h8gi/sxml
|
092e454045e3dbfb98afed593f5a2527d81edecf
|
b60a081e330cc61ee28ee724a2e88e7ac20448e7
|
refs/heads/master
| 2016-09-11T03:11:06.345104 | 2015-08-31T04:06:51 | 2015-08-31T04:06:51 | 41,655,154 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,070 |
scm
|
main.scm
|
;(set! format:max-iterations 10000)
(define (print-tag name alst closingp)
(with-output-to-string
(lambda ()
(display "<")
(when closingp
(display "/" ))
(display (string-downcase (symbol->string name)))
(for-each
(lambda (att)
(printf " ~a=\"~a\"" (string-downcase (symbol->string (car att))) (cdr att)))
alst)
(display ">"))))
(define (print-tag/ name alst)
(with-output-to-string
(lambda ()
(display "<")
(display (string-downcase (symbol->string name)))
(for-each
(lambda (att)
(printf " ~a=\"~a\"" (string-downcase (symbol->string (car att))) (cdr att)))
alst)
(display " />"))))
(define-syntax @->pairs
(syntax-rules ()
[(_ (pairs ...))
(@->pairs (pairs ...) ())]
[(_ () (ps ...))
(list ps ...)]
[(_ ((name value) rest ...) (ps ...))
(@->pairs (rest ...) (ps ... (cons 'name value)))]
[(_ ((name) rest ...) (ps ...))
(@->pairs (rest ...) (ps ... (cons 'name "")))]))
(define-syntax tag
(syntax-rules (@)
[(_ name (@ pairs ...) body ...)
(string-append (print-tag 'name (@->pairs (pairs ...)) #f)
body ...
(print-tag 'name '() #t))]
[(_ name body ...)
(tag name (@) body ...)]))
(define-syntax tag/
(syntax-rules (@)
[(_ name (@ pairs ...))
(print-tag/ 'name (@->pairs (pairs ...)))]
[(_ name)
(tag/ name (@))]))
(define-syntax define-tag
(ir-macro-transformer
(lambda (expr inject compare)
(let ((name (cadr expr))
(body (gensym)))
`(define-syntax ,(inject name)
(syntax-rules ()
[(_ ,body ...)
(tag ,(inject name) ,body ...)]))))))
(define-syntax define-tag/
(ir-macro-transformer
(lambda (expr inject compare)
(let ((name (cadr expr))
(body (gensym)))
`(define-syntax ,(inject name)
(syntax-rules ()
[(_ ,body ...)
(tag/ ,(inject name) ,body ...)]))))))
| true |
75f1c26b2355d79442670d3d82696b6f28708325
|
6b675e55991fdcfc249da935e3ff15ba62e0f2ed
|
/main.ss
|
f9818e8277c5c4565af9eb46c19201233b8b0e93
|
[] |
no_license
|
mrmathematica/MrMathematica
|
a0addbab10561e6edd1c14adf6c44fe51b8d9f03
|
801cd29e1e4ac57a71e86fa0f4b750a60068c75d
|
refs/heads/master
| 2021-06-22T09:56:52.409291 | 2020-12-30T11:46:02 | 2020-12-30T11:46:02 | 12,832,108 | 8 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 354 |
ss
|
main.ss
|
#lang racket/base
(require "light.ss"
racket/gui/base
racket/class)
(provide (all-from-out "light.ss")
Mexp->image)
(define (Mexp->image exp . lp)
(let ((r (apply MathEval `(ExportString ,exp "PNG") lp)))
(if (string? r)
(make-object image-snip% (open-input-bytes (string->bytes/latin-1 r)) 'png)
r)))
| false |
72787954a2918186356b592523eedd38bce206cb
|
2c01a6143d8630044e3629f2ca8adf1455f25801
|
/xitomatl/ssax/private-5-1/input-parse.sls
|
70d4251c870e655a428796870736bc0289035ac4
|
[
"X11-distribute-modifications-variant"
] |
permissive
|
stuhlmueller/scheme-tools
|
e103fac13cfcb6d45e54e4f27e409adbc0125fe1
|
6e82e873d29b34b0de69b768c5a0317446867b3c
|
refs/heads/master
| 2021-01-25T10:06:33.054510 | 2017-05-09T19:44:12 | 2017-05-09T19:44:12 | 1,092,490 | 5 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 811 |
sls
|
input-parse.sls
|
#!r6rs
;; Copyright 2009 Derick Eddington. My MIT-style license is in the file named
;; LICENSE from the original collection this file is distributed with.
(library (xitomatl ssax private-5-1 input-parse)
(export
peek-next-char
assert-curr-char
skip-until
skip-while
input-parse:init-buffer
next-token-old
next-token
next-token-of
*read-line-breaks*
read-text-line
read-string)
(import
(rnrs)
(xitomatl include)
(xitomatl ssax private-5-1 define-opt)
(xitomatl ssax raise)
(xitomatl ssax private-5-1 misc)
(except (srfi :13 strings)
string-copy string-for-each string->list
string-upcase string-downcase string-titlecase string-hash))
(include/resolve ("xitomatl" "ssax" "private-5-1") "input-parse.scm")
)
| false |
de7760ecb31d2f851e746d24cda85e078134bc5a
|
53cb8287b8b44063adcfbd02f9736b109e54f001
|
/csys/cache-structs.scm
|
ba38840963fa170654ef89a0fa9ca385e894bcf9
|
[] |
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 | 2,272 |
scm
|
cache-structs.scm
|
;;; these structures deal with the compilation system and the unit cache.
;;; An entry in the unit cache:
(define-struct ucache
(slots
(ufile (type string)) ; the name of the file containing the unit definition
(cifile (type string)) ; the filename of the (compiled) interface file
(sifile (type string)) ; the filename of the (uncompiled) interface file
(cfile (type string)) ; the filename of the (compiled) output file
(sfile (type string)) ; the filename of the (uncompiled) output file
(udate (type integer)) ; the write date of ufile
(idate (type integer)) ; the time stamp of the binary interface file
(stable? (type bool)) ; the stable flag
(load-prelude? (type bool)) ; true if unit uses standard prelude
;; status is initially available (in cache). It is set to loading when
;; requested and loaded once all imported units are loaded.
(status (type (enum loaded loading available)))
(ifile-loaded (type bool)) ; true when interface is loaded (modules)
(code-loaded (type bool)) ; true when the associated code is in memory
(source-files (type (list string))) ; source files in the unit
(imported-units (type (list string))) ; the filenames of imported unit files
(lisp-files (type (list (tuple string string)))) ; source/binary pairs
(modules (type (list module)))
(printers-set? (type bool))
(printers (type (list symbol)))
(optimizers-set? (type bool))
(optimizers (type (list symbol)))
(chunk-size (type (maybe int)))
))
;;; This is used to hold various flags used by the compilation system,
;;; instead of passing them all as individual arguments.
(define-struct cflags
(slots
;; Whether to load code for unit into core
(load-code? (type bool) (default '#t))
;; Whether to create an output code file.
(write-code? (type bool) (default '#t))
;; Affects whether write-code? creates a source or compiled file,
;; and whether load-code? uses the interpreter or compiler.
;; Ignored if load-code? and write-code? are both false.
(compile-code? (type bool) (default '#t))
;; Whether to create an output interface file.
(write-interface? (type bool) (default '#t))
))
| false |
7c799f5bc7461743293e165920858df5cb1ff48f
|
db4a1a32853f56c62bfc37b46d2312e699d5d82e
|
/modules/sph-info/text.scm
|
d1885d5fadfe2d4d9cad8377fefd2358752432df
|
[] |
no_license
|
sph-mn/sph-info
|
087c6210c90675d75d9aedb873fca2af8292dce3
|
9791562e0d3f84e7e484c00cc3d8231c924a1d1b
|
refs/heads/master
| 2023-08-18T21:18:08.872500 | 2023-08-13T16:50:45 | 2023-08-13T16:50:45 | 183,882,744 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,297 |
scm
|
text.scm
|
(library (sph-info text)
(export
text-routes)
(import
(rnrs sorting)
(sph)
(sph alist)
(sph hashtable)
(sph list)
(sph pattern)
(sph string)
(sph vector)
(sph web app)
(sph web app client)
(sph web app http)
(sph web shtml)
(ytilitu helper))
(define operations
(map (l (a) (pair (string-replace-char a #\- #\space) (string-replace-char a #\- #\_)))
(list-sort string<?
(append
(list "lowercase" "camelcase-to-dashes"
"remove-hash-commment-lines" "compress-whitespace-horizontal"
"compress-whitespace-vertical" "randomise-lines")
(filter-map
(l (a)
(let ((a-first (vector-first a)) (a-second (vector-second a)))
(if (string-equal? a-first a-second) #f (string-append a-first "-to-" a-second))))
(permutations (vector "commas" "newlines" "spaces") 2))))))
(define (shtml-operations route)
(shtml-section 0 (route-title route)
(qq
( (p (@ (class "small-font"))
"enter text in the text area, select a text processing operation and press apply to transform the text. with some options further description appears when it has been selected.")
(br) (select (@ (id operations)) (unquote-splicing (shtml-alist->options operations)))
(button (@ (id apply)) "apply") " "
(button (@ (id undo)) "undo") (br)
(div (@ (id description) (class "small-font") (style "display:none")) "") (br)
(textarea (@ (id text)) "")))))
(define text-operations-route
(route-new "/text/operations" "text operations"
(l (request)
(ytilitu-request-bind request (swa-env data route routes time-start)
(respond-html request
(alist-q body-class "operations"
title (route-title route)
css (client-static swa-env (q ytilitu) (q css) (q (default text-operations)))
js (client-static swa-env (q ytilitu) (q js) (q (default text-operations)))
nav-one (shtml-nav-one-section routes "/text" "operations"))
(q ytilitu) (list (list shtml-layout (shtml-operations route)))
(cache-headers time-start))))))
(define text-routes (list text-operations-route)))
| false |
b797184833511af2665bae3d7176baa584187d85
|
6be443e2def01b1f9a5285f1287983e10e167515
|
/ch2/2-31.scm
|
1d27de6bb3fd428ece463f51c195b7d5ac8ce690
|
[
"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 | 712 |
scm
|
2-31.scm
|
(define (tree-map1 f tree)
(cond ((null? tree) nil)
((not (pair? tree)) (f tree))
(else (cons (tree-map1 f (car tree))
(tree-map1 f (cdr tree))))))
(define nil `())
(define (tree-map2 f tree)
(map (lambda(sub-tree)
(if (pair? sub-tree)
(tree-map2 f sub-tree)
(f sub-tree)))
tree))
(define (square-tree1 tree) (tree-map1 square tree))
(define (square-tree2 tree) (tree-map2 square tree))
(print (square-tree1 (list 1
(list 2 (list 3 4) 5)
(list 6 7))))
(print (square-tree2 (list 1
(list 2 (list 3 4) 5)
(list 6 7))))
| false |
a5d8069373bc07ddbca804d6cd541074a5f71e59
|
37c751fc27e790303b84730013217d1c8cbb60cc
|
/scsh/thttpd/packages.scm
|
5a67d151477a2ab1d0054e0e637cb3174ced5afe
|
[
"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 | 161 |
scm
|
packages.scm
|
(define-interface thttpd-interface
(export
run-daemon-child-http))
(define-structure thttpd
thttpd-interface
(open scheme)
(files thttpdaemon load))
| false |
2a0d49dcb135ac2f6853de89bebcf6e6906520b0
|
2767601ac7d7cf999dfb407a5255c5d777b7b6d6
|
/sandbox/examples/rolling-out-of-time.ss
|
04698c120e002693ce852222ab9cebd0c0b92334
|
[] |
no_license
|
manbaum/moby-scheme
|
7fa8143f3749dc048762db549f1bcec76b4a8744
|
67fdf9299e9cf573834269fdcb3627d204e402ab
|
refs/heads/master
| 2021-01-18T09:17:10.335355 | 2011-11-08T01:07:46 | 2011-11-08T01:07:46 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,146 |
ss
|
rolling-out-of-time.ss
|
#lang s-exp "../moby-lang.ss"
;; Rolling out of time
;;
;; Roll the blue ball onto the red target:
;; if the blue ball shrinks down to zero,
;; then the game ends.
;; A world is a posn, a radius, a vel, a
;; target posn, and a score.
(define-struct world
(posn r vel target-posn score))
(define WIDTH 300)
(define HEIGHT 460)
(define TARGET-RADIUS 30)
;; A velocity has an x and y component.
(define-struct vel (x y))
;; The initial world starts at the center.
(define initial-world
(make-world (make-posn (quotient WIDTH 2)
(quotient HEIGHT 2))
30
(make-vel 0 0)
(make-posn 0 0)
0))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; tick: world -> world
;; Moves the ball by a velocity, and shrinks
;; it.
(define (tick w)
(cond
[(collide? w)
(make-world (posn+vel (world-posn w)
(world-vel w))
30
(world-vel w)
(make-random-posn)
(add1 (world-score w)))]
[else
(make-world (posn+vel (world-posn w)
(world-vel w))
(- (world-r w) 1/2)
(world-vel w)
(world-target-posn w)
(world-score w))]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; tilt: world number number number -> world
;; Adjusts velocity based on the tilt.
(define (tilt w azimuth pitch roll)
(make-world (world-posn w)
(world-r w)
(make-vel roll (- pitch))
(world-target-posn w)
(world-score w)))
;; render: world -> scene
;; Renders the world.
(define (render w)
(maybe-add-game-over
w
(place-image/posn
(text (format "Score: ~a" (world-score w))
20 "black")
(make-posn 20 20)
(place-image/posn
(circle TARGET-RADIUS "solid" "red")
(world-target-posn w)
(place-image/posn
(circle (world-r w) "solid" "blue")
(world-posn w)
(empty-scene WIDTH HEIGHT))))))
;; maybe-add-game-over: world scene -> scene
(define (maybe-add-game-over w a-scene)
(cond
[(game-ends? w)
(place-image/posn
(text "GAME OVER" 30 "red")
(make-posn 20 100)
a-scene)]
[else
a-scene]))
;; collide?: world -> boolean
;; Produces true if the target and the ball
;; have collided.
(define (collide? w)
(< (distance (world-posn w)
(world-target-posn w))
(+ TARGET-RADIUS (world-r w))))
;; game-ends?: world -> boolean
;; Produces true if the game should finish;
;; we end when there's no more ball left.
(define (game-ends? w)
(<= (world-r w) 1))
;; make-random-posn: -> posn
;; Produces a random position for the target.
(define (make-random-posn)
(make-posn (random WIDTH)
(random HEIGHT)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; posn+vel: posn velocity -> posn
;; Adds a position by a velocity.
(define (posn+vel a-posn a-vel)
(make-posn (clamp (+ (posn-x a-posn)
(vel-x a-vel))
0 WIDTH)
(clamp (+ (posn-y a-posn)
(vel-y a-vel))
0 HEIGHT)))
;; clamp: number number number -> number
;; Clamps a number x between a and b.
(define (clamp x a b)
(cond [(> x b) b]
[(< x a) a]
[else x]))
;; distance: posn posn -> number
;; Produces the Euclidean distance between
;; two positions.
(define (distance posn-1 posn-2)
(sqrt
(+ (sqr (- (posn-x posn-1)
(posn-x posn-2)))
(sqr (- (posn-y posn-1)
(posn-y posn-2))))))
;; place-image/posn: image posn scene -> scene
;; Place an image at a position into the
;; scene.
(define (place-image/posn img a-posn a-scene)
(place-image img
(posn-x a-posn)
(posn-y a-posn)
a-scene))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(js-big-bang initial-world
(on-tick 1/20 tick)
(on-tilt tilt)
(on-redraw render)
(stop-when game-ends?))
| false |
1c2f6d887634cda6d7b101653b744d74cc657446
|
03e4064a7a55b5d00937e74cddb587ab09cf7af9
|
/nscheme/include/base/mvector.scm
|
cf40f848df500de8ba49713a23c6718d0d0d4141
|
[
"BSD-2-Clause"
] |
permissive
|
gregr/ina
|
29f28396cd47aa443319147ecde5235d11e1c3d1
|
16188050caa510899ae22ff303a67897985b1c3b
|
refs/heads/master
| 2023-08-25T13:31:44.131598 | 2023-08-14T16:46:48 | 2023-08-14T16:46:48 | 40,606,975 | 17 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,533 |
scm
|
mvector.scm
|
(define (mvector . args)
(let ((x (make-mvector (length args) 0)))
(let loop ((i 0) (args args))
(cond ((null? args) x)
(else (mvector-set! x i (car args))
(loop (+ i 1) (cdr args)))))))
(define (mvector-transform-range! mv start end f)
;; TODO: always requiring (= 0 start) ? That's not very useful.
(unless (and (= 0 start) (<= start end) (<= end (mvector-length mv)))
(error "invalid mvector range"
'length (mvector-length mv) 'start start 'end end))
(let loop ((i start)) (when (< i end)
(mvector-set! mv i (f i))
(loop (+ i 1)))))
(define (mvector-fill! mv v)
(mvector-transform-range! mv 0 (mvector-length mv) (lambda (_) v)))
(define (mvector-copy! mv start src start.src end.src)
(let-values (((ref length)
(cond ((mvector? src) (values mvector-ref mvector-length))
((vector? src) (values vector-ref vector-length))
(else (error "invalid source for mvector-copy!" src)))))
(unless (and (<= 0 start.src) (<= start.src end.src) (<= end.src (length src)))
(error "invalid source range" 'length (length src) 'start start.src 'end end.src))
(mvector-transform-range! mv start (+ start (- end.src start.src))
(lambda (i) (ref src (+ start.src (- i start)))))))
(define (box x) (mvector x))
(define (unbox b) (mvector-ref b 0))
(define (set-box! b x) (mvector-set! b 0 x))
| false |
5dde54571e15ffff55987996d1330f02b59b3e3c
|
43612e5ed60c14068da312fd9d7081c1b2b7220d
|
/unit-tests/IFT3065/1/etape1-sub2.scm
|
0124a0d72a894e932acda6e0e025b5f322902c49
|
[
"BSD-3-Clause"
] |
permissive
|
bsaleil/lc
|
b1794065183b8f5fca018d3ece2dffabda6dd9a8
|
ee7867fd2bdbbe88924300e10b14ea717ee6434b
|
refs/heads/master
| 2021-03-19T09:44:18.905063 | 2019-05-11T01:36:38 | 2019-05-11T01:36:38 | 41,703,251 | 27 | 1 |
BSD-3-Clause
| 2018-08-29T19:13:33 | 2015-08-31T22:13:05 |
Scheme
|
UTF-8
|
Scheme
| false | false | 177 |
scm
|
etape1-sub2.scm
|
(let ((a 7) (b 3)) (println (- a b)))
(let ((a -7) (b 3)) (println (- a b)))
(let ((a 7) (b -3)) (println (- a b)))
(let ((a -7) (b -3)) (println (- a b)))
;4
;-10
;10
;-4
| false |
fa3f96dc4c0bfd16e9d0d60153242da26dd090d8
|
68c4bab1f5d5228078d603066b6c6cea87fdbc7a
|
/lab/frozen/just-born/rifle/src/mzscheme/util/TODO.ss
|
482be600b36466c9d2c2cd5db6f572f526d3d1a2
|
[] |
no_license
|
felipelalli/micaroni
|
afab919dab304e21ba916aa6310dca102b1a04a5
|
741b628754b7c7085d3e68009a621242c2a1534e
|
refs/heads/master
| 2023-08-03T06:25:15.405861 | 2023-07-25T14:44:56 | 2023-07-25T14:44:56 | 537,536 | 2 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 235 |
ss
|
TODO.ss
|
(load "../little-type/little-type.ss")
(define-syntax TODO
(syntax-rules ()
((TODO message)
(make-little-object 'TODO message))))
(define-syntax TODO?
(syntax-rules ()
((TODO? obj)
(little-object obj is? 'TODO))))
| true |
0124ad72ccb74b2047afb6425c0427476b268737
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/ext/crypto/sagittarius/crypto/keys/operations/asymmetric/apis.scm
|
e027d13bcfa3da85f3e464b42cb4f3e4b7bf0f30
|
[
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
] |
permissive
|
ktakashi/sagittarius-scheme
|
0a6d23a9004e8775792ebe27a395366457daba81
|
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
|
refs/heads/master
| 2023-09-01T23:45:52.702741 | 2023-08-31T10:36:08 | 2023-08-31T10:36:08 | 41,153,733 | 48 | 7 |
NOASSERTION
| 2022-07-13T18:04:42 | 2015-08-21T12:07:54 |
Scheme
|
UTF-8
|
Scheme
| false | false | 7,890 |
scm
|
apis.scm
|
;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; sagittarius/crypto/keys/operations/asymmetric/apis.scm - Asymmetric key op
;;;
;;; Copyright (c) 2022 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
#!nounbound
(library (sagittarius crypto keys operations asymmetric apis)
(export generate-key-pair
generate-public-key
generate-private-key
import-public-key
import-private-key
export-public-key
export-private-key
oid->key-operation
key->oid
public-key-format
*public-key-formats*
public-key-format?
calculate-key-agreement
private-key-format
*private-key-formats*
private-key-format?
)
(import (rnrs)
(sagittarius crypto asn1)
(sagittarius crypto keys types)
(clos user))
(define-generic generate-key-pair)
(define-generic generate-public-key)
(define-generic generate-private-key)
(define-generic import-public-key)
(define-generic import-private-key)
(define-generic export-public-key)
(define-generic export-private-key)
(define-generic oid->key-operation :class <one-of-specializable-generic>)
(define-generic key->oid)
(define-generic calculate-key-agreement) ;; key agreement
(define-enumeration public-key-format (raw subject-public-key-info)
public-key-formats)
(define *public-key-formats* (enum-set-universe (public-key-formats)))
(define (public-key-format? s) (enum-set-member? s *public-key-formats*))
(define-method import-public-key ((key <bytevector>)
(format (eq 'subject-public-key-info)))
(import-public-key (open-bytevector-input-port key) format))
(define-method import-public-key ((key <port>)
(format (eq 'subject-public-key-info)))
(import-public-key (read-asn1-object key) format))
#|
SubjectPublicKeyInfo {PUBLIC-KEY: IOSet} ::= SEQUENCE {
algorithm AlgorithmIdentifier {PUBLIC-KEY, {IOSet}},
subjectPublicKey BIT STRING
}
|#
(define-method import-public-key ((key <der-sequence>)
(format (eq 'subject-public-key-info)))
(let*-values (((aid pk) (deconstruct-asn1-collection key))
((oid . maybe-param) (deconstruct-asn1-collection aid)))
(let ((s (oid->key-operation (der-object-identifier->oid-string oid))))
(apply import-public-key s (der-bit-string->bytevector pk) 'raw
(if (null? maybe-param)
'()
(extract-parameter (der-object-identifier->oid-string oid)
(car maybe-param)))))))
(define-enumeration private-key-format (raw private-key-info)
private-key-formats)
(define *private-key-formats* (enum-set-universe (private-key-formats)))
(define (private-key-format? s) (enum-set-member? s *public-key-formats*))
(define-method import-private-key ((key <bytevector>)
(format (eq 'private-key-info)))
(import-private-key (open-bytevector-input-port key) format))
(define-method import-private-key ((key <port>)
(format (eq 'private-key-info)))
(import-private-key (read-asn1-object key) format))
;; OneAsymmetricKey ::= SEQUENCE {
;; version Version,
;; privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
;; privateKey PrivateKey,
;; attributes [0] Attributes OPTIONAL,
;; ...,
;; [[2: publicKey [1] PublicKey OPTIONAL ]],
;; ...
;; }
(define-method import-private-key ((key <der-sequence>)
(format (eq 'private-key-info)))
(import-pki-private-key #f key))
(define-method import-private-key (m
(key <der-sequence>)
(format (eq 'private-key-info)))
(import-pki-private-key m key))
(define (import-pki-private-key m key)
(let*-values (((version pka pk . ignore) (deconstruct-asn1-collection key))
((oid . maybe-param) (deconstruct-asn1-collection pka)))
(let ((s (oid->key-operation (der-object-identifier->oid-string oid))))
(unless (or (not m) (eq? m s))
(assertion-violation 'import-private-key
"Specified key scheme and actual OID mismatches"
m (der-object-identifier->oid-string oid)))
(apply import-private-key s
(adjust-key-value (der-object-identifier->oid-string oid)
(bytevector->asn1-object (der-octet-string->bytevector pk)))
(if (null? maybe-param)
'()
(extract-parameter (der-object-identifier->oid-string oid)
(car maybe-param)))))))
;; internal method
(define *ed25519-key-oid* "1.3.101.112")
(define *ed448-key-oid* "1.3.101.113")
(define-generic adjust-key-value)
(define-method adjust-key-value (o v) v)
(define-method adjust-key-value ((oid (equal *ed25519-key-oid*)) v)
(der-octet-string->bytevector v))
(define-method adjust-key-value ((oid (equal *ed448-key-oid*)) v)
(der-octet-string->bytevector v))
(define-generic wrap-key-value)
(define-method wrap-key-value (o v) v)
;; EdDSA uses CurvePrivateKey for PrivateKeyInfo/OneAsymmetricKey
;; ref: https://www.rfc-editor.org/rfc/rfc8410
;; CurvePrivateKey ::= OCTET STRING
(define-method wrap-key-value ((oid (equal *ed25519-key-oid*)) v)
(asn1-encodable->bytevector (bytevector->der-octet-string v)))
(define-method wrap-key-value ((oid (equal *ed448-key-oid*)) v)
(asn1-encodable->bytevector (bytevector->der-octet-string v)))
;; Use :around specifier to let the subclass of the key match...
(define-method export-private-key :around (m k (format (eq 'private-key-info)))
(export-private-key k format))
(define-method export-private-key :around ((key <private-key>)
(format (eq 'private-key-info)))
(let ((raw (export-private-key key 'raw))
(oid (key->oid key)))
(asn1-encodable->bytevector
(der-sequence
(integer->der-integer 0)
(der-sequence (oid-string->der-object-identifier oid)
(extract-aid-parameter oid raw))
(bytevector->der-octet-string (wrap-key-value oid raw))))))
;; internal method
(define *dsa-oid* "1.2.840.10040.4.1")
(define *ecdsa-oid* "1.2.840.10045.2.1")
(define-generic extract-parameter)
(define-method extract-parameter (oid raw) '())
(define-method extract-parameter ((oid (equal *ecdsa-oid*)) param)
(list param))
(define-method extract-parameter ((oid (equal *dsa-oid*)) param)
(list param))
(define-generic extract-aid-parameter)
(define-method extract-aid-parameter (oid raw) (make-der-null))
(define-method extract-aid-parameter ((oid (equal *ecdsa-oid*)) raw)
;; Fxxk, we need to deconstruct and provide curve parameter here...
(let* ((seq (bytevector->asn1-object raw))
(obj (asn1-collection-find-tag seq 0)))
(if obj
(ber-tagged-object-obj obj)
(make-der-null)))) ;; mustn't happen, but we don't want to fail it
)
| false |
a05e58ab2bfdf3a3f575d47ff9331986109790de
|
eef5f68873f7d5658c7c500846ce7752a6f45f69
|
/spheres/structure/lru-cache.sld
|
143bf8a2b53a1f0e5247e7df2dda6d8fe9f46e1c
|
[
"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 | 468 |
sld
|
lru-cache.sld
|
;;!!! LRU Cache
;; .author Jim Ursetto, 2009
;; .author Alvaro Castro-Castilla, 2015
(define-library (spheres/structure lru-cache)
(export make-lru-cache
lru-cache-ref
lru-cache-set!
lru-cache-walk
lru-cache-fold
lru-cache-delete!
lru-cache-flush!
lru-cache-size
lru-cache-capacity)
(import (spheres/core base)
(spheres/structure hash-table))
(include "lru-cache.scm"))
| false |
f63e3d89a1416b581e247b69407bc2c172843537
|
784dc416df1855cfc41e9efb69637c19a08dca68
|
/src/gerbil/expander/top.ss
|
73075257598eced9c75cbd7542e33a3ad8cc4991
|
[
"LGPL-2.1-only",
"Apache-2.0",
"LGPL-2.1-or-later"
] |
permissive
|
danielsz/gerbil
|
3597284aa0905b35fe17f105cde04cbb79f1eec1
|
e20e839e22746175f0473e7414135cec927e10b2
|
refs/heads/master
| 2021-01-25T09:44:28.876814 | 2018-03-26T21:59:32 | 2018-03-26T21:59:32 | 123,315,616 | 0 | 0 |
Apache-2.0
| 2018-02-28T17:02:28 | 2018-02-28T17:02:28 | null |
UTF-8
|
Scheme
| false | false | 23,353 |
ss
|
top.ss
|
;;; -*- Gerbil -*-
;;; (C) vyzo at hackzen.org
;;; gerbil.expander top syntax
prelude: :<core>
package: gerbil/expander
namespace: gx
(export #t)
(import "common" "stx" "core")
;;; blocks
;; (%#begin <form> ...)
(def (core-expand-begin% stx)
(def (expand-special hd K rest r)
(K rest (cons (core-expand-top hd) r)))
(core-expand-block stx expand-special))
;; (%#begin-syntax top-syntax-form ...)
;; top-syntax-form:
;; definition
;; expression
;; (%#begin-syntax top-syntax-form ...)
;;
;; phi+1 expansion and evaluation
;; if in module core-top-context
;; then syntax is residualized to core expanded form
;; else syntax is evaled to quoted compile-time value
(def (core-expand-begin-syntax% stx)
(def (expand-special hd K rest r)
(let (K (lambda (e) (K rest (cons e r))))
(core-syntax-case hd (%#begin-syntax
%#define-values %#define-syntax %#define-alias
%#define-runtime)
((%#begin-syntax . _)
(K (core-expand-begin-syntax% hd)))
((%#define-values hd-bind expr)
(core-bind-values? hd-bind)
(begin
(core-bind-values! hd-bind)
(K hd)))
((%#define-syntax . _)
(K (core-expand-define-syntax% hd)))
((%#define-alias . _)
(K (core-expand-define-alias% hd)))
((%#define-runtime . _)
(K (core-expand-define-runtime% hd))))))
(def (eval-body rbody)
(let lp ((rest rbody) (body '()) (ebody '()))
(match rest
([hd . rest]
(core-syntax-case hd (%#define-values %#begin-syntax)
((%#define-values hd-bind expr)
(let (ehd
(core-quote-syntax
[(core-quote-syntax '%#define-values)
(core-quote-bind-values hd-bind)
(core-expand-expression expr)]
(stx-source hd)))
(lp rest (cons ehd body) (cons ehd ebody))))
((%#begin-syntax . _)
(lp rest (cons hd body) ebody))
(else
(lp rest (cons hd body) (cons hd ebody)))))
(else
(values body
(eval-syntax*
(core-quote-syntax
(core-cons '%#begin ebody)
(stx-source stx))))))))
(parameterize ((current-expander-phi (fx1+ (current-expander-phi))))
(let (rbody (core-expand-block stx expand-special #f))
(let-values (((expanded-body value) (eval-body rbody)))
(core-quote-syntax
(if (module-context? (current-expander-context))
(core-cons '%#begin-syntax expanded-body)
[(core-quote-syntax '%#quote) value])
(stx-source stx))))))
;; (%#begin-foreign foreign-top ...)
(def (core-expand-begin-foreign% stx)
(core-syntax-case stx ()
((_ . body)
(stx-list? body)
(core-quote-syntax
(core-cons '%#begin-foreign body)
(stx-source stx)))))
;; (%#begin-module body ...)
;; transient form for module expansion; cannot appear in the wild
(def (core-expand-begin-module% stx)
(raise-syntax-error #f "Illegal expansion" stx))
;; (%#begin-annotation annotation expr ...)
(def (core-expand-begin-annotation% stx)
(core-syntax-case stx ()
((_ ann expr)
(core-quote-syntax
[(core-quote-syntax '%#begin-annotation) ann
(core-expand-expression expr)]
(stx-source stx)))))
;; local expression blocks -- lambda/let mf
(def (core-expand-local-block stx body)
(def (expand-special hd K rest r)
(K [] (cons (expand-internal hd rest) r)))
(def (expand-internal hd rest)
(parameterize ((current-expander-context (make-local-context)))
(wrap-internal
(core-expand-block
(stx-wrap-source (cons* '%#begin hd rest)
(stx-source stx))
expand-internal-special #f))))
(def (expand-internal-special hd K rest r)
(core-syntax-case hd (%#define-values
%#define-syntax %#define-alias
%#declare)
((%#define-values hd-bind expr)
(core-bind-values? hd-bind)
(begin
(core-bind-values! hd-bind)
(K rest (cons hd r))))
((%#define-syntax . _)
(begin
(core-expand-define-syntax% hd)
(K rest r)))
((%#define-alias . _)
(begin
(core-expand-define-alias% hd)
(K rest r)))
((%#declare . _)
(K rest (cons (core-expand-declare% hd) r)))))
(def (wrap-internal rbody)
(let lp ((rest rbody) (decls []) (bind []) (body []))
(core-syntax-case rest ()
((hd . rest)
(core-syntax-case hd (%#define-values %#declare)
((%#define-values hd-bind expr)
(lp rest decls
(cons [(core-quote-bind-values hd-bind)
(core-expand-expression expr)]
bind)
body))
((%#declare . xdecls)
(lp rest (stx-foldr cons decls xdecls) bind body))
(else
(if (null? bind)
(lp rest decls bind (cons hd body))
(lp rest decls (cons [#f hd] bind) body)))))
(else
(let* ((body
(match body
([] (raise-syntax-error #f "Bad syntax" stx))
([expr] expr)
(else
(core-quote-syntax
(core-cons '%#begin body)
(stx-source stx)))))
(body
(if (null? bind) body
(core-quote-syntax
[(core-quote-syntax '%#letrec*-values) bind body]
(stx-source stx)))))
(if (null? decls) body
(core-quote-syntax
[(core-quote-syntax '%#begin-annotation) decls body]
(stx-source stx))))))))
(core-expand-block*
(stx-wrap-source (cons '%#begin body)
(stx-source stx))
expand-special))
;; (%#declare decl ...)
(def (core-expand-declare% stx)
(core-syntax-case stx ()
((_ . body)
(stx-list? body)
(core-quote-syntax
(core-cons '%#declare
(stx-map
(lambda (decl)
(core-syntax-case decl ()
((head . args)
(stx-list? args)
(stx-map core-quote-syntax decl))))
body))
(stx-source stx)))))
;;; definitions
;; (%#extern (id binding-id) ...)
(def (core-expand-extern% stx)
(core-syntax-case stx ()
((_ . body)
(stx-list? body)
(begin
(stx-for-each
(lambda (bind)
(core-syntax-case bind ()
((id eid)
(and (identifier? id)
(identifier? eid))
(core-bind-extern! id (stx-e eid)))))
body)
(core-quote-syntax
(core-cons '%#extern
(stx-map
(lambda (bind)
(core-syntax-case bind ()
((id eid) [(core-quote-syntax id) (stx-e eid)])))
body))
(stx-source stx))))))
;; (%#define-values hd expr)
(def (core-expand-define-values% stx)
(core-syntax-case stx ()
((_ hd expr)
(core-bind-values? hd)
(begin
(core-bind-values! hd)
(core-quote-syntax
[(core-quote-syntax '%#define-values)
(core-quote-bind-values hd)
(core-expand-expression expr)]
(stx-source stx))))))
;; (%#define-runtime id binding-id)
(def (core-expand-define-runtime% stx)
(core-syntax-case stx ()
((_ id binding-id)
(and (identifier? id) (identifier? binding-id))
(begin
(core-bind-runtime-reference! id (stx-e binding-id))
(core-quote-syntax
[(core-quote-syntax '%#define-runtime)
(core-quote-syntax id)
(core-quote-syntax binding-id)])))))
;; (%#define-syntax id expr)
(def (core-expand-define-syntax% stx)
(core-syntax-case stx ()
((_ id expr)
(identifier? id)
(let-values (((e-stx e) (core-expand-expression+1 expr)))
(core-bind-syntax! id e)
(core-quote-syntax
[(core-quote-syntax '%#define-syntax)
(core-quote-syntax id)
e-stx]
(stx-source stx))))))
;; (%#define-alias id id)
(def (core-expand-define-alias% stx)
(core-syntax-case stx ()
((_ id alias-id)
(and (identifier? id)
(identifier? alias-id))
(let (alias-id (core-quote-syntax alias-id))
(core-bind-alias! id alias-id)
(core-quote-syntax
[(core-quote-syntax '%#define-alias)
(core-quote-syntax id)
alias-id])))))
;;; closures
(def (core-expand-lambda% stx (wrap? #t))
(core-syntax-case stx ()
((_ hd . body)
(core-bind-values? hd)
(parameterize ((current-expander-context (make-local-context)))
(core-bind-values! hd)
(let (body [(core-quote-bind-values hd)
(core-expand-local-block stx body)])
(if wrap?
(core-quote-syntax
(core-cons '%#lambda body)
(stx-source stx))
body))))))
(def (core-expand-case-lambda% stx)
(core-syntax-case stx ()
((_ . clauses)
(stx-list? clauses)
(core-quote-syntax
(core-cons '%#case-lambda
(stx-map
(lambda (clause)
(core-expand-lambda%
(stx-wrap-source
(cons '%#case-lambda-clause clause)
(or (stx-source clause)
(stx-source stx)))
#f))
clauses))
(stx-source stx)))))
;;; local bindings
(def (core-expand-let-values% stx)
(core-syntax-case stx ()
((_ hd . body)
(core-expand-let-bind? hd)
(let (expressions (stx-map core-expand-let-bind-expression hd))
(parameterize ((current-expander-context (make-local-context)))
(stx-for-each core-expand-let-bind-values! hd)
(core-quote-syntax
[(core-quote-syntax '%#let-values)
(stx-map core-expand-let-bind-quote hd expressions)
(core-expand-local-block stx body)]
(stx-source stx)))))))
(def (core-expand-letrec-values% stx (form '%#letrec-values))
(core-syntax-case stx ()
((_ hd . body)
(core-expand-let-bind? hd)
(parameterize ((current-expander-context (make-local-context)))
(stx-for-each core-expand-let-bind-values! hd)
(core-quote-syntax
[(core-quote-syntax form)
(stx-map core-expand-let-bind-quote hd
(stx-map core-expand-let-bind-expression hd))
(core-expand-local-block stx body)]
(stx-source stx))))))
(def (core-expand-letrec*-values% stx)
(core-expand-letrec-values% stx '%#letrec*-values))
(def (core-expand-let-bind? stx)
(and (stx-list? stx)
(stx-andmap (lambda (bind)
(core-syntax-case bind ()
((hd _) (core-bind-values? hd))
(else #f)))
stx)))
(def (core-expand-let-bind-expression bind)
(core-syntax-case bind ()
((_ expr) (core-expand-expression expr))))
(def (core-expand-let-bind-values! bind)
(core-syntax-case bind ()
((hd _) (core-bind-values! hd))))
(def (core-expand-let-bind-quote bind expr)
(core-syntax-case bind ()
((hd _) [(core-quote-bind-values hd) expr])))
(def (core-expand-let-syntax% stx)
(core-syntax-case stx ()
((_ hd . body)
(core-expand-let-bind-syntax? hd)
(let (expanders (stx-map core-expand-let-bind-syntax-expression hd))
(parameterize ((current-expander-context (make-local-context)))
(stx-for-each core-expand-let-bind-syntax! hd expanders)
(core-expand-local-block stx body))))))
(def (core-expand-letrec-syntax% stx)
(core-syntax-case stx ()
((_ hd . body)
(core-expand-let-bind-syntax? hd)
(parameterize ((current-expander-context (make-local-context)))
(stx-for-each core-expand-let-bind-syntax!
hd (make-list (stx-length hd) #!void))
(stx-for-each (cut core-expand-let-bind-syntax! <> <> #t)
hd (stx-map core-expand-let-bind-syntax-expression hd))
(core-expand-local-block stx body)))))
(def (core-expand-let-bind-syntax? stx)
(and (stx-list? stx)
(stx-andmap (lambda (bind)
(core-syntax-case bind ()
((hd _) (identifier? hd))
(else #f)))
stx)))
(def (core-expand-let-bind-syntax-expression bind)
(core-syntax-case bind ()
((_ expr)
(let-values (((_ e) (core-expand-expression+1 expr)))
e))))
(def (core-expand-let-bind-syntax! bind e (rebind? #f))
(core-syntax-case bind ()
((id _) (core-bind-syntax! id e rebind?))))
;;; expressions
(def (core-expand-expression% stx)
(core-syntax-case stx ()
((_ expr)
(core-expand-expression expr))))
(def (core-expand-quote% stx)
(core-syntax-case stx ()
((_ e)
(core-quote-syntax
[(core-quote-syntax '%#quote) (syntax->datum e)]
(stx-source stx)))))
(def (core-expand-quote-syntax% stx)
(core-syntax-case stx ()
((_ e)
(core-quote-syntax
[(core-quote-syntax '%#quote-syntax) (core-quote-syntax e)]
(stx-source stx)))))
(def (core-expand-call% stx)
(core-syntax-case stx ()
((_ rator . args)
(stx-list? args)
(core-quote-syntax
(core-cons* '%#call
(core-expand-expression rator)
(stx-map core-expand-expression args))
(stx-source stx)))))
(def (core-expand-if% stx)
(core-syntax-case stx ()
((_ test K E)
(core-quote-syntax
[(core-quote-syntax '%#if)
(core-expand-expression test)
(core-expand-expression K)
(core-expand-expression E)]
(stx-source stx)))))
(def (core-expand-ref% stx)
(core-syntax-case stx ()
((_ id)
(core-runtime-ref? id)
(core-quote-syntax
[(core-quote-syntax '%#ref) (core-quote-runtime-ref id stx)]
(stx-source stx)))))
(def (core-expand-setq% stx)
(core-syntax-case stx ()
((_ id expr)
(core-runtime-ref? id)
(core-quote-syntax
[(core-quote-syntax '%#set!)
(core-quote-runtime-ref id stx)
(core-expand-expression expr)]
(stx-source stx)))))
;;; macros
(def (macro-expand-extern stx)
(define (generate body)
(let lp ((rest body) (ns (core-context-namespace)) (r '()))
(core-syntax-case rest ()
((namespace: ns . rest)
(let (ns (cond
((identifier? ns)
(symbol->string (stx-e ns)))
((or (stx-string? ns) (stx-false? ns))
(stx-e ns))
(else
(raise-syntax-error #f "Bad syntax" stx ns))))
(lp rest ns r)))
((hd . rest)
(if (identifier? hd)
(lp rest ns
(cons [hd (if ns (stx-identifier hd ns "#" hd) hd)] r))
(core-syntax-case hd ()
((id eid)
(and (identifier? id) (identifier? eid))
(lp rest ns (cons [id eid] r))))))
(() (reverse r)))))
(core-syntax-case stx ()
((_ . body)
(stx-list? body)
(core-cons '%#extern
(generate body)))))
(def (macro-expand-define-values stx)
(core-syntax-case stx ()
((_ hd expr)
(stx-andmap identifier? hd)
[(core-quote-syntax '%#define-values)
(stx-map user-binding-identifier hd)
expr])))
(def (macro-expand-define-syntax stx)
(core-syntax-case stx ()
((_ hd expr)
(identifier? hd)
[(core-quote-syntax '%#define-syntax) hd expr])))
(def (macro-expand-define-alias stx)
(core-syntax-case stx ()
((_ id alias-id)
(and (identifier? id)
(identifier? alias-id))
[(core-quote-syntax '%#define-alias) id alias-id])))
(def (macro-expand-lambda% stx)
(core-syntax-case stx ()
((_ hd . body)
(and (stx-andmap identifier? hd)
(stx-list? body)
(not (stx-null? body)))
(core-cons* '%#lambda
(stx-map user-binding-identifier hd)
body))))
(def (macro-expand-case-lambda stx)
(def (generate clause)
(core-syntax-case clause ()
((hd . body)
(and (stx-andmap identifier? hd)
(stx-list? body)
(not (stx-null? body)))
(stx-wrap-source
(cons (stx-map user-binding-identifier hd)
body)
(stx-source clause)))
(else
(raise-syntax-error #f "Bad syntax; malformed clause" stx clause))))
(core-syntax-case stx ()
((_ . clauses)
(stx-list? clauses)
(core-cons '%#case-lambda
(stx-map generate clauses)))))
(def (macro-expand-let-values stx (form '%#let-values))
(def (generate bind)
(core-syntax-case bind ()
((ids expr)
(stx-andmap identifier? ids)
[(stx-map user-binding-identifier ids) expr])
(else
(raise-syntax-error #f "Bad syntax; malformed binding" stx bind))))
(core-syntax-case stx ()
((_ hd . body)
(and (stx-list? hd)
(stx-list? body)
(not (stx-null? body)))
(core-cons* form
(stx-map generate hd)
body))))
(def (macro-expand-letrec-values stx)
(macro-expand-let-values stx '%#letrec-values))
(def (macro-expand-letrec*-values stx)
(macro-expand-let-values stx '%#letrec*-values))
(def (macro-expand-if stx)
(core-syntax-case stx ()
((_ test K)
(core-list '%#if test K #!void))
((_ test K E)
(core-list '%#if test K E))))
;;; user identifiers
(def (free-identifier=? xid yid)
(let ((xe (resolve-identifier xid))
(ye (resolve-identifier yid)))
(cond
((and xe ye) ; both bound
(or (eq? xe ye)
(and (binding? xe)
(binding? ye)
(eq? (binding-id xe) (binding-id ye)))))
((or xe ye) #f) ; one bound
(else ; none bound
(stx-eq? xid yid)))))
(def (bound-identifier=? xid yid)
(def (context e)
(if (syntax-quote? e)
(syntax-quote-context e)
(current-expander-context)))
(def (marks e)
(cond
((symbol? e) [])
((identifier-wrap? e)
(identifier-wrap-marks e))
(else
(syntax-quote-marks e))))
(def (unwrap e)
(if (symbol? e) e
(syntax-local-unwrap e)))
(let ((x (unwrap xid))
(y (unwrap yid)))
(and (stx-eq? x y)
(eq? (context x) (context y))
(equal? (marks x) (marks y)))))
(def (underscore? stx)
(and (identifier? stx)
(core-identifier=? stx '_)))
(def (ellipsis? stx)
(and (identifier? stx)
(core-identifier=? stx '...)))
(def (user-binding-identifier x)
(and (identifier? x) (not (underscore? x))
x))
(def (check-duplicate-identifiers stx (where stx))
(let lp ((rest (syntax->list stx)))
(match rest
([hd . rest]
(cond
((not (identifier? hd))
(raise-syntax-error #f "Bad identifier" where hd))
((find (cut bound-identifier=? <> hd) rest)
(raise-syntax-error #f "Duplicate identifier" where hd))
(else
(lp rest))))
(else #t))))
;;; etc
(def (core-bind-values? stx)
(stx-andmap (lambda (x) (or (identifier? x) (stx-false? x)))
stx))
(def (core-bind-values! stx
(rebind? #f)
(phi (current-expander-phi))
(ctx (current-expander-context)))
(stx-for-each
(lambda (id)
(when (identifier? id)
(core-bind-runtime! id rebind? phi ctx)))
stx))
(def (core-quote-bind-values stx)
(stx-map (lambda (x)
(and (identifier? x)
(core-quote-syntax x)))
stx))
(def (core-runtime-ref? stx)
(and (identifier? stx)
(let (bind (resolve-identifier stx))
(or (not bind)
(runtime-binding? bind)))))
(def (core-quote-runtime-ref id form)
(let (bind (resolve-identifier id))
(cond
((runtime-binding? bind)
(core-quote-syntax id))
((not bind)
(if (or (core-context-rebind? (core-context-top))
(core-extern-symbol? (stx-e id)))
(core-quote-syntax id)
(raise-syntax-error #f "Reference to unbound identifier" form id)))
(else
(raise-syntax-error #f "Bad syntax; not a runtime binding" form id)))))
(def (core-bind-runtime! id
(rebind? #f)
(phi (current-expander-phi))
(ctx (current-expander-context)))
(let* ((key (core-identifier-key id))
(eid (make-binding-id key #f phi ctx))
(bind
(cond
((module-context? ctx)
(make-module-binding eid key phi ctx))
((top-context? ctx)
(make-top-binding eid key phi))
((local-context? ctx)
(make-local-binding eid key phi))
(else
(make-runtime-binding eid key phi)))))
(bind-identifier! id bind rebind? phi ctx)))
(def (core-bind-runtime-reference! id eid
(rebind? #f)
(phi (current-expander-phi))
(ctx (current-expander-context)))
(let* ((key (core-identifier-key id))
(bind
(cond
((module-context? ctx)
(make-module-binding eid key phi ctx))
((top-context? ctx)
(make-top-binding eid key phi))
(else
(make-runtime-binding eid key phi)))))
(bind-identifier! id bind rebind? phi ctx)))
(def (core-bind-extern! id eid
(rebind? #f)
(phi (current-expander-phi))
(ctx (current-expander-context)))
(bind-identifier! id
(make-extern-binding eid (core-identifier-key id) phi)
rebind? phi ctx))
(def (core-bind-syntax! id e
(rebind? #f)
(phi (current-expander-phi))
(ctx (current-expander-context)))
(bind-identifier! id
(let ((key (core-identifier-key id))
(e (if (or (expander? e) (expander-context? e)) e
(make-user-expander e ctx phi))))
(make-syntax-binding (make-binding-id key #t phi ctx) key phi e))
rebind? phi ctx))
(def (core-bind-root-syntax! id e (rebind? #f))
(core-bind-syntax! id e rebind? 0 (core-context-root)))
(def (core-bind-alias! id alias-id
(rebind? #f)
(phi (current-expander-phi))
(ctx (current-expander-context)))
(bind-identifier! id
(let (key (core-identifier-key id))
(make-alias-binding (make-binding-id key #t phi ctx) key phi
alias-id))
rebind? phi ctx))
(def (make-binding-id key
(syntax? #f)
(phi (current-expander-phi))
(ctx (current-expander-context)))
(cond
((uninterned-symbol? key)
(gensym 'L))
((pair? key)
(gensym (car key)))
((top-context? ctx)
(let (ns (core-context-namespace ctx))
(cond
((and (fxzero? phi) (not syntax?))
(if ns
(make-symbol ns "#" key)
key))
(syntax?
(make-symbol (or ns "") "[:" (number->string phi) ":]#" key))
(else
(make-symbol (or ns "") "[" (number->string phi) "]#" key)))))
(else
(gensym key))))
| true |
578f900192091757c2be77710679d70f7239422b
|
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
|
/exercises/practice/strain/.meta/example.scm
|
71f7847910dd58c9bc5058fba904613e2bc2ca79
|
[
"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 | 245 |
scm
|
example.scm
|
(define (keep pred seq)
(cond
[(null? seq) '()]
[(pred (car seq)) (cons (car seq)
(keep pred (cdr seq)))]
[else (keep pred (cdr seq))]))
(define (discard pred seq)
(keep (lambda (x) (not (pred x))) seq))
| false |
06bb95f3b56e4efe7c7d34fc73a95bd1eb62c72c
|
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
|
/src/ws/testing/unit_tester.ss
|
7a1cbdf09103e46828ec15b9b6693c850948d62e
|
[
"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 | 13,339 |
ss
|
unit_tester.ss
|
;; Note: becuase of recursive dependencies, this file is included into
;; helpers.ss rather than being its own module.
;(module unit_tester mzscheme
; (require "../../plt/iu-match.ss" "../../plt/chez_compat.ss")
;;[2004.06.13] Making this not allow an error to match against unspecified!
(define (lenient-compare? o1 o2)
(or (eq? o1 o2)
;; Strings are not deep structures according to eq-deep,
;; So we compare them with equal?
(and (string? o1) (equal? o1 o2))
(and (eq? o1 'unspecified) (not (eq? o2 'error)))
(and (eq? o2 'unspecified) (not (eq? o1 'error)))))
;; This provides a weird sort of interface to a deep equal. It walks
;; down the tree, applying the input comparator at every intermediate
;; node, only proceeding downward on negative comparisons.
;; [2004.07.21] - Fixed it's behaviour against dotted pairs.
(define eq-deep
(lambda (eq)
(lambda (obj1 obj2)
(let loop ((o1 obj1) (o2 obj2))
(cond
[(eq o1 o2) #t]
[(and (list? o1) (list? o2))
(if (= (length o1) (length o2))
(for-all loop o1 o2)
#f)]
[(and (pair? o1) (pair? o2)) ;; Kinda silly to have both these.
(and (loop (car o1) (car o2)) ;; the above should save stack space though..
(loop (cdr o1) (cdr o2)))]
[(and (vector? o1) (vector? o2))
; Treat same as lists:
(loop (vector->list o1) (vector->list o2))]
[else #f])))))
(define tester-eq? (eq-deep lenient-compare?))
(define tester-equal? (eq-deep lenient-compare?))
;; [2004.04.21] I've started using the (ad-hoc) convention that every
;; file should define "these-tests" and "test-this" for unit testing.
;; This is inspired by the drscheme philosophy of every file being an
;; executable unit... But it *was* unbearable to duplicate this
;; little tester code across every file
;;
;; [2004.05.24] Replacing the default tester with a better one.
;; [2004.06.03] Adding optional preprocessor function
;; [2004.07.21] Added a 'quiet flag.
;; [2005.02.06] Made the quiet flag also suppress warnings.
;; [2005.09.24] Making failed tests retry optionally, run with flag 'retry
;; This is for nondeterministic tests that merely have a high
;; probability of success. 'retry can be specified either at
;; tester-construction time or test-time.
;; [2005.09.25] Modifying the tester to return true or false based on
;; whether all tests pass.
;; Forms:
;; (default-unit-tester message these-tests)
;; (default-unit-tester message these-tests equalfun)
;; (default-unit-tester message these-tests equalfun preprocessor)
;; [2005.02.24] Working around weird PLT bug:
(define voidproc (lambda args (void)))
(define default-unit-tester
(lambda (message these-tests . extras)
;; Print widths:
;; TODO: I should make these adjustable parameters.
(define TESTWIDTH 70)
(define ORACLEWIDTH 30)
(define INTENDEDWIDTH 20)
;; Default values of tester-construction time parameters:
(let ([teq? tester-equal?]
[preprocessor (lambda (x) x)]
[retry-failures #f]
[enabled #t])
;; Go through tester construction-time additional arguments:
(let arg-loop ([ls extras] [procsseen 0])
(cond
[(null? ls) (void)]
;; This is a little lame, first proc is equality function, second is preprocessor:
[(procedure? (car ls))
(if (= 0 procsseen)
(set! teq? (car ls))
(if (= 1 procsseen)
(set! preprocessor (car ls))
(error 'default-unit-tester "Too many proc arguments!: ~a" (car ls))))
(arg-loop (cdr ls) (+ 1 procsseen))]
[(memq (car ls) '(disable disabled))
(set! enabled #f)
(arg-loop (cdr ls) procsseen)]
[(eq? (car ls) 'retry)
(set! retry-failures #t)
(arg-loop (cdr ls) procsseen)]
[else (error 'default-unit-tester "Unknown argument or flag: ~a" (car ls))]))
;; Now we construct the actual tester procedure:
(let ((testerproc
(let ([entries
;; This canonicalizes them so that they're all four-long:
(map
(lambda (entry)
(match entry
[(,test ,result) `(#f () ,test ,result)]
[(,msg ,test ,result) `(,msg () ,test ,result)]
[(,msg ,moreargs ... ,test ,result)
`(,msg ,moreargs ,test ,result)]
[else (error 'default-unit-tester
" This is a bad test-case entry!: ~s\n" entry)]))
these-tests)])
(lambda args
(call/cc
(lambda (return)
(match (memq 'get args)
[#f (void)]
[(get ,n ,_ ...) (guard (integer? n))
(return (list-ref entries n))]
[,else (return entries)])
(when (or (memq 'print-tests args) (memq 'print args))
(for-eachi (lambda (i test)
(if (string? (car test))
(printf "~a: ~a\n" i (car test))))
entries)
(return (void)))
(let (;; Flag to suppress test output. This had better be passed
;; *after* any comparison or preprocessor arguments.
[quiet (or (memq 'quiet args)
(memq 'silent args)
(memq 'q args)
(not (or (memq 'verbose args)
(memq 'v args))))]
;; Flag to print test descriptions as well as code/output.
[titles (not (or (memq 'silent args)
(memq 'nodescrips args)))]
[retry-failures (or retry-failures ;; If already set above, or..
(memq 'retry args))]
; [descriptions (map car entries)]
; [tests (map caddr entries)]
; [intended (map cadddr entries)]
[success #t]
[tests-to-run (filter number? args)]
)
(define-values (suppressed-test-output suppressed-output-extractor)
(if quiet (open-string-output-port)
(values (current-output-port) #f)))
;; This (long) sub-procedure executes a single test:
(let ([execute-one-test
(lambda (num entry)
; (IFCHEZ (collect) ;; [2006.02.18] Let's do a bit of collection between tests to reduce pauses.
(match entry
[(,descr ,extraflags ,expr ,intended)
;(printf "extraflags! ~a\n" extraflags)
(fluid-let ([retry-failures (or retry-failures (memq 'retry extraflags))])
(let retryloop ((try 0))
(flush-output-port (current-output-port))
;; This prints a name, or description for the test:
(if (and titles descr) (printf " ~s\n" descr))
(display-constrained `(,num 10) " " `(,expr ,TESTWIDTH)
" -> ")
(if (procedure? intended)
(display-constrained "Satisfy oracle? "
`(,intended ,ORACLEWIDTH) ": ")
(display-constrained `(,intended ,INTENDEDWIDTH) ": "))
(flush-output-port (current-output-port))
(let ([result
(let/ec escape-eval
;; Clear output cache for each new test:
(let-values ()
(with-error-handlers (lambda args
;; Should format the output, but don't want to cause *another* error
;; and thereby go into an infinite loop.
;; Could reparameterize the error-handler... TODO
(printf "default-unit-tester, got ERROR: \n")
(match args
[(,cond ,str)
(printf "~a/n" str)
(display-condition cond)
(newline)]
[,oth (printf "default-unit-tester got ERROR, unexpected arguments: ~s\n" oth)])
)
(lambda ()
(printf "ESCAPING..\n")
(escape-eval 'error))
(lambda ()
(printf "RUNNING TEST \n")
(let ([result #f])
(with-warning-handler
(lambda (who str . args)
(printf "Warning in ~a: ~a\n"
who (apply format str args)))
(lambda ()
(with-output-to-port suppressed-test-output
;;========================================
;; RUN THE TEST:
(lambda ()
(set! result
(reg:top-level-eval (preprocessor expr))))
)))
result)
;;========================================
))))])
; (newline)
(if (or (and (procedure? intended) ;; This means its an oracle
;; If we get an error result, don't run the oracle proc!
;; Oracle proc might not be ready to handle 'error result:
(and (not (eq? result 'error)))
(intended result))
(teq? intended result)) ;; Otherwise its an expected answer
;; This test was a success:
(begin
(printf "PASS\n"))
;; This test was a failure:
(if (and retry-failures ;; But if we're in retry mode try again...
(< try (default-unit-tester-retries))
(not (eq? result 'error))) ;; We don't retry an error!
(begin (printf "fail: But retrying... Retry #~a\n" try)
(retryloop (+ 1 try)))
;; Otherwise just print a notification of the failure and bind it to a global var:
(begin
(set! success #f)
(newline)
(if (procedure? intended)
(printf "FAIL: Expected result to satisfy procedure: ~s\n" intended)
(begin
(printf "FAIL: Expected: \n")
(pretty-print intended)))
(printf "\n Received: \n")
(write result)
; (display-constrained `(,intended 40) " got instead " `(,result 40))
(printf "\n\n For Test: \n")
(pretty-print expr)
(newline)
;(eval `(define failed-unit-test ',expr))
(define-top-level-value 'unit-test-received result)
(define-top-level-value 'unit-test-expected intended)
(define-top-level-value 'failed-unit-test expr)
(define-top-level-value 'default-unit-tester-output
(if quiet (suppressed-output-extractor) #f))
(printf " Test Output:\n")
(printf "----------------------------------------\n")
(display (top-level-value 'default-unit-tester-output))
(printf "----------------------------------------\n")
(printf "Violating test bound to global-variable, try (reg:top-level-eval (top-level-value 'failed-unit-test))\n")
(printf "Expected and received also bound to globals, consider: ")
(printf "(diff (top-level-value 'unit-test-expected) (top-level-value 'unit-test-received))\n")
(printf "If test output was suppressed, you may wish to inspect it: ")
(printf "(display (top-level-value 'default-unit-tester-output))\n")
;(display (top-level-value 'default-unit-tester-output))(flush-output-port (current-output-port))(exit)
;; Regiment specific. If we're in batch mode print the error output.
(when (and (top-level-bound? 'REGIMENT-BATCH-MODE)
(top-level-value 'REGIMENT-BATCH-MODE))
(printf "\nBecause we're in batch mode, printing unit test output here:\n")
(printf "======================================================================\n")
(reg:top-level-eval '(display default-unit-tester-output))
)
;; Use the continuation to escape:
(return #f)
))))))]))]) ;; end execute-one-test
;; Main body of tester:
(if titles
(begin (printf ";; Testing module: ~s\n" message)
(if quiet (printf ";; (with test output suppressed)\n"))
))
(flush-output-port (current-output-port))
(let* ((len (length entries))
;; If we have out of range indices, we ignore them:
(tests-to-run (filter (lambda (i) (< i len)) tests-to-run))
(entries
(if (null? tests-to-run) entries
(map (lambda (i) (list-ref entries i)) tests-to-run)))
(indices (if (null? tests-to-run)
(iota len)
tests-to-run)))
(for-each execute-one-test
indices
entries))
;; If we made it this far, we've passed all the tests, return #t:
#t
))))))
)) ;; End testerproc let binding
;; Regiment specific:
(when enabled
;; Add this unit-tester to the global list:
(reg:all-unit-tests (cons (list message testerproc) (reg:all-unit-tests))))
;; Finally, return the test-executor procedure:
testerproc))))
(define (reg:counttests) ;;shorthand
(apply + (map (lambda (x) (length ((cadr x) 'get))) (reg:all-unit-tests))))
;) ;; End Module
;; [2004.06.11] This runs compiler tests for the whole system, then
;; runs all the unit tests.
;;
;; [2005.02.26] Changing it so that it assumes the files under test
;; are already loaded, and just calls their unit testers by name.
(define (test-units . args)
(printf "\n;; Performing all unit tests. First ensuring all libraries initialized...\n")
(flush-output-port (current-output-port))
;; R6RS hack: pull on the names of all unit testers to make sure we've initialized those libraries:
(reg:top-level-eval (cons 'list (reg:all-tester-names)))
(printf ";; All libraries initialized.\n")
(if (for-all ;andmap
(lambda (pr) (newline) (newline) (apply (cadr pr) args))
(reverse (reg:all-unit-tests))
)
(begin (printf "\n PASSED ALL TESTS.\n") #t)
(if (and (top-level-bound? 'REGIMENT-BATCH-MODE)
(top-level-value 'REGIMENT-BATCH-MODE))
(exit 1)
#f)))
;;====================================================================================================;;
;; END UNIT TESTER ;;
;;====================================================================================================;;
| false |
20af2759a559fe70bcfbfd1050a53dd903c5b1bb
|
ade8daa7fbef806b83e534faaec6cc4ad345c124
|
/scheme-basics/a1-tspl-2009.scm
|
cedbf161d1337d16d935f2d3e782dd4d0f5d7adc
|
[] |
no_license
|
standardgalactic/learning-programming
|
0a53cbe8f638cec20bb0c9d3e04a023bed77ca46
|
fc4e2252e1322f16481f8d39d31abd00837f06ea
|
refs/heads/master
| 2023-01-04T10:35:40.049008 | 2020-11-02T09:42:18 | 2020-11-02T09:42:18 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 28,069 |
scm
|
a1-tspl-2009.scm
|
;; Chapters 1-5
(use-modules (ice-9 pretty-print))
(use-modules (srfi srfi-1)) ; drop/take
(use-modules (srfi srfi-11)) ; let-values
(define pp pretty-print)
;; Line comment
(define (my-square n)
#;(pp n) ; s-expression comment
(* n n)) ; inline comment
;; (pp (my-square 0))
;; (pp (my-square 1))
;; (pp (my-square 2))
;; Local bindings
(define (my-max lst dft)
(if [null? lst]
dft
(let ([fst (car lst)]
[rst (cdr lst)])
(if [> fst dft] (my-max rst fst) (my-max rst dft)))))
;; (pp (my-max '() 0))
;; (pp (my-max '(1 2 3 4) 1))
;; (pp (my-max '(1 3 5 4 7 2 0) 0))
;; Recursive map
(define (my-map fun lst)
(if [null? lst]
'()
(cons (fun (car lst)) (my-map fun (cdr lst)))))
;; (pp (my-map (lambda (x) (* x 10)) '(1 2 3 4)))
;; Recursive filter
(define (my-filter prd? lst)
(cond [(null? lst) '()]
[(prd? (car lst))
(cons (car lst) (my-filter prd? (cdr lst)))]
[else (my-filter prd? (cdr lst))]))
;; (pp (my-filter even? '(1 2 3 4 5 6 7)))
(define (my-any prd? lst)
(if [null? lst]
#f
(or (prd? (car lst)) (my-any prd? (cdr lst)))))
;; (pp (my-any odd? '()))
;; (pp (my-any odd? '(2 4 6)))
;; (pp (my-any odd? '(2 4 5 6)))
(define (my-all prd? lst)
(if [null? lst]
#t
(and (prd? (car lst)) (my-all prd? (cdr lst)))))
;; (pp (my-all odd? '()))
;; (pp (my-all odd? '(1 2 3 4 5)))
;; (pp (my-all odd? '(1 3 5)))
(define (my-foldr fun acc lst)
(if [null? lst]
acc
;; initial accumulator value
(fun (car lst) (my-foldr fun acc (cdr lst)))))
;; (pp (my-foldr + 0 '()))
;; (pp (my-foldr + 0 '(1 2 3 4 5)))
;; (pp (my-foldr cons '() '(a b c)))
(define (my-foldl fun acc lst)
(if [null? lst]
acc
;; new accumulator value
(my-foldl fun (fun (car lst) acc) (cdr lst))))
;; (pp (my-foldl + 0 '()))
;; (pp (my-foldl + 0 '(1 2 3 4 5)))
;; (pp (my-foldl cons '() '(a b c)))
(define (d/dx fun)
(define d (/ 1 100000))
(lambda (x) (/ (- (fun (+ x d)) (fun (- x d))) 2 d)))
(define 2x/dx (d/dx (lambda (x) (* 2 x))))
;; (pp (map 2x/dx '(-10 -5 0 3 7 14)))
;; Apply function
(define (my-sum lst)
(apply + lst))
;; (pp (my-sum '(1 2 3 4 5)))
;; case form
(define (classify num)
(case num
((1 2 3 4 5) 'small)
((6 7 8 9) 'mediuml)
(else 'big)))
;; (pp (classify 2))
;; (pp (classify 7))
;; (pp (classify 15))
;; For side effects only
;; (for-each pp '(a b c d))
;; Lazy evaluation with lambda
(define lazy+ (lambda () (apply + '(1 2 3 4 5))))
;; (pp (lazy+))
;; Memoization is result caching via closure
(define (memoize fun)
(let ([run? #f]
[memoized #f])
;; (lambda ()
;; (cond [run? memoized]
;; [else (set! run? #t) (set! memoized (fun)) memoized]))))
(lambda ()
(if [not run?]
(begin (set! run? #t) (set! memoized (fun))))
memoized)))
(define (big-computation)
;; (pp 'compute)
;; (newline)
(pp 'compute)
'result)
(define mbig-computation (memoize big-computation))
;; (pp (mbig-computation))
;; (pp (mbig-computation))
(define (memoize2 fun)
(define (cache)
(let ([memoized (fun)])
(set! cache (lambda () memoized))
memoized))
(lambda () (cache)))
(define m2big-computation (memoize2 big-computation))
;; (pp (m2big-computation))
;; (pp (m2big-computation))
;; Optional positional/unnamed parameters + default parameters
;; (pp ((lambda* (a b #:optional c d (f 'f))
;; (list a b c d f)) 'a 'b 'c 'd))
;; Optional keyword/named parameters + default paramters
;; (pp ((lambda* (a b #:key c d (f 'f))
;; (list a b c d f)) 'a 'b #:d 'd #:c 'c))
;; Optional rest parameters with cons dot
;; (pp ((lambda (a b . rst)
;; (list a b rst)) 'a 'b 'c 'd))
;; Optional rest parameters
;; (pp ((lambda* (a b #:rest c)
;; (list a b c)) 'a 'b 'c 'd))
;; Optional/positional, keword/named, rest, and default parameters: all-in-one
(define* (my-params a #:optional (b 'b) #:key (c 'c) #:rest rst)
(list a b c rst))
;; Mandatory parameter
;; (pp (my-params 'A))
;; Optional/positional parameter
;; (pp (my-params 'A 'B))
;; Keyword/named parameter
;; (pp (my-params 'A 'B #:c 'C))
;; Rest of parameters
;; (pp (my-params 'A 'B #:c 'C 'R 'Q))
;; Closures
(define* (make-counter #:key (start 0) (step 1))
(let ([cnt start])
(lambda ()
(set! cnt (+ cnt step))
cnt)))
;; (define counter1 (make-counter))
;; (define counter2 (make-counter #:step 10 #:start 100))
;; (pp (counter1))
;; (pp (counter2))
;; (pp (counter1))
;; (pp (counter1))
;; (pp (counter2))
#|
** Scheme langauge block comment **
|#
(define square (lambda (x) (* x x)))
;; (pp (square 4))
(define reciprocal (lambda (x) (if [= x 0] "oh" (/ 1 x))))
;; (pp (reciprocal 0))
;; (pp (reciprocal 2))
;; Nested let expressions
;; (let ([a 3] [b 4])
;; (let ([aa (* a a)] [bb (* b b)])
;; (+ aa bb a b)))
;; Local variable binding shadowing
;; (let ([x 1])
;; (let ([x 2])
;; x))
;; Lambda exmpression yield procedure
;; (let ([double (lambda (x) (+ x x))])
;; (list (double 1) (double 2)))
;; (let ([double-any (lambda (fun x) (fun x x))])
;; (list (double-any + 1) (double-any cons 'a)))
;; let is implemented in terms of lambda
;; (let ([x 'a]) (cons x x))
;; ((lambda (x) (cons x x)) 'a)
;; lambda > proper list > exact number of parameters (all mandatory)
;; ((lambda (a b) (cons a b)) 'a 'b)
;; lambda > single variable > all parameters as a rest list (all optional)
;; ((lambda rst rst) 'a 'b 'c)
;; lambda > improper list > exact number + rest parameters (mandatory + optional)
;; ((lambda (a b . rst) (list a b rst)) 'a 'b 'c 'd)
;; Top-level lambda definition
(define my-list (lambda x x))
;; (pp (my-list 1 2 3 4))
(define my-cadr (lambda (lst) (car (cdr lst))))
;; (pp (my-cadr '(1 2 3 4)))
(define my-cddr (lambda (lst) (cdr (cdr lst))))
;; (pp (my-cddr '(1 2 3 4)))
;; Top-level lambda definition (abbrieviated)
(define (my-list2 . rst)
rst)
;; (pp (my-list2))
;; (pp (my-list2 1))
;; (pp (my-list2 1 2))
(define (doubler fun)
(lambda (x) (fun x x)))
;; (define double+ (doubler +))
;; (pp (double+ 1/2))
;; Procedure can be defined in any order
;; Reference proc2, then define proc2
(define (proc1) (proc2))
(define (proc2) 'proc2-from-proc1)
;; (pp (proc1))
;; Procedure composition (less efficient)
(define (my-compose p1 p2)
(lambda (x) (p1 (p2 x))))
;; (define my-cadr2 (my-compose car cdr))
;; (pp (my-cadr2 '(1 2 3 4)))
;; (define my-cddr2 (my-compose cdr cdr))
;; (pp (my-cddr2 '(1 2 3 4)))
;; Conditionals: if
(define (my-abs x)
(if [< x 0] (- x) x))
;; (pp (my-abs 1))
;; (pp (my-abs 0))
;; (pp (my-abs -1))
;; Conditionals: and
(define (reciprocal2 x)
(and (not (= x 0)) (/ 1 x)))
;; (pp (reciprocal2 2))
;; (pp (reciprocal2 0))
;; (pp (reciprocal2 -2))
;; Assertion violation
(define (reciprocal3 x)
(if [and (number? x) (not (= x 0))]
(/ 1 x)
(error "reciprocal3: improper argument:" x)))
;; (pp (reciprocal3 2))
;; (pp (reciprocal3 0))
;; (pp (reciprocal3 -2))
;; Conditionals: cond
(define (my-sign x)
(cond [(> x 0) 1]
[(< x 0) -1]
[else 0]))
;; (pp (my-sign 2))
;; (pp (my-sign 0))
;; (pp (my-sign -2))
(define (atom? x)
(not (pair? x)))
;; (pp (atom? '(a . a)))
;; (pp (atom? '()))
(define (shorter x y)
(if [<= (length x) (length y)] x y))
;; (pp (shorter '(a) '(b)))
;; (pp (shorter '(a) '(b c)))
;; (pp (shorter '(a b) '(c)))
;; Simple recursion
(define (my-length lst)
(if [null? lst] 0 (+ (my-length (cdr lst)) 1)))
;; (pp (my-length '()))
;; (pp (my-length '(a)))
;; (pp (my-length '(a b)))
;; Trace procedure
;; (trace my-length)
;; (my-length '(a b c d))
;; Treat the structure of pairs as a list
;; Singly recursive step for cdr only!
(define (list-copy lst)
(if [null? lst]
'()
(let ([fst (car lst)]
[rst (cdr lst)])
(cons fst (list-copy rst)))))
;; (pp (list-copy '()))
;; (pp (list-copy '(a b c)))
(define (membr x lst)
(cond [(null? lst) #f]
[(eqv? (car lst) x) lst]
[else (membr x (cdr lst))]))
;; (pp (membr 'a '()))
;; (pp (membr 'a '(a b)))
;; (pp (membr 'a '(b a)))
;; (pp (membr 'a '(b c)))
(define (remv x lst)
(cond [(null? lst) '()]
[(eqv? (car lst) x) (remv x (cdr lst))]
[else (cons (car lst) (remv x (cdr lst)))]))
;; (pp (remv 'a '()))
;; (pp (remv 'a '(b c)))
;; (pp (remv 'a '(a b c)))
;; (pp (remv 'a '(a b a c a a)))
;; Treat the structure of pairs as a tree
;; Doubly recursive step for both car and cdr!
(define (tree-copy tr)
(if [not (pair? tr)]
tr
(cons (tree-copy (car tr)) (tree-copy (cdr tr)))))
;; (pp (tree-copy '()))
;; (pp (tree-copy '(a)))
;; (pp (tree-copy '(a b)))
;; (pp (tree-copy '(a b c)))
;; (pp (tree-copy '((a . b) . c)))
(define (my-map2 fun lst)
(if [null? lst]
'()
(let ([fst (car lst)]
[rst (cdr lst)])
(cons (fun fst) (my-map2 fun rst)))))
;; (pp (my-map2 (lambda (x) (* x 10)) '()))
;; (pp (my-map2 (lambda (x) (* x 10)) '(1 2 3 4)))
;; (pp (map cons '(a b c) '(1 2 3)))
(define (my-append x y)
(if [null? x] y (cons (car x) (my-append (cdr x) y))))
;; (pp (my-append '() '()))
;; (pp (my-append '(a) '()))
;; (pp (my-append '() '(A)))
;; (pp (my-append '(a) '(A)))
;; (trace my-append)
;; (pp (my-append '(a b) '(A B)))
(define (my-make-list n x)
;; (or (>= n 0) (error "my-make-list: negative argument" n))
(and (< n 0) (error "my-make-list: negative argument" n))
(if [= n 0] '() (cons x (my-make-list (- n 1) x))))
;; (pp (my-make-list 0 'a))
;; (pp (my-make-list 1 'a))
;; (pp (my-make-list 2 'a))
;; (pp (my-make-list 3 '()))
;; (pp (my-make-list -1 'a))
(define (my-list-ref lst i)
(and (or (< i 0) (> i (- (length lst) 1)))
(error "my-list-ref: index out of bounds" i))
(if [= i 0] (car lst) (my-list-ref (cdr lst) (- i 1))))
;; (pp (my-list-ref '(a b c) 0))
;; (pp (my-list-ref '(a b c) 1))
;; (pp (my-list-ref '(a b c) 2))
;; (pp (my-list-ref '(a b c) 3))
;; (pp (my-list-ref '() 0))
(define (my-list-tail lst i)
(and (or (< i 0) (> i (- (length lst) 1)))
(error "my-list-tail: index out of bounds" i))
(if [= i 0] lst (my-list-tail (cdr lst) (- i 1))))
;; (pp (my-list-tail '(a b c) 0))
;; (pp (my-list-tail '(a b c) 1))
;; (pp (my-list-tail '(a b c) 2))
;; (pp (my-list-tail '(a b c) 3))
;; (pp (my-list-tail '() 0))
(define (shorter? x y)
(cond [(null? x) #t]
[(null? y) #f]
[else (shorter? (cdr x) (cdr y))]))
;; (pp (shorter? '() '()))
;; (pp (shorter? '(a) '()))
;; (pp (shorter? '() '(A)))
;; (pp (shorter? '(a b) '(A)))
;; (pp (shorter? '(a) '(A B)))
(define (shorter2 x y)
(if [shorter? x y] x y))
;; (pp (shorter2 '() '()))
;; (pp (shorter2 '(a) '()))
;; (pp (shorter2 '() '(A)))
;; (pp (shorter2 '(a b) '(A)))
;; (pp (shorter2 '(a) '(A B)))
;; Mutual recursion: same base case, opposite outcomes
(define (my-even? x)
(if [= x 0] #t (my-odd? (- x 1))))
(define (my-odd? x)
(if [= x 0] #f (my-even? (- x 1))))
;; (trace my-even? my-odd?)
;; (pp (my-even? 7))
;; (pp (my-odd? 7))
(define (my-transpose lst)
(let ([a (map car lst)]
[b (map cdr lst)])
(cons a b)))
;; (pp (my-transpose '((a . A) (b . B) (c . C))))
;; Top-level variable assignment
;; (define x 'a)
;; (set! x 'b)
;; (pp x)
;; let- and lambda-bound variable assignment
;; (pp (let ([x 'a])
;; (set! x 'b)
;; x))
;; Quadratic equition solver: ax^2 + bx + c = 0
(define* (solve-quadratic a #:optional (b 0) (c 0))
(let* ([d (sqrt (- (expt b 2) (* 4 a c)))]
[r1 (/ (+ (- b) d) (* 2 a))]
[r2 (/ (- (- b) d) (* 2 a))])
(cons r1 r2)))
;; (pp (solve-quadratic 1))
;; (pp (solve-quadratic 1 -2 -3))
;; Stack implementation using internal state and set! assignment
;; Abstract object design pattern
(define (make-stack)
;; State is maintained in each stack object closure
(let ([stack '()])
;; Expose only set of function for object construction and manipulation
;; (public interface) and change internal implementaiton wihout impacting clients
(lambda (message . args)
(case message
('empty? (null? stack))
('push! (set! stack (cons (car args) stack)))
('top (car stack))
('pop! (set! stack (cdr stack)))
('ref (car (drop stack (car args))))
('set! (let* ([pos (car args)]
[val (cadr args)]
[head (take stack pos)]
[tail (set-car! (drop stack pos) val)])
(append head tail)))
(else (error "stack: unsupported operation" message))))))
;; Each state reference or state change are made explicitly by the object (s1)
(define s1 (make-stack))
;; (pp (s1 'empty?))
;; (s1 'push! 'a)
;; (s1 'push! 'b)
;; (pp (s1 'empty?))
;; (pp (s1 'top))
;; (pp (s1 'ref 0))
;; (pp (s1 'ref 1))
;; (s1 'set! 0 'B)
;; (pp (s1 'ref 0))
;; (s1 'set! 1 'A)
;; (pp (s1 'ref 1))
;; (s1 'pop!)
;; (pp (s1 'top))
;; (s1 'pop!)
;; (pp (s1 'empty?))
;; (s1 'destroy)
;; Change list values via assignment
(define lst '(a b c d))
;; Change first
;; (set-car! lst 'A)
;; (pp lst)
;; Change second
;; (set-car! (cdr lst) 'B)
;; (pp lst)
;; (set-cdr! (cdr lst) '(C D))
;; (pp lst)
;; Queue implementation using list assignment operations
(define (make-queue)
;; Non-empty list (storage for the queue)
(let ([end (cons 'ignored '())])
;; Header pair points to the start and the end of the list
;; Queue is accesed through the header
(cons end end)))
(define (putq! queue value)
(let ([end (cons 'ignored '())])
(set-car! (cdr queue) value)
(set-cdr! (cdr queue) end)
(set-cdr! queue end)))
(define (getq queue)
(if [emptyq? queue] (error "getq: empty queue"))
(car (car queue)))
(define (delq! queue)
(if [emptyq? queue] (error "delq!: empty queue"))
(set-car! queue (cdr (car queue))))
(define (emptyq? queue)
(equal? (car queue) (cdr queue)))
;; (trace make-queue)
;; (trace putq!)
;; (trace delq!)
;; (define q1 (make-queue))
;; (pp (emptyq? q1))
;; (putq! q1 'a)
;; (pp (emptyq? q1))
;; ;; (pp (getq q1))
;; (putq! q1 'b)
;; (putq! q1 'c)
;; (putq! q1 'd)
;; (pp (getq q1))
;; (delq! q1)
;; (pp (getq q1))
;; (delq! q1)
;; (pp (getq q1))
;; (delq! q1)
;; (delq! q1)
;; (pp (emptyq? q1))
;; (pp (delq! q1))
;; letrec for definition of recursive procedures
;; (pp (letrec ([sum (lambda (lst)
;; (if (null? lst) 0 (+ (car lst) (sum (cdr lst)))))])
;; (sum '(1 2 3 4 5))))
;; letrec for definition of mutually recursive procedures
;; (pp (letrec ([even? (lambda (x)
;; (if (= x 0) #t (odd? (- x 1))))]
;; [odd? (lambda (x)
;; (if (= x 0) #f (even? (- x 1))))])
;; (list (even? 14) (odd? 14))))
;; Variables depend on each other
;; (pp (let* ([x 1]
;; [y (+ x 1)])
;; (+ x y)))
;; Factorial with named (let: single recursive
(define (factorial n)
(let fact ([i n] [res 1])
(if [= i 0] res (fact (- i 1) (* i res)))))
;; (pp (factorial 5))
;; Fibonacci numbers with named (let: double recursive
(define (fibonacci n)
(let fib ([i 0] [curr 1] [prev 0])
(if [= i n] curr (fib (+ i 1) (+ curr prev) curr))))
;; (pp (fibonacci 0))
;; (pp (fibonacci 1))
;; (pp (fibonacci 10))
(define (factor n)
;; Initialization: n - argument, i - current factor, fs - factors accumulator
(let ftor ([n n] [i 2] [fs '()])
;; Edge case for 0 and 1
(cond [(and (<= 0 n 1) (null? fs)) (cons n fs)]
;; Base case: ran out of factors
[(> i n) fs]
;; Recursive case: factor found
[(integer? (/ n i)) (ftor (/ n i) i (cons i fs))]
;; Recursive case: check next factor
[else (ftor n (+ i 1) fs)])))
;; (pp (factor 0))
;; (pp (factor 1))
;; (pp (factor 2))
;; (pp (factor 3))
;; (pp (factor 4))
;; (pp (factor 5))
;; (pp (factor 6))
;; (pp (factor 7))
;; (pp (factor 8))
;; (pp (factor 9))
;; (pp (factor 10))
;; (pp (factor 12))
;; (pp (factor 18))
;; Continuations
;; Continuation k is never used
;; Value is the product: 20
;; (pp (call/cc (lambda (k) (* 5 4))))
;; Continuation k is invoked before the multiplication
;; Value is the value passed to the continuation: 4
;; (pp (call/cc (lambda (k) (* 5 (k 4)))))
;; Confituation k includes the addition by 2
;; Value is the value passed to the confituaiton plus 2: 6
;; (pp (+ 2 (call/cc (lambda (k) (* 5 (k 4))))))
;; Continuation may provide a non-local exit from a recustions
(define (product . lst)
;; Capture continuation
(call/cc
(lambda (break)
(let prod ([lst lst] [prd 1])
(cond [(null? lst) prd]
;; Return immediately by invoking the break continuation
;; Break continuation returns the value to the point
;; where continuation was captured
[(= (car lst) 0) (break 0)]
[else (prod (cdr lst) (* (car lst) prd))])))))
;; (pp (product))
;; (pp (product 0))
;; (pp (product 1))
;; (pp (product 1 2))
;; (pp (product 1 2 0 3))
;; CPS: Continuation Passing Style
(define (div x y success failure)
(if (= y 0)
(failure "division by zero")
(success (quotient x y) (remainder x y))))
;; (pp (div 5 3 list identity)); single identity
;; (pp (div 1 0 list values)); generalized identity
;; product rewritten with CPS instead of continuations
(define (product2 k . lst)
(let prod ([lst lst] [prd 1])
(cond [(null? lst) prd]
[(= (car lst) 0) (k 0)]
[else (prod (cdr lst) (* (car lst) prd))])))
;; (pp (product2 identity 1 2 3 4))
;; (pp (product2 identity 1 2 0 3 4))
;; reciprocal rewritten with CPS
(define (reciprocal4 x y success failure)
(if (= y 0)
(failure "division by zero")
(success (/ x y))))
;; (pp (reciprocal4 1 2 identity identity))
;; (pp (reciprocal4 1 0 identity identity))
;; (let* and (letrec* guarantees left-to-right evaluation order
;; The next binding can depend on the previous binding
;; (pp (let* ([x 1] [y x]) (+ x y)))
;; (pp (letrec* ([x 1] [y x]) (+ x y)))
;; Modularization with internal definitions
;; Top-level, export, module public definition
(define calc #f)
(let ()
;; internal private definitions
(define (do-calc ek expr)
(cond [(number? expr) expr]
[(and (list? expr) (= (length expr) 3))
(let ([op (car expr)]
[args (cdr expr)])
(case op
[(add) (apply-op ek + args)]
[(sub) (apply-op ek - args)]
[(mul) (apply-op ek * args)]
[(div) (apply-op ek / args)]
[else (complain ek "invalid operator" op)]))]
[else (complain ek "invalid expression" expr)]))
(define (apply-op ek op args)
;; recursively apply calc to operand subexpressions
(op (do-calc ek (car args)) (do-calc ek (cadr args))))
(define (complain ek msg expr)
(ek (list msg expr)))
;; Assign top-level, export, module public definition
(set! calc
(lambda (expr)
;; Grab error continuation for complain
(call/cc (lambda (ek)
(do-calc ek expr))))))
;; (pp (calc '(add (mul 2 3) 4)))
;; (pp (calc '(div 1/2 1/3)))
;; (pp (calc '(sub (mul 2 3) (div 4))))
;; (pp (calc '(mul (add 1 2) (pow 2 3))))
;; Syntactic extension with (define-syntax
;; (define-syntax associates transformation procedure with a keyword
(define-syntax my-let ; keyword
;; Transformation procedure (transformer)
(syntax-rules () ;
[(_ ((x e) ...) b1 b2 ...)
((lambda (x ...) b1 b2 ...) e ...)]))
;; (pp (my-let ((x 'vlad) (y 'lana)) (cons x y)))
;; Recursive definition
(define-syntax my-and
(syntax-rules ()
;; No arguments
[(_) #t]
;; Base case
[(_ e) e]
;; Recursion step translates (and into nested (if expressions
[(_ e1 e2 e3 ...)
(if e1 (and e2 e3 ...) #f)]))
;; (pp (my-and))
;; (pp (my-and #f))
;; (pp (my-and #t 'a))
;; (pp (my-and 'a 'b #f))
;; Recursive definition with temporary variable
(define-syntax my-or
(syntax-rules ()
[(_) #t]
[(_ e) e]
[(_ e1 e2 e3 ...)
;; Automatic renaming of introduced identifiers
(let ([t e1])
(if t t (or e2 e3 ...)))]))
;; (pp (my-or))
;; (pp (my-or #f))
;; (pp (my-or #f 'a))
;; (pp (my-or 'a 'b))
;; (when and (unless for side effects instead of one-armed (if
;; (let ([x #f])
;; (when x (pp 'true))
;; (unless x (pp 'false)))
;; Guile (define-module, #:export, (use-modules <=> R6RS (library, (import, (export
(use-modules (a-grade))
;; (pp (gpa c a c b b))
;; (pp (gpa->grade 2.8))
;; (pp (gpa d d d))
;; (pp (gpa->grade 0.0))
;; (case-lambda supports optional parameters
(define my-make-list
(case-lambda
[(n) (my-make-list n #f)]
[(n f)
;; (do iteration mechanism from R5RS
;; variable, initialization, step
(do ([n n (- n 1)]
[lst '() (cons f lst)])
;; test and body
((zero? n) lst))]))
;; (pp (my-make-list 5))
;; (pp (my-make-list 5 'a))
(define my-substring
(case-lambda
[(s) (my-substring s 0 (string-length s))]
[(s start) (my-substring s start (string-length s))]
[(s start end) (substring s start end)]))
;; (pp (my-substring "Vlad"))
;; (pp (my-substring "Vlad" 2))
;; (pp (my-substring "Vlad" 1 4))
;; Recusive macro: (my-let* expands into a set of nested (let expressions
(define-syntax my-let*
(syntax-rules ()
;; Base case
[(_ () e1 e2 ...)
(let () e1 e2 ...)]
;; Recursive case
[(_ ([x1 v1] [x2 v2] ...) e1 e2 ...)
(let ([x1 v1])
;; Recursive call
(my-let* ([x2 v2] ...) e1 e2 ...))]))
;; (pp (my-let* ([x 1] [y x])
;; (list x y)))
;; (letrec example: recursive definition of sum
;; (pp (letrec ([sum (lambda (x)
;; (if (zero? x) 0 (+ x (sum (- x 1)))))])
;; (sum 5)))
;; Construct, pattern match and bind multiple return values simultaneously
(define (return-multiple x)
(values x (* x 10) (* x 100)))
;; (pp (let-values ([(x y z) (return-multiple 4)])
;; (list x y z)))
;; (pp (let-values ([(a b) (values 1 2)] [c (values 1 2 3)])
;; (list a b c)))
;; (pp (let*-values ([(a b) (values 1 2)] [(a b) (values b a)])
;; (list a b)))
;; State change with assignment
(define (make-flip-flop)
(let ([state #f])
(lambda ()
(set! state (not state))
state)))
;; (let ([flip-flop (make-flip-flop)])
;; (pp (flip-flop))
;; (pp (flip-flop))
;; (pp (flip-flop)))
;; (pp (apply + 1 2 '(3 4 5)))
(define (my-first lst)
(apply (lambda (x . y) x) lst))
;; (pp (my-first '(a b c)))
(define (my-rest lst)
(apply (lambda (x . y) y) lst))
;; (pp (my-rest '(a b c)))
;; (pp (let ([x 1])
;; (cond
;; ;; Test result is returned
;; [(= x 2)]
;; ;; Last expression is returned
;; [(= x 2) 'is-one]
;; ;; Lambda is applied to the test result
;; [(= x 1) => (lambda (x) (if x 'is-true 'is-false))]
;; ;; Default expression is returned
;; [else 'default])))
(define-syntax my-when
(syntax-rules ()
[(_ e0 e1 e2 ...)
(if e0 (begin e1 e2 ...))]))
;; (my-when #t (pp 'when-true))
(define-syntax my-unless
(syntax-rules ()
[(_ e0 e1 e2 ...)
(if (not e0) (begin e1 e2 ...))]))
;; (my-unless #f (pp 'unless-false))
;; (pp (let ([x 1] [y 2])
;; (case (+ x y)
;; [(0 2 4 6 8) 'even]
;; [(1 3 5 7 9) 'odd]
;; [else 'out-of-range])))
(define (divisors x)
(let divs ([i 2] [ds '()])
(cond
[(>= i x) ds]
[(integer? (/ x i)) (divs (+ i 1) (cons i ds))]
[else (divs (+ i 1) ds)])))
;; (pp (divisors 0))
;; (pp (divisors 1))
;; (pp (divisors 2))
;; (pp (divisors 12))
;; Tail-recursive factorial with (do
(define (factorial2 n)
;; Variable, initialization, update/rebind
;; Both input and results
(do ([i n (- i 1)] [fac 1 (* fac i)])
;; Exit condition and result
([zero? i] fac)))
;; (pp (factorial2 0))
;; (pp (factorial2 1))
;; (pp (factorial2 5))
(define (fibonacci2 n)
(do ([i 0 (+ i 1)] [prev 0 curr] [curr 1 (+ prev curr)])
([= i n] curr)))
;; (pp (fibonacci 0))
;; (pp (fibonacci 1))
;; (pp (fibonacci 2))
;; (pp (fibonacci 3))
;; (pp (fibonacci 4))
;; (pp (fibonacci 5))
(define (divisors2 x)
(do ([i 2 (+ i 1)]
[ds '() (if (integer? (/ x i)) (cons i ds) ds)])
([>= i x] ds)))
;; (pp (divisors2 0))
;; (pp (divisors2 1))
;; (pp (divisors2 2))
;; (pp (divisors2 12))
;; (scale-vector demonstrates (do for side effects
(define (scale-vector! v k)
;; Advance index
(do ([i 0 (+ i 1)])
;; Stop when vector end reached
([= i (vector-length v)])
;; Side effect by updating vector cells
(vector-set! v i (* (vector-ref v i) k))))
;; (pp (let ([v (vector 1 2 3 4 5)])
;; (scale-vector! v 10)
;; v))
;; Mapping unary operation over single list
;; (pp (map abs '(1 -2 3 -4)))
;; Mapping binary operation over two lists
;; (pp (map + '(1 2 3 4) '(10 20 30 40)))
;; (for-each for side effects
;; (for-each pp '(a b c d))
;; (exists = any/some
;; (pp (any symbol? '(1 #\a "hi" b)))
;; (pp (any member '(a b c) '((b c) (a c) (a b c))))
;; (for-all = all/every
;; (pp (every symbol? '(a b c d)))
;; (pp (every = '(1 2 3 4) '(1.0 2.0 3.0 4.0)))
;; (fold left
;; (pp (fold + 0 '(1 2 3 4 5)))
;; (pp (fold cons '() '(a b c d)))
;; (fold-right
;; (pp (fold-right + 0 '(1 2 3 4 5)))
;; (pp (fold-right cons '() '(a b c d)))
;; Continuation allows for non-local exit
(define (my-member x lst)
(call/cc (lambda (break)
(do ([lst lst (cdr lst)])
([null? lst] #f)
;; Non-local exit, side effect
(when (equal? x (car lst)) (break lst))))))
;; (pp (my-member 'e '(a b c d)))
;; (pp (my-member 'b '(a b c d)))
;; (dynamic-wind with normal body
;; (let ()
;; (dynamic-wind
;; (lambda () (pp 'in-guard))
;; (lambda () (pp 'normal-body))
;; (lambda () (pp 'out-guard))))
;; (dynamic-wind with continuation
;; (let ()
;; (dynamic-wind
;; (lambda () (pp 'in-guard))
;; (lambda () (call/cc (lambda (k) (pp 'continuation-body) k)))
;; (lambda () (pp 'out-guard))))
(use-modules (a-stream))
;; Basic delay/force functionality
;; (pp (let ([p (my-delay (+ 1 2))])
;; (my-force p)))
(define c1 (stream-counter))
;; (pp (stream-car c1))
;; (pp (stream-car (stream-cdr c1)))
(define c2 (stream-counter))
(define c1+c2 (stream-add c1 c2))
;; (pp (stream-car c1+c2))
;; (pp (stream-car (stream-cdr c1+c2)))
;; Multiple values
(define (head&tail lst)
(values (car lst) (cdr lst)))
;; Apply latter consumer to the values produced by former producer with no arguments
;; (pp (call-with-values (lambda () (head&tail '(a b c d))) list))
;; (pp (call-with-values
;; (lambda () (values 'vlad 'lana))
;; (lambda (he she) (cons he she))))
(define (split-even-odd lst)
(if [or (null? lst) (null? (cdr lst))]
;; Empty or singular list
;; Future (odds evens)
(values lst '())
(call-with-values
;; Leave first tow elements to be consed by the below consumer
;; Recurse with the rest of the list
(lambda () (split-even-odd (cddr lst)))
(lambda (odds evens)
;; Cons the first two elements if the list with the recursively split list
(values (cons (car lst) odds)
(cons (cadr lst) evens))))))
;; (pp (call-with-values (lambda () (split-even-odd '(1 2 3 4 5))) list))
;; Continuaiton may accept zero or more than one argument
;; (pp (call-with-values
;; (lambda () (call/cc (lambda (k) (k 'a 'b))))
;; (lambda (a b) (list a b))))
;; Syntactic extension to automate producer lambda definition
(define-syntax with-values
(syntax-rules ()
[(_ expr consumer)
(call-with-values (lambda () expr) consumer)]))
;; (pp (with-values (split-even-odd '(1 2 3 4 5 6 7)) list))
;; (let-values to work with multiple values
;; (pp (let-values ([(odds evens) (split-even-odd '(1 2 3 4 5 6 7))])
;; (list odds evens)))
;; vals without parentheses catches all values
;; (pp (let-values ([vals (values 1 2 3 4 5)])
;; (apply list vals)))
| true |
c199fc7b08ce9b08b107790c1fd31768a5db7849
|
ffab405e7a2bc6f97edcd68e839f6957ea9c0617
|
/Junk/guitest.scm
|
3508f7024e12264e50a3358491e536273606eedd
|
[] |
no_license
|
ranveeraggarwal/chess-titans
|
bf4522f0f4a29b60cd23813195352ca81a458390
|
23725d0d34f28a875c3489879b9396a8c2870746
|
refs/heads/master
| 2016-09-10T12:15:03.158038 | 2013-10-18T17:54:25 | 2013-10-18T17:54:25 | 13,684,738 | 1 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,573 |
scm
|
guitest.scm
|
(require graphics/graphics)
(require racket/gui)
(include "pieces.scm")
(include "board.scm")
(include "boardGUI.scm")
;(require "alphabeta.scm")
(open-graphics)
(define imgWidth 75)
(define imgHeight 75)
(define H 8)
(define V 8)
(define horiz-inset 100)
(define vert-inset 35)
(define right-gap 50)
(define bottom-gap 10)
(define width (* H imgWidth))
(define height (* V imgHeight))
(define depth 3)
(define board1 null)
(define mode 2)
;(define turn 'White)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
;;;;;;;;;;;;;;;;;;;;
(define img-button%
(class object%
(init-field button-name)
(init-field h)
(init-field v)
(init-field width)
(init-field height)
(init-field action)
(init-field center)
(super-new)
(define/public (draw)
((draw-pixmap Chess-Window) button-name (make-posn h v) (make-rgb 0 0 0))
(send center insert this))
(define/public (inside? posn)
(define x (posn-x posn))
(define y (posn-y posn))
(cond [(and (>= x h) (<= x (+ h width)) (>= y v) (<= y (+ v height))) #t]
[else #f]))
(define/public (execute!) (action))
))
(define imgHold%
(class object%
(init-field [imgs '()])
(super-new)
(define/public (insert img)
(set! imgs (append (list img) imgs)))
(define/public (lookinside pos)
(define (helper Imgs)
(if (null? Imgs)
'Empty
(let* ([fst (send (car Imgs) inside? pos)])
(if fst (send (car Imgs) execute!) (helper (cdr Imgs))))))
(helper imgs))))
;;;;A few important things needed. :p
(define Chess-Window (open-viewport "Kasparov Chess" (+ right-gap horiz-inset width) (+ bottom-gap vert-inset height)))
;A mouse click listener which takes an image(actually it's center)
(define (MouseClickListener img)
(define posn (mouse-click-posn (get-mouse-click Chess-Window)))
(cond[(equal? (send img lookinside posn) 'Empty) (MouseClickListener img)]))
(define (show)
((draw-pixmap Chess-Window) "Images/ChessNG.jpg" (make-posn 0 0) (make-rgb 0 0 0))
((draw-pixmap Chess-Window) "Images/Chess.png" (make-posn 330 30) (make-rgb 0 0 0))
(define mainImgHold (make-object imgHold%))
(define new-game (make-object img-button%
"Images/new-game.png" 200 165 160 40
(λ()
(begin
(sleep 0.1)
(send board initialise)
;(set! turn 'White)
(set! board1 board)
((clear-viewport Chess-Window))
(new-game-setup)))
mainImgHold))
(send new-game draw)
(MouseClickListener mainImgHold)
)
(define (new-game-setup)
((draw-pixmap Chess-Window) "Images/ChessNG.jpg" (make-posn 0 0) (make-rgb 0 0 0))
((draw-pixmap Chess-Window) "Images/Chess.png" (make-posn 330 30) (make-rgb 0 0 0))
((draw-pixmap Chess-Window) "Images/1-player.png" (make-posn 220 200) (make-rgb 0 0 0))
(define new-gameHold (make-object imgHold%))
(define level-1 (make-object img-button% "Images/level-1.png" 230 290 120 30
(λ ()
(begin
(sleep 0.1)
((clear-viewport Chess-Window))
(set! mode '1-player)
(set! depth 2)
(play)
)) new-gameHold))
(begin
(send level-1 draw)
(MouseClickListener new-gameHold)))
(show)
| false |
50007f759b66a9288a3436ff1eb659ae4a522a76
|
29fdc68ecadc6665684dc478fc0b6637c1293ae2
|
/test/test-bin.scm
|
955f469facf1535bff73b173f13813a7fa1810e3
|
[
"MIT"
] |
permissive
|
shirok/WiLiKi
|
5f99f74551b2755cb4b8deb4f41a2a770138e9dc
|
f0c3169aabd2d8d410a90033d44acae548c65cae
|
refs/heads/master
| 2023-05-11T06:20:48.006068 | 2023-05-05T18:29:48 | 2023-05-05T18:30:12 | 9,766,292 | 20 | 6 |
MIT
| 2018-10-07T19:15:09 | 2013-04-30T07:40:21 |
Scheme
|
UTF-8
|
Scheme
| false | false | 3,327 |
scm
|
test-bin.scm
|
;; test wiliki tool
(use gauche.test)
(use gauche.process)
(use gauche.version)
(use file.util)
(use sxml.ssax)
(use sxml.sxpath)
(when (version<=? (gauche-version) "0.7.3")
;; need some modules that aren't available until later.
(add-load-path "../util"))
(use sxml.xml-test)
(use www.cgi-test)
(sys-system "rm -rf _test")
(define (command . args)
`("gosh" "-I" "../src" "../bin/wiliki" ,@args))
(test-start "wiliki tool")
;; creating test data
(make-directory* "_test/text")
(with-output-to-file "_test/text/t0.txt"
(lambda ()
(print "TestPage0")
(print "")
(print "* The test page")
(print "WikiLinks")
(print "- [[TestPage1]]")
))
(define *t0*
'(html (head (title "TestPage0"))
(body (h1 "TestPage0")
(h2 ?@ "The test page\n")
(p "WikiLinks\n")
(ul (li (a (@ (href "TestPage1")) "TestPage1"))))))
(with-output-to-file "_test/text/t1.txt"
(lambda ()
(print "Test/Page?<>")
(print "zzz")
))
(define *t1*
'(html (head (title "Test/Page?<>"))
(body (h1 "Test/Page?<>")
(p "zzz\n"))))
(test-section "help")
(test* "wiliki" #t
(let1 s (process-output->string-list (command))
(and (pair? s)
(#/^Usage: wiliki <command>/ (car s))
#t)))
(test* "wiliki help format" #t
(let1 s (process-output->string-list (command "help" "format"))
(and (pair? s)
(#/^Usage: wiliki format/ (car s))
#t)))
(test-section "format")
(test* "wiliki format text" *t0*
(let* ((r (string-join
(process-output->string-list
(command "format" "_test/text/t0.txt"))
"\n" 'suffix))
(s (call-with-input-string r
(cut ssax:xml->sxml <> '()))))
(car ((sxpath '(html)) s)))
test-sxml-match?)
(test* "wiliki format text" *t1*
(let* ((r (string-join
(process-output->string-list
(command "format" "_test/text/t1.txt"))
"\n" 'suffix))
(s (call-with-input-string r
(cut ssax:xml->sxml <> '()))))
(car ((sxpath '(html)) s)))
test-sxml-match?)
(test* "wiliki format text to file" *t0*
(let* ((p (apply run-process
(command "format" "-o" "_test/t0.html"
"_test/text/t0.txt")))
(r (process-wait p))
(s (call-with-input-file "_test/t0.html"
(cut ssax:xml->sxml <> '()))))
(car ((sxpath '(html)) s)))
test-sxml-match?)
(test* "wiliki format dir" `(t ,*t0* ,*t1*)
(let* ((p (apply run-process
(command "format" "_test/text" "_test/html")))
(r (process-wait p))
(f0 "_test/html/TestPage0.html")
(f1 "_test/html/Test_2FPage_3F_3C_3E.html")
(s0 (and (file-exists? f0)
(call-with-input-file f0 (cut ssax:xml->sxml <> '()))))
(s1 (and (file-exists? f1)
(call-with-input-file f1 (cut ssax:xml->sxml <> '()))))
)
`(t ,@(append ((sxpath '(html)) s0)
((sxpath '(html)) s1))))
test-sxml-match?)
(test-end)
| false |
3ce2aebb65f0fe6ae96906c7e448299945d5518d
|
b60afc8736c052a6d8dac28e290197acc705243e
|
/pset1/1-3.scm
|
0fe2152336be0becd32eeed22646810f04ae690f
|
[] |
no_license
|
ncvc/6.945
|
416a81f0072436e2ab1aa02c099a144b56f7e4b5
|
e17b057e5ddf69e2210e8766d197896f6dc2aaf1
|
refs/heads/master
| 2021-01-13T01:58:12.373434 | 2013-05-01T09:50:47 | 2013-05-01T09:50:47 | 8,899,512 | 0 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,330 |
scm
|
1-3.scm
|
; 1.3.a
(define (authorization-wrapper-improved procname proc args)
(cond ((member (eq-get proc 'authorization-key)
(or (eq-get current-user-id 'authorizations)
'()))
(apply proc args))
(else
(error "Unauthorized access" current-user-id procname))))
(define (add-auth-to-func func key)
(eq-put! func 'authorization-key (md5-string key)))
(define (add-auth-keys-to-user user keys)
(eq-put! user 'authorizations (map (lambda (key) (md5-string key)) keys)))
(define current-user-id 3)
(display "\nbefore\n")
(display (sin 1))
(add-auth-to-func sin "ok-to-sin")
(advise-n-ary sin authorization-wrapper-improved)
(display "\nafter adding auth to sin\n")
(display (sin 1))
(add-auth-keys-to-user current-user-id (list "ok-to-sin" "ok-to-cos" "ok-to-atan" "ok-to-read-files"))
(display "\nafter adding auth key to current-user-id\n")
(display (sin 1))
; 1.3.b
; We would want to require authorization for directly accessing various resources, such as the filesystem, any connected databases, or the network. This way, if one program on the server is compromised, it can do minimal damage to other programs on the machine.
; Specifically, we should require authorization for the eval function. This allows execution of arbitrary code, and could be very dangerous if an adversary can gain access to it.
| false |
24541a4731e7504338bf918c6adf02bc01a43980
|
9c8c0fb8f206ea8b1871df102737c1cb51b7c516
|
/tests/parallel-pipeline/worker-with-signaling.scm
|
152b18affc08178609516b7e5ea41c2c0e574d66
|
[
"MIT"
] |
permissive
|
massimo-nocentini/chicken-zmq
|
3c4ca6cbed51e2fbcdcc0b5287b7d05194f039b5
|
b62a1dc8c66c84134770a41802f927d36a7e0f81
|
refs/heads/master
| 2020-04-20T02:32:32.536355 | 2019-04-11T09:00:23 | 2019-04-11T09:00:23 | 168,574,171 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 841 |
scm
|
worker-with-signaling.scm
|
(import scheme
(chicken base)
(chicken process-context)
(chicken random))
(import srfi-1)
(import (chicken bitwise))
(import zmq zhelpers zsugar)
(define (start-worker name)
(zmq-socket ((receiver ZMQ_PULL)
(sender ZMQ_PUSH)
(controller (ZMQ_SUB "KILL")))
(✓₀ (zmq_connect receiver "tcp://localhost:5557"))
(✓₀ (zmq_connect sender "tcp://localhost:5558"))
(✓₀ (zmq_connect controller "tcp://localhost:5559"))
(forever (break)
(zmq-poll
((receiver ZMQ_POLLIN)
(let ((workload (s_recv receiver)))
(print `(Worker ,name will be busy for ,workload msec))
(s_sleep (string->number workload))
(s_send sender "")))
((controller ZMQ_POLLIN) (break))))))
(start-worker (car (command-line-arguments)))
| false |
aa89699696524167e72fef2d529080974e9d6ccb
|
9fe2d608e47449b54fb1e35a9b671ba646fbe57c
|
/Mines Courses/CSCI_400/SlytherLisp/examples/is-prime - Copy.scm
|
35c0d2ecc919ead82096e53b81229ef73ccc6474
|
[] |
no_license
|
CarsonStevens/Mines-Courses
|
4ab0e4ef2fe54bdf799eef8a089a1cd980ef5772
|
1328e882e52d9eecfebc23e98cee41f49b8615dd
|
refs/heads/master
| 2021-06-07T10:39:59.126121 | 2021-05-30T17:37:31 | 2021-05-30T17:37:31 | 164,183,386 | 5 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 799 |
scm
|
is-prime - Copy.scm
|
#!/usr/bin/env slyther
(define (divides? a b)
; return #t if a divides b, #f otherwise
(= (remainder b a) 0))
(define (isqrt n)
; compute (floor (sqrt n)), but "efficently"
(define (isqrt-iter guess)
(let ((next (/ (+ guess (/ n guess)) 2)))
(if (< (abs (- next guess)) 1)
(floor next)
(isqrt-iter next))))
(isqrt-iter (/ n 2)))
(define (prime? n)
(define stop (isqrt n))
(define (prime-iter x)
(and (not (divides? x n))
(if (<= x stop)
(prime-iter (+ 2 x))
#t)))
(cond
((> n 3) (and
(not (divides? 2 n))
(prime-iter 3)))
((>= n 2) #t)
(#t #f)))
(define (print-primes x)
(if (prime? x)
(print x)
NIL)
(print-primes (+ 2 x)))
(print 2)
(print-primes 3)
| false |
725c096be4216d50a362d8d87bd65652598e3f7e
|
a19179bb62bce1795f8918e52b2964a33d1534ec
|
/ch4/ex4.5.scm
|
572f5df31db99ade68fd87d4451cc596020d939e
|
[] |
no_license
|
b0oh/sicp-exercises
|
67c22433f761e3ba3818050da9fdcf1abf38815e
|
58b1c6dfa8bb74499f0d674ab58ad5c21d85ba1a
|
refs/heads/master
| 2020-12-24T16:58:55.398175 | 2013-12-09T09:16:42 | 2013-12-09T09:16:42 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,361 |
scm
|
ex4.5.scm
|
;; Exercise 4.5.
;; http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-26.html#%_thm_4.5
;; Scheme allows an additional syntax for cond clauses,
;; (<test> => <recipient>). If <test> evaluates to a true value,
;; then <recipient> is evaluated. Its value must be a procedure
;; of one argument; this procedure is then invoked on the value of
;; the <test>, and the result is returned as the value of the cond expression.
;; For example
;; (cond ((assoc 'b '((a 1) (b 2))) => cadr)
;; (else false))
;; returns 2.
;; Modify the handling of cond so that it supports this extended syntax.
(load "tests.scm")
(load "interp.scm")
(define (cond-extended-clause? clause)
(eq? '=> (car (cond-actions clause))))
(define (cond-extended-action clause)
(cadr (cond-actions clause)))
(define (cond->if exp)
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (first-exp clauses))
(rest (rest-exps clauses)))
(cond ((cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last -- COND->IF" clauses)))
((cond-extended-clause? first)
(make-if (cond-predicate first)
(list (cond-extended-action first)
(cond-predicate first))
(expand-clauses rest)))
(else
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest)))))))
(expand-clauses (cond-clauses exp)))
(define (ex4.5-tests)
(define env (setup-environment))
(describe "extended cond")
(assert (eval '(cond (true 1)) env) 1)
(assert (eval '(cond (false 1) (else 2)) env) 2)
(assert (eval '(cond (false 1) (true 2)) env) 2)
(assert (eval '(cond (false 1)) env) false)
(assert (eval '(cond (true 1 2 3)) env) 3)
(assert (eval '(begin
(define (assoc key alist)
(cond ((null? alist) false)
((eq? key (car (car alist))) (car alist))
(else (assoc key (cdr alist)))))
(cond ((assoc 'b '((a 1) (b 2))) => cadr)))
env)
2))
| false |
149a6e6de9b1055bc3665e200e8dfaf0c607dff8
|
d17943098180a308ae17ad96208402e49364708f
|
/platforms/js-vm/private/private/sandbox/mzscheme-machine/grammar.ss
|
43279388831d190f80fa1ca7c9b564d4dfcffa30
|
[] |
no_license
|
dyoo/benchmark
|
b3f4f39714cc51e1f0bc176bc2fa973240cd09c0
|
5576fda204529e5754f6e1cc8ec8eee073e2952c
|
refs/heads/master
| 2020-12-24T14:54:11.354541 | 2012-03-02T19:40:48 | 2012-03-02T19:40:48 | 1,483,546 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 686 |
ss
|
grammar.ss
|
#lang scheme
(require redex/reduction-semantics)
(define-language bytecode
(e (loc n)
(loc-noclr n)
(loc-clr n)
(loc-box n)
(loc-box-noclr n)
(loc-box-clr n)
(let-one e e)
(let-void n e)
(let-void-box n e)
(boxenv n e)
(install-value n e e)
(install-value-box n e e)
(application e e ...)
(seq e e e ...)
(branch e e e)
(let-rec (l ...) e)
(indirect x)
(proc-const (τ ...) e)
(case-lam l ...)
l
v)
(l (lam (τ ...) (n ...) e))
(v number
void
'variable
b)
(τ val ref)
(n natural)
(b #t #f)
((x y) variable))
(provide bytecode)
| false |
b7df268e226c7f1b1c55ba45bd29252afaf6f0b5
|
4b480cab3426c89e3e49554d05d1b36aad8aeef4
|
/chapter-01/ex1.03-obsidianl.scm
|
4805260757b4a680096676721c4decec2e2d5f18
|
[] |
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
|
ex1.03-obsidianl.scm
|
;-) 한글버전
(define (세수중큰두숫자의제곱의합 a b c)
(cond ((= (세수중젤작은숫자 a b c) a) (두숫자의제곱의합 b c))
((= (세수중젤작은숫자 a b c) b) (두숫자의제곱의합 a c))
((= (세수중젤작은숫자 a b c) c) (두숫자의제곱의합 a b))))
(define (두숫자의제곱의합 x y)
(+ (제곱 x)(제곱 y)))
(define (세수중젤작은숫자 a b c)
(더작은숫자(더작은숫자 a b)c))
(define (더작은숫자 a b)
(if (< a b)
a
b))
(define (제곱 x) (* x x))
| false |
64baa321da7421356c34e2899810b0c1243a1d4a
|
6e359a216e1e435de5d39bc64e75998945940a8c
|
/ex3.60.scm
|
c0062ba2b928373dffd41d78bc1993c913e9bcb2
|
[] |
no_license
|
GuoDangLang/SICP
|
03a774dd4470624165010f65c27acc35d844a93d
|
f81b7281fa779a9d8ef03997214e47397af1a016
|
refs/heads/master
| 2021-01-19T04:48:22.891605 | 2016-09-24T15:26:57 | 2016-09-24T15:26:57 | 69,106,376 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 362 |
scm
|
ex3.60.scm
|
(load "stream-pac")
(load "ex3.59.scm")
(define (mul-series s1 s2)
(cons-stream (* (stream-car s1) (stream-car s2))
(add-stream (scale-stream (stream-cdr s2)
(stream-car s1))
(mul-series (stream-cdr s1) s2))))
(define x (mul-series sine-series sine-series))
(define y (mul-series cosine-series cosine-series))
(define ans (add-stream x y))
| false |
6dac0aef33422a1bffcb3bd5ac6e7e129e4fd182
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/known-terminals.sls
|
df0f91f104855a1e3065a7b43215c3d1682f8406
|
[] |
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 | 604 |
sls
|
known-terminals.sls
|
(library (system known-terminals)
(export is? known-terminals? linux xterm ansi)
(import (ironscheme-clr-port))
(define (is? a) (clr-is System.KnownTerminals a))
(define (known-terminals? a) (clr-is System.KnownTerminals a))
(define-field-port
linux
#f
#f
(static: property:)
System.KnownTerminals
linux
System.Byte[])
(define-field-port
xterm
#f
#f
(static: property:)
System.KnownTerminals
xterm
System.Byte[])
(define-field-port
ansi
#f
#f
(static: property:)
System.KnownTerminals
ansi
System.Byte[]))
| false |
2eff024b03bd0487a4f029db6ec8e31bea32aac8
|
f4cf5bf3fb3c06b127dda5b5d479c74cecec9ce9
|
/Sources/LispKit/Resources/Libraries/lispkit/sxml/xml.sld
|
956e3feb76b8aa567f3156cb8e0fc5fde53d7f32
|
[
"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 | 92,738 |
sld
|
xml.sld
|
;;; LISPKIT SXML XML
;;;
;;; The library implements an XML parser and a version of the parser which returns the XML
;;; in SXML form. The XML standard supported by this library is
;;; http://www.w3.org/TR/1998/REC-xml-19980210.html
;;; The library fully supports the XML namespaces recommendation at
;;; http://www.w3.org/TR/REC-xml-names
;;;
;;; Copyright information:
;;; xml-parse.scm - XML parsing and conversion to SXML (Scheme-XML)
;;; Copyright © 2007 Aubrey Jaffer
;;; 2007-04 jaffer: demacrofied from public-domain SSAX 5.1
;;; 2017: Packaged for R7RS Scheme by Peter Lane
;;; 2020: Packaged and adapted for LispKit by Matthias Zenger
;;;
;;; Permission to copy-bit this software, to modify it, to redistribute it,
;;; to distribute modified versions, and to use it for any purpose is
;;; granted, subject to the following restrictions and understandings.
;;;
;;; 1. Any copy made of this software must include this copyright notice in full.
;;; 2. I have made no warranty or representation that the operation of this software
;;; will be error-free, and I am under no obligation to provide any services, by
;;; way of maintenance, update, or otherwise.
;;; 3. In conjunction with products arising from the use of this material, there
;;; shall be no use of my name in any advertising, promotional, or sales literature
;;; without prior written consent in each case.
;;;
;;; Adaptation to LispKit
;;; Copyright © 2020 Matthias Zenger. All rights reserved.
(define-library (lispkit sxml xml)
(export ssax-read-char-data
ssax-read-attributes
ssax-read-external-id
ssax-scan-misc
ssax-resolve-name
make-ssax-parser
make-ssax-pi-parser
make-ssax-elem-parser
xml->sxml
ssax-warn
xml-token-kind
xml-token-head)
; (export attlist-add
; attlist-remove-top
; ssax:assert-current-char
; ssax:assert-token
; ssax:complete-start-tag
; ssax:handle-parsed-entity
; ssax:init-buffer
; make-ssax-elem-parser
; make-ssax-parser
; make-ssax-pi-parser
; ssax:next-token
; ssax:next-token-of
; ssax:Prefix-XML
; ssax:read-NCName
; ssax:read-QName
; ssax-read-attributes
; ssax:read-cdata-body
; ssax-read-char-data
; ssax:read-char-ref
; ssax-read-external-id
; ssax:read-markup-token
; ssax:read-pi-body-as-string
; ssax:read-string
; ssax-resolve-name
; ssax:reverse-collect-str-drop-ws
; ssax-scan-misc
; ssax:skip-S
; ssax:skip-internal-dtd
; ssax:skip-pi
; ssax:skip-while
; xml->sxml
; ssax-warn
; ssax:reverse-collect-str)
(import (lispkit base)
(srfi 1))
(begin
(define (ssax-warn port msg . other-msg)
(for-each (lambda (x) (display x (current-error-port)))
`("\nWarning: " msg ,@other-msg "\n")))
;; STRING UTILITIES
(define (substring-move-left! string1 start1 end1 string2 start2)
(do ((i start1 (+ i 1))
(j start2 (+ j 1))
(l (- end1 start1) (- l 1)))
((<= l 0))
(string-set! string2 j (string-ref string1 i))))
(define (string-null? str)
(= 0 (string-length str)))
(define (string-index str chr)
(do ((len (string-length str))
(pos 0 (+ 1 pos)))
((or (>= pos len)
(char=? chr (string-ref str pos)))
(and (< pos len) pos))))
(define (find-string-from-port? str <input-port> . max-no-char-in)
(let ((max-no-char (if (null? max-no-char-in) #f (car max-no-char-in))))
(letrec ((no-chars-read 0)
(peeked? #f)
(my-peek-char ; Return a peeked char or #f
(lambda ()
(and (or (not (number? max-no-char))
(< no-chars-read max-no-char))
(let ((c (peek-char <input-port>)))
(cond (peeked? c)
((eof-object? c) #f)
((procedure? max-no-char)
(set! peeked? #t)
(if (max-no-char c) #f c))
((eqv? max-no-char c) #f)
(else c))))))
(next-char
(lambda ()
(set! peeked? #f)
(read-char <input-port>)
(set! no-chars-read (+ 1 no-chars-read))))
(match-1st-char ; of the string str
(lambda ()
(let ((c (my-peek-char)))
(and c (begin (next-char)
(if (char=? c (string-ref str 0))
(match-other-chars 1)
(match-1st-char)))))))
;; There has been a partial match, up to the point pos-to-match
;; (for example, str[0] has been found in the stream)
;; Now look to see if str[pos-to-match] for would be found, too
(match-other-chars
(lambda (pos-to-match)
(if (>= pos-to-match (string-length str))
no-chars-read ; the entire string has matched
(let ((c (my-peek-char)))
(and c
(if (not (char=? c (string-ref str pos-to-match)))
(backtrack 1 pos-to-match)
(begin (next-char)
(match-other-chars (+ 1 pos-to-match)))))))))
;; There had been a partial match, but then a wrong char showed up.
;; Before discarding previously read (and matched) characters, we check
;; to see if there was some smaller partial match. Note, characters read
;; so far (which matter) are those of str[0..matched-substr-len - 1]
;; In other words, we will check to see if there is such i>0 that
;; substr(str,0,j) = substr(str,i,matched-substr-len)
;; where j=matched-substr-len - i
(backtrack
(lambda (i matched-substr-len)
(let ((j (- matched-substr-len i)))
(if (<= j 0)
;; backed off completely to the begining of str
(match-1st-char)
(let loop ((k 0))
(if (>= k j)
(match-other-chars j) ; there was indeed a shorter match
(if (char=? (string-ref str k)
(string-ref str (+ i k)))
(loop (+ 1 k))
(backtrack (+ 1 i) matched-substr-len)))))))))
(match-1st-char))))
;; Three functions from SRFI-13
;; procedure string-concatenate-reverse STRINGS [FINAL END]
(define (ssax:string-concatenate-reverse strs final end)
(if (null? strs) (string-copy final 0 end)
(let*
((total-len
(let loop ((len end) (lst strs))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((len end) (j total-len) (str final) (lst strs))
(substring-move-left! str 0 len result (- j len))
(if (null? lst) result
(loop (string-length (car lst)) (- j len)
(car lst) (cdr lst)))))))
; string-concatenate/shared STRING-LIST -> STRING
(define (ssax:string-concatenate/shared strs)
(cond ((null? strs) "") ; Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(let*
((total-len
(let loop ((len (string-length (car strs))) (lst (cdr strs)))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((j 0) (str (car strs)) (lst (cdr strs)))
(substring-move-left! str 0 (string-length str) result j)
(if (null? lst) result
(loop (+ j (string-length str))
(car lst) (cdr lst))))))))
;; string-concatenate-reverse/shared STRING-LIST [FINAL-STRING END] -> STRING
;; We do not use the optional arguments of this procedure. Therefore,
;; we do not implement them. See SRFI-13 for the complete implementation.
(define (ssax:string-concatenate-reverse/shared strs)
(cond ((null? strs) "") ; Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(ssax:string-concatenate-reverse (cdr strs)
(car strs)
(string-length (car strs))))))
;; Given the list of fragments (some of which are text strings), reverse the list and
;; concatenate adjacent text strings. If LIST-OF-FRAGS has zero or one element, the
;; result of the procedure is `equal?` to its argument.
(define (ssax:reverse-collect-str fragments)
(cond
((null? fragments) '()) ; a shortcut
((null? (cdr fragments)) fragments) ; see the comment above
(else
(let loop ((fragments fragments) (result '()) (strs '()))
(cond
((null? fragments)
(if (null? strs)
result
(cons (ssax:string-concatenate/shared strs) result)))
((string? (car fragments))
(loop (cdr fragments) result (cons (car fragments) strs)))
(else
(loop (cdr fragments)
(cons (car fragments)
(if (null? strs)
result
(cons (ssax:string-concatenate/shared strs) result)))
'())))))))
;; Given the list of fragments (some of which are text strings), reverse the list and
;; concatenate adjacent text strings while dropping "unsignificant" whitespace, that is,
;; whitespace in front, behind and between elements. The whitespace that is included in
;; character data is not affected.
;;
;; Use this procedure to "intelligently" drop "insignificant" whitespace in the parsed
;; SXML. If the strict compliance with the XML Recommendation regarding the whitespace
;; is desired, use the `ssax:reverse-collect-str` procedure instead.
(define (ssax:reverse-collect-str-drop-ws fragments)
; Test if a string is made of only whitespace.
; An empty string is considered made of whitespace as well
(define (string-whitespace? str)
(let ((len (string-length str)))
(cond ((zero? len) #t)
((= 1 len) (char-whitespace? (string-ref str 0)))
(else
(let loop ((i 0))
(or (>= i len)
(and (char-whitespace? (string-ref str i))
(loop (+ 1 i)))))))))
(cond
((null? fragments) '()) ; a shortcut
((null? (cdr fragments)) ; another shortcut
(if (and (string? (car fragments)) (string-whitespace? (car fragments)))
'() ; remove trailing ws
fragments))
(else
(let loop ((fragments fragments) (result '()) (strs '())
(all-whitespace? #t))
(cond
((null? fragments)
(if all-whitespace?
result ; remove leading ws
(cons (ssax:string-concatenate/shared strs) result)))
((string? (car fragments))
(loop (cdr fragments)
result
(cons (car fragments) strs)
(and all-whitespace? (string-whitespace? (car fragments)))))
(else
(loop (cdr fragments)
(cons (car fragments)
(if all-whitespace?
result
(cons (ssax:string-concatenate/shared strs) result)))
'()
#t)))))))
;; CHARACTER AND TOKEN FUNCTIONS
;; The following functions either skip, or build and return tokens,
;; according to inclusion or delimiting semantics. The list of
;; characters to expect, include, or to break at may vary from one
;; invocation of a function to another. This allows the functions to
;; easily parse even context-sensitive languages.
;;
;; Exceptions are mentioned specifically. The list of expected
;; characters (characters to skip until, or break-characters) may
;; include an EOF "character", which is coded as symbol *eof*
;;
;; The input stream to parse is specified as a PORT, which is the last argument.
;; Reads a character from the @3 and looks it up in the
;; @1 of expected characters. If the read character was
;; found among expected, it is returned. Otherwise, the
;; procedure writes a message using @2 as a comment and quits.
(define (ssax:assert-current-char expected-chars comment port)
(let ((c (read-char port)))
(if (memv c expected-chars) c
(error port "Wrong character " c
" (0x" (if (eof-object? c)
"*eof*"
(number->string (char->integer c) 16)) ") "
comment ". " expected-chars " expected"))))
;; Reads characters from the @2 and disregards them, as long as they
;; are mentioned in the @1. The first character (which may be EOF)
;; peeked from the stream that is @emph{not} a member of the @1 is returned.
(define (ssax:skip-while skip-chars port)
(do ((c (peek-char port) (peek-char port)))
((not (memv c skip-chars)) c)
(read-char port)))
;; STREAM TOKENIZERS
;; Note: since we can't tell offhand how large the token being read is
;; going to be, we make a guess, pre-allocate a string, and grow it by
;; quanta if necessary. The quantum is always the length of the string
;; before it was extended the last time. Thus the algorithm does a
;; Fibonacci-type extension, which has been proven optimal.
;;
;; Size 32 turns out to be fairly good, on average. That policy is
;; good only when a Scheme system is multi-threaded with preemptive
;; scheduling, or when a Scheme system supports shared substrings. In
;; all the other cases, it's better for ssax:init-buffer to return the
;; same static buffer. ssax:next-token* functions return a copy (a
;; substring) of accumulated data, so the same buffer can be reused.
;; We shouldn't worry about an incoming token being too large:
;; ssax:next-token will use another chunk automatically. Still, the
;; best size for the static buffer is to allow most of the tokens to
;; fit in. Using a static buffer _dramatically_ reduces the amount of
;; produced garbage (e.g., during XML parsing).
;; Returns an initial buffer for `ssax:next-token*` procedures; may allocate a
;; new buffer at each invocation.
(define (ssax:init-buffer)
(make-string 32))
;;;(define ssax:init-buffer
;;; (let ((buffer (make-string 512)))
;;; (lambda () buffer)))
;; Skips any number of the prefix characters (members of the @1), if
;; any, and reads the sequence of characters up to (but not including)
;; a break character, one of the `break-chars`.
;;
;; The string of characters thus read is returned. The break character
;; is left on the input stream. `break-chars` may include the symbol `*eof*`;
;; otherwise, EOF is fatal, generating an error message including a
;; specified `comment`.
(define (ssax:next-token prefix-skipped-chars break-chars comment port)
(let outer ((buffer (ssax:init-buffer)) (filled-buffer-l '())
(c (ssax:skip-while prefix-skipped-chars port)))
(let ((curr-buf-len (string-length buffer)))
(let loop ((i 0) (c c))
(cond
((memv c break-chars)
(if (null? filled-buffer-l) (string-copy buffer 0 i)
(ssax:string-concatenate-reverse filled-buffer-l buffer i)))
((eof-object? c)
(if (memq '*eof* break-chars) ; was EOF expected?
(if (null? filled-buffer-l) (string-copy buffer 0 i)
(ssax:string-concatenate-reverse filled-buffer-l buffer i))
(error port "EOF while reading a token " comment)))
((>= i curr-buf-len)
(outer (make-string curr-buf-len)
(cons buffer filled-buffer-l) c))
(else
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (+ 1 i) (peek-char port))))))))
;; will try to read an alphabetic token from the current input port,
;; and return it in lower case.
(define (ssax:next-token-of incl-list/pred port)
(let* ((buffer (ssax:init-buffer))
(curr-buf-len (string-length buffer)))
(if (procedure? incl-list/pred)
(let outer ((buffer buffer) (filled-buffer-l '()))
(let loop ((i 0))
(if (>= i curr-buf-len) ; make sure we have space
(outer (make-string curr-buf-len) (cons buffer filled-buffer-l))
(let ((c (incl-list/pred (peek-char port))))
(if c
(begin
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (+ 1 i)))
;; incl-list/pred decided it had had enough
(if (null? filled-buffer-l) (string-copy buffer 0 i)
(ssax:string-concatenate-reverse filled-buffer-l buffer i)))))))
;; incl-list/pred is a list of allowed characters
(let outer ((buffer buffer) (filled-buffer-l '()))
(let loop ((i 0))
(if (>= i curr-buf-len) ; make sure we have space
(outer (make-string curr-buf-len) (cons buffer filled-buffer-l))
(let ((c (peek-char port)))
(cond
((not (memv c incl-list/pred))
(if (null? filled-buffer-l) (string-copy buffer 0 i)
(ssax:string-concatenate-reverse filled-buffer-l buffer i)))
(else
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (+ 1 i))))))))
)))
;; Reads @1 characters from the @2, and returns them in a string. If
;; EOF is encountered before @1 characters are read, a shorter string
;; will be returned.
(define (ssax:read-string len port)
(define buffer (make-string len))
(do ((idx 0 (+ 1 idx)))
((>= idx len) (string-copy buffer 0 idx))
(let ((chr (read-char port)))
(cond ((eof-object? chr)
(set! idx (+ -1 idx))
(set! len idx))
(else (string-set! buffer idx chr))))))
;; DATA TYPES
;; TAG-KIND
;; a symbol 'START, 'END, 'PI, 'DECL, 'COMMENT, 'CDSECT or 'ENTITY-REF that identifies
;; a markup token
;;
;; UNRES-NAME
;; a name (called GI in the XML Recommendation) as given in an xml document for a markup
;; token: start-tag, PI target, attribute name. If a GI is an NCName, UNRES-NAME is this
;; NCName converted into a Scheme symbol. If a GI is a QName, UNRES-NAME is a pair of
;; symbols: (PREFIX . LOCALPART)
;;
;; RES-NAME
;; An expanded name, a resolved version of an UNRES-NAME. For an element or an attribute
;; name with a non-empty namespace URI, RES-NAME is a pair of symbols,
;; (URI-SYMB . LOCALPART). Otherwise, it's a single symbol.
;;
;; ELEM-CONTENT-MODEL
;; A symbol:
;; ANY - anything goes, expect an END tag.
;; EMPTY-TAG - no content, and no END-tag is coming
;; EMPTY - no content, expect the END-tag as the next token
;; PCDATA - expect character data only, and no children elements
;; MIXED
;; ELEM-CONTENT
;;
;; URI-SYMB
;; A symbol representing a namespace URI -- or other symbol chosen
;; by the user to represent URI. In the former case,
;; URI-SYMB is created by %-quoting of bad URI characters and
;; converting the resulting string into a symbol.
;;
;; NAMESPACES
;; A list representing namespaces in effect. An element of the list has one of the
;; following forms:
;; (PREFIX URI-SYMB . URI-SYMB) or
;; (PREFIX USER-PREFIX . URI-SYMB)
;; USER-PREFIX is a symbol chosen by the user to represent the URI.
;; (#f USER-PREFIX . URI-SYMB)
;; Specification of the user-chosen prefix and a URI-SYMBOL.
;; (*DEFAULT* USER-PREFIX . URI-SYMB)
;; Declaration of the default namespace
;; (*DEFAULT* #f . #f)
;; Un-declaration of the default namespace. This notation represents overriding of the
;; previous declaration
;; A NAMESPACES list may contain several elements for the same PREFIX.
;; The one closest to the beginning of the list takes effect.
;;
;; ATTLIST
;; An ordered collection of (NAME . VALUE) pairs, where NAME is
;; a RES-NAME or an UNRES-NAME. The collection is an ADT
;;
;; STR-HANDLER
;; A procedure of three arguments: STRING1 STRING2 SEED returning a new SEED
;; The procedure is supposed to handle a chunk of character data
;; STRING1 followed by a chunk of character data STRING2.
;; STRING2 is a short string, often "\n" and even ""
;;
;; ENTITIES
;; An assoc list of pairs:
;; (named-entity-name . named-entity-body)
;; where named-entity-name is a symbol under which the entity was declared,
;; named-entity-body is either a string, or (for an external entity) a thunk that
;; will return an input port (from which the entity can be read). named-entity-body
;; may also be #f. This is an indication that a named-entity-name is currently being
;; expanded. A reference to this named-entity-name will be an error: violation of the
;; WFC nonrecursion.
;;
;; XML-TOKEN -- a record
;;
;; We define xml-token simply as a pair. Furthermore, xml-token-kind and xml-token-head
;; can be defined as simple procedures.
;;
;; This record represents a markup, which is, according to the XML
;; recommendation, "takes the form of start-tags, end-tags, empty-element tags,
;; entity references, character references, comments, CDATA section delimiters,
;; document type declarations, and processing instructions."
;;
;; kind -- a TAG-KIND
;; head -- an UNRES-NAME. For xml-tokens of kinds 'COMMENT and 'CDSECT, the head is #f
;;
;; For example,
;; <P> => kind='START, head='P
;; </P> => kind='END, head='P
;; <BR/> => kind='EMPTY-EL, head='BR
;; <!DOCTYPE OMF ...> => kind='DECL, head='DOCTYPE
;; <?xml version="1.0"?> => kind='PI, head='xml
;; &my-ent; => kind = 'ENTITY-REF, head='my-ent
;;
;; Character references are not represented by xml-tokens as these references
;; are transparently resolved into the corresponding characters.
;;
;; XML-DECL -- a record
;;
;; The record represents a datatype of an XML document: the list of declared elements and
;; their attributes, declared notations, list of replacement strings or loading procedures
;; for parsed general entities, etc. Normally an xml-decl record is created from a DTD or
;; an XML Schema, although it can be created and filled in in many other ways (e.g.,
;; loaded from a file).
;;
;; elems: an (assoc) list of decl-elem or #f. The latter instructs the parser to do no
;; validation of elements and attributes.
;;
;; decl-elem: declaration of one element:
;; (elem-name elem-content decl-attrs)
;; elem-name is an UNRES-NAME for the element.
;; elem-content is an ELEM-CONTENT-MODEL.
;; decl-attrs is an ATTLIST, of (ATTR-NAME . VALUE) associations
;; !!!This element can declare a user procedure to handle parsing of an
;; element (e.g., to do a custom validation, or to build a hash of
;; IDs as they're encountered).
;;
;; decl-attr: an element of an ATTLIST, declaration of one attribute
;; (attr-name content-type use-type default-value)
;; attr-name is an UNRES-NAME for the declared attribute
;; content-type is a symbol: CDATA, NMTOKEN, NMTOKENS, ...
;; or a list of strings for the enumerated type.
;; use-type is a symbol: REQUIRED, IMPLIED, FIXED
;; default-value is a string for the default value, or #f if not given.
;; see a function make-empty-xml-decl to make a XML declaration entry
;; suitable for a non-validating parsing.
;; We define xml-token simply as a pair.
(define (make-xml-token kind head) (cons kind head))
(define xml-token? pair?)
(define xml-token-kind car)
(define xml-token-head cdr)
;; LOW-LEVEL PARSERS AND SCANNERS
;;
;; These procedures deal with primitive lexical units (Names, whitespaces, tags)
;; and with pieces of more generic productions. Most of these parsers
;; must be called in appropriate context. For example, ssax:complete-start-tag
;; must be called only when the start-tag has been detected and its GI
;; has been read.
(define char-return (integer->char 13))
(define ssax:S-chars (map integer->char '(32 10 9 13)))
;; Skip the S (whitespace) production as defined by
;; [3] S ::= (#x20 | #x9 | #xD | #xA)
;; The procedure returns the first not-whitespace character it
;; encounters while scanning the PORT. This character is left
;; on the input stream.
;;
;; `ssax:skip-S` returns the first not-whitespace character it encounters while
;; scanning `port`. This character is left on the input stream.
(define (ssax:skip-S port)
(ssax:skip-while ssax:S-chars port))
;; Check to see if a-char may start a NCName
(define (ssax:ncname-starting-char? a-char)
(and (char? a-char)
(or (char-alphabetic? a-char)
(char=? #\_ a-char))))
;; Read a Name lexem and return it as string
;;
;; [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender
;; [5] Name ::= (Letter | '_' | ':') (NameChar)*
;;
;; This code supports the XML Namespace Recommendation REC-xml-names,
;; which modifies the above productions as follows:
;;
;; [4] NCNameChar ::= Letter | Digit | '.' | '-' | '_' | CombiningChar | Extender
;; [5] NCName ::= (Letter | '_') (NCNameChar)*
;;
;; As the Rec-xml-names says,
;; "An XML document conforms to this specification if all other tokens
;; [other than element types and attribute names] in the document which
;; are required, for XML conformance, to match the XML production for
;; Name, match this specification's production for NCName."
;; Element types and attribute names must match the production QName,
;; defined below.
;;
;; Read a NCName starting from the current position in the PORT and
;; return it as a symbol.
(define (ssax:read-NCName port)
(let ((first-char (peek-char port)))
(or (ssax:ncname-starting-char? first-char)
(error port "XMLNS [4] for '" first-char "'")))
(string->symbol (ssax:next-token-of (lambda (c)
(cond ((eof-object? c) #f)
((char-alphabetic? c) c)
((string-index "0123456789.-_" c) c)
(else #f)))
port)))
;; Read a (namespace-) Qualified Name, QName, from the current
;; position in the PORT.
;; From REC-xml-names:
;; [6] QName ::= (Prefix ':')? LocalPart
;; [7] Prefix ::= NCName
;; [8] LocalPart ::= NCName
;; Return: an UNRES-NAME
(define (ssax:read-QName port)
(let ((prefix-or-localpart (ssax:read-NCName port)))
(case (peek-char port)
((#\:)
(read-char port)
(cons prefix-or-localpart (ssax:read-NCName port)))
(else prefix-or-localpart))))
;;The prefix of the pre-defined XML namespace
(define ssax:Prefix-XML (string->symbol "xml"))
;;An UNRES-NAME that is postulated to be larger than anything that can
;;occur in a well-formed XML document. ssax:name-compare enforces
;;this postulate.
(define ssax:largest-unres-name (cons (string->symbol "#LARGEST-SYMBOL")
(string->symbol "#LARGEST-SYMBOL")))
;; Compare one RES-NAME or an UNRES-NAME with the other.
;; Return a symbol '<, '>, or '= depending on the result of
;; the comparison.
;; Names without PREFIX are always smaller than those with the PREFIX.
(define ssax:name-compare
(letrec ((symbol-compare
(lambda (symb1 symb2)
(cond
((eq? symb1 symb2) '=)
((string<? (symbol->string symb1) (symbol->string symb2))
'<)
(else '>)))))
(lambda (name1 name2)
(cond
((symbol? name1) (if (symbol? name2) (symbol-compare name1 name2)
'<))
((symbol? name2) '>)
((eq? name2 ssax:largest-unres-name) '<)
((eq? name1 ssax:largest-unres-name) '>)
((eq? (car name1) (car name2)) ; prefixes the same
(symbol-compare (cdr name1) (cdr name2)))
(else (symbol-compare (car name1) (car name2)))))))
;; procedure: ssax:read-markup-token PORT
;; This procedure starts parsing of a markup token. The current position
;; in the stream must be #\<. This procedure scans enough of the input stream
;; to figure out what kind of a markup token it is seeing. The procedure returns
;; an xml-token structure describing the token. Note, generally reading
;; of the current markup is not finished! In particular, no attributes of
;; the start-tag token are scanned.
;;
;; Here's a detailed break out of the return values and the position in the PORT
;; when that particular value is returned:
;; PI-token: only PI-target is read.
;; To finish the Processing Instruction and disregard it,
;; call ssax:skip-pi. ssax-read-attributes may be useful
;; as well (for PIs whose content is attribute-value
;; pairs)
;; END-token: The end tag is read completely; the current position
;; is right after the terminating #\> character.
;; COMMENT is read and skipped completely. The current position
;; is right after "-->" that terminates the comment.
;; CDSECT The current position is right after "<!CDATA["
;; Use ssax:read-cdata-body to read the rest.
;; DECL We have read the keyword (the one that follows "<!")
;; identifying this declaration markup. The current
;; position is after the keyword (usually a
;; whitespace character)
;;
;; START-token We have read the keyword (GI) of this start tag.
;; No attributes are scanned yet. We don't know if this
;; tag has an empty content either.
;; Use ssax:complete-start-tag to finish parsing of
;; the token.
(define ssax:read-markup-token ; procedure ssax:read-markup-token port
(let ()
;; we have read "<!-". Skip through the rest of the comment
;; Return the 'COMMENT token as an indication we saw a comment
;; and skipped it.
(define (skip-comment port)
(ssax:assert-current-char '(#\-) "XML [15], second dash" port)
(if (not (find-string-from-port? "-->" port))
(error port "XML [15], no -->"))
(make-xml-token 'COMMENT #f))
;; we have read "<![" that must begin a CDATA section
(define (read-cdata port)
(define cdstr (ssax:read-string 6 port))
(if (not (string=? "CDATA[" cdstr))
(error "expected 'CDATA[' but read " cdstr))
(make-xml-token 'CDSECT #f))
(lambda (port)
(ssax:assert-current-char '(#\<) "start of the token" port)
(case (peek-char port)
((#\/) (read-char port)
(let ((val (make-xml-token 'END (ssax:read-QName port))))
(ssax:skip-S port)
(ssax:assert-current-char '(#\>) "XML [42]" port)
val))
((#\?) (read-char port) (make-xml-token 'PI (ssax:read-NCName port)))
((#\!)
(read-char port)
(case (peek-char port)
((#\-) (read-char port) (skip-comment port))
((#\[) (read-char port) (read-cdata port))
(else (make-xml-token 'DECL (ssax:read-NCName port)))))
(else (make-xml-token 'START (ssax:read-QName port)))))))
;; The current position is inside a PI. Skip till the rest of the PI
(define (ssax:skip-pi port)
(if (not (find-string-from-port? "?>" port))
(error port "Failed to find ?> terminating the PI")))
;; procedure: ssax:read-pi-body-as-string PORT
;; The current position is right after reading the PITarget. We read the
;; body of PI and return is as a string. The port will point to the
;; character right after '?>' combination that terminates PI.
;; [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
(define (ssax:read-pi-body-as-string port)
(ssax:skip-S port) ; skip WS after the PI target name
(ssax:string-concatenate/shared
(let loop ()
(let ((pi-fragment
(ssax:next-token '() '(#\?) "reading PI content" port)))
(read-char port)
(if (eqv? #\> (peek-char port))
(begin
(read-char port)
(cons pi-fragment '()))
(cons* pi-fragment "?" (loop)))))))
;; procedure: ssax:skip-internal-dtd PORT
;; The current pos in the port is inside an internal DTD subset
;; (e.g., after reading #\[ that begins an internal DTD subset)
;; Skip until the "]>" combination that terminates this DTD
(define (ssax:skip-internal-dtd port)
(ssax-warn port "Internal DTD subset is not currently handled ")
(if (not (find-string-from-port? "]>" port))
(error port "Failed to find ]> terminating the internal DTD subset")))
;; procedure+: ssax:read-cdata-body PORT STR-HANDLER SEED
;;
;; This procedure must be called after we have read a string "<![CDATA["
;; that begins a CDATA section. The current position must be the first
;; position of the CDATA body. This function reads _lines_ of the CDATA
;; body and passes them to a STR-HANDLER, a character data consumer.
;;
;; The str-handler is a STR-HANDLER, a procedure STRING1 STRING2 SEED.
;; The first STRING1 argument to STR-HANDLER never contains a newline.
;; The second STRING2 argument often will. On the first invocation of
;; the STR-HANDLER, the seed is the one passed to ssax:read-cdata-body
;; as the third argument. The result of this first invocation will be
;; passed as the seed argument to the second invocation of the line
;; consumer, and so on. The result of the last invocation of the
;; STR-HANDLER is returned by the ssax:read-cdata-body. Note a
;; similarity to the fundamental 'fold' iterator.
;;
;; Within a CDATA section all characters are taken at their face value,
;; with only three exceptions:
;; CR, LF, and CRLF are treated as line delimiters, and passed
;; as a single #\newline to the STR-HANDLER
;; "]]>" combination is the end of the CDATA section.
;; > is treated as an embedded #\> character
;; Note, < and & are not specially recognized (and are not expanded)!
(define ssax:read-cdata-body
(let ((cdata-delimiters (list char-return #\newline #\] #\&)))
(lambda (port str-handler seed)
(let loop ((seed seed))
(let ((fragment (ssax:next-token '() cdata-delimiters "reading CDATA" port)))
;; that is, we're reading the char after the 'fragment'
(case (read-char port)
((#\newline) (loop (str-handler fragment (string #\newline) seed)))
((#\])
(if (not (eqv? (peek-char port) #\]))
(loop (str-handler fragment "]" seed))
(let check-after-second-braket
((seed (if (string-null? fragment) seed
(str-handler fragment "" seed))))
(read-char port)
(case (peek-char port) ; after the second bracket
((#\>) (read-char port) seed) ; we have read "]]>"
((#\]) (check-after-second-braket
(str-handler "]" "" seed)))
(else (loop (str-handler "]]" "" seed)))))))
((#\&) ; Note that #\& within CDATA may stand for itself
(let ((ent-ref ; it does not have to start an entity ref
(ssax:next-token-of
(lambda (c)
(and (not (eof-object? c)) (char-alphabetic? c) c))
port)))
(cond ; replace ">" with #\>
((and (string=? "gt" ent-ref) (eqv? (peek-char port) #\;))
(read-char port)
(loop (str-handler fragment ">" seed)))
(else
(loop
(str-handler ent-ref ""
(str-handler fragment "&" seed)))))))
(else ; Must be CR: if the next char is #\newline, skip it
(if (eqv? (peek-char port) #\newline) (read-char port))
(loop (str-handler fragment (string #\newline) seed)))
))))))
;; procedure+: ssax:read-char-ref PORT
;;
;; [66] CharRef ::= '&#' [0-9]+ ';'
;; | '&#x' [0-9a-fA-F]+ ';'
;;
;; This procedure must be called after we we have read "&#"
;; that introduces a char reference.
;; The procedure reads this reference and returns the corresponding char
;; The current position in PORT will be after ";" that terminates
;; the char reference
;; Faults detected:
;; WFC: XML-Spec.html#wf-Legalchar
;;
;; According to Section "4.1 Character and Entity References"
;; of the XML Recommendation:
;; "[Definition: A character reference refers to a specific character
;; in the ISO/IEC 10646 character set, for example one not directly
;; accessible from available input devices.]"
;; Therefore, we use a ucscode->char function to convert a character
;; code into the character -- *regardless* of the current character
;; encoding of the input stream.
(define (ssax:read-char-ref port)
(let* ((base (cond ((eqv? (peek-char port) #\x) (read-char port) 16)
(else 10)))
(name (ssax:next-token '() '(#\;) "XML [66]" port))
(char-code (string->number name base)))
(read-char port) ; read the terminating #\; char
(if (integer? char-code) (integer->char char-code)
(error port "[wf-Legalchar] broken for '" name "'"))))
(define ssax:predefined-parsed-entities
`(
(,(string->symbol "amp") . "&")
(,(string->symbol "lt") . "<")
(,(string->symbol "gt") . ">")
(,(string->symbol "apos") . "'")
(,(string->symbol "quot") . "\"")
))
;; procedure+: ssax:handle-parsed-entity PORT NAME ENTITIES
;; CONTENT-HANDLER STR-HANDLER SEED
;;
;; Expand and handle a parsed-entity reference
;; port - a PORT
;; name - the name of the parsed entity to expand, a symbol
;; entities - see ENTITIES
;; content-handler -- procedure PORT ENTITIES SEED
;; that is supposed to return a SEED
;; str-handler - a STR-HANDLER. It is called if the entity in question
;; turns out to be a pre-declared entity
;;
;; The result is the one returned by CONTENT-HANDLER or STR-HANDLER
;; Faults detected:
;; WFC: XML-Spec.html#wf-entdeclared
;; WFC: XML-Spec.html#norecursion
(define (ssax:handle-parsed-entity port name entities content-handler str-handler seed)
(cond ; First we check the list of the declared entities
((assq name entities) =>
(lambda (decl-entity)
(let ((ent-body (cdr decl-entity)) ; mark the list to prevent recursion
(new-entities (cons (cons name #f) entities)))
(cond
((string? ent-body)
(call-with-port (open-input-string ent-body)
(lambda (port) (content-handler port new-entities seed))))
((procedure? ent-body)
(let ((port (ent-body)))
(define val (content-handler port new-entities seed))
(close-input-port port)
val))
(else
(error port "[norecursion] broken for " name))))))
((assq name ssax:predefined-parsed-entities)
=> (lambda (decl-entity)
(str-handler (cdr decl-entity) "" seed)))
(else (error port "[wf-entdeclared] broken for " name))))
;; THE ATTLIST ABSTRACT DATA TYPE
;; Currently is implemented as an assoc list sorted in the ascending
;; order of NAMES.
(define attlist-fold fold)
(define attlist-null? null?)
(define attlist->alist identity)
(define (make-empty-attlist) '())
;; procedure: attlist-add ATTLIST NAME-VALUE-PAIR
;; Add a name-value pair to the existing attlist preserving the order
;; Return the new list, in the sorted ascending order.
;; Return #f if a pair with the same name already exists in the attlist
(define (attlist-add attlist name-value)
(if (null? attlist) (cons name-value attlist)
(case (ssax:name-compare (car name-value) (caar attlist))
((=) #f)
((<) (cons name-value attlist))
(else (cons (car attlist) (attlist-add (cdr attlist) name-value)))
)))
;; procedure: attlist-remove-top ATTLIST
;; Given an non-null attlist, return a pair of values: the top and the rest
(define (attlist-remove-top attlist)
(values (car attlist) (cdr attlist)))
;; procedure+: ssax-read-attributes PORT ENTITIES
;;
;; This procedure reads and parses a production Attribute*
;; [41] Attribute ::= Name Eq AttValue
;; [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
;; | "'" ([^<&'] | Reference)* "'"
;; [25] Eq ::= S? '=' S?
;;
;; The procedure returns an ATTLIST, of Name (as UNRES-NAME), Value (as string)
;; pairs. The current character on the PORT is a non-whitespace character
;; that is not an ncname-starting character.
;;
;; Note the following rules to keep in mind when reading an 'AttValue'
;; "Before the value of an attribute is passed to the application
;; or checked for validity, the XML processor must normalize it as follows:
;;
;; - a character reference is processed by appending the referenced
;; character to the attribute value
;; - an entity reference is processed by recursively processing the
;; replacement text of the entity [see ENTITIES]
;; [named entities amp lt gt quot apos are assumed pre-declared]
;; - a whitespace character (#x20, #xD, #xA, #x9) is processed by appending #x20
;; to the normalized value, except that only a single #x20 is appended for a
;; "#xD#xA" sequence that is part of an external parsed entity or the
;; literal entity value of an internal parsed entity
;; - other characters are processed by appending them to the normalized value "
;;
;; Faults detected:
;; WFC: XML-Spec.html#CleanAttrVals
;; WFC: XML-Spec.html#uniqattspec
(define ssax-read-attributes ; ssax-read-attributes port entities
(let ((value-delimeters (append '(#\< #\&) ssax:S-chars)))
;; Read the AttValue from the PORT up to the delimiter (which can
;; be a single or double-quote character, or even a symbol *eof*).
;; 'prev-fragments' is the list of string fragments, accumulated
;; so far, in reverse order. Return the list of fragments with
;; newly read fragments prepended.
(define (read-attrib-value delimiter port entities prev-fragments)
(let* ((new-fragments
(cons (ssax:next-token '() (cons delimiter value-delimeters)
"XML [10]" port)
prev-fragments))
(cterm (read-char port)))
(cond
((or (eof-object? cterm) (eqv? cterm delimiter))
new-fragments)
((eqv? cterm char-return) ; treat a CR and CRLF as a LF
(if (eqv? (peek-char port) #\newline) (read-char port))
(read-attrib-value delimiter port entities
(cons " " new-fragments)))
((memv cterm ssax:S-chars)
(read-attrib-value delimiter port entities
(cons " " new-fragments)))
((eqv? cterm #\&)
(cond
((eqv? (peek-char port) #\#)
(read-char port)
(read-attrib-value delimiter port entities
(cons (string (ssax:read-char-ref port)) new-fragments)))
(else
(read-attrib-value delimiter port entities
(read-named-entity port entities new-fragments)))))
(else (error port "[CleanAttrVals] broken")))))
;; we have read "&" that introduces a named entity reference.
;; read this reference and return the result of normalizing of the
;; corresponding string (that is, read-attrib-value is applied to
;; the replacement text of the entity). The current position will
;; be after ";" that terminates the entity reference
(define (read-named-entity port entities fragments)
(let ((name (ssax:read-NCName port)))
(ssax:assert-current-char '(#\;) "XML [68]" port)
(ssax:handle-parsed-entity port name entities
(lambda (port entities fragments)
(read-attrib-value '*eof* port entities fragments))
(lambda (str1 str2 fragments)
(if (equal? "" str2) (cons str1 fragments)
(cons* str2 str1 fragments)))
fragments)))
(lambda (port entities)
(let loop ((attr-list (make-empty-attlist)))
(if (not (ssax:ncname-starting-char? (ssax:skip-S port))) attr-list
(let ((name (ssax:read-QName port)))
(ssax:skip-S port)
(ssax:assert-current-char '(#\=) "XML [25]" port)
(ssax:skip-S port)
(let ((delimiter
(ssax:assert-current-char '(#\' #\" ) "XML [10]" port)))
(loop
(or (attlist-add attr-list
(cons name
(ssax:string-concatenate-reverse/shared
(read-attrib-value delimiter port entities
'()))))
(error port "[uniqattspec] broken for " name))))))))
))
;; ssax-resolve-name PORT UNRES-NAME NAMESPACES apply-default-ns?
;;
;; Convert an UNRES-NAME to a RES-NAME given the appropriate NAMESPACES
;; declarations.
;; the last parameter apply-default-ns? determines if the default
;; namespace applies (for instance, it does not for attribute names)
;;
;; Per REC-xml-names/#nsc-NSDeclared, "xml" prefix is considered pre-declared
;; and bound to the namespace name "http://www.w3.org/XML/1998/namespace".
;;
;; This procedure tests for the namespace constraints:
;; http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared
(define (ssax-resolve-name port unres-name namespaces apply-default-ns?)
(cond
((pair? unres-name) ; it's a QNAME
(cons
(cond
((assq (car unres-name) namespaces) => cadr)
((eq? (car unres-name) ssax:Prefix-XML) ssax:Prefix-XML)
(else
(error port "[nsc-NSDeclared] broken; prefix " (car unres-name))))
(cdr unres-name)))
(apply-default-ns? ; Do apply the default namespace, if any
(let ((default-ns (assq '*DEFAULT* namespaces)))
(if (and default-ns (cadr default-ns))
(cons (cadr default-ns) unres-name)
unres-name))) ; no default namespace declared
(else unres-name))) ; no prefix, don't apply the default-ns
;;Procedure: ssax:uri-string->symbol URI-STR
;;Convert a URI-STR to an appropriate symbol
(define ssax:uri-string->symbol string->symbol)
;; procedure+: ssax:complete-start-tag TAG PORT ELEMS ENTITIES NAMESPACES
;;
;; This procedure is to complete parsing of a start-tag markup. The procedure must be
;; called after the start tag token has been read. TAG is an UNRES-NAME. ELEMS is an
;; instance of xml-decl::elems; it can be #f to tell the function to do _no_ validation
;; of elements and their attributes.
;;
;; This procedure returns several values:
;; ELEM-GI: a RES-NAME.
;; ATTRIBUTES: element's attributes, an ATTLIST of (RES-NAME . STRING)
;; pairs. The list does NOT include xmlns attributes.
;; NAMESPACES: the input list of namespaces amended with namespace
;; (re-)declarations contained within the start-tag under parsing
;; ELEM-CONTENT-MODEL
;;
;; On exit, the current position in PORT will be the first character after
;; #\> that terminates the start-tag markup.
;;
;; Faults detected:
;; VC: XML-Spec.html#enum
;; VC: XML-Spec.html#RequiredAttr
;; VC: XML-Spec.html#FixedAttr
;; VC: XML-Spec.html#ValueType
;; WFC: XML-Spec.html#uniqattspec (after namespaces prefixes are resolved)
;; VC: XML-Spec.html#elementvalid
;; WFC: REC-xml-names/#dt-NSName
;;
;; Note, although XML Recommendation does not explicitly say it, xmlns and xmlns:
;; attributes don't have to be declared (although they can be declared, to specify
;; their default value)
;;
;; Procedure: ssax:complete-start-tag tag-head port elems entities namespaces
(define ssax:complete-start-tag
(let ((xmlns (string->symbol "xmlns"))
(largest-dummy-decl-attr (list ssax:largest-unres-name #f #f #f)))
;; Scan through the attlist and validate it, against decl-attrs
;; Return an assoc list with added fixed or implied attrs.
;; Note that both attlist and decl-attrs are ATTLISTs, and therefore,
;; sorted
(define (validate-attrs port attlist decl-attrs)
;; Check to see decl-attr is not of use type REQUIRED. Add
;; the association with the default value, if any declared
(define (add-default-decl decl-attr result)
(let*-values
(((attr-name content-type use-type default-value)
(apply values decl-attr)))
(and (eq? use-type 'REQUIRED)
(error port "[RequiredAttr] broken for" attr-name))
(if default-value
(cons (cons attr-name default-value) result)
result)))
(let loop ((attlist attlist) (decl-attrs decl-attrs) (result '()))
(if (attlist-null? attlist)
(attlist-fold add-default-decl result decl-attrs)
(let*-values
(((attr attr-others)
(attlist-remove-top attlist))
((decl-attr other-decls)
(if (attlist-null? decl-attrs)
(values largest-dummy-decl-attr decl-attrs)
(attlist-remove-top decl-attrs)))
)
(case (ssax:name-compare (car attr) (car decl-attr))
((<)
(if (or (eq? xmlns (car attr))
(and (pair? (car attr)) (eq? xmlns (caar attr))))
(loop attr-others decl-attrs (cons attr result))
(error port "[ValueType] broken for " attr)))
((>)
(loop attlist other-decls
(add-default-decl decl-attr result)))
(else ; matched occurrence of an attr with its declaration
(let*-values
(((attr-name content-type use-type default-value)
(apply values decl-attr)))
;; Run some tests on the content of the attribute
(cond
((eq? use-type 'FIXED)
(or (equal? (cdr attr) default-value)
(error port "[FixedAttr] broken for " attr-name)))
((eq? content-type 'CDATA) #t) ; everything goes
((pair? content-type)
(or (member (cdr attr) content-type)
(error port "[enum] broken for " attr-name "="
(cdr attr))))
(else
(ssax-warn port "declared content type " content-type
" not verified yet")))
(loop attr-others other-decls (cons attr result)))))
))))
;; Add a new namespace declaration to namespaces.
;; First we convert the uri-str to a uri-symbol and search namespaces for
;; an association (_ user-prefix . uri-symbol).
;; If found, we return the argument namespaces with an association
;; (prefix user-prefix . uri-symbol) prepended.
;; Otherwise, we prepend (prefix uri-symbol . uri-symbol)
(define (add-ns port prefix uri-str namespaces)
(and (equal? "" uri-str)
(error port "[dt-NSName] broken for " prefix))
(let ((uri-symbol (ssax:uri-string->symbol uri-str)))
(let loop ((nss namespaces))
(cond
((null? nss)
(cons (cons* prefix uri-symbol uri-symbol) namespaces))
((eq? uri-symbol (cddar nss))
(cons (cons* prefix (cadar nss) uri-symbol) namespaces))
(else (loop (cdr nss)))))))
;; partition attrs into proper attrs and new namespace declarations
;; return two values: proper attrs and the updated namespace declarations
(define (adjust-namespace-decl port attrs namespaces)
(let loop ((attrs attrs) (proper-attrs '()) (namespaces namespaces))
(cond
((null? attrs) (values proper-attrs namespaces))
((eq? xmlns (caar attrs)) ; re-decl of the default namespace
(loop (cdr attrs) proper-attrs
(if (equal? "" (cdar attrs)) ; un-decl of the default ns
(cons (cons* '*DEFAULT* #f #f) namespaces)
(add-ns port '*DEFAULT* (cdar attrs) namespaces))))
((and (pair? (caar attrs)) (eq? xmlns (caaar attrs)))
(loop (cdr attrs) proper-attrs
(add-ns port (cdaar attrs) (cdar attrs) namespaces)))
(else
(loop (cdr attrs) (cons (car attrs) proper-attrs) namespaces)))))
;; The body of the function
(lambda (tag-head port elems entities namespaces)
(let*-values
(((attlist) (ssax-read-attributes port entities))
((empty-el-tag?)
(begin
(ssax:skip-S port)
(and
(eqv? #\/
(ssax:assert-current-char '(#\> #\/) "XML [40], XML [44], no '>'" port))
(ssax:assert-current-char '(#\>) "XML [44], no '>'" port))))
((elem-content decl-attrs) ; see xml-decl for their type
(if elems ; elements declared: validate!
(cond
((assoc tag-head elems) =>
(lambda (decl-elem) ; of type xml-decl::decl-elem
(values
(if empty-el-tag? 'EMPTY-TAG (cadr decl-elem))
(caddr decl-elem))))
(else
(error port "[elementvalid] broken, no decl for " tag-head)))
(values ; non-validating parsing
(if empty-el-tag? 'EMPTY-TAG 'ANY)
#f) ; no attributes declared
))
((merged-attrs) (if decl-attrs (validate-attrs port attlist decl-attrs)
(attlist->alist attlist)))
((proper-attrs namespaces)
(adjust-namespace-decl port merged-attrs namespaces))
)
;; build the return value
(values
(ssax-resolve-name port tag-head namespaces #t)
(fold-right
(lambda (name-value attlist)
(or
(attlist-add attlist
(cons (ssax-resolve-name port (car name-value) namespaces #f)
(cdr name-value)))
(error port "[uniqattspec] after NS expansion broken for "
name-value)))
(make-empty-attlist)
proper-attrs)
namespaces
elem-content)))))
;; procedure+: ssax-read-external-id PORT
;;
;; This procedure parses an ExternalID production:
;; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
;; | 'PUBLIC' S PubidLiteral S SystemLiteral
;; [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
;; [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
;; [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%]
;;
;; This procedure is supposed to be called when an ExternalID is expected; that is, the
;; current character must be either #\S or #\P that start correspondingly a SYSTEM or
;; PUBLIC token. This procedure returns the SystemLiteral as a string. A PubidLiteral
;; is disregarded if present.
(define (ssax-read-external-id port)
(let ((discriminator (ssax:read-NCName port)))
(ssax:assert-current-char ssax:S-chars "space after SYSTEM or PUBLIC" port)
(ssax:skip-S port)
(let ((delimiter
(ssax:assert-current-char '(#\' #\" ) "XML [11], XML [12]" port)))
(cond
((eq? discriminator (string->symbol "SYSTEM"))
(let ((val (ssax:next-token '() (list delimiter) "XML [11]" port)))
(read-char port) ; reading the closing delim
val))
((eq? discriminator (string->symbol "PUBLIC"))
(let loop ((c (read-char port)))
(cond
((eqv? c delimiter) c)
((eof-object? c)
(error port "Unexpected EOF while skipping until " delimiter))
(else (loop (read-char port)))))
(ssax:assert-current-char ssax:S-chars "space after PubidLiteral" port)
(ssax:skip-S port)
(let* ((delimiter
(ssax:assert-current-char '(#\' #\" ) "XML [11]" port))
(systemid
(ssax:next-token '() (list delimiter) "XML [11]" port)))
(read-char port) ; reading the closing delim
systemid))
(else
(error port "XML [75], " discriminator
" rather than SYSTEM or PUBLIC"))))))
;; MID-LEVEL PARSERS AND SCANNERS
;; The following procedures parse productions corresponding to the whole (document) entity
;; or its higher-level pieces (prolog, root element, etc).
;;
;; Scan the Misc production in the context
;; [1] document ::= prolog element Misc*
;; [22] prolog ::= XMLDecl? Misc* (doctypedec l Misc*)?
;; [27] Misc ::= Comment | PI | S
;;
;; The following function should be called in the prolog or epilog contexts.
;; In these contexts, whitespaces are completely ignored.
;; The return value from ssax-scan-misc is either a PI-token,
;; a DECL-token, a START token, or EOF. Comments are ignored and not reported.
(define (ssax-scan-misc port)
(let loop ((c (ssax:skip-S port)))
(cond
((eof-object? c) c)
((not (char=? c #\<))
(error port "XML [22], char '" c "' unexpected"))
(else
(let ((token (ssax:read-markup-token port)))
(case (xml-token-kind token)
((COMMENT) (loop (ssax:skip-S port)))
((PI DECL START) token)
(else
(error port "XML [22], unexpected token of kind "
(xml-token-kind token)
))))))))
;; procedure+: ssax-read-char-data PORT EXPECT-EOF? STR-HANDLER SEED
;;
;; This procedure is to read the character content of an XML document
;; or an XML element.
;; [43] content ::= (element | CharData | Reference | CDSect | PI | Comment)*
;; To be more precise, the procedure reads CharData, expands CDSect
;; and character entities, and skips comments. The procedure stops
;; at a named reference, EOF, at the beginning of a PI or a start/end tag.
;;
;; port
;; a PORT to read
;; expect-eof?
;; a boolean indicating if EOF is normal, i.e., the character
;; data may be terminated by the EOF. EOF is normal
;; while processing a parsed entity.
;; str-handler
;; a STR-HANDLER
;; seed
;; an argument passed to the first invocation of STR-HANDLER.
;;
;; The procedure returns two results: SEED and TOKEN.
;; The SEED is the result of the last invocation of STR-HANDLER, or the original seed
;; if STR-HANDLER was never called.
;;
;; TOKEN can be either an eof-object (this can happen only if expect-eof? was #t), or:
;; - an xml-token describing a START tag or an END-tag;
;; For a start token, the caller has to finish reading it.
;; - an xml-token describing the beginning of a PI. It's up to an
;; application to read or skip through the rest of this PI;
;; - an xml-token describing a named entity reference.
;;
;; CDATA sections and character references are expanded inline and
;; never returned. Comments are silently disregarded.
;;
;; As the XML Recommendation requires, all whitespace in character data
;; must be preserved. However, a CR character (#xD) must be disregarded
;; if it appears before a LF character (#xA), or replaced by a #xA character
;; otherwise. See Secs. 2.10 and 2.11 of the XML Recommendation. See also
;; the canonical XML Recommendation.
;;
;; ssax-read-char-data port expect-eof? str-handler seed
(define ssax-read-char-data
(let ((terminators-usual (list #\< #\& char-return))
(terminators-usual-eof (list #\< '*eof* #\& char-return))
(handle-fragment
(lambda (fragment str-handler seed)
(if (string-null? fragment) seed
(str-handler fragment "" seed)))))
(lambda (port expect-eof? str-handler seed)
;; Very often, the first character we encounter is #\<
;; Therefore, we handle this case in a special, fast path
(if (eqv? #\< (peek-char port))
;; The fast path
(let ((token (ssax:read-markup-token port)))
(case (xml-token-kind token)
((START END) ; The most common case
(values seed token))
((CDSECT)
(let ((seed (ssax:read-cdata-body port str-handler seed)))
(ssax-read-char-data port expect-eof? str-handler seed)))
((COMMENT)
(ssax-read-char-data port expect-eof? str-handler seed))
(else
(values seed token))))
;; The slow path
(let ((char-data-terminators
(if expect-eof? terminators-usual-eof terminators-usual)))
(let loop ((seed seed))
(let* ((fragment
(ssax:next-token '() char-data-terminators
"reading char data" port))
(term-char (peek-char port)) ; one of char-data-terminators
)
(if (eof-object? term-char)
(values
(handle-fragment fragment str-handler seed)
term-char)
(case term-char
((#\<)
(let ((token (ssax:read-markup-token port)))
(case (xml-token-kind token)
((CDSECT)
(loop
(ssax:read-cdata-body port str-handler
(handle-fragment fragment str-handler seed))))
((COMMENT)
(loop (handle-fragment fragment str-handler seed)))
(else
(values
(handle-fragment fragment str-handler seed)
token)))))
((#\&)
(read-char port)
(case (peek-char port)
((#\#) (read-char port)
(loop (str-handler fragment
(string (ssax:read-char-ref port))
seed)))
(else
(let ((name (ssax:read-NCName port)))
(ssax:assert-current-char '(#\;) "XML [68]" port)
(values
(handle-fragment fragment str-handler seed)
(make-xml-token 'ENTITY-REF name))))))
(else ; This must be a CR character
(read-char port)
(if (eqv? (peek-char port) #\newline)
(read-char port))
(loop (str-handler fragment (string #\newline) seed))))
))))))))
;; procedure+: ssax:assert-token TOKEN KIND GI
;; Make sure that TOKEN is of anticipated KIND and has anticipated GI. Note GI argument
;; may actually be a pair of two symbols, Namespace URI or the prefix, and of the localname.
;; If the assertion fails, error-cont is evaluated by passing it three arguments: token
;; kind gi. The result of error-cont is returned.
(define (ssax:assert-token token kind gi error-cont)
(or (and (xml-token? token)
(eq? kind (xml-token-kind token))
(equal? gi (xml-token-head token)))
(error-cont token kind gi)))
;; HIGH-LEVEL PARSERS
;; These parsers are a set of syntactic forms to instantiate a SSAX parser. A user can
;; instantiate the parser to do the full validation, or no validation, or any particular
;; validation. The user specifies which PI he wants to be notified about. The user tells
;; what to do with the parsed character and element data. The latter handlers
;; determine if the parsing follows a SAX or a DOM model.
;
;; syntax: make-ssax-pi-parser my-pi-handlers
;; Create a parser to parse and process one Processing Element (PI).
;
;; my-pi-handlers
;; An assoc list of pairs (PI-TAG . PI-HANDLER) where PI-TAG is an NCName symbol, the
;; PI target, and PI-HANDLER is a procedure PORT PI-TAG SEED where PORT points to the
;; first symbol after the PI target. The handler should read the rest of the PI up to
;; and including the combination '?>' that terminates the PI. The handler should
;; return a new seed.
;; One of the PI-TAGs may be the symbol *DEFAULT*. The corresponding handler will handle
;; PIs that no other handler will. If the *DEFAULT* PI-TAG is not specified,
;; make-ssax-pi-parser will assume the default handler that skips the body of the PI
;;
;; The output of the make-ssax-pi-parser is a procedure
;; PORT PI-TAG SEED
;; that will parse the current PI according to the user-specified handlers.
(define (make-ssax-pi-parser handlers)
(lambda (port target seed)
(define pair (assv target handlers))
(or pair (set! pair (assv '*DEFAULT* handlers)))
(cond ((not pair)
(ssax-warn port "Skipping PI: " target #\newline)
(ssax:skip-pi port)
seed)
(else
((cdr pair) port target seed)))))
;; syntax: make-ssax-elem-parser my-new-level-seed my-finish-element
;; my-char-data-handler my-pi-handlers
;;
;; Create a parser to parse and process one element, including its character content or
;; children elements. The parser is typically applied to the root element of a document.
;;
;; my-new-level-seed
;; procedure ELEM-GI ATTRIBUTES NAMESPACES EXPECTED-CONTENT SEED
;; where ELEM-GI is a RES-NAME of the element
;; about to be processed.
;; This procedure is to generate the seed to be passed to handlers that process the
;; content of the element. This is the function identified as 'fdown' in the denotational
;; semantics of the XML parser given in the title comments to this file.
;;
;; my-finish-element
;; procedure ELEM-GI ATTRIBUTES NAMESPACES PARENT-SEED SEED
;; This procedure is called when parsing of ELEM-GI is finished. The SEED is the result
;; from the last content parser (or from my-new-level-seed if the element has the empty
;; content). PARENT-SEED is the same seed as was passed to my-new-level-seed.
;; The procedure is to generate a seed that will be the result of the element parser.
;; This is the function identified as 'fup' in the denotational semantics of the XML
;; parser given in the title comments to this file.
;;
;; my-char-data-handler
;; A STR-HANDLER
;;
;; my-pi-handlers
;; See ssax:make-pi-handler above
;;
;; The generated parser is a
;; procedure START-TAG-HEAD PORT ELEMS ENTITIES
;; NAMESPACES PRESERVE-WS? SEED
;; The procedure must be called after the start tag token has been read. START-TAG-HEAD
;; is an UNRES-NAME from the start-element tag. ELEMS is an instance of xml-decl::elems.
;; See ssax:complete-start-tag::preserve-ws?
;;
;; Faults detected:
;; VC: XML-Spec.html#elementvalid
;; WFC: XML-Spec.html#GIMatch
(define (make-ssax-elem-parser my-new-level-seed my-finish-element
my-char-data-handler my-pi-handlers)
(lambda (start-tag-head port elems entities namespaces preserve-ws? seed)
(define xml-space-gi (cons ssax:Prefix-XML
(string->symbol "space")))
(let handle-start-tag ((start-tag-head start-tag-head)
(port port) (entities entities)
(namespaces namespaces)
(preserve-ws? preserve-ws?) (parent-seed seed))
(let*-values
(((elem-gi attributes namespaces expected-content)
(ssax:complete-start-tag start-tag-head port elems
entities namespaces))
((seed)
(my-new-level-seed elem-gi attributes
namespaces expected-content parent-seed)))
(case expected-content
((EMPTY-TAG)
(my-finish-element
elem-gi attributes namespaces parent-seed seed))
((EMPTY) ; The end tag must immediately follow
(ssax:assert-token (and (eqv? #\< (ssax:skip-S port))
(ssax:read-markup-token port))
'END
start-tag-head
(lambda (token exp-kind exp-head)
(error port "[elementvalid] broken for " token
" while expecting "
exp-kind exp-head)))
(my-finish-element
elem-gi attributes namespaces parent-seed seed))
(else ; reading the content...
(let ((preserve-ws? ; inherit or set the preserve-ws? flag
(cond ((assoc xml-space-gi attributes) =>
(lambda (name-value)
(equal? "preserve" (cdr name-value))))
(else preserve-ws?))))
(let loop ((port port) (entities entities)
(expect-eof? #f) (seed seed))
(let*-values
(((seed term-token)
(ssax-read-char-data port expect-eof?
my-char-data-handler seed)))
(if (eof-object? term-token)
seed
(case (xml-token-kind term-token)
((END)
(ssax:assert-token term-token 'END start-tag-head
(lambda (token exp-kind exp-head)
(error port "[GIMatch] broken for "
term-token " while expecting "
exp-kind exp-head)))
(my-finish-element
elem-gi attributes namespaces parent-seed seed))
((PI)
(let ((seed
((make-ssax-pi-parser my-pi-handlers)
port (xml-token-head term-token) seed)))
(loop port entities expect-eof? seed)))
((ENTITY-REF)
(let ((seed
(ssax:handle-parsed-entity
port (xml-token-head term-token)
entities
(lambda (port entities seed)
(loop port entities #t seed))
my-char-data-handler
seed))) ; keep on reading the content after ent
(loop port entities expect-eof? seed)))
((START) ; Start of a child element
(if (eq? expected-content 'PCDATA)
(error port "[elementvalid] broken for "
elem-gi
" with char content only; unexpected token "
term-token))
;; Do other validation of the element content
(let ((seed
(handle-start-tag
(xml-token-head term-token)
port entities namespaces
preserve-ws? seed)))
(loop port entities expect-eof? seed)))
(else
(error port "XML [43] broken for "
term-token))))))))
)))
))
;;This is make-ssax-parser with all the (specialization) handlers given
;;as positional arguments. It is called by make-ssax-parser, see below
(define (make-ssax-parser/positional-args
*handler-DOCTYPE
*handler-UNDECL-ROOT
*handler-DECL-ROOT
*handler-NEW-LEVEL-SEED
*handler-FINISH-ELEMENT
*handler-CHAR-DATA-HANDLER
*handler-PROCESSING-INSTRUCTIONS)
(lambda (port seed)
;; We must've just scanned the DOCTYPE token. Handle the
;; doctype declaration and exit to
;; scan-for-significant-prolog-token-2, and eventually, to the
;; element parser.
(define (handle-decl port token-head seed)
(or (eq? (string->symbol "DOCTYPE") token-head)
(error port "XML [22], expected DOCTYPE declaration, found "
token-head))
(ssax:assert-current-char ssax:S-chars "XML [28], space after DOCTYPE" port)
(ssax:skip-S port)
(let*-values
(((docname) (ssax:read-QName port))
((systemid)
(and (ssax:ncname-starting-char? (ssax:skip-S port))
(ssax-read-external-id port)))
((internal-subset?)
(begin
(ssax:skip-S port)
(eqv? #\[
(ssax:assert-current-char '(#\> #\[)
"XML [28], end-of-DOCTYPE" port))))
((elems entities namespaces seed)
(*handler-DOCTYPE port docname systemid internal-subset? seed)))
(scan-for-significant-prolog-token-2 port elems entities namespaces
seed)))
;; Scan the leading PIs until we encounter either a doctype
;; declaration or a start token (of the root element). In the
;; latter two cases, we exit to the appropriate continuation
(define (scan-for-significant-prolog-token-1 port seed)
(let ((token (ssax-scan-misc port)))
(if (eof-object? token)
(error port "XML [22], unexpected EOF")
(case (xml-token-kind token)
((PI)
(let ((seed
((make-ssax-pi-parser *handler-PROCESSING-INSTRUCTIONS)
port (xml-token-head token) seed)))
(scan-for-significant-prolog-token-1 port seed)))
((DECL) (handle-decl port (xml-token-head token) seed))
((START)
(let*-values
(((elems entities namespaces seed)
(*handler-UNDECL-ROOT (xml-token-head token) seed)))
(element-parser (xml-token-head token) port elems
entities namespaces #f seed)))
(else (error port "XML [22], unexpected markup "
token))))))
;; Scan PIs after the doctype declaration, till we encounter
;; the start tag of the root element. After that we exit
;; to the element parser
(define (scan-for-significant-prolog-token-2 port elems entities namespaces seed)
(let ((token (ssax-scan-misc port)))
(if (eof-object? token)
(error port "XML [22], unexpected EOF")
(case (xml-token-kind token)
((PI)
(let ((seed ((make-ssax-pi-parser *handler-PROCESSING-INSTRUCTIONS)
port (xml-token-head token) seed)))
(scan-for-significant-prolog-token-2 port elems entities
namespaces seed)))
((START)
(element-parser (xml-token-head token) port elems
entities namespaces #f
(*handler-DECL-ROOT (xml-token-head token) seed)))
(else (error port "XML [22], unexpected markup "
token))))))
;; A procedure start-tag-head port elems entities namespaces
;; preserve-ws? seed
(define element-parser
(make-ssax-elem-parser *handler-NEW-LEVEL-SEED
*handler-FINISH-ELEMENT
*handler-CHAR-DATA-HANDLER
*handler-PROCESSING-INSTRUCTIONS))
;; Get the ball rolling ...
(scan-for-significant-prolog-token-1 port seed)
))
(define DOCTYPE 'DOCTYPE)
(define UNDECL-ROOT 'UNDECL-ROOT)
(define DECL-ROOT 'DECL-ROOT)
(define NEW-LEVEL-SEED 'NEW-LEVEL-SEED)
(define FINISH-ELEMENT 'FINISH-ELEMENT)
(define CHAR-DATA-HANDLER 'CHAR-DATA-HANDLER)
(define PROCESSING-INSTRUCTIONS 'PROCESSING-INSTRUCTIONS)
;; syntax: make-ssax-parser user-handler-tag user-handler-proc ...
;;
;; Create an XML parser, an instance of the XML parsing framework.
;; This will be a SAX, a DOM, or a specialized parser depending
;; on the supplied user-handlers.
;;
;; user-handler-tag is a symbol that identifies a procedural expression
;; that follows the tag. Given below are tags and signatures of the
;; corresponding procedures. Not all tags have to be specified. If some
;; are omitted, reasonable defaults will apply.
;;
;;
;; tag: DOCTYPE
;; handler-procedure: PORT DOCNAME SYSTEMID INTERNAL-SUBSET? SEED
;; If internal-subset? is #t, the current position in the port
;; is right after we have read #\[ that begins the internal DTD subset.
;; We must finish reading of this subset before we return
;; (or must call skip-internal-subset if we aren't interested in reading it).
;; The port at exit must be at the first symbol after the whole
;; DOCTYPE declaration.
;; The handler-procedure must generate four values:
;; ELEMS ENTITIES NAMESPACES SEED
;; See xml-decl::elems for ELEMS. It may be #f to switch off the validation.
;; NAMESPACES will typically contain USER-PREFIXes for selected URI-SYMBs.
;; The default handler-procedure skips the internal subset,
;; if any, and returns (values #f '() '() seed)
;
;; tag: UNDECL-ROOT
;; handler-procedure: ELEM-GI SEED
;; where ELEM-GI is an UNRES-NAME of the root element. This procedure
;; is called when an XML document under parsing contains _no_ DOCTYPE
;; declaration.
;; The handler-procedure, as a DOCTYPE handler procedure above,
;; must generate four values:
;; ELEMS ENTITIES NAMESPACES SEED
;; The default handler-procedure returns (values #f '() '() seed)
;
;; tag: DECL-ROOT
;; handler-procedure: ELEM-GI SEED
;; where ELEM-GI is an UNRES-NAME of the root element. This procedure
;; is called when an XML document under parsing does contains the DOCTYPE
;; declaration.
;; The handler-procedure must generate a new SEED (and verify
;; that the name of the root element matches the doctype, if the handler
;; so wishes).
;; The default handler-procedure is the identity function.
;
;; tag: NEW-LEVEL-SEED
;; handler-procedure: see make-ssax-elem-parser, my-new-level-seed
;
;; tag: FINISH-ELEMENT
;; handler-procedure: see make-ssax-elem-parser, my-finish-element
;
;; tag: CHAR-DATA-HANDLER
;; handler-procedure: see make-ssax-elem-parser, my-char-data-handler
;
;; tag: PI
;; handler-procedure: see make-ssax-pi-parser
;; The default value is '()
;
;; The generated parser is a
;; procedure PORT SEED
;
;; This procedure parses the document prolog and then exits to
;; an element parser (created by make-ssax-elem-parser) to handle
;; the rest.
;;
;; [1] document ::= prolog element Misc*
;; [22] prolog ::= XMLDecl? Misc* (doctypedec | Misc*)?
;; [27] Misc ::= Comment | PI | S
;;
;; [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
;; ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
;; [29] markupdecl ::= elementdecl | AttlistDecl
;; | EntityDecl
;; | NotationDecl | PI
;; | Comment
(define make-ssax-parser
(let ((descriptors
`((DOCTYPE
,(lambda (port docname systemid internal-subset? seed)
(cond (internal-subset?
(ssax:skip-internal-dtd port)))
(ssax-warn port "DOCTYPE DECL " docname " " systemid " found and skipped")
(values #f '() '() seed)))
(UNDECL-ROOT
,(lambda (elem-gi seed) (values #f '() '() seed)))
(DECL-ROOT
,(lambda (elem-gi seed) seed))
(NEW-LEVEL-SEED) ; required
(FINISH-ELEMENT) ; required
(CHAR-DATA-HANDLER) ; required
(PROCESSING-INSTRUCTIONS ()))))
(lambda proplist
(define count 0)
(if (odd? (length proplist))
(error 'make-ssax-parser "takes even number of arguments" proplist))
(let ((posititional-args
(map (lambda (spec)
(define ptail (member (car spec) proplist))
(cond ((and ptail (odd? (length ptail)))
(error 'make-ssax-parser 'bad 'argument ptail))
(ptail
(set! count (+ 1 count))
(cadr ptail))
((not (null? (cdr spec)))
(cadr spec))
(else
(error
'make-ssax-parser 'missing (car spec) 'property))))
descriptors)))
(if (= count (quotient (length proplist) 2))
(apply make-ssax-parser/positional-args posititional-args)
(error 'make-ssax-parser 'extra 'arguments proplist))))))
;; PARSING XML TO SXML
(define (res-name->sxml res-name)
(string->symbol
(string-append (symbol->string (car res-name)) ":" (symbol->string (cdr res-name)))))
;; This is an instance of the SSAX parser that returns an SXML representation of the XML
;; document to be read from `port`. `namespace-prefixes` is a list of
;; `(user-prefix . uri-string)` that assigns `user-prefix`es to certain
;; namespaces identified by particular `uri-string`s. It may be an empty list.
;; `xml->sxml` returns an SXML tree. The port points out to the first character
;; after the root element.
(define xml->sxml
(lambda args
(let-optionals args ((port (current-input-port))
(namespace-prefixes '()))
(let* ((namespaces
(map (lambda (el) (cons* #f (car el) (ssax:uri-string->symbol (cdr el))))
namespace-prefixes))
(result
(reverse
((make-ssax-parser
'DOCTYPE
(lambda (port docname systemid internal-subset? seed)
(cond (internal-subset?
(ssax:skip-internal-dtd port)))
(ssax-warn port "DOCTYPE DECL " docname " " systemid " found and skipped")
(values #f '() namespaces seed))
'NEW-LEVEL-SEED
(lambda (elem-gi attributes namespaces expected-content seed) '())
'FINISH-ELEMENT
(lambda (elem-gi attributes namespaces parent-seed seed)
(let ((nseed (ssax:reverse-collect-str-drop-ws seed))
(attrs (attlist-fold
(lambda (attr accum)
(cons (list (if (symbol? (car attr))
(car attr)
(res-name->sxml (car attr)))
(cdr attr))
accum))
'() attributes)))
(cons (cons (if (symbol? elem-gi)
elem-gi
(res-name->sxml elem-gi))
(if (null? attrs)
nseed
(cons (cons '@ attrs) nseed)))
parent-seed)))
'CHAR-DATA-HANDLER
(lambda (string1 string2 seed)
(if (string-null? string2)
(cons string1 seed)
(cons* string2 string1 seed)))
'UNDECL-ROOT
(lambda (elem-gi seed) (values #f '() namespaces seed))
'PROCESSING-INSTRUCTIONS
(list
(cons '*DEFAULT*
(lambda (port pi-tag seed)
(cons (list '*PROCESSING-INSTRUCTIONS*
pi-tag
(ssax:read-pi-body-as-string port))
seed)))))
port
'()))))
(cons '*TOP*
(if (null? namespace-prefixes)
result
(cons (list '@ (cons '*NAMESPACES*
(map (lambda (ns) (list (car ns) (cdr ns)))
namespace-prefixes)))
result)))))))
)
)
| false |
5e82fac43b2a6a9d5bfa437c986a805d5ee1c90b
|
e621b477c04e329b876780c2c47daeae8a7ffc50
|
/flatten-tree.ss
|
4a72bd969f0216b7488945f083a06535fd3ec3bd
|
[] |
no_license
|
DavidAlphaFox/match
|
ecfac4da1d2c24b2c779e3fda5eff793c65890c9
|
f1d9818eee10327fb25db033de31cdf6e565d5a5
|
refs/heads/main
| 2023-07-22T18:38:28.456807 | 2021-09-07T07:57:21 | 2021-09-07T07:57:21 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 205 |
ss
|
flatten-tree.ss
|
(load "match.ss")
(define (flatten tree)
(match tree
[() '()]
[(,hd . ,tl) `(,@(flatten hd) ,@(flatten tl))]
[,x (list x)]
))
(printf "~a\n" (flatten '(((1 2 (3 4))) (5) ((6 7) 8 9))))
| false |
d29a3f56154633f1722878ab67dcef7d66c9d848
|
a3e69e68969e57643538d45253b3034f8a48b354
|
/share/ksi/3.9.1/ksi/getopt.scm
|
8df76038980a51eb71e34a3aa9e0d2c77d6c9eb5
|
[] |
no_license
|
ivan-demakov/win64
|
1a6638798379f9bd625e4917d186e1c4020f2b4d
|
8eea8274983de735719272bf3d6716c1307318e7
|
refs/heads/master
| 2020-04-12T06:42:46.762500 | 2017-05-05T09:51:03 | 2017-05-05T09:51:03 | 61,844,432 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,863 |
scm
|
getopt.scm
|
;;;
;;; getopt.scm
;;; command line options
;;;
;;; Copyright (C) 1998-2010, Ivan Demakov.
;;;
;;; This code is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License as published by
;;; the Free Software Foundation; either version 2.1 of the License, or (at your
;;; option) any later version.
;;;
;;; This code 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 code; see the file COPYING.LESSER. If not, write to
;;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
;;; MA 02110-1301, USA.
;;;
;;; Author: Ivan Demakov <[email protected]>
;;; Creation date: Fri Sep 11 19:00:52 1998
;;; Last Update: Fri Aug 13 14:51:13 2010
;;;
;;;
(library (ksi getopt)
(export get-option parse-options)
(import (ksi core syntax)
(ksi core base)
(ksi core list)
(ksi core string)
(ksi core number))
(define (get-option argv kw-opts kw-args)
(cond
((null? argv)
(values '() 'end-args '()))
((or (not (eqv? #\- (string-ref (car argv) 0))) (eqv? (string-length (car argv)) 1))
(values (cdr argv) 'normal-arg (car argv)))
((eqv? #\- (string-ref (car argv) 1))
(if (= (string-length (car argv)) 2)
(values '() 'end-args (cdr argv))
(let ((kw-arg-pos (string-index (car argv) #\=)))
(if kw-arg-pos
(let ((kw (string->keyword (substring (car argv) 2 kw-arg-pos))))
(if (memq kw kw-args)
(values (cdr argv)
(string->keyword (substring (car argv) 2 kw-arg-pos))
(substring (car argv) (+ kw-arg-pos 1) (string-length (car argv))))
(values (cdr argv) 'usage-error kw)))
(let ((kw (string->keyword
(substring (car argv) 2 (string-length (car argv))))))
(cond ((memq kw kw-opts)
(values (cdr argv) kw #f))
((and (memq kw kw-args) (pair? (cdr argv)))
(values (cddr argv) kw (cadr argv)))
(else
(values (cdr argv) 'usage-error kw))))))))
(else
(let ((kw (string->keyword (substring (car argv) 1 2))) (rest-kw (substring (car argv) 2 (string-length (car argv)))))
(cond
((memq kw kw-opts)
(values (if (zero? (string-length rest-kw))
(cdr argv)
(cons (string-append "-" rest-kw) (cdr argv)))
kw #f))
((memq kw kw-args)
(if (zero? (string-length rest-kw))
(if (null? (cdr argv))
(values (cdr argv) 'usage-error kw)
(values (cddr argv) kw (cadr argv)))
(values (cdr argv) kw rest-kw)))
(else (values (cdr argv) 'usage-error kw)))))))
(define (parse-options argv kw-opts kw-args do-opt)
(letrec ((next-option (lambda (argv kw arg)
(let ((res (do-opt kw arg argv)))
(if res
(begin
(if (list? res)
(set! argv res))
(call-with-values
(lambda () (get-option argv kw-opts kw-args))
next-option)))))))
(call-with-values
(lambda () (get-option argv kw-opts kw-args))
next-option)))
)
;;; End of code
| false |
2cc90c12e3b8f63619ca490aade2f2b5ce9ac1f7
|
e5dba5542b7780c561c3750ef25aca6cbf40b5bc
|
/pixman.scm
|
2c1b5c5bdab47bff2f9066da7a75700a42a96303
|
[
"MIT"
] |
permissive
|
drewt/chicken-pixman
|
54e48f00db8e44a8754f953b6a8cb413ac731080
|
3d15381ae1c690874dfec8988861cfb3c856b47d
|
refs/heads/master
| 2020-04-26T16:00:29.550366 | 2019-03-04T03:15:09 | 2019-03-04T03:15:09 | 173,664,557 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 24,436 |
scm
|
pixman.scm
|
;; Copyright 2019 Drew Thoreson
;;
;; 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.
(foreign-declare "#include <pixman.h>")
(module (pixman)
(;pixman-fixed-e
;pixman-fixed-1
;pixman-fixed-1-minus-e
;pixman-fixed-minus-1
;pixman-fixed-to-int
;pixman-int-to-fixed
;pixman-fixed-to-double
;pixman-double-to-fixed
;pixman-fixed-frac
;pixman-fixed-floor
;pixman-fixed-ceil
;pixman-fixed-fraction
;pixman-fixed-mod-2
;pixman-max-fixed-48-16
;pixman-min-fixed-48-16
pixman-color-red
pixman-color-green
pixman-color-blue
pixman-color-alpha
pixman-point-fixed-x
pixman-point-fixed-y
pixman-line-fixed-p1
pixman-line-fixed-p2
pixman-vector
pixman-transform
pixman-transform-init-identity
pixman-transform-point-3d
pixman-transform-point
pixman-transform-multiply
pixman-transform-init-scale
pixman-transform-scale
pixman-transform-init-rotate
pixman-transform-rotate
pixman-transform-init-translate
pixman-transform-translate
pixman-transform-bounds
pixman-transform-invert
pixman-transform-is-identity?
pixman-transform-is-scale?
pixman-transform-is-int-translate?
pixman-transform-is-inverse?
pixman-f-vector
pixman-f-transform
pixman-transform-from-pixman-f-transform
pixman-f-transform-from-pixman-transform
pixman-f-transform-invert
pixman-f-transform-point
pixman-f-transform-point-3d
pixman-f-transform-multiply
pixman-f-transform-init-scale
pixman-f-transform-scale
pixman-f-transform-init-rotate
pixman-f-transform-rotate
pixman-f-transform-init-translate
pixman-f-transform-translate
pixman-f-transform-bounds
pixman-f-transform-init-identity
pixman-repeat/none
pixman-repeat/normal
pixman-repeat/pad
pixman-repeat/reflect
pixman-filter/fast
pixman-filter/good
pixman-filter/best
pixman-filter/nearest
pixman-filter/bilinear
pixman-filter/convolution
pixman-filter/separable-convolution
pixman-op/clear
pixman-op/src
pixman-op/dst
pixman-op/over
pixman-op/over-reverse
pixman-op/in
pixman-op/in-reverse
pixman-op/out
pixman-op/out-reverse
pixman-op/atop
pixman-op/atop-reverse
pixman-op/xor
pixman-op/add
pixman-op/saturate
pixman-op/disjoint-clear
pixman-op/disjoint-src
pixman-op/disjoint-dst
pixman-op/disjoint-over
pixman-op/disjoint-over-reverse
pixman-op/disjoint-in
pixman-op/disjoint-in-reverse
pixman-op/disjoint-out
pixman-op/disjoint-out-reverse
pixman-op/disjoint-atop
pixman-op/disjoint-atop-reverse
pixman-op/disjoint-xor
pixman-op/conjoint-clear
pixman-op/conjoint-src
pixman-op/conjoint-dst
pixman-op/conjoint-over
pixman-op/conjoint-over-reverse
pixman-op/conjoint-in
pixman-op/conjoint-in-reverse
pixman-op/conjoint-out
pixman-op/conjoint-out-reverse
pixman-op/conjoint-atop
pixman-op/conjoint-atop-reverse
pixman-op/conjoint-xor
pixman-op/multiply
pixman-op/screen
pixman-op/overlay
pixman-op/darken
pixman-op/lighten
pixman-op/color-dodge
pixman-op/color-burn
pixman-op/hard-light
pixman-op/soft-light
pixman-op/difference
pixman-op/exclusion
pixman-op/hsl-hue
pixman-op/hsl-saturation
pixman-op/hsl-color
pixman-op/hsl-luminosity
pixman-region16-data-size
pixman-region16-data-num-rects
pixman-rectangle16-x
pixman-rectangle16-y
pixman-rectangle16-width
pixman-rectangle16-height
pixman-box16-x1
pixman-box16-y1
pixman-box16-x2
pixman-box16-y2
make-pixman-region16
pixman-region16-extents
pixman-region16-data
pixman-region/out
pixman-region/in
pixman-region/part
pixman-region-set-static-pointers
pixman-region-init
pixman-region-init-rect
pixman-region-init-rects
pixman-region-init-with-extents
pixman-region-init-from-image
pixman-region-fini
pixman-region-translate
pixman-region-copy
pixman-region-intersect
pixman-region-union
pixman-region-union-rect
pixman-region-intersect-rect
pixman-region-subtract
pixman-region-inverse
pixman-region-contains-point?
pixman-region-contains-rectangle?
pixman-region-not-empty?
pixman-region-extents
pixman-region-n-rects
pixman-region-rectangles
pixman-region-equal?
pixman-region-selfcheck
pixman-region-reset
pixman-region-clear
pixman-region32-data-size
pixman-region32-data-num-rects
pixman-rectangle32-x
pixman-rectangle32-y
pixman-rectangle32-width
pixman-rectangle32-height
pixman-box32-x1
pixman-box32-y1
pixman-box32-x2
pixman-box32-y2
make-pixman-region32
pixman-region32-extents
pixman-region32-data
pixman-region32-init
pixman-region32-init-rect
pixman-region32-init-rects
pixman-region32-init-with-extents
pixman-region32-init-from-image
pixman-region32-fini
pixman-region32-translate
pixman-region32-copy
pixman-region32-intersect
pixman-region32-union
pixman-region32-intersect-rect
pixman-region32-union-rect
pixman-region32-subtract
pixman-region32-inverse
pixman-region32-contains-point?
pixman-region32-contains-rectangle?
pixman-region32-not-empty?
pixman-region32-extents
pixman-region32-n-rects
pixman-region32-rectangles
pixman-region32-equal?
pixman-region32-selfcheck
pixman-region32-reset
pixman-region32-clear
pixman-blt
pixman-fill
pixman-version
pixman-version-string
pixman-gradient-stop-x
pixman-gradient-stop-color
pixman-max-indexed
pixman-indexed-color
pixman-indexed-rgba
pixman-indexed-ent
;pixman-format
;pixman-format-byte
;pixman-format-reshift
;pixman-format-bpp
;pixman-format-shift
;pixman-format-type
;pixman-format-a
;pixman-format-r
;pixman-format-g
;pixman-format-b
;pixman-format-rgb
;pixman-format-vis
;pixman-format-depth
pixman-type-other
pixman-type-a
pixman-type-argb
pixman-type-abgr
pixman-type-color
pixman-type-gray
pixman-type-yuy2
pixman-type-yv12
pixman-type-bgra
pixman-type-rgba
pixman-type-argb-srgb
pixman-type-rgba-float
;pixman-format-color
pixman-rgba-float
pixman-rgb-float
pixman-a8r8g8b8
pixman-x8r8g8b8
pixman-a8b8g8r8
pixman-x8b8g8r8
pixman-b8g8r8a8
pixman-b8g8r8x8
pixman-r8g8b8a8
pixman-r8g8b8x8
pixman-x14r6g6b6
pixman-x2r10g10b10
pixman-a2r10g10b10
pixman-x2b10g10r10
pixman-a2b10g10r10
pixman-a8r8g8b8-sRGB
pixman-r8g8b8
pixman-b8g8r8
pixman-r5g6b5
pixman-b5g6r5
pixman-a1r5g5b5
pixman-x1r5g5b5
pixman-a1b5g5r5
pixman-x1b5g5r5
pixman-a4r4g4b4
pixman-x4r4g4b4
pixman-a4b4g4r4
pixman-x4b4g4r4
pixman-a8
pixman-r3g3b2
pixman-b2g3r3
pixman-a2r2g2b2
pixman-a2b2g2r2
pixman-c8
pixman-g8
pixman-x4a4
pixman-x4c4
pixman-x4g4
pixman-a4
pixman-r1g2b1
pixman-b1g2r1
pixman-a1r1g1b1
pixman-a1b1g1r1
pixman-c4
pixman-g4
pixman-a1
pixman-g1
pixman-yuy2
pixman-yv12
pixman-format-supported-destination
pixman-format-supported-source
pixman-image-create-solid-fill
pixman-image-create-linear-gradient
pixman-image-create-radial-gradient
pixman-image-create-conical-gradient
pixman-image-create-bits
pixman-image-create-bits-no-clear
pixman-image-ref
pixman-image-unref
pixman-image-set-destroy-function
pixman-image-get-destroy-data
pixman-image-set-clip-region
pixman-image-set-clip-region32
pixman-image-set-has-client-clip
pixman-image-set-transform
pixman-image-set-repeat
pixman-image-set-filter
pixman-image-set-source-clipping
pixman-image-set-alpha-map
pixman-image-set-component-alpha
pixman-image-get-component-alpha
pixman-image-set-accessors
pixman-image-set-indexed
pixman-image-get-data
pixman-image-get-width
pixman-image-get-height
pixman-image-get-stride
pixman-image-get-depth
pixman-image-get-format
pixman-kernel/impulse
pixman-kernel/box
pixman-kernel/linear
pixman-kernel/cubic
pixman-kernel/gaussian
pixman-kernel/lanczos2
pixman-kernel/lanczos3
pixman-kernel/lanczos3-stretched
pixman-filter-create-separable-convolution
pixman-image-fill-rectangles
pixman-image-fill-boxes
pixman-compute-composite-region
pixman-image-composite
pixman-image-composite32
;pixman-disable-out-of-bounds-workaround ; deprecated
pixman-glyph-x
pixman-glyph-y
pixman-glyph-glyph
pixman-glyph-cache-create
pixman-glyph-cache-destroy
pixman-glyph-cache-freeze
pixman-glyph-cache-thaw
pixman-glyph-cache-lookup
pixman-glyph-cache-insert
pixman-glyph-cache-remove
pixman-glyph-get-extents
pixman-glyph-get-mask-format
pixman-composite-glyphs
pixman-composite-glyphs-no-mask
pixman-edge-x
pixman-edge-e
pixman-edge-stepx
pixman-edge-signdx
pixman-edge-dy
pixman-edge-dx
pixman-edge-stepx-small
pixman-edge-stepx-big
pixman-edge-dx-small
pixman-edge-dx-big
pixman-trapezoid-top
pixman-trapezoid-bottom
pixman-trapezoid-left
pixman-trapezoid-right
pixman-triangle-p1
pixman-triangle-p2
pixman-triangle-p3
;pixman-trapezoid-valid?
pixman-span-fix-l
pixman-span-fix-r
pixman-span-fix-y
pixman-sample-ceil-y
pixman-sample-floor-y
pixman-edge-step
pixman-edge-init
pixman-line-fixed-edge-init
pixman-rasterize-edges
pixman-add-traps
pixman-add-trapezoids
pixman-rasterize-trapezoid
pixman-composite-trapezoids
pixman-composite-triangles
pixman-add-triangles)
(import (scheme)
(srfi 1)
(chicken base)
(chicken foreign)
(chicken gc)
(chicken memory)
(foreigners)
(bind))
(bind-options export-constants: #t
mutable-fields: #t
default-renaming: "")
(bind-rename pixman_region_rectangles %pixman-region-rectangles)
(bind-rename pixman_region32_rectangles %pixman-region32-rectangles)
(bind-file "pixman.h")
(define pixman-transform-is-scale? pixman-transform-is-scale)
(define pixman-transform-is-int-translate? pixman-transform-is-int-translate)
(define pixman-transform-is-inverse? pixman-transform-is-inverse)
(define pixman-transform-is-identity? pixman-transform-is-identity)
(define pixman-region-contains-point? pixman-region-contains-point)
(define pixman-region-contains-rectangle? pixman-region-contains-rectangle)
(define pixman-region-not-empty? pixman-region-not-empty)
(define pixman-region-equal? pixman-region-equal)
(define pixman-region32-contains-point? pixman-region32-contains-point)
(define pixman-region32-contains-rectangle? pixman-region32-contains-rectangle)
(define pixman-region32-not-empty? pixman-region32-not-empty)
(define pixman-region32-equal? pixman-region32-equal)
; Define a series of foreign values of the same type.
(define-syntax define-foreign-values
(syntax-rules ()
((define-foreign-values type)
(begin))
((define-foreign-values type (scm-name c-name) . rest)
(begin
(define scm-name (foreign-value c-name type))
(define-foreign-values type . rest)))))
(define-foreign-record-type (pixman-line-fixed* "struct pixman_line_fixed")
((struct "pixman_point_fixed") p1 pixman-line-fixed-p1)
((struct "pixman_point_fixed") p2 pixman-line-fixed-p2))
(define pixman-vector #f) ;TODO
(define pixman-transform #f) ;TODO
(define pixman-f-vector #f) ;TODO
(define pixman-f-transform #f) ;TODO
; pixman_repeat_t
(define-foreign-values int
(pixman-repeat/none "PIXMAN_REPEAT_NONE")
(pixman-repeat/normal "PIXMAN_REPEAT_NORMAL")
(pixman-repeat/pad "PIXMAN_REPEAT_PAD")
(pixman-repeat/reflect "PIXMAN_REPEAT_REFLECT"))
; pixman_filter_t
(define-foreign-values int
(pixman-filter/fast "PIXMAN_FILTER_FAST")
(pixman-filter/good "PIXMAN_FILTER_GOOD")
(pixman-filter/best "PIXMAN_FILTER_BEST")
(pixman-filter/nearest "PIXMAN_FILTER_NEAREST")
(pixman-filter/bilinear "PIXMAN_FILTER_BILINEAR")
(pixman-filter/convolution "PIXMAN_FILTER_CONVOLUTION")
(pixman-filter/separable-convolution "PIXMAN_FILTER_SEPARABLE_CONVOLUTION"))
; pixman_op_t
(define-foreign-values int
(pixman-op/clear "PIXMAN_OP_CLEAR")
(pixman-op/src "PIXMAN_OP_SRC")
(pixman-op/dst "PIXMAN_OP_DST")
(pixman-op/over "PIXMAN_OP_OVER")
(pixman-op/over-reverse "PIXMAN_OP_OVER_REVERSE")
(pixman-op/in "PIXMAN_OP_IN")
(pixman-op/in-reverse "PIXMAN_OP_IN_REVERSE")
(pixman-op/out "PIXMAN_OP_OUT")
(pixman-op/out-reverse "PIXMAN_OP_OUT_REVERSE")
(pixman-op/atop "PIXMAN_OP_ATOP")
(pixman-op/atop-reverse "PIXMAN_OP_ATOP_REVERSE")
(pixman-op/xor "PIXMAN_OP_XOR")
(pixman-op/add "PIXMAN_OP_ADD")
(pixman-op/saturate "PIXMAN_OP_SATURATE")
(pixman-op/disjoint-clear "PIXMAN_OP_DISJOINT_CLEAR")
(pixman-op/disjoint-src "PIXMAN_OP_DISJOINT_SRC")
(pixman-op/disjoint-dst "PIXMAN_OP_DISJOINT_DST")
(pixman-op/disjoint-over "PIXMAN_OP_DISJOINT_OVER")
(pixman-op/disjoint-over-reverse "PIXMAN_OP_DISJOINT_OVER_REVERSE")
(pixman-op/disjoint-in "PIXMAN_OP_DISJOINT_IN")
(pixman-op/disjoint-in-reverse "PIXMAN_OP_DISJOINT_IN_REVERSE")
(pixman-op/disjoint-out "PIXMAN_OP_DISJOINT_OUT")
(pixman-op/disjoint-out-reverse "PIXMAN_OP_DISJOINT_OUT_REVERSE")
(pixman-op/disjoint-atop "PIXMAN_OP_DISJOINT_ATOP")
(pixman-op/disjoint-atop-reverse "PIXMAN_OP_DISJOINT_ATOP_REVERSE")
(pixman-op/disjoint-xor "PIXMAN_OP_DISJOINT_XOR")
(pixman-op/conjoint-clear "PIXMAN_OP_CONJOINT_CLEAR")
(pixman-op/conjoint-src "PIXMAN_OP_CONJOINT_SRC")
(pixman-op/conjoint-dst "PIXMAN_OP_CONJOINT_DST")
(pixman-op/conjoint-over "PIXMAN_OP_CONJOINT_OVER")
(pixman-op/conjoint-over-reverse "PIXMAN_OP_CONJOINT_OVER_REVERSE")
(pixman-op/conjoint-in "PIXMAN_OP_CONJOINT_IN")
(pixman-op/conjoint-in-reverse "PIXMAN_OP_CONJOINT_IN_REVERSE")
(pixman-op/conjoint-out "PIXMAN_OP_CONJOINT_OUT")
(pixman-op/conjoint-out-reverse "PIXMAN_OP_CONJOINT_OUT_REVERSE")
(pixman-op/conjoint-atop "PIXMAN_OP_CONJOINT_ATOP")
(pixman-op/conjoint-atop-reverse "PIXMAN_OP_CONJOINT_ATOP_REVERSE")
(pixman-op/conjoint-xor "PIXMAN_OP_CONJOINT_XOR")
(pixman-op/multiply "PIXMAN_OP_MULTIPLY")
(pixman-op/screen "PIXMAN_OP_SCREEN")
(pixman-op/overlay "PIXMAN_OP_OVERLAY")
(pixman-op/darken "PIXMAN_OP_DARKEN")
(pixman-op/lighten "PIXMAN_OP_LIGHTEN")
(pixman-op/color-dodge "PIXMAN_OP_COLOR_DODGE")
(pixman-op/color-burn "PIXMAN_OP_COLOR_BURN")
(pixman-op/hard-light "PIXMAN_OP_HARD_LIGHT")
(pixman-op/soft-light "PIXMAN_OP_SOFT_LIGHT")
(pixman-op/difference "PIXMAN_OP_DIFFERENCE")
(pixman-op/exclusion "PIXMAN_OP_EXCLUSION")
(pixman-op/hsl-hue "PIXMAN_OP_HSL_HUE")
(pixman-op/hsl-saturation "PIXMAN_OP_HSL_SATURATION")
(pixman-op/hsl-color "PIXMAN_OP_HSL_COLOR")
(pixman-op/hsl-luminosity "PIXMAN_OP_HSL_LUMINOSITY"))
; pixman_region_overlap_t
(define-foreign-values int
(pixman-region/out "PIXMAN_REGION_OUT")
(pixman-region/in "PIXMAN_REGION_IN")
(pixman-region/part "PIXMAN_REGION_PART"))
(define-foreign-record-type (pixman_region16* "struct pixman_region16")
(constructor: %make-pixman-region16)
(destructor: free-pixman-region16)
((struct "pixman_box16") extents pixman-region16-extents)
((c-pointer (struct "pixman_region16_data")) data pixman-region16-data))
(define (make-pixman-region16)
(let ((region (%make-pixman-region16)))
(pixman-region-init region)
(set-finalizer! region free-pixman-region16)
region))
(define-foreign-record-type (pixman-region32* "struct pixman_region32")
(constructor: %make-pixman-region32)
(destructor: free-pixman-region32)
((struct "pixman_box32") extents pixman-region32-extents)
((c-pointer (struct "pixman_region32_data")) data pixman-region32-data))
(define (make-pixman-region32)
(let ((region (%make-pixman-region32)))
(pixman-region32-init region)
(set-finalizer! region free-pixman-region32)
region))
(define-foreign-record-type (pixman-gradient-stop* "struct pixman_gradient_stop")
(int32 x pixman-gradient-stop-x)
((struct "pixman_color") color pixman-gradient-stop-color))
(define pixman-indexed-rgba #f) ;TODO
(define pixman-indexed-ent #f) ;TODO
(define-foreign-values int
(pixman-rgba-float "PIXMAN_rgba_float")
(pixman-rgb-float "PIXMAN_rgb_float")
(pixman-a8r8g8b8 "PIXMAN_a8r8g8b8")
(pixman-x8r8g8b8 "PIXMAN_x8r8g8b8")
(pixman-a8b8g8r8 "PIXMAN_a8b8g8r8")
(pixman-x8b8g8r8 "PIXMAN_x8b8g8r8")
(pixman-b8g8r8a8 "PIXMAN_b8g8r8a8")
(pixman-b8g8r8x8 "PIXMAN_b8g8r8x8")
(pixman-r8g8b8a8 "PIXMAN_r8g8b8a8")
(pixman-r8g8b8x8 "PIXMAN_r8g8b8x8")
(pixman-x14r6g6b6 "PIXMAN_x14r6g6b6")
(pixman-x2r10g10b10 "PIXMAN_x2r10g10b10")
(pixman-a2r10g10b10 "PIXMAN_a2r10g10b10")
(pixman-x2b10g10r10 "PIXMAN_x2b10g10r10")
(pixman-a2b10g10r10 "PIXMAN_a2b10g10r10")
(pixman-a8r8g8b8-sRGB "PIXMAN_a8r8g8b8_sRGB")
(pixman-r8g8b8 "PIXMAN_r8g8b8")
(pixman-b8g8r8 "PIXMAN_b8g8r8")
(pixman-r5g6b5 "PIXMAN_r5g6b5")
(pixman-b5g6r5 "PIXMAN_b5g6r5")
(pixman-a1r5g5b5 "PIXMAN_a1r5g5b5")
(pixman-x1r5g5b5 "PIXMAN_x1r5g5b5")
(pixman-a1b5g5r5 "PIXMAN_a1b5g5r5")
(pixman-x1b5g5r5 "PIXMAN_x1b5g5r5")
(pixman-a4r4g4b4 "PIXMAN_a4r4g4b4")
(pixman-x4r4g4b4 "PIXMAN_x4r4g4b4")
(pixman-a4b4g4r4 "PIXMAN_a4b4g4r4")
(pixman-x4b4g4r4 "PIXMAN_x4b4g4r4")
(pixman-a8 "PIXMAN_a8")
(pixman-r3g3b2 "PIXMAN_r3g3b2")
(pixman-b2g3r3 "PIXMAN_b2g3r3")
(pixman-a2r2g2b2 "PIXMAN_a2r2g2b2")
(pixman-a2b2g2r2 "PIXMAN_a2b2g2r2")
(pixman-c8 "PIXMAN_c8")
(pixman-g8 "PIXMAN_g8")
(pixman-x4a4 "PIXMAN_x4a4")
(pixman-x4c4 "PIXMAN_x4c4")
(pixman-x4g4 "PIXMAN_x4g4")
(pixman-a4 "PIXMAN_a4")
(pixman-r1g2b1 "PIXMAN_r1g2b1")
(pixman-b1g2r1 "PIXMAN_b1g2r1")
(pixman-a1r1g1b1 "PIXMAN_a1r1g1b1")
(pixman-a1b1g1r1 "PIXMAN_a1b1g1r1")
(pixman-c4 "PIXMAN_c4")
(pixman-g4 "PIXMAN_g4")
(pixman-a1 "PIXMAN_a1")
(pixman-g1 "PIXMAN_g1")
(pixman-yuy2 "PIXMAN_yuy2")
(pixman-yv12 "PIXMAN_yv12"))
(define-foreign-values int
(pixman-kernel/impulse "PIXMAN_KERNEL_IMPULSE")
(pixman-kernel/box "PIXMAN_KERNEL_BOX")
(pixman-kernel/linear "PIXMAN_KERNEL_LINEAR")
(pixman-kernel/cubic "PIXMAN_KERNEL_CUBIC")
(pixman-kernel/gaussian "PIXMAN_KERNEL_GAUSSIAN")
(pixman-kernel/lanczos2 "PIXMAN_KERNEL_LANCZOS2")
(pixman-kernel/lanczos3 "PIXMAN_KERNEL_LANCZOS3")
(pixman-kernel/lanczos3-stretched "PIXMAN_KERNEL_LANCZOS3_STRETCHED"))
(define pixman-glyph-x #f) ;TODO
(define pixman-glyph-y #f) ;TODO
(define pixman-glyph-glyph #f) ;TODO
(define-foreign-record-type (pixman-trapezoid* "struct pixman_trapezoid")
((struct "pixman_line_fixed") left pixman-trapezoid-left)
((struct "pixman_line_fixed") right pixman-trapezoid-right))
(define-foreign-record-type (pixman-triangle* "struct pixman_triangle")
((struct "pixman_point_fixed") p1 pixman-triangle-p1)
((struct "pixman_point_fixed") p2 pixman-triangle-p2)
((struct "pixman_point_fixed") p3 pixman-triangle-p3))
(define-foreign-type pixman-box16* (c-pointer (struct "pixman_box16")))
(define (pixman-region-rectangles region)
(let-values (((rects n) (%pixman-region-rectangles region)))
(map (lambda (i)
((foreign-lambda* pixman-box16* ((int i) (pixman-box16* rects))
"C_return(&rects[i]);")
i rects))
(iota n))))
(define-foreign-type pixman-box32* (c-pointer (struct "pixman_box32")))
(define (pixman-region32-rectangles region)
(let-values (((rects n) (%pixman-region32-rectangles region)))
(map (lambda (i)
((foreign-lambda* pixman-box32* ((int i) (pixman-box32* rects))
"C_return(&rects[i]);")
i rects))
(iota n)))))
| true |
659c71fa11ea15eee83a25e13d762e0b22a340ea
|
8c05c8a8b526dfbdc5320fd4d64088a6f4bd8eec
|
/m3ua-param-testtool.scm
|
81ce20437942bac2ab34d580d4ecb99d754b61a5
|
[
"BSD-2-Clause"
] |
permissive
|
nplab/m3ua-testtool
|
da66235156ee06e180a192091d43aef22691c0f6
|
ae3e1b3f5e13b67dd68d5d3598805f26afbfcfda
|
refs/heads/master
| 2022-02-03T22:28:17.781739 | 2022-01-21T10:19:08 | 2022-01-21T10:19:08 | 66,705,740 | 6 | 1 |
NOASSERTION
| 2021-12-15T19:48:45 | 2016-08-27T09:02:57 |
Scheme
|
UTF-8
|
Scheme
| false | false | 5,105 |
scm
|
m3ua-param-testtool.scm
|
;;;
;;; Copyright (C) 2004, 2005 M. Tuexen [email protected]
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or
;;; without modification, are permitted provided that the
;;; following conditions are met:
;;; 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. Neither the name of the project 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 PROJECT 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 PROJECT 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.
;;; $Id: m3ua-param-testtool.scm,v 1.5 2012/08/28 19:56:13 tuexen Exp $
;;; Define a transport address of the system under test
(define sut-addr "127.0.0.1")
(define sut-port 0)
(define sut-port-1 0)
(define sut-port-2 0)
;;; Define the transport address of the tester
(define tester-addr "127.0.0.1")
(define tester-port m3ua-port)
(define tester-port-1 3000)
(define tester-port-2 3001)
;;; Define the point code of the IUT
(define iut-pc 4001)
;;; Define the point code of the tester
(define tester-pc 100)
(define tester-pc-1 100)
(define tester-pc-2 101)
(define tester-invalid-pc 102)
(define tester-unauthorized-pc 103)
(define tester-unprovisioned-pc 104)
(define tester-unavailable-pc 1234)
(define tester-available-pc 1235)
(define tester-congested-pc 1236)
(define tester-restricted-pc 1237)
;;; Define a valid SS7 message and SI
(define ss7-message (list 11 34 45 67 67 89))
(define ss7-si 0)
(define iut-ni 1)
(define iut-mp 0)
(define iut-sls 0)
;;; Define correlation id
(define correlation-id 1)
;;; Define network appearance
(define network-appearance 1)
(define invalid-network-appearance 2)
;;; Define an routing context
(define tester-rc-valid 1)
(define tester-rc-valid-1 1)
(define tester-rc-valid-2 2)
;;; Define an invalid routing context
(define tester-rc-invalid 3)
;;; Define an asp-identifier
(define asp-id 1)
(define asp-id-1 1)
(define asp-id-2 2)
;;; Define traffic-type-mode
;;;(define traffic-mode m3ua-traffic-mode-type-override)
(define traffic-mode m3ua-traffic-mode-type-loadshare)
;;;(define traffic-mode m3ua-traffic-mode-type-broadcast)
(define asp-up-message-parameters (list))
;;; (define asp-up-message-parameters (list (m3ua-make-asp-id-parameter asp-id)))
;;;asp-up-message-parameters
(define asp-active-message-parameters (list))
;;;(define asp-active-message-parameters (list (m3ua-make-traffic-mode-type-parameter traffic-mode)
;;; (m3ua-make-routing-context-parameter (list tester-rc-valid))))
;;;asp-active-message-parameters
(define asp-active-ack-message-parameters (list))
;;;(define asp-active-ack-message-parameters (list (m3ua-make-traffic-mode-type-parameter traffic-mode)
;;; (m3ua-make-routing-context-parameter (list tester-rc-valid))))
;;;asp-active-ack-message-parameters
(define asp-inactive-message-parameters (list))
;;;(define asp-inactive-message-parameters (list (m3ua-make-traffic-mode-type-parameter traffic-mode)
;;; (m3ua-make-routing-context-parameter (list tester-rc-valid))))
;;;asp-inactive-message-parameters
(define asp-inactive-ack-message-parameters (list))
;;;(define asp-inactive-ack-message-parameters (list (m3ua-make-routing-context-parameter (list tester-rc-valid))))
;;;asp-inactive-ack-message-parameters
(define data-message-parameters (list))
;;;(define data-message-parameters (list (m3ua-make-network-appearance-parameter network-appearance)
;;; (m3ua-make-routing-context-parameter (list tester-rc-valid))))
;;;data-message-parameters
;;; Define parameter for DATA message
(define rc 1)
(define opc 1)
(define dpc 2)
(define si 0)
(define sls 0)
(define ni 0)
(define mp 0)
(define ss7-message (list 11 34 45 67 67 89))
(define data-message-parameters (list (m3ua-make-routing-context-parameter (list rc))))
| false |
1ec2d02f0d466ced2126d1b6a6c15a57e4add248
|
ffee55543efba56a659d78cb89f417f4e44ae63f
|
/led/buffer.scm
|
88dd69d03c1bb2ded53dcf0d90b0d462bbfc22eb
|
[
"MIT"
] |
permissive
|
pfmaggi/led
|
11f4f71f11e36157434b1983a7fbfd4f304c4ef0
|
16f94efb7ac64dce3d22efdea978afd311479ae4
|
refs/heads/master
| 2020-11-30T12:31:08.851678 | 2017-05-09T16:53:51 | 2018-04-08T19:12:32 | 67,937,950 | 0 | 0 | null | 2016-09-11T15:33:39 | 2016-09-11T15:33:38 | null |
UTF-8
|
Scheme
| false | false | 5,199 |
scm
|
buffer.scm
|
(define-library (led buffer)
(import
(owl base)
(owl sys)
(led log)
(led node))
(export
buffer
make-buffer-having
make-empty-buffer
buffer-meta
set-buffer-meta
put-buffer-meta
get-buffer-meta
get-global-meta
put-global-meta
buffer-path
buffer-path-str
buffer-x
put-copy-buffer
get-copy-buffer
screen-width
screen-height
buffer-screen-size
buffer-y
buffer->lines
buffer-current-line ;; get value of .
buffer-line-count ;; get value of $
write-buffer
buffer-range->bytes
)
(begin
(define (buffer up down left right x y off meta)
(tuple up down left right x y off meta))
(define (make-buffer-having w h meta data)
(lets ((r d (uncons data null)))
(buffer null d null r 1 1 (cons 0 0) meta)))
(define (make-empty-buffer w h meta)
(make-buffer-having w h meta null))
(define (buffer-meta buff) (ref buff 8))
(define (set-buffer-meta buff meta) (set buff 8 meta))
(define (put-buffer-meta buff key val)
(set-buffer-meta buff (put (buffer-meta buff) key val)))
(define (get-buffer-meta buff key def)
(get (buffer-meta buff) key def))
(define (get-global-meta buff key def)
(get (get-buffer-meta buff 'global #empty) key def))
(define (screen-width buff) (get-global-meta buff 'width 10))
(define (screen-height buff) (get-global-meta buff 'height 10))
(define (buffer-screen-size buff)
(values
(get-global-meta buff 'width 20)
(get-global-meta buff 'height 10)))
(define (put-global-meta buff key val)
(put-buffer-meta buff 'global
(put (get-buffer-meta buff 'global #empty) key val)))
(define (put-copy-buffer buff key val)
(put-global-meta buff 'copy
(put (get-global-meta buff 'copy #empty) key val)))
(define (get-copy-buffer buff key def)
(get (get-global-meta buff 'copy #empty) key def))
(define (buffer-path buff default)
(get-buffer-meta buff 'path default))
(define (buffer-path-str buff)
(get-buffer-meta buff 'path "*scratch*"))
(define (buffer-x buff) (ref buff 5))
(define (buffer-y buff) (ref buff 6))
(define (buffer->lines buff)
(lets ((u d l r x y off meta buff))
(log "buffer->lines bound")
(map (λ (line) (list->string (foldr render-code-point null line)))
(append (reverse u)
(cons (append (reverse l) r) d)))))
;; buffer writing
(define (nodes->bytes nodes)
(foldr render-node null nodes))
(define (lines->bytes ls)
(nodes->bytes
(foldr
(λ (line tl)
(append line (cons #\newline tl)))
null ls)))
(define (buffer->bytes buff)
(lets ((u d l r x y off meta buff))
(lines->bytes
(append (reverse u) (list (append (reverse l) r)) d))))
(define (pick-lines ls start end)
(let ((off (- start 1)))
(take (drop ls off) (- end off))))
;; buffer → line-number
(define (buffer-current-line buff)
(lets ((u d l r x y off meta buff)
(dx dy off))
(+ y dy)))
(define (buffer-line-count buff)
(lets ((u d l r x y off meta buff))
; = (+ 1 (length u) (length d))
(+ (buffer-current-line buff)
(length d))))
;; buff start end → (byte ...)
(define (buffer-range->bytes buff start end)
(lets ((u d l r x y off meta buff))
(if (and start end (<= start end))
(lines->bytes
(pick-lines
(append (reverse u) (list (append (reverse l) r)) d)
start end))
#false)))
(define (write-buffer buff path)
(log "writing to " path)
(cond
((not path)
(values #false
(foldr render null
(list "Give me a name for this"))))
((directory? path)
(values #false
(foldr render null
(list "'" path "' is a directory"))))
(else
(lets
((port (open-output-file path))
(lst (buffer->bytes buff))
(n (length lst))
(res (if port (byte-stream->port lst port) #f)))
(if port
(close-port port))
(if res
(values #true
(foldr render null
(list "Wrote " n " bytes to '" path "'")))
(values #false
(foldr render null
(list "Failed to write to '" path "'"))))))))
))
| false |
b447d1757ff490d9b2ab927aaa2874ce6414c231
|
8ff65fde19dd9350abe14b939956b4f6eb951c8a
|
/15.ss
|
13aa037af8994774db59a2a6b2569236b8031ec6
|
[] |
no_license
|
chenxiany11/Programming-Language-Concept
|
ce8f1e242a31b5f8c42d3e1eb4bf46eecfac84f2
|
80f21d6cd5aac8420e2c81d30120d5982b4134fc
|
refs/heads/main
| 2023-02-25T03:20:35.937934 | 2021-01-29T03:11:10 | 2021-01-29T03:11:10 | 334,022,933 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,987 |
ss
|
15.ss
|
; Assigenment 15
; #15.ss
; Sybil Chen
; 10/20/2020
; #1a
(define apply-k
(lambda (k v)
(k v)))
(define make-k ; lambda is the "real" continuation
(lambda (v) v)) ; constructor here.
(define (member?-cps item L k)
(cond [(null? L) (apply-k k #f)]
[(equal? item (car L))
(apply-k k #t)]
[else (member?-cps item (cdr L) k)]))
(define (set?-cps L k)
(cond [(null? L) (apply-k k #t)]
[(not (pair? L)) (apply-k k #f)]
[else (set?-cps (cdr L)
(make-k (lambda (x)
(member?-cps (car L) (cdr L)
(make-k (lambda (y)
(if y (apply-k k #f)
(apply-k k x))))))))]))
(define (set-of-cps L k)
(if (null? L)
(apply-k k '())
(set-of-cps (cdr L)
(make-k (lambda (x)
(member?-cps (car L) (cdr L)
(make-k (lambda (m)
(apply-k k
(if m x (cons (car L) x)))))))))))
(define (1st-cps L k)
(apply-k k (car L)))
;(trace set-of-cps)
(define (map-cps proc L k)
(if (null? L)
(apply-k k '())
(map-cps proc (cdr L)
(make-k (lambda (x)
(proc (car L)
(make-k (lambda (result)
(apply-k k (cons result x))))))))))
(define (domain-cps L k)
(map-cps 1st-cps L (make-k (lambda (x) (set-of-cps x k)))))
; #1b
(define (make-cps proc)
(lambda (arg k)
(apply-k k (proc arg))))
; #1c
(define (andmap-cps pred-cps ls continuation)
(if (null? ls)
(apply-k continuation #t)
(pred-cps (car ls)
(lambda (result)
(if result
(andmap-cps pred-cps (cdr ls)
(lambda (x)
(apply-k continuation x)))
(apply-k continuation #f))))))
;(trace andmap-cps)
; #2
;(load "chez-init.ss")
; get code from live-in-class
(define scheme-value? (lambda (x) #t))
(define 1st car)
(define 2nd cadr)
(define 3rd caddr)
(define-datatype continuation continuation?
[init-k] ; These first continuation variants need no fields.
[list-k]
[not-k]
)
(define exp? ; Is obj a lambda-calculus expression? This uses
(lambda (obj) ; our original simple definition of lc-expressions.
(or (symbol? obj)
(and (list? obj)
(or
(and (= (length obj) 3)
(eq? (1st obj) 'lambda)
(list? (2nd obj))
(= (length (2nd obj)) 1)
(symbol? (caadr obj))
(exp? (3rd obj)))
(and (= (length obj) 2)
(exp? (1st obj))
(exp? (2nd obj))))))))
(define apply-k-ds
(lambda (k v)
(if (procedure? k) (k v)
(cases continuation k
[init-k () v]
[list-k () (list v)]
[not-k () (not v)]
))))
(define memq-cps
(lambda (sym ls k)
(cond [(null? ls)
(apply-k-ds k #f)]
[(eq? (car ls) sym)
(apply-k-ds k #t)]
[else (memq-cps sym (cdr ls) k)])
))
(define free-vars-cps ; convert to CPS
(lambda (exp k)
(cond [(symbol? exp) ;fill it in
(apply-k-ds k (list exp))]
[(eq? (car exp) 'lambda) ; fill it in
(free-vars-cps (caddr exp)
(make-k (lambda (x)
(remove-cps (car (cadr exp)) x k))))
]
[else ; fill it in
(free-vars-cps (car exp)
(make-k (lambda (x)
(free-vars-cps (cadr exp)
(make-k (lambda (y)
(union-cps x y k)))))))
])))
;(trace free-vars-cps)
(define union-cps ; assumes that both arguments are sets of symbols
(lambda (s1 s2 k)
(if (null? s1) ; fill it in
(apply-k-ds k s2)
(memq-cps (car s1) s2
(make-k (lambda (x)
(union-cps (cdr s1) s2
(make-k (lambda (y)
(if x (union-cps (cdr s1) s2 k)
(apply-k-ds k (cons (car s1) y)))))))))
)))
(define remove-cps ; removes the first occurrence of element in ls
(lambda (element ls k)
(cond [(null? ls) (apply-k-ds k '())]
[(equal? element (car ls)) (apply-k-ds k (cdr ls))]
[else (remove-cps element (cdr ls)
(make-k (lambda (x)
(apply-k-ds k (if (eq? element (car ls))
x
(cons (car ls) x))))))])))
| false |
97091963c8e20cfe7a42015a9e55045c84d277e8
|
2a4d841aa312e1759f6cea6d66b4eaae81d67f99
|
/lisp/scheme/chicken/updaate-chicken.ss
|
bb2771b4e488a0610c093fc69a4b8fc45c4ff4f4
|
[] |
no_license
|
amit-k-s-pundir/computing-programming
|
9f8e136658322bb9a61e7160301c1a780cec84ca
|
9104f371fe97c9cd3c9f9bcd4a06038b936500a4
|
refs/heads/master
| 2021-07-12T22:46:09.849331 | 2017-10-16T08:50:48 | 2017-10-16T08:50:48 | 106,879,266 | 1 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 810 |
ss
|
updaate-chicken.ss
|
(module update-chicken
(*)
(import posix files)
(define chicken-install-dir "/opt/lisp/scheme/chicken")
(define chicken-dev-install-dir "/opt/lisp/scheme/chicken_dev")
(define chicken-stable-install-dir "/opt/lisp/scheme/chicken_stable")
(define source-download-dir "/opt/lisp/scheme/sources")
(define (update-chicken (url install-dir)
(define update-chicken-stable (#!optional url)
(unless (directory? chicken-stable-install-dir)
(create-directory chicken-stable-install-dir))
(change-directory source-download-dir)
(let ((temp-dir (create-temporary-directory)))
(change-directory temp-dir)
(if (irregex-search "^https?.*$" url)
(download url source-download-dir)
(rsync url source-download-dir))
(rsync url (current-directory))
| false |
75c78917765513637144c4bdca6f34497b3567a5
|
fb6c8976daedad7dc2c5230c6927d6c2ee067b64
|
/src/data.scm
|
d45c1c84b02d421492c748aeaf7992057a3892c4
|
[] |
no_license
|
Smirnoff/WireMap
|
e24e497325fb228ff5c91f0042855d92767515e6
|
d523ab311a516f7ae950698f543a3fc9e22a1c92
|
refs/heads/master
| 2020-05-25T19:54:06.377565 | 2012-06-13T02:31:18 | 2012-06-13T02:31:18 | 4,343,379 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,890 |
scm
|
data.scm
|
(use srfi-1 srfi-69)
(use berkeleydb posix)
;; filenames
(define relative-path
(let ((path ##sys#current-load-path))
(lambda (filename)
(string-append path filename))))
(define +iso-3166+ (relative-path "../data/iso_3166-1_alpha-2.scm"))
(define +iso-4217+ (relative-path "../data/iso_4217.scm"))
(define +bank-details+ (relative-path "../data/bank_details.scm"))
(define +bank-details-db+ (relative-path "../data/bank_details.db"))
(define +payment-templates+ (relative-path "../data/payment_templates.scm"))
(define +iban-registry+ (relative-path "../data/iban_registry.scm"))
(define +abm-banks+ (relative-path "../data/abm_bank_numbers.scm"))
(define (file-data filename) (with-input-from-file filename read-file))
(define (dump-to-file filename data)
(with-output-to-file filename
(lambda () (for-each (lambda (x) (write x) (newline)) data))))
(define (run-once func)
(let ((res #f) (ran? #f))
(lambda args
(if ran?
res
(begin
(set! res (apply func args))
(set! ran? #t)
res)))))
(define-syntax define/run-once
(syntax-rules ()
((define/run-once (name . args) body . rest)
(define name (run-once (lambda args body . rest))))))
(define/run-once (country-code-hash)
(alist->hash-table (file-data +iso-3166+)))
(define/run-once (reverse-country-code-hash)
(alist->hash-table
(map (lambda (x) (cons (cdr x) (car x)))
(hash-table->alist (country-code-hash)))))
(define (country-code->country-name code)
(hash-table-ref/default
(country-code-hash) (if (string? code) (string->symbol code) code) #f))
(define (country-name->country-code name)
(hash-table-ref/default (reverse-country-code-hash) name #f))
(define (valid-country-code? code) (and (country-code->country-name code) #t))
(define/run-once (currency-data) (file-data +iso-4217+))
(define/run-once (transaction-templates) (file-data +payment-templates+))
(define (obj->string x)
(with-output-to-string (lambda () (write x))))
(define (string->obj x)
(with-input-from-string x read))
(define (swift+branch-key swift branch)
(obj->string (list swift branch)))
(define/run-once (transaction-templates/currency)
(fold (lambda (item res)
(hash-table-update!
res (alist-ref 'currency (alist-ref 'matcher item))
(lambda (x) (cons item x))
(lambda () (list item)))
res)
(make-hash-table)
(transaction-templates)))
(define/run-once (iban-registry) (file-data +iban-registry+))
(define/run-once (iban-registry/country)
(alist->hash-table
(map (lambda (x) (cons (alist-ref 'country-code x) x))
(iban-registry))))
(define (redo-bank-details-db?)
(or (not (file-exists? +bank-details-db+))
(< (file-modification-time +bank-details-db+)
(file-modification-time +bank-details+))))
(define/run-once (bank-details) (file-data +bank-details+))
(define (db-append-obj! db key value)
(let ((key/str (obj->string key)))
(db-put!
db
key/str
(obj->string
(cons value
(string->obj (db-get/default db key/str (obj->string '()))))))))
(define (file-contents-for-each filename func)
(with-input-from-file filename
(lambda ()
(let iter ((next (read)))
(if (eof-object? next)
#f
(begin
(func next)
(iter (read))))))))
(define (ensure-bank-details-db!)
(when (redo-bank-details-db?)
(error "bank_details.db needs to be regenerated"))
(when (redo-bank-details-db?)
(with-input-from-file +bank-details+
(lambda ()
(call-with-fresh-db +bank-details-db+
(lambda (db)
(let iter ((x (read)))
(when (not (eof-object? x))
(let ((swift (alist-ref 'swift x))
(branch (alist-ref 'swift-branch x)))
(db-put!
db
(obj->string (list swift branch))
(obj->string x))
(db-append-obj! db (list swift #f) (list swift branch))
(db-sync db))
(iter (read))))))))))
(define (bank-details-db-ref swift #!optional (branch "XXX"))
(ensure-bank-details-db!)
(call-with-db
+bank-details-db+
(lambda (db)
(string->obj
(db-get/default db (obj->string (list swift branch)) (obj->string #f))))))
(define (bank-swifts-db-ref swift)
(ensure-bank-details-db!)
(call-with-db
+bank-details-db+
(lambda (db)
(string->obj
(db-get/default db (obj->string (list swift #f)) (obj->string #f))))))
(define/run-once (abm-banks) (file-data +abm-banks+))
(define/run-once (abm-number-hash)
(alist->hash-table
(map (lambda (x) (cons (alist-ref 'number x) x)) (abm-banks))))
(define (abm-bank-number-ref num)
(hash-table-ref/default (abm-number-hash) num #f))
| true |
55e3dcd87ae0e71e9b8d979b2e6cfaaccf8336ef
|
92b8d8f6274941543cf41c19bc40d0a41be44fe6
|
/testsuite/match1.scm
|
c06b99f6e73306b03194535a19e2bee143a00cb8
|
[
"MIT"
] |
permissive
|
spurious/kawa-mirror
|
02a869242ae6a4379a3298f10a7a8e610cf78529
|
6abc1995da0a01f724b823a64c846088059cd82a
|
refs/heads/master
| 2020-04-04T06:23:40.471010 | 2017-01-16T16:54:58 | 2017-01-16T16:54:58 | 51,633,398 | 6 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,530 |
scm
|
match1.scm
|
(format #t "to string: ~w~%"
(map (lambda (x) (if (? s ::string x) s "N/A")) '(3 "hello" 3.5 #\?)))
;; Output: to string: ("N/A" "hello" "N/A" "N/A")
(format #t "to String: ~w~%"
(map (lambda (x) (if (? s ::String x) s "N/A")) '(3 "hello" 3.5 #\?)))
;; Output: to String: ("3" "hello" "3.5" "'?'")
(format #t "to character: ~w~%"
(map (lambda (x) (if (? c ::character x) c #\?))
(list #!eof 3 "hello" #\X (java.lang.Character #\Y))))
;; Output: to character: (#\? #\? #\? #\X #\Y)
(format #t "to character-or-eof: ~w~%"
(map (lambda (x) (if (? c ::character-or-eof x) c #\?))
(list #!eof 3 "hello" #\X (java.lang.Character #\Y))))
;; Output: to character-or-eof: (#!eof #\? #\? #\X #\Y)
(format #t "to char: ~w~%"
(map (lambda (x) (if (? c ::char x) c #\?))
(list #!eof 3 #\X (java.lang.Character #\Y) #\x12345)))
;; Output: to char: (#\? #\? #\X #\Y #\?)
(format #t "to boolean: ~w~%"
(map (lambda (x) (if (? b::boolean x) b -1)) '(1 #f #\X #t)))
;; Output: to boolean: (-1 #f -1 #t)
(define (to-v o)
(if (? v ::vector o) v '#()))
(format #t "to vector: ~w~%"
(map to-v '(4 (5) #(6))))
;; Output: to vector: (#() #() #(6))
(define (to-f64v o)
(if (? f64v ::f64vector o) f64v '#f64(-1 0)))
(format #t "to f64v: ~w~%"
(map to-f64v '(4 #(5) #f64(7))))
;; Output: to f64v: (#f64(-1.0 0.0) #f64(-1.0 0.0) #f64(7.0))
(define (to-list o)
(if (? l ::list o) l '()))
(format #t "to list: ~w~%"
(map to-list '(4 #(5 6) (7 6))))
;; Output: to list: (() () (7 6))
(define (to-FVector o)
(if (? v ::gnu.lists.FVector o) v '#()))
(format #t "to FVector: ~w~%"
(map to-FVector '(4 (5) #(6))))
;; Output: to FVector: (#() #() #(6))
(define (to-F64Vector o)
(if (? f64v ::gnu.lists.F64Vector o) f64v '#f64(1 2)))
(format #t "to F64Vector: ~w~%"
(map to-f64v '(4 #(5) #f64(7))))
;; Output: to F64Vector: (#f64(-1.0 0.0) #f64(-1.0 0.0) #f64(7.0))
(define (to-LList o)
(if (? l ::gnu.lists.LList o) l '()))
(format #t "to LList: ~w~%"
(map to-LList '(4 #(5 6) (7 6))))
;; Output: to LList: (() () (7 6))
(define (to-list2 o)
(if (? [a b] o) (format "[a:~w b:~w]" a b) (format "no-match:~w" o)))
(display (format #f "to list2: ~a"
(map to-list2 (list 12 #(4 5) #(9) '(m n) '(m n o) '())))) (newline)
;; Output: to list2: (no-match:12 [a:4 b:5] no-match:#(9) [a:m b:n] no-match:(m n o) no-match:())
(define (to-list2+1 o)
(if (? [[a b] c] o) (format "[a:~w b:~w c:~w]" a b c)
(format "no-match:~w" o)))
(display (format #f "to list2+1: ~a"
(map to-list2+1 (list 12 #((4 5) 7) #(9 8) '(#(p q) r) '(m n o) '()))))
(newline)
;; Output: to list2+1: (no-match:12 [a:4 b:5 c:7] no-match:#(9 8) [a:p b:q c:r] no-match:(m n o) no-match:())
(display (format "to list2+1-ignore1: ~a"
(map (lambda (o) (if (? [[a _] b] o) (format "[a:~w b:~w]" a b)
(format "no-match:~w" o)))
(list 12 #((4 5) 7) #(9 8) '(#(p q) r) '(m n o) '()))))
(newline)
;; Output: to list2+1-ignore1: (no-match:12 [a:4 b:7] no-match:#(9 8) [a:p b:r] no-match:(m n o) no-match:())
(display (format "to list2-int: ~a"
(map (lambda (o) (if (? [a::integer b] o) (format "[a:~w b:~w]" a b)
(format "no-match:~w" o)))
(list 12 #((4 5) 7) #(9 8) '(#(p q) r) '(m n) '()))))
(newline)
;; Output: to list2-int: (no-match:12 no-match:#((4 5) 7) [a:9 b:8] no-match:(#(p q) r) no-match:(m n) no-match:())
| false |
0e33c9f6ed2193ac9c9ccff2f2cbd6a8dac6ce89
|
46a26f8b026f5b7036bebd9d0baaa6edf18bfe12
|
/tests/trig-tests.scm
|
8c5a10c5a2aa7ec3de949a371d4df47e46b4c648
|
[
"MIT"
] |
permissive
|
pqnelson/calculator
|
4d8be428e2efc45bb40c0f3f8f193806a6049449
|
d8fd94703dcbe7917dbcc140fd0f5271093379c4
|
refs/heads/master
| 2016-09-05T21:42:41.524941 | 2014-02-09T17:27:54 | 2014-02-09T17:27:54 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 861 |
scm
|
trig-tests.scm
|
(import "./src/trig.scm")
(log/info "\nRunning trig tests...")
(log/info "Testing cosine identities...")
(assert (float= (cos 0) 1))
(assert (float= (cos (/ :pi 12))
(/ (+ (sqrt 2) (sqrt 6)) 4)))
(assert (float= (cos (/ :pi 8))
(/ (sqrt (+ 2 (sqrt 2))) 2)))
(assert (float= (cos (/ :pi 6))
(/ (sqrt 3) 2)))
(log/info "Testing sine identities...")
(assert (= (real-sin 0) 0))
(assert (float= (sin (/ :pi 12))
(/ (- (sqrt 6) (sqrt 2)) 4)))
(assert (float= (sin (/ :pi 8))
(/ (sqrt (- 2 (sqrt 2))) 2)))
(assert (float= (sin (/ :pi 6)) 1/2))
(assert (float= (sin :pi/4) (/ 1 (sqrt 2))))
(assert (float= (sin (/ :pi 3))
(/ (sqrt 3) 2)))
(assert (float= (sin (* 5/12 :pi))
(/ (+ (sqrt 2) (sqrt 6)) 4)))
(log/info "All trig tests passed successfully!")
| false |
d9130ca50de3fa360e7bed767df5b954b7e44718
|
0ffe5235b0cdac3846e15237c2232d8b44995421
|
/src/scheme/Section_1.2/1.27.scm
|
399b8d595ad53c0dc77a81cbe4ff830cabe9a326
|
[] |
no_license
|
dawiedotcom/SICP
|
4d05014ac2b075b7de5906ff9a846e42298fa425
|
fa6ccac0dad8bdad0645aa01197098c296c470e0
|
refs/heads/master
| 2020-06-05T12:36:41.098263 | 2013-05-16T19:41:38 | 2013-05-16T19:41:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 818 |
scm
|
1.27.scm
|
; SICP Exercise 1.27
; Dawie de Klerk
; 2012-08-09
(define (square x) (* x x))
(define (expmod base exp m)
(cond ((zero? exp) 1)
((even? exp)
(remainder (square (expmod base (/ exp 2) m)) m))
(else
(remainder (* base (expmod base (- exp 1) m)) m))))
(define (fermat-test n)
(define (try a)
(= (expmod a n n) a))
;(try-it (+ 1 (random (- n 1)))))
(define (fermat-test-iter a)
(cond ((= a n) #t)
((try a) (fermat-test-iter (+ a 1)))
(else #f)))
(fermat-test-iter 1))
(println "")
(println "Testing some composits")
(println (map fermat-test '(10 100 4 6)))
(println "Testing some primes:")
(println (map fermat-test '(2 3 5 13 19 23)))
(println "Testing the Carmicheal numbers")
(println "561 1105 1729 2465 2821 6601:")
(println (map fermat-test '(561 1105 1729 2465 2821 6601)))
| false |
f55e0c69f957280cf648afdc7125cdfd4420970f
|
e42c980538d5315b9cca17460c90d9179cc6fd3a
|
/Work/Template.scm
|
aa5c30ca4bcd11bf9754094f7873e90f31778dda
|
[] |
no_license
|
KenDickey/Scheme2Smalltalk-Translator
|
c4415f2053932a2c83b59ac9a554097836c55873
|
9ccd4e45fb386f99d2e62fc769f78241fbe29c77
|
refs/heads/master
| 2020-12-24T19:46:30.348021 | 2016-05-13T23:12:06 | 2016-05-13T23:12:06 | 58,775,118 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 445 |
scm
|
Template.scm
|
;; FILE: "Template.scm"
;; IMPLEMENTS: Scheme file template for whatever..
;; AUTHOR: Ken Dickey
;; DATE: 08 December 2001
;; COPYRIGHT (c) 2001 by Kenneth A Dickey
;; This software may be used for any purpose but
;; without warrenty or liability of any kind
;; provided this notice is included.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; WHATEVER
;;;;;;;;;;;
;; --- E O F --- ;;
| false |
262810af32565c11c0da602039daaa29cdb7e7a4
|
f04768e1564b225dc8ffa58c37fe0213235efe5d
|
/Interpreter/all.ss
|
c1b509c30167a834ad558ce2ec651ea43490947f
|
[] |
no_license
|
FrancisMengx/PLC
|
9b4e507092a94c636d784917ec5e994c322c9099
|
e3ca99cc25bd6d6ece85163705b321aa122f7305
|
refs/heads/master
| 2021-01-01T05:37:43.849357 | 2014-09-09T23:27:08 | 2014-09-09T23:27:08 | 23,853,636 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 13,152 |
ss
|
all.ss
|
;: Single-file version of the interpreter.
;; Easier to submit to server, probably harder to use in the development process
; (load "chez-init.ss")
;-------------------+
; |
; DATATYPES |
; |
;-------------------+
;; Parsed expression datatypes
(define-datatype expression expression? ; based on the simple expression grammar, EoPL-2 p6
[var-exp (id symbol?)]
[val-exp (val integer?)]
[lit-exp (datum (lambda (x) (ormap (lambda (pred) (pred x)) (list number? vector? boolean? symbol? string? pair? null?))))]
[lambda-exp (args symbol?)
(body (list-of expression?))]
[lambda-list-exp (args pair?)
(body (list-of expression?))]
[let-exp (assign list?)
(body (list-of expression?))]
[app-exp (rator expression?)
(rands (list-of expression?))]
[prim-exp (proc proc-val?)
(args list?)]
[if-exp (con expression?)
(body expression?)]
[if-else-exp (con expression?)
(t-body expression?)
(f-body expression?)]
[set!-exp (var symbol?)
(val expression?)])
; datatype for procedures. At first there is only one
; kind of procedure, but more kinds will be added later.
(define-datatype proc-val proc-val?
[prim-proc (name (lambda (x) (member x *prim-proc-names*)))]
[closure (vars (list-of symbol?))
(body (list-of expression?))
(env environment?)])
;; environment type definitions
(define scheme-value?
(lambda (x) #t))
(define-datatype environment environment?
[empty-env-record]
[extended-env-record (syms (list-of symbol?))
(vals (list-of scheme-value?))
(env environment?)])
;-------------------+
; |
; PARSER |
; |
;-------------------+
; This is a parser for simple Scheme expressions, such as those in EOPL, 3.1 thru 3.3.
; You will want to replace this with your parser that includes more expression types, more options for these types, and error-checking.
; Procedures to make the parser a little bit saner.
(define 1st car)
(define 2nd cadr)
(define 3rd caddr)
(define parse-exp
(lambda (datum)
(cond [(member datum *prim-proc-names*) (lit-exp (prim-proc datum))]
[(integer? datum) (val-exp datum)]
[(symbol? datum) (var-exp datum)]
[(null? datum) (lit-exp datum)]
[(vector? datum) (lit-exp datum)]
[(boolean? datum) (lit-exp datum)]
[(number? datum) (lit-exp datum)]
[(string? datum) (lit-exp datum)]
[(pair? datum) (cond [(eqv? (car datum) 'lambda) (parse-lambda-exp datum)]
[(eqv? (car datum) 'set!) (parse-set!-exp datum)]
[(eqv? (car datum) 'if) (parse-if-exp datum)]
[(eqv? (car datum) 'let) (parse-let-exp datum)]
[(eqv? (car datum) 'quote) (lit-exp (cadr datum))]
[(member (car datum) *prim-proc-names*) (prim-exp (prim-proc (car datum)) (map parse-exp (cdr datum)))]
[(list? datum) (app-exp (parse-exp (car datum)) (map parse-exp (cdr datum)))]
[else (eopl:error 'parse-exp "expression ~s is not a proper list" datum)])]
[else (eopl:error 'parse-exp "Invalid concrete syntax ~s" datum)])))
(define parse-lambda-exp
(lambda (exp)
(if (> (length exp) 2)
(if (symbol? (cadr exp)) (lambda-exp (cadr exp) (map parse-exp (cddr exp)))
(lambda-list-exp (parse-lambda-args (cadr exp)) (map parse-exp (cddr exp))))
(eopl:error 'parse-exp "lambda-expression: incorrect length ~s" exp))))
(define parse-lambda-args
(lambda (args)
(if (andmap symbol? args) args
(eopl:error 'parse-exp "lambda's formal arguments ~s must all be symbols" args))))
(define parse-if-exp
(lambda (exp)
(cond [(= (length exp) 3) (if-exp (parse-exp (cadr exp)) (parse-exp (caddr exp)))]
[(= (length exp) 4) (if-else-exp (parse-exp (cadr exp)) (parse-exp (caddr exp)) (parse-exp (cadddr exp)))]
[else (eopl:error 'parse-exp "if-expression ~s does not have (only) test, then, and else" exp)])))
(define parse-set!-exp
(lambda (exp)
(if (= (length exp) 3) (set!-exp (cadr exp) (parse-exp (caddr exp)))
(eopl:error 'parse-exp "set! expression ~s does not have (only) variable and expression" exp))))
(define parse-let-exp
(lambda (exp)
(if (> (length exp) 2) (let-exp (parse-let-args (cadr exp)) (map parse-exp (cddr exp)))
(eopl:error 'parse-exp "~s-expression has incorrect length ~s" exp))))
(define parse-let*-exp
(lambda (exp)
(if (> (length exp) 2) (let*-exp (parse-let-args (cadr exp)) (map parse-exp (cddr exp)))
(eopl:error 'parse-exp "~s-expression has incorrect length ~s" exp))))
(define parse-letrec-exp
(lambda (exp)
(if (> (length exp) 2) (letrec-exp (parse-let-args (cadr exp)) (map parse-exp (cddr exp)))
(eopl:error 'parse-exp "~s-expression has incorrect length ~s" exp))))
(define parse-let-args
(lambda (args)
(cond [(not (list? args)) (eopl:error 'parse-exp "decls: not all proper lists: ~s" args)]
[(not (andmap list? args)) (eopl:error 'parse-exp "decls: not all proper lists: ~s" args)]
[(not (andmap (lambda (l) (= 2 (length l))) args)) (eopl:error 'parse-exp "declaration in ~s-exp must be a list of length 2 ~s" args)]
[(not (andmap (lambda (l) (symbol? (car l))) args)) (eopl:error 'parse-exp "decls: first members must be symbols: ~s" args)]
[else (map list (map var-exp (map car args)) (map parse-exp (map cadr args)))])))
;-------------------+
; |
; ENVIRONMENTS |
; |
;-------------------+
; Environment definitions for CSSE 304 Scheme interpreter. Based on EoPL section 2.3
(define empty-env
(lambda ()
(empty-env-record)))
(define extend-env
(lambda (syms vals env)
(extended-env-record syms vals env)))
(define list-find-position
(lambda (sym los)
(list-index (lambda (xsym) (eqv? sym xsym)) los)))
(define list-index
(lambda (pred ls)
(cond
((null? ls) #f)
((pred (car ls)) 0)
(else (let ((list-index-r (list-index pred (cdr ls))))
(if (number? list-index-r)
(+ 1 list-index-r)
#f))))))
(define apply-env
(lambda (env sym succeed fail) ; succeed and fail are procedures applied if the var is or isn't found, respectively.
(cases environment env
(empty-env-record ()
(fail))
(extended-env-record (syms vals env)
(let ((pos (list-find-position sym syms)))
(if (number? pos)
(succeed (list-ref vals pos))
(apply-env env sym succeed fail)))))))
;-----------------------+
; |
; SYNTAX EXPANSION |
; |
;-----------------------+
; To be added later
;-------------------+
; |
; INTERPRETER |
; |
;-------------------+
; top-level-eval evaluates a form in the global environment
(define *prim-proc-names* '(+ - * / set-car! set-cdr! vector->list list->vector length symbol? procedure? number? pair? vector? list? equal? eq? null? zero? add1 sub1 cons = >= <= not list quote car cdr cadr cdar cddr caar caaar caadr cadar cdaar caddr cdadr cddar cdddr))
(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)))
(define top-level-eval
(lambda (form)
; later we may add things that are not expressions.
(eval-exp form)))
; eval-exp is the main component of the interpreter
(define env init-env)
(define eval-exp
(lambda (exp)
(cases expression exp
[lit-exp (datum) datum]
[val-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 "variable not found in environment: ~s" id)))]
[app-exp (rator rands) (let ([proc-value (eval-exp rator)]
[args (eval-rands rands)])
(apply-proc proc-value args))]
[prim-exp (proc args) (apply-proc proc (map eval-exp args))]
[if-exp (con body) (if (eval-exp con) (eval-exp body))]
[if-else-exp (con t f) (eval-exp (if (eval-exp con) t f))]
[let-exp (assign body) (set! env (extend-env (map cadr (map car assign)) (map eval-exp (map cadr assign)) env))
(eval-bodies body)]
[lambda-list-exp (args body) (closure args body env)]
[lambda-exp (args body) (closure args body env)]
[else (eopl:error 'eval-exp "Bad abstract syntax: ~a" exp)])))
(define eval-bodies
(lambda (b)
(cond [(null? (cdr b)) (eval-exp (car b))]
[else (eval-exp (car b))
(eval-bodies (cdr b))])))
; evaluate the list of operands, putting results into a list
(define eval-rands
(lambda (rands)
(map eval-exp rands)))
; Apply a procedure to its arguments.
; At this point, we only have primitive procedures.
; User-defined procedures will be added later.
(define apply-proc
(lambda (proc-value args)
(cases proc-val proc-value
[prim-proc (op) (apply-prim-proc op args)]
[closure (vars body env) (if (symbol? vars)
(apply-closure (list args) (list vars) body env)
(if (list? vars)
(apply-closure args vars body env)
(let ([format (format-lambda-pair vars args)])
(apply-closure (cadr format) (car format) body env))))]
; You will add other cases
[else (error 'apply-proc
"Attempt to apply bad procedure: ~s"
proc-value)])))
(define (apply-closure args vars body envi)
(begin (set! env (extend-env vars args envi)) (eval-bodies body))
)
(define (format-lambda-pair vars args)
(if (not (pair? (cdr vars)))
(list (list (car vars) (cdr vars)) (list (car args) (cdr args)))
(let ([result (format-lambda-pair (cdr vars) (cdr args))])
(list (cons (car vars) (car result)) (cons (car args) (cadr result))))
))
; Usually an interpreter must define each
; built-in procedure individually. We are "cheating" a little bit.
(define apply-prim-proc
(lambda (prim-proc args)
(case prim-proc
[(+) (apply + args)]
[(-) (apply - args)]
[(*) (apply * args)]
[(/) (apply / args)]
[(add1) (+ (1st args) 1)]
[(sub1) (- (1st args) 1)]
[(cons) (cons (1st args) (2nd args))]
[(=) (= (1st args) (2nd args))]
[(>=) (>= (1st args) (2nd args))]
[(<=) (<= (1st args) (2nd args))]
[(not) (not (1st args))]
[(list) args]
[(quote) args]
[(zero?) (zero? (1st args))]
[(null?) (null? (1st args))]
[(eq?) (apply eq? args)]
[(equal?) (apply equal? args)]
[(pair?) (pair? (1st args))]
[(list?) (list? (1st args))]
[(vector?) (vector? (1st args))]
[(number?) (number? (1st args))]
[(symbol?) (symbol? (1st args))]
[(procedure?) (if (proc-val? (1st args)) #t (procedure? (1st args)))]
[(length) (length (1st args))]
[(list->vector) (list->vector (1st args))]
[(vector->list) (vector->list (1st args))]
[(set-car!) (set-car! (1st args) (2nd args))]
[(set-cdr!) (set-cdr! (1st args) (2nd args))]
[(car) (car (1st args))]
[(cdr) (cdr (1st args))]
[(caar) (caar (1st args))]
[(cadr) (cadr (1st args))]
[(cddr) (cddr (1st args))]
[(cdar) (cdar (1st args))]
[(caddr) (caddr (1st args))]
[(cdadr) (cdadr (1st args))]
[(cddar) (cddar (1st args))]
[(caadr) (caadr (1st args))]
[(cdaar) (cdaar (1st args))]
[(cadar) (cadar (1st args))]
[(caaar) (caaar (1st args))]
[(cdddr) (cdddr (1st args))]
[else (error 'apply-prim-proc "Bad primitive procedure name: ~s" prim-proc)])))
(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 (parse-exp x))))
| false |
fd8be7b6942587e36e09c661a7f18953624b0fa6
|
ac2a3544b88444eabf12b68a9bce08941cd62581
|
/tests/unit-tests/02-flonum/flacosh.scm
|
6d79cc90b591c1a8ad26249d8293b73e8be39972
|
[
"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 | 276 |
scm
|
flacosh.scm
|
(include "#.scm")
(check-= (flacosh 1.) (flacosh-144 1.))
(check-= (flacosh 1.5) (flacosh-144 1.5))
(check-tail-exn type-exception? (lambda () (flacosh 1)))
(check-tail-exn type-exception? (lambda () (flacosh 1/2)))
(check-tail-exn type-exception? (lambda () (flacosh 'a)))
| false |
a191fd10500daea4cdf60e337f9a2dd5da76971c
|
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
|
/scheme/swl1.3/tests/error-help/test2.ss
|
4594c9dbaa98a211dd5e2485d42c6293b20c1786
|
[
"SWL",
"TCL"
] |
permissive
|
ktosiu/snippets
|
79c58416117fa646ae06a8fd590193c9dd89f414
|
08e0655361695ed90e1b901d75f184c52bb72f35
|
refs/heads/master
| 2021-01-17T08:13:34.067768 | 2016-01-29T15:42:14 | 2016-01-29T15:42:14 | 53,054,819 | 1 | 0 | null | 2016-03-03T14:06:53 | 2016-03-03T14:06:53 | null |
UTF-8
|
Scheme
| false | false | 98 |
ss
|
test2.ss
|
; Test error "bracketed list terminated by close parenthesis"
(cond [(foobar) 'baz) [else 'ok])
| false |
b71aa63992be52f111aeb4024ff4879337ab5f73
|
d7bf863d84b6f492aca912b7934b78653aa0575f
|
/src/run-mats.ss
|
b6a833ecca335d437e48835eaad67f7864129f76
|
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
yanshuf0/swish
|
6cc14c5a8d534206d9ebe9f073246396a56fbfc8
|
0b43e8e31bd0cd2d6860689fb32cb9cfaa02ca1d
|
refs/heads/master
| 2020-03-26T21:01:53.049204 | 2018-08-20T03:40:16 | 2018-08-20T03:40:16 | 145,361,958 | 0 | 0 | null | 2018-08-20T03:32:45 | 2018-08-20T03:32:44 | null |
UTF-8
|
Scheme
| false | false | 5,055 |
ss
|
run-mats.ss
|
;;; Copyright 2017 Beckman Coulter, Inc.
;;;
;;; 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.
(import
(chezscheme)
(swish erlang)
(swish io)
(swish mat)
(swish osi)
(swish profile)
(swish string-utils)
)
(define (run-suite basename)
(define (start-profiler)
(match (profile:start)
[#(ok ,_) #t]
[ignore #f]
[#(error ,reason) (raise 'profile-failed-to-start)]))
(reset-handler (lambda () (display "\nTest Failed\n") (abort 1)))
(base-dir (path-parent (cd)))
(parameterize ([compile-profile #f])
(load (string-append basename ".ms")))
(let ([profiling? (start-profiler)])
(on-exit (when profiling? (profile:save))
(run-mats-to-file (string-append basename ".mo")))))
(define (find-mo-files root)
(define (find-mo root rel)
(fold-left
(lambda (fns x)
(match x
[(,fn . ,@DIRENT_FILE)
(guard (ends-with? fn ".mo"))
(cons (string-append rel fn) fns)]
[,_ fns]))
'()
(list-directory (string-append root "/" rel))))
(define (find-subdirs root rel)
(fold-left
(lambda (fns x)
(match x
[(,fn . ,@DIRENT_DIR) (cons (string-append rel fn "/") fns)]
[,_ fns]))
'()
(list-directory (string-append root "/" rel))))
(let lp ([files (find-mo root "")] [dirs (find-subdirs root "")])
(if (null? dirs)
files
(lp
(append files (find-mo root (car dirs)))
(append (cdr dirs) (find-subdirs root (car dirs)))))))
(define (html-report indir filename)
(define (stringify x)
(if (string? x)
x
(format "~s" x)))
(define (html-encode s)
(let-values ([(op get) (open-string-output-port)])
(let ([len (string-length s)])
(do ((i 0 (+ i 1))) ((= i len))
(let ([c (string-ref s i)])
(case c
[(#\") (display """ op)]
[(#\&) (display "&" op)]
[(#\<) (display "<" op)]
[(#\>) (display ">" op)]
[else (write-char c op)])))
(get))))
(define (output-row op c1 c2 c3)
(fprintf op "<tr><td>~a</td><td>~a</td><td>~a</td></tr>\n"
(html-encode (stringify c1))
(html-encode (stringify c2))
(if c3
(html-encode (stringify c3))
"<p style='color:#007F00;'>PASS</p>")))
(define (output-result op name tags result)
(match result
[pass (output-row op "" name #f)]
[(fail . ,reason)
(output-row op "" name reason)]))
(define (results< x y)
(match-let* ([(,name1 . ,_) x]
[(,name2 . ,_) y])
(string-ci<? (symbol->string name1) (symbol->string name2))))
(call-with-output-file filename
(lambda (op)
(fprintf op "<html>\n")
(fprintf op "<body style='font-family:monospace;'>\n")
(let-values ([(pass fail) (summarize-directory indir)])
(if (eq? fail 0)
(fprintf op "<h1>PASSED all ~a tests.</h1>\n" pass)
(fprintf op
"<h1>Failed ~a of ~a tests.</h1>\n" fail (+ fail pass))))
(fprintf op "<table>\n")
(output-row op "Suite" "Name" "Message")
(for-each
(lambda (in-file)
(output-row op in-file "" "")
(for-each (lambda (ls) (apply output-result op ls))
(sort results< (load-results (string-append indir "/" in-file)))))
(find-mo-files indir))
(fprintf op "</table>\n")
(fprintf op "</body></html>\n"))
'replace))
(define (console-summary indir)
(let-values ([(pass fail) (summarize-directory indir)])
(printf "Tests run: ~s Pass: ~s Fail: ~s\n\n"
(+ pass fail) pass fail)))
(define (exit-summary indirs)
(match indirs
[() (exit 0)]
[(,indir . ,rest)
(let-values ([(pass fail) (summarize-directory indir)])
(if (> fail 0)
(exit 1)
(exit-summary rest)))]))
(define (summarize-directory indir)
(summarize (map (lambda (x) (string-append indir "/" x))
(find-mo-files indir))))
| false |
732f714bffbd457be5f59ddb3721013df2a37d9e
|
5667f13329ab94ae4622669a9d53b649c4551e24
|
/number-theory/math.number-theory.scm
|
58e58c4204dcbc816f0459a54138a7e2992cc605
|
[] |
no_license
|
dieggsy/chicken-math
|
f01260e53cdb14ba4807f7e662c9e5ebd2da4dda
|
928c9793427911bb5bb1d6b5a01fcc86ddfe7065
|
refs/heads/master
| 2021-06-11T07:14:21.461591 | 2021-04-12T22:12:14 | 2021-04-12T22:12:14 | 172,310,771 | 2 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,320 |
scm
|
math.number-theory.scm
|
(module math.number-theory ()
(import chicken.module)
(import math.number-theory.divisibility
math.number-theory.modular-arithmetic
math.number-theory.base
math.number-theory.factorial
math.number-theory.binomial
math.number-theory.bernoulli
math.number-theory.eulerian-number
math.number-theory.farey
math.number-theory.fibonacci
math.number-theory.partitions
math.number-theory.polygonal
math.number-theory.primitive-roots
math.number-theory.quadratic
math.number-theory.quadratic-residues
math.number-theory.tangent-number)
(reexport math.number-theory.divisibility
math.number-theory.modular-arithmetic
math.number-theory.base
math.number-theory.factorial
math.number-theory.binomial
math.number-theory.bernoulli
math.number-theory.eulerian-number
math.number-theory.farey
math.number-theory.fibonacci
math.number-theory.partitions
math.number-theory.polygonal
math.number-theory.primitive-roots
math.number-theory.quadratic
math.number-theory.quadratic-residues
math.number-theory.tangent-number))
| false |
497aa5daf4411796ab2e86012b0879a55bf88a80
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/runtime/interop-services/imported-from-type-lib-attribute.sls
|
c69c647ec347485987cb758cc8187c4e0a47a6cc
|
[] |
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 | 805 |
sls
|
imported-from-type-lib-attribute.sls
|
(library (system
runtime
interop-services
imported-from-type-lib-attribute)
(export new is? imported-from-type-lib-attribute? value)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Runtime.InteropServices.ImportedFromTypeLibAttribute
a
...)))))
(define (is? a)
(clr-is
System.Runtime.InteropServices.ImportedFromTypeLibAttribute
a))
(define (imported-from-type-lib-attribute? a)
(clr-is
System.Runtime.InteropServices.ImportedFromTypeLibAttribute
a))
(define-field-port
value
#f
#f
(property:)
System.Runtime.InteropServices.ImportedFromTypeLibAttribute
Value
System.String))
| true |
ef8aa5b58d9896a2becb81c48ef88fd71c6a1f2f
|
6e9c9cefc78bdeaa3902ebfdd7d3a3367db26ef5
|
/comp.ss
|
d1d3042b6ac19f00eeb0e3ba6c89d4e1c36db876
|
[] |
no_license
|
liumingc/frac
|
39971c055dea4e6130862501a7cd6bd0f9790ac4
|
655734946338ac041fffea472a1eca304c52832a
|
refs/heads/master
| 2021-01-20T13:48:04.089112 | 2019-10-08T13:54:02 | 2019-10-08T13:54:02 | 18,410,646 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 45,154 |
ss
|
comp.ss
|
(import (nanopass))
(define debug-pass #f)
(define-language L1
(terminals
(symbol (x))
(const (c))
(prim (pr)))
(Expr (e body)
x
c
pr
(or e* ...)
(and e* ...)
(not e0)
(if e0 e1 e2)
(if e0 e1)
(e0 e* ...)
(quote e0)
(lambda (x* ...) body* ... body)
(let ([x* e*] ...)
body* ... body)
(letrec ([x* e*] ...)
body* ... body)
(begin e* ... e)
(set! x e)
))
(define const?
(lambda (x)
(or (number? x)
(string? x)
(boolean? x)
(char? x)
(null? x)
)))
(define prim-tbl
'((+ . 2)
(- . 2)
(* . 2)
(/ . 2)
(% . 2)
(= . 2)
(< . 2)
(<= . 2)
(> . 2)
(>= . 2)
(cons . 2)
(car . 1)
(cdr . 1)
(set-car! . 2)
(set-cdr! . 2)
(null? . 1)
(pair? . 1)
(void . 0)
;;; closure prim
(make-clo . 1)
(clo-code-set! . 2)
(clo-data-set! . 3)
(clo-code . 1)
(clo-data . 2)
))
(define prim?
(lambda (x)
(assq x prim-tbl)))
;(memq x '(+ - * / % = < >
; cons car cdr null?))))
(define-parser parse-L1 L1)
(define gensym
(let ([n 0])
(case-lambda
[()
(gensym 'tmp)]
[(x)
(let ([x (if (symbol? x) (symbol->string x) x)])
(let ([on n])
(set! n (+ n 1))
(string->symbol
(string-append x (number->string on)))))])))
(define-pass rename : L1 (ir) -> L1 ()
(definitions
(define env '())
(define extend
(lambda (x e r)
(cons (cons x e) r)))
(define extend*
(lambda (x* e* r)
(if (null? x*)
r
(cons (cons (car x*) (car e*))
(extend* (cdr x*) (cdr e*) r)))))
)
(Expr : Expr (ir r) -> Expr ()
[(lambda (,x* ...) ,body* ... ,body)
(let ([nx* (map (lambda (x) (gensym x)) x*)])
(let* ([r (extend* x* nx* r)]
[body* (map (lambda (x) (Expr x r)) body*)])
`(lambda (,nx* ...)
,body* ...
,(Expr body r))))]
[(let ([,x* ,[e* r -> e*]] ...) ,body* ... ,body)
(let ([nx* (map (lambda (x) (gensym x)) x*)])
(let* ([r (extend* x* nx* r)]
[body* (map (lambda (x) (Expr x r)) body*)])
`(let ([,nx* ,e*] ...)
,body* ...
,(Expr body r))))]
[(letrec ([,x* ,e*] ...) ,body* ... ,body)
(let ([nx* (map (lambda (x) (gensym x)) x*)])
(let ([nr (extend* x* nx* r)])
(let ([e* (map (lambda (e) (Expr e nr)) e*)]
[body* (map (lambda (b) (Expr b nr)) body*)]
[body (Expr body nr)])
`(letrec ([,nx* ,e*] ...) ,body* ... ,body))))]
[(set! ,x ,[e])
(let ([ans (assq x r)])
(if ans
`(set! ,(cdr ans) ,e)
`(set! ,x ,e)))]
[,x
(let ([ans (assq x r)])
(if ans
(cdr ans)
x))]
)
(Expr ir '()))
(define-language L2
(extends L1)
(Expr (e body)
(- (if e0 e1)
)))
(define-pass remove-one-armed-if : L1 (ir) -> L2 ()
(Proc : Expr (ir) -> Expr ()
[(if ,e0 ,e1)
`(if ,e0 ,e1 #f)])
(Proc ir))
(define-language L3
(extends L2)
(Expr (e body)
(- (lambda (x* ...) body* ... body)
(let ([x* e*] ...) body* ... body)
(letrec ([x* e*] ...) body* ... body))
(+ (lambda (x* ...) body)
(let ([x* e*] ...) body)
(letrec ([x* e*] ...) body))))
(define-pass make-explicit-begin : L2 (ir) -> L3 ()
(Proc : Expr (ir) -> Expr ()
[(lambda (,x* ...) ,[body*] ... ,[body])
(if (null? body*)
`(lambda (,x* ...) ,body)
`(lambda (,x* ...)
(begin ,body* ... ,body)))]
[(let ([,x* ,[e*]] ...) ,[body*] ... ,[body])
`(let ([,x* ,e*] ...)
,(if (null? body*)
`,body
`(begin ,body* ... ,body)))]
[(letrec ([,x* ,[e*]] ...) ,[body*] ... ,[body])
`(letrec ([,x* ,e*] ...)
,(if (null? body*)
`,body
`(begin ,body* ... ,body)))]
))
(define-language L4
(extends L3)
(Expr (e body)
(- (or e* ...)
(and e* ...)
(not e0))))
(define-pass reduce-logic : L3 (ir) -> L4 ()
(Expr : Expr (ir) -> Expr ()
[(or ,[e*] ...)
(if (null? e*)
`#f
(let f ([e* e*])
(if (null? e*)
'#f
(let ([t (gensym)])
`(let ([,t ,(car e*)])
(if ,t ,t ,(f (cdr e*))))))))]
[(and ,[e*] ...)
(if (null? e*)
#t
(let f ([e0 (car e*)] [e* (cdr e*)])
(if (null? e*)
e0
`(if ,e0
,(f (car e*) (cdr e*))
#f))))]
[(not ,e0)
`(if ,e0 #f #t)]
))
;;; prim to primcall
(define-language L5
(extends L4)
(Expr (e body)
(- pr)
(+ (primcall pr e* ...))))
;;; introduce primcall
(define-pass inverse-eta : L4 (ir) -> L5 ()
(Proc : Expr (ir) -> Expr ()
[(,pr ,[e*] ...)
`(primcall ,pr ,e* ...)]
[,pr
(let ([as (assq pr prim-tbl)])
(let f ([i (cdr as)] [x* '()])
(if (= i 0)
`(lambda (,x* ...) (primcall ,pr ,x* ...))
(f (- i 1) (cons (gensym) x*)))))]))
;;;
(define-language L6
(extends L5)
(Expr (e body)
(- c
(quote e0))
(+ (quote d)))
(Datum (d)
(+ c e)))
#;(define datum?
(lambda (d)
(or (const? d)
(and (pair? d)
(and (datum? (car d))
(datum? (cdr d)))))))
(define-pass quote-const : L5 (ir) -> L6 ()
(Proc : Expr (ir) -> Expr ()
[',c `(quote ,c)]
[,c `(quote ,c)]))
;;; remove complex quote
;;; '(3 4) => (cons '3 '4)
;;; and <code> (eq? '(3 4) '(3 4)) => #f </code>
(define-language L7
(extends L6)
(Expr (e body)
(- (quote d))
(+ (quote c)))
(Datum (d)
(- e c)))
(define-pass remove-complex-quote : L6 (ir) -> L7 ()
(Expr : Expr (ir) -> Expr ()
[(quote ,d)
(nanopass-case (L6 Datum) d
[,c `(quote ,c)]
[(,e0 ,e* ...)
(let f ([e0 (Expr e0)]
[e* (map Expr e*)])
(if (null? e*)
`(primcall cons ,e0 '())
`(primcall cons ,e0 ,(f (car e*) (cdr e*)))))])]))
;;; find assigned var
(define-language L8
(extends L7)
(terminals
(- (symbol (x)))
(+ (symbol (x a))))
(Expr (e body)
(- (lambda (x* ...) body)
(let ([x* e*] ...) body)
(letrec ([x* e*] ...) body))
(+ (lambda (x* ...) abody)
(let ([x* e*] ...) abody)
(letrec ([x* e*] ...) abody)))
(Abody (abody)
(+ (assigned (a* ...) body))))
(define set:cons
(lambda (x s)
(if (memq x s) s (cons x s))))
#;
(define set:union
(lambda (s1 s2)
(fold-right (lambda (x acc)
(set:cons x acc)) s2 s1)))
(define set:union
(lambda set*
(if (null? set*)
'()
(fold-right (lambda (seta acc)
(fold-right (lambda (x acc)
(set:cons x acc))
acc seta))
(car set*) (cdr set*)))))
(define set:diff
(lambda (s1 s2)
(let f ([s1 s1] [s '()])
(if (null? s1)
s
(if (memq (car s1) s2)
(f (cdr s1) s)
(f (cdr s1) (cons (car s1) s)))))))
(define set:intersect
(lambda (s1 s2)
(fold-right (lambda (x acc)
(if (memq x s2)
(set:cons x acc)
acc)) '() s1)))
(define-pass identify-assigned : L7 (ir) -> L8 ()
(Proc : Expr (ir) -> Expr ('())
[(lambda (,x* ...) ,[body a*])
(let ([this-a* (set:intersect a* x*)]
[out-a* (set:diff a* x*)])
(values `(lambda (,x* ...) (assigned (,this-a* ...) ,body)) out-a*))]
[(set! ,x ,[e a*])
(values `(set! ,x ,e) (set:cons x a*))]
[(begin ,[e* a**] ... ,[e a*])
(values `(begin ,e* ... ,e)
(apply set:union a* a**))]
[(let ([,x* ,[e* a**]] ...)
,[body a*])
(values `(let ([,x* ,e*] ...)
(assigned (,(set:intersect a* x*) ...) ,body))
(apply set:union (set:diff a* x*) a**))]
[(letrec ([,x* ,[e* a**]] ...)
,[body a*])
(values `(letrec ([,x* ,e*] ...)
(assigned (,(set:intersect a* x*) ...) ,body))
(apply set:union (set:diff a* x*) a**))]
[(primcall ,pr ,[e* a**] ...)
(values `(primcall ,pr ,e* ...) (apply set:union a**))]
[(if ,[e0 a0] ,[e1 a1] ,[e2 a2])
(values `(if ,e0 ,e1 ,e2) (set:union a0 a1 a2))]
[(,[e0 a*] ,[e* a**] ...)
(values `(,e0 ,e* ...) (apply set:union a* a**))]
)
(let-values ([(ir a*) (Proc ir)])
#;
(unless (null? a*)
(error 'identify-assigned "found one or more unbound variables" a*))
ir))
(define-language L9
(extends L8)
(Expr (e body)
(- (letrec ([x* e*] ...)
abody)
(lambda (x* ...) abody))
(+ (letrec ([x* le*] ...)
body)
le))
(LambdaExpr (le)
(+ (lambda (x* ...) abody))))
(define-pass purify-letrec : L8 (ir) -> L9 ()
(definitions
(define build-let
(lambda (x* e* a* body)
(with-output-language (L9 Expr)
(if (null? x*)
body
`(let ([,x* ,e*] ...) (assigned (,a* ...) ,body))))))
(define build-letrec
(lambda (x* e* body)
(with-output-language (L9 Expr)
(if (null? x*)
body
`(letrec ([,x* ,e*] ...) ,body)))))
(define build-begin
(lambda (e* e)
(if (null? e*)
e
(with-output-language (L9 Expr)
`(begin ,e* ... ,e)))))
(define simple?
;;; (quote c) | (primcall ,pr, e* ...) | (begin ,e* ... e) |
;;; (if ,e0 ,e1 ,e2) | ,x
(lambda (e)
(nanopass-case (L9 Expr) e
[(quote ,c) #t]
[(primcall ,pr ,e* ...)
(for-all simple? e*)]
[(begin ,e* ... ,e)
(and (for-all simple? e*) (simple e))]
[(if ,e0 ,e1 ,e2) (and (simple? e0) (simple? e1) (simple? e2))]
[,x #t]
[else #f])))
(define lambda?
(lambda (e)
(nanopass-case (L9 Expr) e
[(lambda (,x* ...) ,abody) #t]
[else #f])))
)
(Proc : Expr (ir) -> Expr ()
[(letrec ([,x* ,[e*]] ...) (assigned (,a* ...) ,[body]))
(let f ([xb* x*] [e* e*]
[xs* '()] [es* '()] ; simple
[xl* '()] [el* '()] ; letrec function
[xc* '()] [ec* '()] ; complex
)
(if (null? xb*)
(build-let xc* (make-list (length xc*) `(quote #f)) xc*
(build-letrec xl* el*
(build-let xs* es* '()
(build-begin
(map (lambda (xc xe)
`(set! ,xc ,xe)) xc* ec*)
body))))
(let ([x (car xb*)] [e (car e*)])
(cond
[(lambda? e) (f (cdr xb*) (cdr e*) xs* es* (cons x xl*) (cons e el*) xc* ec*)]
[(simple? e) (f (cdr xb*) (cdr e*) (cons x xs*) (cons e es*) xl* el* xc* ec*)]
[else (f (cdr xb*) (cdr e*) xs* es* xl* el* (cons x xc*) (cons e ec*))]))))]))
;;; ((lambda (x* ...) abody) e* ...) -> (let ([x* e*] ...) abody)
(define-pass optimize-direct-call : L9 (ir) -> L9 ()
(Proc : Expr (e) -> Expr ()
[((lambda (,x* ...) ,[abody]) ,[e*] ...)
`(let ([,x* ,e*] ...)
,abody)]))
(define-pass find-let-bound-lambdas : L9 (ir) -> L9 ()
(Proc : Expr (e) -> Expr ()
(definitions
(define lambda?
(lambda (e)
(nanopass-case (L9 Expr) e
[(lambda (,x* ...) ,abody) #t]
[else #f])))
(define build-letrec
(lambda (x* e* body)
(with-output-language (L9 Expr)
(if (null? x*)
body
`(letrec ([,x* ,e*] ...) ,body)))))
(define build-let
(lambda (x* e* a* body)
(with-output-language (L9 Expr)
(if (null? x*)
body
`(let ([,x* ,e*] ...) (assigned (,a* ...) ,body))))))
)
[(let ([,x* ,[e*]] ...) (assigned (,a* ...) ,[body]))
(let f ([x* x*] [e* e*]
[xv* '()] [ev* '()]
[xl* '()] [el* '()])
(if (null? x*)
(build-let xv* ev* a*
(build-letrec xl* el* body))
(cond
[(lambda? (car e*))
(f (cdr x*) (cdr e*) xv* ev* (cons (car x*) xl*) (cons (car e*) el*))]
[else
(f (cdr x*) (cdr e*) (cons (car x*) xv*) (cons (car e*) ev*) xl* el*)])))]))
(define-language L10
(extends L9)
(Expr (e body)
(- le)))
(define-pass remove-anonymous-lambda : L9 (ir) -> L10 ()
(Proc : Expr (e) -> Expr ()
[(lambda (,x* ...) ,[abody])
(let ([f (gensym 'anony)])
`(letrec ([,f (lambda (,x* ...) ,abody)])
,f))]))
(define-language L11
(extends L10)
(terminals
(- (symbol (x a)))
(+ (symbol (x))))
(Expr (e body)
(- (let ([x* e*] ...) abody)
(set! x e))
(+ (let ([x* e*] ...) body)))
(Abody (abody)
(- (assigned (a* ...) body)))
(LambdaExpr (le)
(- (lambda (x* ...) abody))
(+ (lambda (x* ...) body))))
(define-pass convert-assignments : L10 (ir) -> L11 ()
(definitions
(define build-let
(lambda (x* e* body)
(with-output-language (L11 Expr)
(if (null? x*)
body
`(let ([,x* ,e*] ...) ,body)))))
(define lookup
(lambda (x r)
(let ([ans (assq x r)])
(if ans (cdr ans) x))))
)
(Proc : Expr (e r) -> Expr ()
[(let ([,x* ,[e*]] ...) (assigned (,a* ...) ,body))
(let ([t* (map (lambda (a) (gensym)) a*)])
(let ([r (append (map cons a* t*) r)])
(build-let (map (lambda (x) (lookup x r)) x*) e*
(build-let a* (map (lambda (t) `(primcall cons ,t '#f)) t*)
(Proc body r)))))]
[(set! ,x ,[e r -> e])
`(primcall set-car! ,x ,e)]
[,x (guard (assq x r)) `(primcall car ,x)])
(LambdaExpr : LambdaExpr (le r) -> LambdaExpr ()
[(lambda (,x* ...) (assigned (,a* ...) ,body))
(let ([t* (map (lambda (a) (gensym)) a*)])
(let ([r (append (map cons a* t*) r)])
`(lambda (,(map (lambda (x) (lookup x r)) x*) ...)
,(build-let a* (map (lambda (t) `(primcall cons ,t '#f)) t*)
(Proc body r)))))])
(Proc ir '()))
(define-language L12
(extends L11)
(terminals
(- (symbol (x)))
(+ (symbol (x f))))
(LambdaExpr (le)
(- (lambda (x* ...) body))
(+ (lambda (x* ...) fbody)))
(FreeBody (fbody)
(+ (free (f* ...) body))))
(define-pass uncover-free : L11 (ir) -> L12 ()
(Expr : Expr (e) -> Expr (free*)
[(let ([,x* ,[e* f**]] ...) ,[body f*])
(values
`(let ([,x* ,e*] ...) ,body)
(apply set:union (set:diff f* x*) f**))]
[(letrec ([,x* ,[le* f**]] ...) ,[body f*])
(values
`(letrec ([,x* ,le*] ...) ,body)
(set:diff (apply set:union f* f**) x*))]
[(primcall ,pr ,[e* f**] ...)
(values `(primcall ,pr ,e* ...) (apply set:union f**))]
[(quote ,c) (values `(quote ,c) '())]
[(if ,[e0 f0*] ,[e1 f1*] ,[e2 f2*]) (values `(if ,e0 ,e1 ,e2) (set:union f0* f1* f2*))]
[(,[e0 f0*] ,[e* f**] ...)
(values `(,e0 ,e* ...) (apply set:union f0* f**))]
[(begin ,[e* f**] ... ,[e f*])
(values `(begin ,e* ... ,e) (apply set:union f* f**))]
[,x (values x (list x))]
)
(LambdaExpr : LambdaExpr (le) -> LambdaExpr (free*)
[(lambda (,x* ...) ,[body f*])
(let ([f* (set:diff f* x*)])
(values `(lambda (,x* ...) (free (,f* ...) ,body)) f*))])
(let-values ([(ir free*) (Expr ir)])
ir))
(define-language L13
(extends L12)
(terminals
(- (symbol (x f)))
(+ (symbol (x f l))))
(Expr (e body)
(- (letrec ([x* le*] ...) body))
(+ (closures ([x* l* f** ...] ...) lbody)
(label l)))
(LabelsBody (lbody)
(+ (labels ([l* le*] ...) body))))
(define-pass convert-closures : L12 (ir) -> L13 ()
(Expr : Expr (e) -> Expr ()
[(letrec ([,x* ,[le*]] ...) ,[body])
(let ([l* (map (lambda (x)
(let ([l (string-append "l:" (symbol->string x))])
(gensym l))) x*)]
[cp* (map (lambda (x)
(gensym 'cp)) x*)])
(let ([clo* (map (lambda (le cp)
(nanopass-case (L13 LambdaExpr) le
[(lambda (,x* ...) (free (,f* ...) ,body))
(cons (with-output-language (L13 LambdaExpr)
`(lambda (,cp ,x* ...)
(free (,f* ...) ,body)))
f*)]))
le* cp*)])
(let ([f** (map cdr clo*)]
[le* (map car clo*)])
`(closures ([,x* ,l* ,f** ...] ...)
(labels ([,l* ,le*] ...) ,body)))))]
[(,x ,[e*] ...)
`(,x ,x ,e* ...)]
[(,[e] ,[e*] ...)
(let ([t (gensym)])
`(let ([,t ,e])
(,t ,t ,e* ...)))]))
;;; TODO optimize-known-call
(define-language L14
(extends L13)
(Expr (e body)
(- (closures ([x* l* f** ...] ...) lbody))
(+ (labels ([l* le*] ...) body)))
(LabelsBody (lbody)
(- (labels ([l* le*] ...) body)))
(LambdaExpr (le)
(- (lambda (x* ...) fbody))
(+ (lambda (x* ...) body)))
(FreeBody (fbody)
(- (free (f* ...) body)))
)
(define-pass expose-clo-prims : L13 (ir) -> L14 ()
(definitions
(define build-clo-set
(lambda (x* l* f** cp free*)
(let ([o
(with-output-language (L14 Expr)
(fold-left
(lambda (e* x l f*)
(let lp ([f* f*] [e* e*] [i 0])
(if (null? f*)
(cons `(primcall clo-code-set! ,x ,l) e*)
(lp (cdr f*)
(cons `(primcall clo-data-set! ,x ',i ,(handle-clo-ref (car f*) cp free*))
e*)
(+ i 1)))))
'() x* l* f**))])
;(printf "~s~%" (map (lambda (x) (unparse-L14 x)) o))
#;
(for-each (lambda (x)
(printf "~s~%" (pretty-print (unparse-L14 x)))) o)
o
)))
(define handle-clo-ref
(lambda (f cp free*)
(with-output-language (L14 Expr)
(let lp ([free* free*] [i 0])
(cond
[(null? free*) f]
[(eq? f (car free*)) `(primcall clo-data ,cp ',i)]
[else (lp (cdr free*) (+ i 1))])))))
)
(Expr : Expr (e cp free*) -> Expr ()
[(closures ([,x* ,l* ,f** ...] ...)
(labels ([,l1* ,[le*]] ...) ,[body]))
(let ([size* (map (lambda (f*) (length f*)) f**)])
`(let ([,x* (primcall make-clo ',size*)] ...)
;,body
(labels ([,l1* ,le*] ...)
(begin
,(build-clo-set x* l* f** cp free*) ...
,body))))]
[(,[e] ,[e*] ...) `((primcall clo-code ,e) ,e* ...)]
[,x (handle-clo-ref x cp free*)])
(LambdaExpr : LambdaExpr (le) -> LambdaExpr ()
[(lambda (,x ,x* ...) (free (,f* ...) ,[body x f* -> body]))
`(lambda (,x ,x* ...) ,body)]
)
(Expr ir #f '()))
(define-language L15
(extends L14)
(entry Program)
(Program (p)
(+ (labels ([l* le*] ...) l)))
(Expr (e body)
(- (labels ([l* le*] ...) body))))
(define-pass lift-lambdas : L14 (ir) -> L15 ()
(definitions
(define cl* '())
(define cle* '()))
(Expr : Expr (e) -> Expr ()
[(labels ([,l* ,[le*]] ...) ,[body])
(set! cl* (append l* cl*))
(set! cle* (append le* cle*))
body])
(let ([ir (Expr ir)])
(with-output-language (L15 Program)
`(labels ([,cl* ,cle*] ... [l:main (lambda () ,ir)])
l:main))))
(define-language L16
(extends L15)
(entry Program)
(Expr (e body)
(- (primcall pr e* ...)
(e0 e* ...)
x
'c
(label l))
(+ (primcall pr se* ...) => (pr se* ...)
(se0 se* ...)
se))
(SimpleExpr (se)
(+ x
'c
(label l)))
)
(define-pass remove-complex-opera* : L15 (ir) -> L16 ()
(definitions
(define simple1?
(lambda (x)
(nanopass-case (L16 Expr) x
[,x #t]
[',c #t]
[(label ,l) #t]
[else #f])))
(define simple?
(lambda (x)
(let ([a (simple1? x)])
;(printf "~s simple? ~s~%" (unparse-L16 x) a)
a)))
(define convert-e*
(lambda (e* f)
(let lp ([e* e*] [x* '()] [xe* '()] [ans '()])
(if (null? e*)
(begin
;(printf "x*: ~s~% xe*:~s~% ans:~s~%~%" x* xe* (map unparse-L16 ans))
(f x* xe* (reverse ans)))
(let ([e (car e*)])
(if (simple? e)
(lp (cdr e*) x* xe* (cons e ans))
(let ([x (gensym 's)])
(lp (cdr e*) (cons x x*) (cons e xe*) (cons x ans)))))))))
)
(Expr : Expr (e) -> Expr ()
[(primcall ,pr ,[e*] ...)
(convert-e* e*
(lambda (x* xe* ans)
(if (null? x*)
`(primcall ,pr ,ans ...)
`(let ([,x* ,xe*] ...)
(primcall ,pr ,ans ...)))))]
[(,[e0] ,[e*] ...)
(convert-e* (cons e0 e*)
(lambda (x* xe* ans)
(if (null? x*)
ans
`(let ([,x* ,xe*] ...)
(,(car ans) ,(cdr ans) ...)
))))]))
(define effect-prim-tbl
'((set-car! . 2)
(set-cdr! . 2)
(clo-code-set! . 2)
(clo-data-set! . 3)))
(define value-prim-tbl
'((+ . 2)
(- . 2)
(* . 2)
(/ . 2)
(% . 2)
(cons . 2)
(car . 1)
(cdr . 1)
(make-clo . 1)
(clo-code . 1)
(clo-data . 2)
(void . 0)
))
(define pred-prim-tbl
'((null? . 1)
(pair? . 1)
(eq? . 2)
(= . 2)
(< . 2)
(<= . 2)
(> . 2)
(>= . 2)
))
(define effect-prim?
(lambda (x)
(assq x effect-prim-tbl)))
(define value-prim?
(lambda (x)
(assq x value-prim-tbl)))
(define pred-prim?
(lambda (x)
(assq x pred-prim-tbl)))
(define-language L17
(terminals
(symbol (x l))
(const (c))
(effect-prim (epr))
(value-prim (vpr))
(pred-prim (ppr)))
(entry Program)
(Program (prog)
(labels ([l* le*] ...) l))
(LambdaExpr (le)
(lambda (x* ...) body))
(SimpleExpr (se)
x
(quote c)
(label l))
(Value (v body)
se
(se se* ...)
(primcall vpr se* ...) => (vpr se* ...)
(if p0 v1 v2)
(begin e* ... v)
(let ([x* v*] ...) v))
(Effect (e)
(nop)
(primcall epr se* ...) => (epr se* ...)
(if p0 e1 e2)
(begin e* ... e)
(let ([x* v*] ...) e)
(se se* ...))
(Pred (p)
(true)
(false)
(primcall ppr se* ...) => (ppr se* ...)
(if p0 p1 p2)
(begin e* ... p)
(let ([x* v*] ...) p)
)
)
(define-pass recognize-context : L16 (ir) -> L17 ()
(Value : Expr (e) -> Value ()
[(primcall ,pr ,[se*] ...)
(guard (value-prim? pr))
`(primcall ,pr ,se* ...)]
[(primcall ,pr ,[se*] ...)
(guard (pred-prim? pr))
`(if (primcall ,pr ,se* ...) (true) (false))]
[(primcall ,pr ,[se*] ...)
(guard (effect-prim? pr))
`(begin (primcall ,pr ,se* ...) (primcall void))]
[(if ,[p0] ,[v1] ,[v2])
(nanopass-case (L17 Pred) p0
[(true) v1]
[(false) v2]
[else `(if ,p0 ,v1 ,v2)])]
)
(Effect : Expr (e) -> Effect ()
[(primcall ,pr ,[se*] ...)
(guard (or (value-prim? pr) (pred-prim? pr)))
`(nop)]
[(primcall ,pr ,[se*] ...)
(guard (effect-prim? pr))
`(primcall ,pr ,se* ...)]
[,se `(nop)]
)
(Pred : Expr (e) -> Pred ()
[(quote ,c) (if c `(true) `(false))]
[,se
`(if (primcall eq? ,se '#f)
(false)
(true))]
[(if ,[p0] ,[p1] ,[p2])
(nanopass-case (L17 Pred) p0
[(true) p1]
[(false) p2]
[else `(if ,p0 ,p1 ,p2)])]
[(,[se] ,[se*] ...)
(let ([t (gensym)])
`(let ([,t (,se ,se* ...)])
(if ,t (true) (false))))]
[(primcall ,pr ,[se*] ...)
(guard (pred-prim? pr))
`(primcall ,pr ,se* ...)]
[(primcall ,pr ,[se*] ...)
(guard (effect-prim? pr))
`(begin (primcall ,pr ,se* ...) (true))]
[(primcall ,pr ,[se*] ...)
(guard (value-prim? pr))
(let ([t (gensym)])
`(let ([,t (primcall ,pr ,se* ...)])
(if (primcall eq? ,t '#f) (false) (true))))]
))
(define i64?
(lambda (x)
(and (number? x)
(<= (- (expt 2 63)) x)
(< x (expt 2 63)))))
(define-language L18
(extends L17)
(terminals
(+ (i64 (i))))
(Value (v body)
(+ (alloc i se))))
(define fixnum-tag #b000)
(define pair-tag #b001)
(define closure-tag #b100)
(define boolean-tag #b1101)
(define true-rep #b111101)
(define false-rep #b101101)
(define null-rep #b100101)
(define void-rep #b110101)
(define type-mask #b111)
(define word-size 8)
(define-pass expose-alloc-primitives : L17 (ir) -> L18 ()
(Value : Value (e) -> Value ()
[(primcall ,vpr ,[se1] ,[se2])
(guard (eq? vpr 'cons))
(let ([t1 (gensym)] [t2 (gensym)] [t3 (gensym)])
`(let ([,t1 (alloc ,pair-tag '2)]
[,t2 ,se1]
[,t3 ,se2])
(begin
(primcall set-car! ,t1 ,t2)
(primcall set-cdr! ,t1 ,t3)
,t1)))]
[(primcall ,vpr ,[se])
(guard (eq? vpr 'make-clo))
;(printf "input:~s, c:~s~%" (pretty-print (unparse-L17 e)) (pretty-print (unparse-L17 se)))
(let ([n (nanopass-case (L18 SimpleExpr) se
[(quote ,c) c])])
`(alloc ,closure-tag (quote ,(+ n 1))))]))
(define-language L19
(extends L18)
(LambdaExpr (le)
(- (lambda (x* ...) body))
(+ (lambda (x* ...) lbody)))
(LocalsBody (lbody)
(+ (local (x* ...) body)))
(Value (v body)
(- (let ([x* v*] ...) v)))
(Effect (e)
(- (let ([x* v*] ...) e))
(+ (set! x v)))
(Pred (p)
(- (let ([x* v*] ...) p))))
(define-pass return-of-set! : L18 (ir) -> L19 ()
#;
(definitions
(define build-set!
(lambda (x* v* body build-begin)
(with-output-language (L19 Effect)
(build-begin
(map (lambda (x v) `(set! ,x ,v)) x* v*)
body)))))
(LambdaExpr : LambdaExpr (le) -> LambdaExpr ()
; l for local
[(lambda (,x* ...) ,[body l*])
`(lambda (,x* ...)
(local (,l* ...) ,body))])
(Value : Value (e) -> Value ('())
[(let ([,x* ,[v* l1**]] ...)
,(v l2*))
(let ([out-l* (apply append x* l2* l1**)])
(values
`(begin (set! ,x* ,v*) ... ,v)
out-l*))]
[(,(se l*) ,(se* l**) ...)
(values `(,se ,se* ...) (apply append l* l**))]
[(primcall ,vpr ,(se* l**) ...)
(values `(primcall ,vpr ,se* ...) (apply append l**))]
[(if ,(p0 l0*) ,(v1 l1*) ,(v2 l2*))
(values `(if ,p0 ,v1 ,v2) (append l0* l1* l2*))]
[(begin ,(e* l**) ... ,(v l*))
(values `(begin ,e* ... ,v) (apply append l* l**))]
)
(SimpleExpr : SimpleExpr (se) -> SimpleExpr ('()))
(Effect : Effect (e) -> Effect ('())
[(let ([,x* ,[v* l1**]] ...)
,(e l*))
(let ([out-l* (apply append x* l* l1**)])
(values
`(begin (set! ,x* ,v*) ... ,e)
out-l*))]
[(primcall ,epr ,(se* l**) ...)
(values `(primcall ,epr ,se* ...) (apply append l**))]
[(if ,(p0 l0*) ,(e1 l1*) ,(e2 l2*))
(values `(if ,p0 ,e1 ,e2) (append l0* l1* l2*))]
[(begin ,(e* l**) ... ,(e l*))
(values `(begin ,e* ... ,e) (apply append l* l**))]
)
(Pred : Pred (e) -> Pred ('())
[(let ([,x* ,[v* l1**]] ...)
,(p l1*))
(let ([out-l* (apply append x* l1* l1**)])
(values
`(begin (set! ,x* ,v*) ... ,p)
out-l*))]
[(primcall ,ppr ,(se* l**) ...)
(values `(primcall ,ppr ,se* ...) (apply append l**))]
[(if ,(p0 l0*) ,(p1 l1*) ,(p2 l2*))
(values `(if ,p0 ,p1 ,p2) (append l0* l1* l2*))]
[(begin ,(e* l**) ... ,(p l*))
(values `(begin ,e* ... ,p) (apply append l* l**))]
)
)
(define-language L20
(extends L19)
(Value (v body)
(- (alloc i se)
se
(se se* ...)
(primcall vpr se* ...))
(+ rhs))
(Rhs (rhs)
(+ (alloc i se)
se
(se se* ...)
(primcall vpr se* ...) => (vpr se* ...)
))
(Effect (e)
(- (set! x v))
(+ (set! x rhs))))
;;;
(define-pass flatten-set! : L19 (ir) -> L20 ()
(SimpleExpr : SimpleExpr (se) -> SimpleExpr ())
(Effect : Effect (e) -> Effect ()
[(set! ,x ,v)
(flatten v x)])
(flatten : Value (e x) -> Effect ()
[(alloc ,i ,[se])
`(set! ,x (alloc ,i ,se))]
[,se `(set! ,x ,(SimpleExpr se))]
[(,[se] ,[se*] ...) `(set! ,x (,se ,se* ...))]
[(primcall ,vpr ,[se*] ...) `(set! ,x (primcall ,vpr ,se* ...))]
; the next line is not necessary, but to illustrated the auto generate pass
; code
[(if ,[p0] ,[flatten : v1 x -> e1] ,[e2])
`(if ,p0 ,e1 ,e2)]
))
(define-language L21
(extends L20)
(terminals
(- (const (c))))
(SimpleExpr (se)
(- (quote c))
(+ i)))
(define-pass convert-const-representation : L20 (ir) -> L21 ()
(SimpleExpr : SimpleExpr (se) -> SimpleExpr ()
[(quote ,c)
(cond
[(eq? c #f) false-rep]
[(eq? c #t) true-rep]
[(null? c) null-rep]
[(i64? c) (bitwise-arithmetic-shift-left c 3)])]))
(define-language L22
(extends L21)
(Effect (e)
(- (primcall epr se* ...))
(+ (mset! se0 (maybe se1?) i se2)))
(Pred (p)
(- (primcall ppr se* ...))
(+ (= se0 se1)
(< se0 se1)
(<= se0 se1)))
(Rhs (rhs)
(- (primcall vpr se* ...)))
(SimpleExpr (se)
(+ (mref se0 (maybe se1?) i)
(add se0 se1)
(sub se0 se1)
(mul se0 se1)
(div se0 se1)
(sl se0 se1)
(sr se0 se1)
(logand se0 se1))))
(define pretty-format
(lambda xs
(let ([o (open-output-string)])
(for-each (lambda (x)
(pretty-print x o)) xs)
(get-output-string o))))
(define-pass expand-primitives : L21 (ir) -> L22 ()
(definitions
(define build-begin
(lambda (e* x f)
(let lp ([e* e*] [re* '()])
#;
(printf "comm-build-begin~% e* is ~a~% re* is ~a~%"
(pretty-format (map unparse-L22 e*))
(pretty-format (map unparse-L22 re*)))
(cond
[(null? e*)
(f re* x)]
[else
(let ([e (car e*)])
;;; note, here you can't write (begin ,[e0]) etc
;(printf "one! ~a~%" e)
;(printf "one ~a~%" (pretty-format (unparse-L22 e)))
(nanopass-case (L22 Effect) e
[(begin ,e0)
;(printf "case e0~%")
(lp (cdr e*) (cons e0 re*))]
[(begin ,e0* ... ,e0)
;(printf "case e0* e0~%")
(lp (cdr e*) (append (cons e0 (reverse e0*)) re*))]
[else
;(printf "case else~%")
(lp (cdr e*) (cons (car e*) re*))]))])))))
(Pred : Pred (p) -> Pred ()
;;; note: you can't write
;;; (primcall null? se0)
[(primcall ,ppr ,[se0])
(case ppr
[(null?) `(= ,se0 ,null-rep)]
[(pair?) `(= (logand ,se0 ,type-mask) ,pair-tag)])]
[(primcall ,ppr ,[se0] ,[se1])
(case ppr
[(eq?) `(= ,se0 ,se1)]
[(=) `(= ,se0 ,se1)]
[(<) `(< ,se0 ,se1)]
[(<=) `(<= ,se0 ,se1)]
[(>) `(<= ,se1 ,se0)]
[(>=) `(< ,se1 ,se0)])]
[(begin ,[e*] ... ,[p])
(build-begin e* p
(lambda (re* x)
(let f ([re* re*] [x x])
(nanopass-case (L22 Pred) x
[(begin ,e0* ... ,p0)
(f (append (reverse e0*) re*) p0)]
[else
(if (null? re*)
x
`(begin ,(reverse re*) ... ,x))]))))]
)
(Effect : Effect (e) -> Effect ()
[(primcall ,epr ,[se0] ,[se1])
(case epr
[(set-car!) `(mset! ,se0 #f ,(- pair-tag) ,se1)]
[(set-cdr!) `(mset! ,se0 #f ,(- word-size pair-tag) ,se1)]
[(clo-code-set!) `(mset! ,se0 #f ,(- closure-tag) ,se1)]
)]
[(primcall ,epr ,[se0] ,[se1] ,[se2])
;;; clo-data-set!
`(mset! ,se0 ,se1 ,(- word-size closure-tag) ,se2)]
[(begin ,[e0])
e0]
[(begin ,[e*] ... ,[e])
#;
(printf "Effect->Effect: input is e*=~a~% e=~a~%"
(pretty-format (map unparse-L22 e*))
(pretty-format e))
(build-begin e* e
(lambda (re* x)
(let f ([re* re*] [x x])
(nanopass-case (L22 Effect) x
[(begin ,e0* ... ,e0)
(f (append (reverse e0*) re*) e0)]
[else
(if (null? re*)
x
`(begin ,(reverse re*) ... ,x))]))))]
)
(Rhs : Rhs (rhs) -> Rhs ()
(definitions
(define convert-op
(let ([tbl '((+ . add) (- . sub)
(* . mul) (/ . div))])
(lambda (x)
(let ([t (assq x tbl)])
(if t (cdr t) x))))))
[(primcall ,vpr ,[se0] ,[se1])
(case vpr
[(+ - * / %)
`(,(convert-op vpr) ,se0 ,se1)]
[(clo-data)
`(mref ,se0 ,se1 ,(- word-size closure-tag))]
)]
[(primcall ,vpr ,[se0])
(case vpr
[(car) `(mref ,se0 #f ,(- pair-tag))]
[(cdr) `(mref ,se0 #f ,(- word-size pair-tag))]
[clo-code `(mref ,se0 #f ,(- closure-tag))])]
[(primcall ,vpr)
;(guard (eq? vpr 'void))
void-rep]
)
(Value : Value (v) -> Value ()
[(begin ,[e*] ... ,[v])
#;
(printf "Value->Value input:~% e* is ~a~% v is ~a~%"
(pretty-format (map unparse-L22 e*))
(pretty-format (unparse-L22 v)))
(let ([res
(build-begin e* v
(lambda (re* x)
(let f ([re* re*] [x x])
(nanopass-case (L22 Value) x
[(begin ,e0* ... ,v0)
(f (append (reverse e0*) re*) v0)]
[else
(if (null? re*)
x
`(begin ,(reverse re*) ... ,x))]))))
])
;(printf "Value->Value: output~%~s~%" (unparse-L22 res))
res)
]
)
)
(define-pass generate-c : L22 (ir) -> * ()
(definitions
(define emit-multi-str
(lambda xs
(for-each
(lambda (x)
(printf x)) xs)))
(define emit-header
(lambda ()
(printf
"#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define TAG(x) (((long)x)&7)
#define FIXNUMP(x) (TAG(x)==0)
#define PAIRP(x) (TAG(x)==1)
#define CLOSUREP(x) (TAG(x)==4)
#define TRUEP(x) ((long)x==~a)
#define FALSEP(x) ((long)x==~a)
#define VOIDP(x) ((long)x==~a)
#define NULLP(x) ((long)x==~a)
#define CAR(x) (*(ptr*)((long)x-1))
#define CDR(x) (*(ptr*)((long)x+7))
typedef long* ptr;
"
true-rep
false-rep
void-rep
null-rep
)))
(define emit-common_func
(lambda ()
(emit-multi-str
"
void print_value(ptr x);
void print_value(ptr x) {
if(FIXNUMP(x)) {
printf(\"%lu\", ((long)x) >> 3);
} else if(TRUEP(x)) {
printf(\"#t\");
} else if(FALSEP(x)) {
printf(\"#f\");
} else if(CLOSUREP(x)) {
printf(\"#<proc>\");
} else if(NULLP(x)) {
printf(\"()\");
} else if(VOIDP(x)) {
printf(\"(void)\");
} else if(PAIRP(x)) {
printf(\"(\");
print_value(CAR(x));
ptr cdr = CDR(x);
lp:
if(NULLP(cdr)) {
//printf(\")\");
} else if(PAIRP(cdr)) {
printf(\" \");
print_value(CAR(x));
cdr = CDR(cdr);
goto lp;
} else {
printf(\" . \");
print_value(cdr);
}
printf(\")\");
} else {
//printf(\"#<unknown>\");
printf(\"(void)\");
}
}
"
)))
(define emit-main
(lambda ()
(printf
"int main(int argc, char **argv) {
print_value(l_main());
printf(\"\\n\");
return 0;
}
")))
(define id->c
(lambda (id)
(list->string
(map (lambda (c)
(case c
[(#\- #\! #\? #\$ #\* #\. #\:) #\_]
[else c]))
(string->list (symbol->string id))))))
(define emit-func-decl
(lambda (l le)
(nanopass-case (L22 LambdaExpr) le
[(lambda (,x* ...) ,lbody)
(printf "ptr ~a(~a);\n" (id->c l)
(string-join (map (lambda (x) "ptr") x*) ", "))])))
(define emit-func-def
(lambda (l le)
(nanopass-case (L22 LambdaExpr) le
[(lambda (,x* ...) (local (,x1* ...) ,body))
(printf "ptr ~a(~a) {\n" (id->c l)
(string-join (map (lambda (x) (format "ptr ~a" x)) x*) ", "))
;;; local vars
(printf "ptr ~a;\n"
(string-join (map (lambda (x) (format "~a" x)) x1*) ", "))
(Value body)
(printf "}\n")])))
(define string-join
(lambda (xs j)
(cond
[(null? xs) ""]
[(null? (cdr xs)) (car xs)]
[else (string-append (car xs) j (string-join (cdr xs) j))])))
(define format-binop
(lambda (op se1 se2)
(format "(long)~a ~a (long)~a" (format-se se1) op (format-se se2))))
(define format-gen-call
(lambda (se se*)
(format "((ptr(*)(~a))~a) (~a)"
(string-join (map (lambda (se) "ptr") se*) ", ")
(format-se se)
(string-join (map (lambda (se) (format-se se)) se*) ", "))))
)
(Program : Program (ir) -> * ()
[(labels ([,l* ,le*] ...) ,l)
(let ([filename "test.c"])
(if (file-exists? filename)
(delete-file filename)))
(with-output-to-file "test.c"
(lambda ()
(emit-header)
(emit-common_func)
(map emit-func-decl l* le*)
(map emit-func-def l* le*)
(emit-main)))
(let ([lst (process "gcc test.c >/dev/null 2>&1 ; ./a.out")])
#;
(let f ([line (get-line (car lst))])
(if (not (eof-object? line))
(begin
(printf "-> ~a~%" line)
(f (get-line (car lst))))))
(let ([ans (read (car lst))])
(printf "-> ~a~%" ans))
)
])
(Value : Value (ir) -> * ()
[(if ,p0 ,v1 ,v2)
(printf "if(~a) {\n" (format-pred p0))
(Value v1)
(printf "} else {\n")
(Value v2)
(printf"}\n")]
[(begin ,e* ... ,v)
(for-each (lambda (e)
(emit-effect e)) e*)
(Value v)]
[,rhs
(printf "return ~a;\n" (format-rhs rhs))]
)
(format-pred : Pred (ir) -> * ()
[(<= ,se0 ,se1)
(format-binop "<=" se0 se1)]
[(< ,se0 ,se1)
(format-binop "<" se0 se1)]
[(= ,se0 ,se1)
(format-binop "==" se0 se1)]
[(true)
(format "~a" true-rep)]
[(false)
(format "~a" false-rep)]
[(if ,p0 ,p1 ,p2)
(format "(~a)?(~a):(~a)" p0 p1 p2)]
[(begin ,e* ... ,p)
(printf "~a, ~a"
(string-join (map (lambda (e)
(format-effect e)) e*) ",")
(foramt-pred p))])
(emit-effect : Effect (ir) -> * ()
[(mset! ,se0 ,se1? ,i ,se2)
(if se1?
(printf "*(ptr*)((long)~a + (long)~a + (~a)) = (ptr)~a;\n"
(format-se se0) (format-se se1?) i (format-se se2))
(printf "*(ptr*)((long)~a + (~a)) = (ptr)~a;\n" (format-se se0) i (format-se se2)))]
[(set! ,x ,rhs)
(printf "~a = ~a;\n" (id->c x) (format-rhs rhs))]
[(nop) (printf "")]
[(if ,p0 ,e1 ,e2) (printf "")]
[(begin ,e* ... ,e) (printf "")]
[(,se ,se* ...) (printf "")])
(format-effect : Effect (ir) -> * ()
[(mset! ,se0 ,se1? ,i ,se2)
(if se1?
(format "*(ptr*)((long)~a + (long)~a + ~a) = (ptr)~a;\n"
(format-se se0) (format-se se1?) i (format-se se2))
(format "*(ptr*)((long)~a + ~a) = (ptr)~a;\n" (format-se se0) i (format-se se2)))]
[(set! ,x ,rhs)
(format "~a = ~a;\n" (id->c x) (format-rhs rhs))]
[(nop) ""]
[(if ,p0 ,e1 ,e2) (format "")]
[(begin ,e* ... ,e) (format "")]
[(,se ,se* ...)
(format-gen-call se se*)]
[(,se ,se* ...) (format "")])
(format-rhs : Rhs (ir) -> * ()
[(alloc ,i ,se)
(format "(ptr)(malloc(~a) + ~a)" se i)]
[,se
(format "~a" (format-se se))]
[(,se ,se* ...)
(format-gen-call se se*)]
)
(format-se : SimpleExpr (se) -> * ()
[,i
(if (< i 0)
(format "(~a)" i)
(format "~a" i))]
[(logand ,se0 ,se1)
(format-binop "|" se0 se1)]
[(sr ,se0 ,se1)
(format-binop ">>" se0 se1)]
[(sl ,se0 ,se1)
(format-binop "<<" se0 se1)]
[(add ,se0 ,se1)
(format-binop "+" se0 se1)]
[(sub ,se0 ,se1)
(format-binop "-" se0 se1)]
[(mul ,se0 ,se1)
(format "(((long)(~a) >> 3) * ((long)(~a)))" se0 se1)
;(format-binop "*" (se0 se1)
]
[(div ,se0 ,se1)
;(format "((long)(~a) / 8) / ((long)(~a)/ 8)" se0 se1)
(format-binop "/" se0 se1)
]
[,x
(format "~a" (id->c x))]
[(mref ,se0 ,se1? ,i)
(if se1?
(format "*(ptr*)((long)~a + (long)~a + (~a))"
se0 se1? i)
(format "*(ptr*)((long)~a + (~a))" se0 i))]
[else (format "todo")])
)
(define convert
(lambda (sexp)
(let ([passes
`((,parse-L1 . ,unparse-L1)
(,rename . ,unparse-L1)
(,remove-one-armed-if . ,unparse-L2)
(,make-explicit-begin . ,unparse-L3)
(,reduce-logic . ,unparse-L4)
(,inverse-eta . ,unparse-L5)
(,quote-const . ,unparse-L6)
(,remove-complex-quote . ,unparse-L7)
(,identify-assigned . ,unparse-L8)
(,purify-letrec . ,unparse-L9)
(,optimize-direct-call . ,unparse-L9)
(,find-let-bound-lambdas . ,unparse-L9)
(,remove-anonymous-lambda . ,unparse-L10)
(,convert-assignments . ,unparse-L11)
(,uncover-free . unparse-L12)
(,convert-closures . unparse-L13)
(,expose-clo-prims . unparse-L14)
(,lift-lambdas . unparse-L15)
(,remove-complex-opera* . unparse-L16)
(,recognize-context . unparse-L17)
(,expose-alloc-primitives . unparse-L18)
(,return-of-set! . unparse-L19)
(,flatten-set! . unparse-L20)
(,convert-const-representation . unparse-L21)
(,expand-primitives . unparse-L22)
)
])
(let f ([passes passes] [ir sexp])
(if (null? passes)
(unparse-L22 ir)
(let ([pass (car passes)])
(let ([ir ((car pass) ir)])
(if debug-pass
(begin
(pretty-print ((cdr pass) ir))
(newline)
(newline)))
(f (cdr passes) ir))))))))
#|
(define run
(lambda (x)
(let ([x (convert x)])
;(eval x)
x
(pretty-print x)
)))
|#
(define-parser parse-L22 L22)
(define run
(lambda (x)
(let ([x (parse-L22 (convert x))])
(generate-c x))))
;;; do some test
(let ()
#|
(run '(if 3 4))
(run '(let ([x 4])
(+ x 4)
(- y 6)))
(run '(let ([x (lambda (x) (+ x 1))])
(x 7)))
(run '(or 3 4 5))
(run '(or))
(run '(or (or 3 4) (+ (or 5) (or 6 7))))
(run ''(3 4))
(run '(letrec ([x 3]
[y 4]
[f (lambda (x y) (+ x y))]
[multiply (lambda (x y) (* x y))])
(f (multiply x 7) (f y 8))))
(run '((lambda (a b) (+ a b)) 3 4))
(run '(let ([foo (lambda (a b) (+ a b))]
[x 3]
[y 4])
(letrec ([m 5] [n 6] [bar (lambda (x y) (- x y))])
(+ (foo x y) (bar m n)))))
(run '((lambda (x y) (+ x y)) 3 4))
(run '(let ([foo (lambda (f a b) (f a b))])
(foo + 3 4)))
(run '(let ([x 3]
[y 4])
(set! x (+ x 5))
(+ x y)))
(run '(lambda (x y z)
(set! x (+ x 3))
(set! y (+ x z))
(+ x y)))
(run '(let ([n 0])
(let ([f (lambda (x)
(set! n (+ n x))
n)])
(f 5))))
|#
(run '(let ([n 0]
[init 5])
(let ([foo (lambda (x)
(set! n (+ n x))
n)]
[bar (lambda (x)
(set! n (- n x))
n)]
[reset (lambda ()
(set! n init))])
(foo 3)
(bar 1)
(reset)
n)))
(run '(let ([x (let ([y 3]
[z 4])
(+ y z))]
[m (let ([n 5])
(+ n 6))])
(* x m)))
(run '(letrec ([fib (lambda (x)
(if (< x 2) 1
(+ (fib (- x 1))
(fib (- x 2)))))])
(fib 6)))
)
(run '(letrec ([frac (lambda (n)
(if (<= n 1) 1
(* n (frac (- n 1)))))])
(frac 8)))
#!eof
;(unparse-L3 (remove-one-armed-if (parse-L1 '(if 3 4))))
| false |
7ab649777a44d097dc327f4b3710f5c878e54459
|
1dfe3abdff4803aee6413c33810f5570d0061783
|
/.chezscheme_libs/spells/finite-types.sls
|
bf89a23e25e11afb9df8c973bcab35ef932b8210
|
[] |
no_license
|
Saigut/chezscheme-libs
|
73cb315ed146ce2be6ae016b3f86cf3652a657fc
|
1fd12abbcf6414e4d50ac8f61489a73bbfc07b9d
|
refs/heads/master
| 2020-06-12T14:56:35.208313 | 2016-12-11T08:51:15 | 2016-12-11T08:51:15 | 75,801,338 | 6 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,353 |
sls
|
finite-types.sls
|
#!r6rs
;;; finite-types.sls --- Scheme48-style finite types
;; Copyright (C) 2009-2011 Andreas Rottmann <[email protected]>
;; Based on code from Scheme48 1.8, Copyright (c) 1993-2008 by Richard
;; Kelsey and Jonathan Rees.
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;;; Commentary:
;;; Code:
;;@ Types with a finite number of instances.
(library (spells finite-types)
(export define-enumerated-type
define-finite-type
finite-type-case)
(import (for (rnrs base) run expand)
(for (rnrs syntax-case) expand)
(srfi srfi-9 records))
;;@subheading Introduction
;; @i{(This section was derived from work copyrighted @copyright{}
;; 1993--2005 by Richard Kelsey, Jonathan Rees, and Mike Sperber.)}
;; The library @code{(spells finite-types)} has two macros for
;; defining @dfn{finite} or @dfn{enumerated record types}. These are
;; record types for which there is a fixed set of instances, all of
;; which are created at the same time as the record type itself..
;;
;;@deffn syntax define-enumerated-type
;; @lisp
;; (define-enumerated-type @var{dispatcher} @var{type}
;; @var{predicate}
;; @var{instance-vector}
;; @var{name-accessor}
;; @var{index-accessor}
;; (@var{instance-name}
;; @dots{}))@end lisp
;; This defines a new record type, to which @var{type} is bound, with as
;; many instances as there are @var{instance-name}s. @var{Predicate} is
;; defined to be the record type's predicate. @var{Instance-vector} is
;; defined to be a vector containing the instances of the type in the same
;; order as the @var{instance-name} list. @var{Dispatcher} is defined to
;; be a macro of the form (@var{dispatcher} @var{instance-name}); it
;; evaluates to the instance with the given name, which is resolved at
;; macro-expansion time. @var{Name-accessor} & @var{index-accessor} are
;; defined to be unary procedures that return the symbolic name & index
;; into the instance vector, respectively, of the new record type's
;; instances.
;;
;; For example,
;;
;; @lisp
;; (define-enumerated-type colour :colour
;; colour?
;; colours
;; colour-name
;; colour-index
;; (black white purple maroon))
;;
;; (colour-name (vector-ref colours 0)) @result{} black
;; (colour-name (colour white)) @result{} white
;; (colour-index (colour purple)) @result{} 2@end lisp
;;@end deffn
(define-syntax define-enumerated-type
(syntax-rules ()
((_ dispatcher rtd
predicate
instance-vector
name-accessor
index-accessor
(instance-name ...))
(define-finite-type dispatcher rtd () predicate instance-vector
name-accessor index-accessor ((instance-name) ...)))))
;;@deffn syntax define-finite-type
;; @lisp
;; (define-finite-type @var{dispatcher} @var{type}
;; (@var{field-tag} @dots{})
;; @var{predicate}
;; @var{instance-vector}
;; @var{name-accessor}
;; @var{index-accessor}
;; (@var{field-tag} @var{accessor} [@var{modifier}])
;; @dots{}
;; ((@var{instance-name} @var{field-value} @dots{})
;; @dots{}))@end lisp
;; This is like @code{define-enumerated-type}, but the instances can also
;; have added fields beyond the name and the accessor. The first list of
;; field tags lists the fields that each instance is constructed with, and
;; each instance is constructed by applying the unnamed constructor to the
;; initial field values listed. Fields not listed in the first field tag
;; list must be assigned later.
;; For example,
;; @lisp
;; (define-finite-type colour :colour
;; (red green blue)
;; colour?
;; colours
;; colour-name
;; colour-index
;; (red colour-red)
;; (green colour-green)
;; (blue colour-blue)
;; ((black 0 0 0)
;; (white 255 255 255)
;; (purple 160 32 240)
;; (maroon 176 48 96)))
;;
;; (colour-name (colour black)) @result{} black
;; (colour-name (vector-ref colours 1)) @result{} white
;; (colour-index (colour purple)) @result{} 2
;; (colour-red (colour maroon)) @result{} 176@end lisp
;;@end deffn
(define-syntax define-finite-type
(lambda (stx)
(syntax-case stx ()
((_ dispatcher rtd
instance-fields
predicate
instance-vector
name-accessor
index-accessor
(field-tag . field-get&set) ...
((instance-name . instance-field-values) ...))
;; the outer `with-syntax' is there just to work around a
;; Guile psyntax issue, see <http://savannah.gnu.org/bugs/?31472>.
(with-syntax (((constructor) (generate-temporaries '(constructor))))
(with-syntax (((constructor-invocation ...)
(let loop ((invocations '())
(i 0)
(names #'(instance-name ...))
(values #'(instance-field-values ...)))
(if (null? names)
(reverse invocations)
(loop (cons #`(constructor '#,(car names)
#,i
#,@(car values))
invocations)
(+ i 1)
(cdr names)
(cdr values))))))
#'(begin
(define-record-type rtd
(constructor name index . instance-fields)
predicate
(name name-accessor)
(index index-accessor)
(field-tag . field-get&set) ...)
(define instance-vector
(vector constructor-invocation ...))
(define-dispatch dispatcher (instance-name ...) instance-vector))))))))
(define-syntax define-dispatch
(lambda (stx)
(syntax-case stx ()
((_ name (instance-name ...) instance-vector)
#`(define-syntax name
(lambda (stx)
(syntax-case stx ()
((dispatcher-name tag)
(let loop ((names (syntax->datum #'(instance-name ...)))
(i 0))
(cond ((null? names)
(syntax-violation (syntax->datum #'dispatcher-name)
"no such instance"
(syntax->datum #'tag)))
((eq? (syntax->datum #'tag) (car names))
#`(vector-ref instance-vector #,i))
(else
(loop (cdr names) (+ i 1)))))))))))))
;;@deffn syntax finite-type-case
;;
;; @lisp
;; (finite-type-case @var{dispatcher} @var{expr} @var{clause} @dots{})@end lisp
;;
;; Similarly to R5RS @code{case}, dispatches according to an instance
;; of a finite type. After evaluating @var{expr}, the resulting value
;; is checked against each @var{clause}, which have the same syntax as
;; a @code{case} clause, but instead of literals must contain only
;; instance names for the finite type specified by @var{dispatcher}.
;;
;; For example,
;;
;; @lisp
;; (define (classify c)
;; (finite-type-case colour c
;; ((black white) 'not-a-real-colour)
;; ((purple maroon) 'real-colour)
;; (else 'unknown)))
;;
;; (classify (colour black)) @result{} not-a-real-colour
;; (classify (colour maroon)) @result{} real-color
;; (classify 4) @result{} unknown@end lisp
;;
;;@end deffn
(define-syntax finite-type-case
(syntax-rules (else)
((_ dispatcher value-expr ((name ...) expr ...) ... (else alt-expr ...))
(let ((val value-expr))
(cond ((or (eq? (dispatcher name) val) ...)
expr ...) ...
(else
alt-expr ...))))
((_ dispatcher value-expr ((name ...) expr ...) ...)
(let ((val value-expr))
(cond ((or (eq? (dispatcher name) val) ...)
expr ...) ...)))))
)
| true |
a3d46fe131a737665a9d343aeba7a32b1b7c0171
|
40395de4446cbdbf1ffd0d67f9076c1f61d572ad
|
/benchmarks/chicken/deriv.scm
|
f02d2e890cfb378fe4425bb82a92ec8254eb304c
|
[] |
no_license
|
justinethier/nugget
|
959757d66f0a8597ab9a25d027eb17603e3e1823
|
0c4e3e9944684ea83191671d58b5c8c342f64343
|
refs/heads/master
| 2020-12-22T06:36:53.844584 | 2016-07-14T03:30:09 | 2016-07-14T03:30:09 | 3,466,831 | 16 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,131 |
scm
|
deriv.scm
|
;;; DERIV -- Symbolic derivation.
#; (import (scheme base)
(scheme cxr)
(scheme read)
(scheme write)
(scheme time))
;;; Returns the wrong answer for quotients.
;;; Fortunately these aren't used in the benchmark.
(define (deriv a)
(cond ((not (pair? a))
(if (eq? a 'x) 1 0))
((eq? (car a) '+)
(cons '+
(map deriv (cdr a))))
((eq? (car a) '-)
(cons '-
(map deriv (cdr a))))
((eq? (car a) '*)
(list '*
a
(cons '+
(map (lambda (a) (list '/ (deriv a) a)) (cdr a)))))
((eq? (car a) '/)
(list '-
(list '/
(deriv (cadr a))
(caddr a))
(list '/
(cadr a)
(list '*
(caddr a)
(caddr a)
(deriv (caddr a))))))
(else
(error #f "No derivation method available"))))
(define (main)
(let* ((count (read))
(input1 (read))
(output (read))
(s (number->string count))
(name "deriv"))
(run-r7rs-benchmark
(string-append name ":" s)
count
(lambda () (deriv (hide count input1)))
(lambda (result) (equal? result output)))))
;;; The following code is appended to all benchmarks.
;;; Given an integer and an object, returns the object
;;; without making it too easy for compilers to tell
;;; the object will be returned.
(define (hide r x)
(call-with-values
(lambda ()
(values (vector values (lambda (x) x))
(if (< r 100) 0 1)))
(lambda (v i)
((vector-ref v i) x))))
;;; Given the name of a benchmark,
;;; the number of times it should be executed,
;;; a thunk that runs the benchmark once,
;;; and a unary predicate that is true of the
;;; correct results the thunk may return,
;;; runs the benchmark for the number of specified iterations.
(define (run-r7rs-benchmark name count thunk ok?)
;; Rounds to thousandths.
(define (rounded x)
(/ (round (* 1000 x)) 1000))
(display "Running ")
(display name)
(newline)
;(flush-output-port)
(let* ((j/s 1 #;(jiffies-per-second))
(t0 1 #;(current-second))
(j0 1 #;(current-jiffy)))
(let loop ((i 0)
(result (if #f #f)))
(cond ((< i count)
(loop (+ i 1) (thunk)))
((ok? result)
(let* ((j1 1 #;(current-jiffy))
(t1 1 #;(current-second))
(jifs (- j1 j0))
(secs (exact->inexact (/ jifs j/s)))
(secs2 (rounded (- t1 t0))))
(display "Elapsed time: ")
(write secs)
(display " seconds (")
(write secs2)
(display ") for ")
(display name)
(newline))
result)
(else
(display "ERROR: returned incorrect result: ")
(write result)
(newline)
result)))))
(main)
| false |
0a7e579bff99a8827f0b187fb7bc37fbe8885821
|
4b5dddfd00099e79cff58fcc05465b2243161094
|
/chapter_5/exercise_5_13.scm
|
2b78cbd119e0f21639a1fc601e3eb225e91ae06c
|
[
"MIT"
] |
permissive
|
hjcapple/reading-sicp
|
c9b4ef99d75cc85b3758c269b246328122964edc
|
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
|
refs/heads/master
| 2023-05-27T08:34:05.882703 | 2023-05-14T04:33:04 | 2023-05-14T04:33:04 | 198,552,668 | 269 | 41 |
MIT
| 2022-12-20T10:08:59 | 2019-07-24T03:37:47 |
Scheme
|
UTF-8
|
Scheme
| false | false | 3,725 |
scm
|
exercise_5_13.scm
|
#lang sicp
;; P372 - [练习 5.13]
(#%require "ch5support.scm")
(#%require "ch5-regsim.scm")
(define (make-machine ops controller-text)
(let ((machine (make-new-machine)))
((machine 'install-operations) ops)
((machine 'install-instruction-sequence)
(assemble controller-text machine))
machine))
(define (make-new-machine)
(let ((pc (make-register 'pc))
(flag (make-register 'flag))
(stack (make-stack))
(the-instruction-sequence '()))
(let ((the-ops
(list (list 'initialize-stack
(lambda () (stack 'initialize)))
;;**next for monitored stack (as in section 5.2.4)
;; -- comment out if not wanted
(list 'print-stack-statistics
(lambda () (stack 'print-statistics)))))
(register-table
(list (list 'pc pc) (list 'flag flag))))
(define (lookup-register name)
(let ((val (assoc name register-table)))
(if val
(cadr val)
(let ((reg (list name (make-register name))))
(set! register-table (cons reg register-table))
(cadr reg)))))
(define (execute)
(let ((insts (get-contents pc)))
(if (null? insts)
'done
(begin
((instruction-execution-proc (car insts)))
(execute)))))
(define (dispatch message)
(cond ((eq? message 'start)
(set-contents! pc the-instruction-sequence)
(execute))
((eq? message 'install-instruction-sequence)
(lambda (seq) (set! the-instruction-sequence seq)))
((eq? message 'get-register) lookup-register)
((eq? message 'install-operations)
(lambda (ops) (set! the-ops (append the-ops ops))))
((eq? message 'stack) stack)
((eq? message 'operations) the-ops)
(else (error "Unknown request -- MACHINE" message))))
dispatch)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define fib-machine
(make-machine
(list (list '< <)
(list '- -)
(list '+ +)
)
'(
(assign continue (label fib-done))
fib-loop
(test (op <) (reg n) (const 2))
(branch (label immediate-answer))
;; set up to compute Fib(n - 1)
(save continue)
(assign continue (label afterfib-n-1))
(save n) ; save old value of n
(assign n (op -) (reg n) (const 1)); clobber n to n - 1
(goto (label fib-loop)) ; perform recursive call
afterfib-n-1 ; upon return, val contains Fib(n - 1)
(restore n)
(restore continue)
;; set up to compute Fib(n - 2)
(assign n (op -) (reg n) (const 2))
(save continue)
(assign continue (label afterfib-n-2))
(save val) ; save Fib(n - 1)
(goto (label fib-loop))
afterfib-n-2 ; upon return, val contains Fib(n - 2)
(assign n (reg val)) ; n now contains Fib(n - 2)
(restore val) ; val now contains Fib(n - 1)
(restore continue)
(assign val ; Fib(n - 1) + Fib(n - 2)
(op +) (reg val) (reg n))
(goto (reg continue)) ; return to caller, answer is in val
immediate-answer
(assign val (reg n)) ; base case: Fib(n) = n
(goto (reg continue))
fib-done
)))
(set-register-contents! fib-machine 'n 10)
(start fib-machine)
(get-register-contents fib-machine 'val)
| false |
bf4f9c29f6a9d9d12ea96deec412cc2b91de81ca
|
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
|
/ch4/4.34.scm
|
fa921a9e610a81251366a3613718be7e4a8440be
|
[] |
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 | 4,835 |
scm
|
4.34.scm
|
(define dont-run-any 1)
(include "4.33.scm")
#|
; preserve primitive scheme cons/car/cdr
(map
(lambda (name proc) (define-variable! name (list 'primitive proc) the-global-environment))
(list 'scm-cons 'scm-car 'scm-cdr)
(list cons car cdr)
)
; install tagged ones into env
(actual-value
'(begin
(define (cons x y)
(scm-cons 'cons (lambda (m) (m x y)))
)
(define (car z)
((scm-cdr z) (lambda (p q) p))
)
(define (cdr z)
((scm-cdr z) (lambda (p q) q))
)
)
the-global-environment
)
(define (disp-cons obj depth)
(letrec
((user-car (lambda (z) (force-it (lookup-variable-value 'x (procedure-environment (cdr z))))))
(user-cdr (lambda (z) (force-it (lookup-variable-value 'y (procedure-environment (cdr z)))))))
(cond
((>= depth 10) (display "...)"))
((null? obj) (display ""))
(else
(let ((cdr-val (user-cdr obj)))
(display "(")
(display (user-car obj))
(if (tagged-list? cdr-val 'cons)
(begin
(display " ")
(disp-cons cdr-val (+ depth 1))
)
(begin
(display " . ")
(display cdr-val)
)
)
(display ")")
)
)
)
)
)
(define (user-print obj)
(if (compound-procedure? obj)
(display
(list
'compound-procedure
(procedure-parameters obj)
(procedure-body obj)
'<procedure-env>
)
)
(if (tagged-list? obj 'cons)
(disp-cons obj 0)
(display obj)
)
)
)
(driver-loop)
|#
(define (eval exp env)
(cond
; base {{
; self-eval
((self-evaluating? exp) exp)
; lookup var
((variable? exp) (lookup-variable-value exp env))
; }}
; special {{
; quotation
((quoted? exp) (text-of-quotation exp env))
; assignment/define
((assignment? exp) (eval-assignment exp env))
((definition? exp) (eval-definition exp env))
; if
((if? exp) (eval-if exp env))
; lambda
((list-lambda? exp) (make-list-procedure (lambda-parameters exp) (lambda-body exp) env))
((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env))
; begin
((begin? exp) (eval-sequence (begin-actions exp) env))
; cond
((cond? exp) (eval (cond->if exp) env))
; let
((let? exp) (eval (let->combination exp) env))
; apply
((application? exp) (apply (actual-value (operator exp) env) (operands exp) env)) ; <- operator is `actual-value` handeld? yes, since itself can a procedure returned from a compound procedure
; }}
; unhandled
(else (error "Unknown expression type -- EVAL" exp))
)
)
;; list-lambda: ('list-lambda (..) ..) just like lambda
;; list-procedure: ('list-procedure <paras> <body> <env>) as for cons..
;; ('list-procedure m <..> the-global-environment + cons' x&y)
(define (list-lambda? exp) (tagged-list? exp 'list-lambda))
(define (make-list-procedure parameters body env)
(list 'list-procedure parameters body env)
)
;; override
(define (compound-procedure? p)
(or (normal-procedure? p) (list-procedure? p))
)
(define (normal-procedure? p) (tagged-list? p 'procedure))
(define (list-procedure? p) (tagged-list? p 'list-procedure))
(define LIST-MAX-DEPTH 5)
(define (user-print obj)
(cond
((normal-procedure? obj)
(display (list 'compound-procedure (procedure-parameters obj) (procedure-body obj) '<procedure-env>)))
((list-procedure? obj)
(display (list-proc->list obj LIST-MAX-DEPTH)))
(else (display obj))
)
)
(define (list-proc->list list-proc count)
(define (apply-proc-to-list proc lst env)
(eval-sequence
(procedure-body proc) ; cons/car/cdr body
(extend-environment (procedure-parameters proc) lst (procedure-environment proc)) ; since cons return a list-procedure, which has only one parameter 'm, so (list list-proc) only feed one arg, that is list-procedure
)
)
(define (list-element opt) ; opt as symbol -> get the true proc via actual-value (lookup in global env)
(force-it
(apply-proc-to-list (actual-value opt the-global-environment) (list list-proc) the-global-environment)
)
)
(define (make-it-normal x n)
(if (list-procedure? x)
(if (zero? n)
'(...)
(list-proc->list x n) ; recursive
)
x
)
)
(cons (make-it-normal (list-element 'car) LIST-MAX-DEPTH) ; here is MAX not count since car may be a list-procedure, too
(make-it-normal (list-element 'cdr) (- count 1)))
)
; ; install tagged ones into env
(actual-value
'(begin
(define (cons x y)
(list-lambda (m) (m x y))
)
(define (car z)
(z (lambda (p q) p))
)
(define (cdr z)
(z (lambda (p q) q))
)
)
the-global-environment
)
(driver-loop)
| false |
c8269800573cf10b82a84e041c0967cfc54cf80c
|
2f17124e3438460e41d3f6242b2bf047ed80fbee
|
/lab2/solutions/aufgabe7.scm
|
b0f684eed12529578c38b58e8cc4a921fa0ed5dc
|
[] |
no_license
|
truenicfel/scheme
|
e5b2dbd532038c45eba464c35c33c0d4f06efe55
|
babbf5d895c0817b180fb2da3c8ce0d46434cda9
|
refs/heads/master
| 2020-03-23T07:29:56.483376 | 2018-07-29T11:08:15 | 2018-07-29T11:08:15 | 141,275,259 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 227 |
scm
|
aufgabe7.scm
|
; Aufgabe 7
; Mengen von Zahlen als Listen
(define (union-set set1 set2)
(cond ((null? set1) set2)
((member (car set1) set2) (union-set (cdr set1) set2))
(else (cons (car set1) (union-set (cdr set1) set2)))))
| false |
1cab83d6e603247d3ee4237894fdbbded6557f92
|
42814fb3168a44672c8d69dbb56ac2e8898f042e
|
/examples/graph-function/posn-to-boolean.ss
|
1c233c19ea299301f1946a247f3662bef8c8a869
|
[] |
no_license
|
dyoo/gui-world
|
520096c3e66b904a9b361fe852be3c5e2ab35e88
|
41e52a1c4686cc6ee4014bf7ded2fcbec337f6eb
|
refs/heads/master
| 2016-09-06T14:54:13.316419 | 2009-04-02T19:10:18 | 2009-04-02T19:10:18 | 159,708 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,750 |
ss
|
posn-to-boolean.ss
|
#lang scheme
;; posn -> boolean graph
(require "../../gui-world.ss"
lang/posn)
;; The world consists of all the points that return true.
(define-struct world (mode posns))
(define-updaters world)
(define mode:clear 'clear)
(define mode:fill 'fill)
(define initial-world (make-world mode:fill empty))
(define (draw-world a-world)
(place-posns (world-posns a-world) (empty-scene 500 500)))
(define (place-posns posns a-scene)
(cond
[(empty? posns)
a-scene]
[else
(place-posns (rest posns)
(place-posn (first posns) a-scene))]))
(define (place-posn a-posn a-scene)
(place-image (text (posn->string a-posn) 10 "black")
(posn-x a-posn)
(posn-y a-posn)
(place-image (circle 5 "solid" "red")
(posn-x a-posn)
(posn-y a-posn)
a-scene)))
;; posn->string: posn -> string
;; Converts a posn to a printable representation.
(define (posn->string a-posn)
(string-append "(" (number->string (posn-x a-posn))
"," (number->string (posn-y a-posn))
")"))
(define (on-click world x y)
(toggle-world-posn world (make-posn (snap-to-grid x) (snap-to-grid y))))
(define (toggle-world-posn a-world a-posn)
(cond [(symbol=? (world-mode a-world) mode:fill)
(cond
[(contains-posn? (world-posns a-world) a-posn)
a-world]
[else
(update-world-posns a-world
(cons a-posn (world-posns a-world)))])]
[(symbol=? (world-mode a-world) mode:clear)
(update-world-posns a-world
(remove-posn (world-posns a-world) a-posn))]))
(define (contains-posn? posns a-posn)
(cond
[(empty? posns)
false]
[(equal? (first posns) a-posn)
true]
[else
(contains-posn? (rest posns) a-posn)]))
(define (remove-posn posns a-posn)
(cond
[(empty? posns)
empty]
[(equal? (first posns) a-posn)
(rest posns)]
[else
(cons (first posns)
(remove-posn (rest posns) a-posn))]))
(define (snap-to-grid n)
(* 50 (round (/ n 50))))
(define (on-mode-drop-down a-world a-choice)
(cond
[(string=? a-choice "fill")
(update-world-mode a-world mode:fill)]
[(string=? a-choice "clear")
(update-world-mode a-world mode:clear)]))
(define view
(col (canvas/callback draw-world on-click)
(drop-down world-mode (list mode:fill mode:clear) on-mode-drop-down)))
#;(big-bang initial-world view)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (world->syntax a-world)
(with-syntax ([graph
(map (lambda (a-posn)
(list (list (posn->sexp a-posn))
#t))
(world-posns a-world))])
#'(quote graph)))
;; posn->sexp: posn -> sexp
(define (posn->sexp a-posn)
(list (posn-x a-posn)
(posn-y a-posn)))
;; sexp->posn: sexp -> posn
(define (sexp->posn an-sexp)
(match an-sexp
[(list x y)
(make-posn x y)]))
(define (world->bytes a-world)
(match a-world
[(struct world (mode posns))
(let ([op (open-output-bytes)])
(write (list mode (map posn->sexp posns))
op)
(get-output-bytes op))]))
(define (bytes->world some-bytes)
(match (read (open-input-bytes some-bytes))
[(list mode posn-sexps)
(make-world mode (map sexp->posn posn-sexps))]))
(define (world->thumbnail a-world)
(draw-world a-world))
(provide initial-world
view
world->syntax
world->bytes
bytes->world
world->thumbnail)
| false |
0eaffb7fd7827e1a635057a2a108ad4204bce757
|
e82d67e647096e56cb6bf1daef08552429284737
|
/frame.scm
|
67705b981b0c89aa2d541042e431211ee5931580
|
[] |
no_license
|
ashishmax31/sicp-exercises
|
97dfe101dd5c91208763dcc4eaac2c17977d1dc1
|
097f76a5637ccb1fba055839d389541a1a103e0f
|
refs/heads/master
| 2020-03-28T11:16:28.197294 | 2019-06-30T20:25:18 | 2019-06-30T20:25:18 | 148,195,859 | 6 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 271 |
scm
|
frame.scm
|
#lang scheme
(define (make-frame-coord-map frame)
(lambda(v)
(add-vect
(origin-frame frame)
(add-vect (scale-vect (x-cord v) (frame-edge-1 frame))
(scale-vect (y-cord v) (frame-edge-2 frame))))))
| false |
60d6710a668b44f2a308de1a81b1653b19db1af1
|
ee232691dcbaededacb0778247f895af992442dd
|
/kirjasto/lib/kaava/ranger.scm
|
dca57d278f6e65f83fa9ca62f9561283ce14690e
|
[] |
no_license
|
mytoh/panna
|
c68ac6c6ef6a6fe79559e568d7a8262a7d626f9f
|
c6a193085117d12a2ddf26090cacb1c434e3ebf9
|
refs/heads/master
| 2020-05-17T02:45:56.542815 | 2013-02-13T19:18:38 | 2013-02-13T19:18:38 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 270 |
scm
|
ranger.scm
|
;;; -*- coding: utf-8 -*-
(use panna.kaava)
(kaava "ranger")
(homepage "http://ranger.nongnu.org")
(repository "git://git.savannah.nongnu.org/ranger.git")
(define (install tynnyri)
(system
`(python setup.py install ,(string-append "--prefix=" tynnyri))
))
| false |
537fee7efa37fbf7476253a2b7fd899903fc1710
|
7f8e3eb6b64a12225cbc704aedb390f8fb9186de
|
/ch2/2_76.scm
|
bae9d4890c1c5dc685bce456fce9618d2f341216
|
[] |
no_license
|
fasl/sicp
|
70e257b6a5fdd44d2dc5783e99d98f0af527fe45
|
c7228b6b284c525a4195358f91e27ebd6a419fa3
|
refs/heads/master
| 2020-12-26T01:12:07.019658 | 2017-02-01T10:13:38 | 2017-02-01T10:13:38 | 17,853,161 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,280 |
scm
|
2_76.scm
|
(define true #t)
(define false #f)
(define nil '())
;2.76
;汎用演算を使った巨大システムが発展すると, 新しいデータオブジェクトの型や, 新しい演算が必要になる.
;三つの戦略---明白な振分けを持つ汎用演算, データ主導流, メッセージパッシング流---のそれぞれにつき,
;新しい型や新しい演算を追加する時, システムに施すべき変更につき述べよ. 新しい型が絶えず追加されるシステムにはどの方法が最も適切か.
;新しい演算が絶えず追加されるシステムには, どれが最も適切か.
新しい型 新しい演算
汎用演算 全演算の書き換え 新しい演算のみ追加
データ主導流 新しい型のみ追加 全演算の書き換え
メッセージパッシング流 新しい型のみ追加 新しい演算のみ追加
とテーブルの変更 とテーブルの変更
新しい型が絶えず追加されるシステム
データ主導流
新しい演算が絶えず追加されるシステム
汎用演算
| false |
4e8d9f8b8c327fe080a0c5ac86c0fa40727fd0e1
|
29ea7c27a13dfcd0c7273619d0d915442298764f
|
/test/test-page.scm
|
3ccedaf536ca9b97d3993e454cb9b11df218fca6
|
[] |
no_license
|
kenhys/gauche-hpdf
|
f637fc85a9a54a8112913b348daa8e04aecebb9b
|
d0993ead47cceaaee2e0ca2ac57df7964ddcb720
|
refs/heads/master
| 2016-09-05T16:54:09.776801 | 2012-08-19T15:17:50 | 2012-08-19T15:17:50 | 3,368,344 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 10,171 |
scm
|
test-page.scm
|
;;;
;;; Test hpdf
;;;
(use gauche.test)
(use math.mt-random)
(use gauche.sequence)
(use gauche.collection)
(use gauche.interactive)
(use hpdf)
(test-record-file "test.record")
(test-module 'hpdf)
(test-start "page")
;;
;; portrait
;;
(define page-size
`(("letter" ,HPDF_PAGE_SIZE_LETTER 612 792)
("legal" ,HPDF_PAGE_SIZE_LEGAL 612 1008)
("a3" ,HPDF_PAGE_SIZE_A3 841.8900146484375 1199.551025390625)
("a4" ,HPDF_PAGE_SIZE_A4 595.2760009765625 841.8900146484375)
("a5" ,HPDF_PAGE_SIZE_A5 419.52801513671875 595.2760009765625)
("executive" ,HPDF_PAGE_SIZE_EXECUTIVE 522 756)
("b4" ,HPDF_PAGE_SIZE_B4 708.6610107421875 1000.6300048828125)
("b5" ,HPDF_PAGE_SIZE_B5 498.89801025390625 708.6610107421875)
("us4x6" ,HPDF_PAGE_SIZE_US4x6 288 432)
("us4x8" ,HPDF_PAGE_SIZE_US4x8 288 576)
("us5x7" ,HPDF_PAGE_SIZE_US5x7 360 504)
("comm10" ,HPDF_PAGE_SIZE_COMM10 297 684)
))
;;
;; hpdf-page-set-size
;;
(test-section "hpdf-page-set-size")
(define (mktest name size direction)
(let* ([pdf (hpdf-new)]
[page (hpdf-add-page pdf)]
[dir (if (= direction HPDF_PAGE_PORTRAIT) "portrait" "landscape")]
[filename (format #f "test/data/page-set-size-~a-~a.pdf" dir name)]
[msg (format #f "~a ~a size" dir name)])
(test* msg HPDF_OK (hpdf-page-set-size page size direction))
(hpdf-save-to-file pdf filename)))
;; portrait
(test-subsection "portrait")
(map (^ (arg)
(mktest (~ arg 0) (~ arg 1) HPDF_PAGE_PORTRAIT)) page-size)
;; landscape
(test-subsubsection "landscape")
(map (^ (arg)
(mktest (~ arg 0) (~ arg 1) HPDF_PAGE_LANDSCAPE)) page-size)
;;
;; hpdf-page-get-width/height
;;
(test-subsection "hpdf-page-get-width/height")
(define (mktest page_style page_direction width height)
(let* ([page (hpdf-add-page (hpdf-new))]
[null (d page)]
[s (hpdf-page-set-size page page_style page_direction)]
[null (d s)]
[w (hpdf-page-get-width page)]
[null (d w)]
[h (hpdf-page-get-height page)]
[null (d h)]
)
(if (and (= width w) (= height h))
#t
#f)))
;; (map (^ (arg)
;; (mktest (~ arg 1) HPDF_PAGE_LANDSCAPE (~ arg 2) (~ arg 3))) page-size)
;; (map (^ (arg)
;; (mktest (~ arg 1) HPDF_PAGE_PORTRAIT (~ arg 3) (~ arg 2))) page-size)
(define (test-hpdf-page-set-height height)
(let* ((page (hpdf-add-page (hpdf-new))))
(hpdf-page-set-height page height)))
;;
;; hpdf-page-set-width/height
;;
(test-subsection "hpdf-page-set-width/height")
(define (mktest expect width)
(let* ([page (hpdf-add-page (hpdf-new))]
[msg (cond ((< width 3) (format #f "page width(~D) under 3" width))
((> width 14400) (format #f "page width(~D) over 14400" width))
(else (format #f "page width(~D) between 3 and 14400" width)))]
)
(test* msg expect (hpdf-page-set-width page width))))
(map (^ (width) (mktest *test-error* width))
'(0 1 2 14401))
(map (^ (width) (mktest HPDF_OK width))
'(3 4 14399 14400))
;; error
;; (test* "-1" *test-error* (hpdf-page-set-size (hpdf-add-page (hpdf-new)) -1 HPDF_PAGE_PORTRAIT))
;; (test* "HPDF_PAGE_SIZE_EOF" *test-error* (hpdf-page-set-size (hpdf-add-page (hpdf-new)) HPDF_PAGE_SIZE_EOF HPDF_PAGE_PORTRAIT))
;; (define (test-page-content pdf m page)
;; (let* ((font (hpdf-get-font pdf "Helvetica" ""))
;; (h (hpdf-page-get-height page))
;; (w (hpdf-page-get-width page))
;; (s (hpdf-page-begin-text page))
;; (i (round (/ w 2)))
;; (st (hpdf-page-move-text-pos page (mt-random-integer m 290) (- h 36)))
;; (s (hpdf-page-set-font-and-size page font 24))
;; (s (hpdf-page-set-text-leading page 24))
;; (s (hpdf-page-show-text page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-show-text-next-line page "Hello, I'm Robot."))
;; (s (hpdf-page-end-text page))
;; )
;; page))
;; (define (test-hpdf-page-set-slide-show file slide)
;; (let* ((pdf (hpdf-new))
;; (disp 3)
;; (trans 5)
;; (m (make <mersenne-twister> :seed (sys-time)))
;; (s (if (equal? slide #t)
;; (begin0
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_WIPE_RIGHT disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_WIPE_UP disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_WIPE_LEFT disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_WIPE_DOWN disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BARN_DOORS_HORIZONTAL_OUT disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BARN_DOORS_HORIZONTAL_IN disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BARN_DOORS_VERTICAL_OUT disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BARN_DOORS_VERTICAL_IN disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BOX_OUT disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BOX_IN disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BLINDS_HORIZONTAL disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_BLINDS_VERTICAL disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_DISSOLVE disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_GLITTER_RIGHT disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_GLITTER_DOWN disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) HPDF_TS_REPLACE disp trans)
;; (hpdf-save-to-file pdf file)
;; )
;; (begin0
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) slide disp trans)
;; (hpdf-page-set-slide-show (test-page-content pdf m (hpdf-add-page pdf)) slide disp trans)
;; (hpdf-save-to-file pdf file)
;; )
;; )))
;; s))
;;
;; hpdf-page-set-slide-show
;;
(define slide-show
`(("HPDF_TS_WIPE_RIGHT" ,HPDF_TS_WIPE_RIGHT "wipe-right")
("HPDF_TS_WIPE_UP" ,HPDF_TS_WIPE_UP "wipe-up")
("HPDF_TS_WIPE_LEFT" ,HPDF_TS_WIPE_LEFT "wipe-left")
("HPDF_TS_WIPE_DOWN" ,HPDF_TS_WIPE_DOWN "wipe-down")
("HPDF_TS_BARN_DOORS_HORIZONTAL_IN" ,HPDF_TS_BARN_DOORS_HORIZONTAL_IN "h-in")
("HPDF_TS_BARN_DOORS_HORIZONTAL_OUT" ,HPDF_TS_BARN_DOORS_HORIZONTAL_OUT "h-out")
("HPDF_TS_BARN_DOORS_VERTICAL_IN" ,HPDF_TS_BARN_DOORS_VERTICAL_IN "v-in")
("HPDF_TS_BARN_DOORS_VERTICAL_OUT" ,HPDF_TS_BARN_DOORS_VERTICAL_OUT "v-out")
("HPDF_TS_BOX_OUT" ,HPDF_TS_BOX_OUT "box-out")
("HPDF_TS_BOX_IN" ,HPDF_TS_BOX_IN "box-in")
("HPDF_TS_BLINDS_HORIZONTAL" ,HPDF_TS_BLINDS_HORIZONTAL "blinds-h")
("HPDF_TS_BLINDS_VERTICAL" ,HPDF_TS_BLINDS_VERTICAL "blinds-v")
("HPDF_TS_DISSOLVE" ,HPDF_TS_DISSOLVE "dissolve")
("HPDF_TS_GLITTER_RIGHT" ,HPDF_TS_GLITTER_RIGHT "g-right")
("HPDF_TS_GLITTER_DOWN" ,HPDF_TS_GLITTER_DOWN "g-down")
("HPDF_TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT" ,HPDF_TS_GLITTER_TOP_LEFT_TO_BOTTOM_RIGHT "g-tl2br")
("HPDF_TS_REPLACE" ,HPDF_TS_REPLACE "replace")
))
(define (mktest name effect sname)
(let* ([pdf (hpdf-new)]
[s (hpdf-use-jp-fonts pdf)]
[disp 3]
[trans 10]
[page (hpdf-add-page pdf)]
[font (hpdf-get-font pdf "Helvetica" "")]
[s (hpdf-page-set-font-and-size page font 24)]
[s (hpdf-page-set-text-leading page 24)]
[filename (format #f "test/data/hpdf-page-set-slide-show-~a.pdf" sname)])
(hpdf-page-set-slide-show page effect disp trans)
(hpdf-page-begin-text page)
(dotimes (n 20)
(hpdf-page-show-text-next-line page name))
(hpdf-page-end-text page)
(set! page (hpdf-add-page pdf))
(hpdf-page-set-slide-show page effect disp trans)
(hpdf-page-begin-text page)
(dotimes (n 20)
(hpdf-page-show-text-next-line page name))
(hpdf-page-end-text page)
(hpdf-save-to-file pdf filename)))
(map (^ (entry)
(mktest (~ entry 0) (~ entry 1) (~ entry 2))) slide-show)
;; epilogue
(test-end)
| false |
979e92976ed5a527c7f8082437d7697f78858ef3
|
923209816d56305004079b706d042d2fe5636b5a
|
/sitelib/http/header-field/accept-encoding.scm
|
a5a443c06bcd641987a95f1b2f09df0e9ea686a9
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
tabe/http
|
4144cb13451dc4d8b5790c42f285d5451c82f97a
|
ab01c6e9b4e17db9356161415263c5a8791444cf
|
refs/heads/master
| 2021-01-23T21:33:47.859949 | 2010-06-10T03:36:44 | 2010-06-10T03:36:44 | 674,308 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 611 |
scm
|
accept-encoding.scm
|
(library (http header-field accept-encoding)
(export Accept-Encoding)
(import (rnrs (6))
(http abnf)
(http content-coding)
(http quality-value))
;;; 14.2 Accept-Encoding
(define configs (bar content-coding (char->rule #\*)))
(define Accept-Encoding
(seq (string->rule "Accept-Encoding")
(char->rule #\:)
(num+
(seq configs
(opt
(seq
(char->rule #\;)
*LWS ; implied *LWS
(char->rule #\q)
(char->rule #\=)
qvalue))))))
)
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.