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
97965109af87d9c4a99527107ccb325d78ec5195
b14c18fa7a4067706bd19df10f846fce5a24c169
/Chapter2/2.97.scm
aa2057c0a98a5ea8b109cef25d230acdb66efddf
[]
no_license
silvesthu/LearningSICP
eceed6267c349ff143506b28cf27c8be07e28ee9
b5738f7a22c9e7967a1c8f0b1b9a180210051397
refs/heads/master
2021-01-17T00:30:29.035210
2016-11-29T17:57:16
2016-11-29T17:57:16
19,287,764
3
0
null
null
null
null
UTF-8
Scheme
false
false
750
scm
2.97.scm
#lang scheme (require srfi/1) (include "./algebra.scm") (define p1 (make-polynomial 'x '((1 1) (0 1)))) (define p2 (make-polynomial 'x '((3 1) (0 -1)))) (define p3 (make-polynomial 'x '((1 1)))) (define p4 (make-polynomial 'x '((2 1) (0 -1)))) (define rf1 (make-rational p1 p2)) (define rf2 (make-rational p3 p4)) ; (x + 1) / (x^3 - 1) + x / (x^2 - 1) ;(apply-generic 'numer rf1) ;(apply-generic 'denom rf2) ;(apply-generic 'reduce p1 p1) ;(apply-generic 'mul (apply-generic 'numer rf1) (apply-generic 'denom rf2)) (newline) (add rf1 rf2) ; Spent almost 2 hours to find out there is a bug in 'sub' impl.... ; I forgot to apply op on L2 when L1 is empty term list ; More test case with a good test framework will make things better I suppose
false
efbff0e3f24e05b2569752a45dc13c1efc5493ff
12fc725f8273ebfd9ece9ec19af748036823f495
/tools/schemelib/wg/type-util.scm
2d40e08795105233d62157f2e365cdcc3b2cde86
[]
no_license
contextlogger/contextlogger2
538e80c120f206553c4c88c5fc51546ae848785e
8af400c3da088f25fd1420dd63889aff5feb1102
refs/heads/master
2020-05-05T05:03:47.896638
2011-10-05T23:50:14
2011-10-05T23:50:14
1,675,623
1
0
null
null
null
null
UTF-8
Scheme
false
false
3,798
scm
type-util.scm
;; ;; Copyright 2006 Helsinki Institute for Information Technology (HIIT) ;; and the authors. All rights reserved. ;; ;; Authors: Tero Hasu <[email protected]> ;; ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation files ;; (the "Software"), to deal in the Software without restriction, ;; including without limitation the rights to use, copy, modify, merge, ;; publish, distribute, sublicense, and/or sell copies of the Software, ;; and to permit persons to whom the Software is furnished to do so, ;; subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. ;; ;; Provides utilities for checking whether a given datum is of the ;; desired basic Scheme data type. Also provides utilities for ;; coercing Scheme data types to others. (module type-util mzscheme (require (lib "usual.scm" "wg")) ;; Queries. (define* (true-boolean? x) (and (boolean? x) (true? x))) (define* (false-boolean? x) (and (boolean? x) (false? x))) (define* (string-of-length? x n) (and (string? x) (= (string-length x) n))) (define* (non-null? x) (not (null? x))) (define* (non-empty-list? x) (and (list? x) (non-null? x))) (define* (named-list? x) (and (non-empty-list? x) (symbol? (car x)))) (define* (list-named? x name) (and (named-list? x) (eq? (car x) name))) (define* (list-named-one-of? x names) (and (named-list? x) (include-eq? names (car x)))) ;; Enforcing checks. (define* (check-with f msg x) (if (f x) x (error (format msg x)))) (define* (check-boolean x) (check-with boolean? "~s is not a boolean" x)) (define* (check-number x) (check-with number? "~s is not a number" x)) (define* (check-integer x) (check-with integer? "~s is not an integer" x)) (define* (check-symbol x) (check-with symbol? "~s is not a symbol" x)) (define* (check-string x) (check-with string? "~s is not a string" x)) (define* (check-char x) (check-with char? "~s is not a character" x)) (define* (check-list x) (check-with list? "~s is not a list" x)) (define* (check-named-list x) (check-with named-list? "~s is not a named list" x)) (define* (check-list-named x name) (check-with (lambda (x) (list-named? x name)) (format "~~s is not a list named ~s" name) x)) ;; Coercions. ;; Coerces a string-like object to a string. (define* (to-string obj) (cond ((string? obj) obj) ((symbol? obj) (symbol->string obj)) ((path? obj) (path->string obj)) (else (error (format "cannot coerce ~s to a string" obj))))) ;; Coerces a string-like object to a symbol. (define* (to-symbol obj) (cond ((symbol? obj) obj) ((string? obj) (string->symbol obj)) ((path? obj) (string->symbol (path->string obj))) (else (error (format "cannot coerce ~s to a symbol" obj))))) ;; Coerces a character-like object to a character. (define* (to-char obj) (cond ((char? obj) obj) ((integer? obj) (integer->char obj)) ((string-of-length? obj 1) (string-ref obj 0)) (else (error (format "cannot coerce ~s to a character" obj))))) ) ; (require (lib "util.scm" "wg")) ; (require type-util) ; (write-nl (check-integer 1.2))
false
b1203dfd2b0f6b67e15939d373e5f728b88e2ab7
784dc416df1855cfc41e9efb69637c19a08dca68
/src/gerbil/prelude/gambit/readtables.ss
096281df0d8315d92cab66514423e8e770452fb1
[ "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
780
ss
readtables.ss
;;; -*- Gerbil -*- ;;; (C) vyzo at hackzen.org ;;; gambit specific runtime symbols: readtables package: gerbil/gambit (export #t) (extern namespace: #f current-readtable readtable? readtable-case-conversion? readtable-case-conversion?-set readtable-keywords-allowed? readtable-keywords-allowed?-set readtable-sharing-allowed? readtable-sharing-allowed?-set readtable-eval-allowed? readtable-eval-allowed?-set readtable-write-cdr-read-macros? readtable-write-cdr-read-macros?-set readtable-write-extended-read-macros? readtable-write-extended-read-macros?-set readtable-max-write-level readtable-max-write-level-set readtable-max-write-length readtable-max-write-length-set readtable-max-unescaped-char readtable-max-unescaped-char-set )
false
b273596b624af354cb8c59fff997e91c2e51fc3a
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/code-dom/compiler/generated-code-attribute.sls
afff6c4101bbc8b1f748bcfb82305b27878894a6
[]
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
818
sls
generated-code-attribute.sls
(library (system code-dom compiler generated-code-attribute) (export new is? generated-code-attribute? tool version) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.CodeDom.Compiler.GeneratedCodeAttribute a ...))))) (define (is? a) (clr-is System.CodeDom.Compiler.GeneratedCodeAttribute a)) (define (generated-code-attribute? a) (clr-is System.CodeDom.Compiler.GeneratedCodeAttribute a)) (define-field-port tool #f #f (property:) System.CodeDom.Compiler.GeneratedCodeAttribute Tool System.String) (define-field-port version #f #f (property:) System.CodeDom.Compiler.GeneratedCodeAttribute Version System.String))
true
ce8655512ed0312b673e73ccb2ddf2df2ae2f8de
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/system/xml/xsl/xsl-transform.sls
4e500132b6eaead296f70b71f11ca00da4985795
[]
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,703
sls
xsl-transform.sls
(library (system xml xsl xsl-transform) (export new is? xsl-transform? transform load xml-resolver) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Xml.Xsl.XslTransform a ...))))) (define (is? a) (clr-is System.Xml.Xsl.XslTransform a)) (define (xsl-transform? a) (clr-is System.Xml.Xsl.XslTransform a)) (define-method-port transform System.Xml.Xsl.XslTransform Transform (System.Void System.String System.String System.Xml.XmlResolver) (System.Void System.String System.String) (System.Void System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList System.IO.TextWriter System.Xml.XmlResolver) (System.Void System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList System.IO.TextWriter) (System.Void System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList System.IO.Stream System.Xml.XmlResolver) (System.Void System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList System.IO.Stream) (System.Void System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList System.Xml.XmlWriter System.Xml.XmlResolver) (System.Void System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList System.Xml.XmlWriter) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList System.Xml.XmlWriter System.Xml.XmlResolver) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList System.Xml.XmlWriter) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList System.IO.Stream System.Xml.XmlResolver) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList System.IO.Stream) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList System.IO.TextWriter System.Xml.XmlResolver) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList System.IO.TextWriter) (System.Xml.XmlReader System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList System.Xml.XmlResolver) (System.Xml.XmlReader System.Xml.XPath.XPathNavigator System.Xml.Xsl.XsltArgumentList) (System.Xml.XmlReader System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList System.Xml.XmlResolver) (System.Xml.XmlReader System.Xml.XPath.IXPathNavigable System.Xml.Xsl.XsltArgumentList)) (define-method-port load System.Xml.Xsl.XslTransform Load (System.Void System.Xml.XmlReader System.Xml.XmlResolver System.Security.Policy.Evidence) (System.Void System.Xml.XPath.XPathNavigator System.Xml.XmlResolver System.Security.Policy.Evidence) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.XmlResolver System.Security.Policy.Evidence) (System.Void System.Xml.XPath.IXPathNavigable System.Xml.XmlResolver) (System.Void System.Xml.XPath.IXPathNavigable) (System.Void System.Xml.XPath.XPathNavigator System.Xml.XmlResolver) (System.Void System.Xml.XPath.XPathNavigator) (System.Void System.Xml.XmlReader System.Xml.XmlResolver) (System.Void System.Xml.XmlReader) (System.Void System.String System.Xml.XmlResolver) (System.Void System.String)) (define-field-port #f xml-resolver #f (property:) System.Xml.Xsl.XslTransform XmlResolver System.Xml.XmlResolver))
true
d760eee866c91090c458ba42d3d4b5d6b82f69a9
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/381/381-imp.scm
12856b13f13dcc08acaafcf8bb3ad83519272011
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,938
scm
381-imp.scm
(define eular-filter (lambda (n) (let-syntax ([v-ref (syntax-rules () [(_ vec i) (vector-ref vec (- i 1))])] [v-set! (syntax-rules () [(_ vec i j) (vector-set! vec (- i 1) j)])]) (let ([vec (make-vector n 1)] [half (quotient n 2)] [prime-ls (list 2)]) (letrec ([add-tail! (let ([ptr prime-ls]) (lambda (new) (set-cdr! ptr (list new)) (set! ptr (cdr ptr))))]) (v-set! vec 1 0) (v-set! vec 4 0) (let f ([i 3]) (cond [(> i half) (let f ([j i]) (cond [(> j n) (list->vector prime-ls)] [(not (zero? (v-ref vec j))) (add-tail! j) (f (+ j 2))] [else (f (+ j 2))]))] [else (let g ([ls prime-ls]) (cond [(null? ls) (when (not (zero? (v-ref vec i))) (add-tail! i) (if (<= (* i i) n) (v-set! vec (* i i) 0))) (f (+ i 1))] [else (let ([now (car ls)]) (cond [(> (* now i) n) (if (not (zero? (v-ref vec i))) (add-tail! i)) (f (+ i 1))] [(zero? (remainder i now)) (v-set! vec (* i now) 0) (if (not (zero? (v-ref vec i))) (add-tail! i)) (f (+ i 1))] [else (v-set! vec (* now i) 0) (g (cdr ls))]))]))]))))))) (define n!-mod (lambda (n k) (cond ((< n 0) #f) ((= n 0) 1) ((= n 1) 1) (else (let f ([n n] [pow 1]) (cond ((= n 1) pow) (else (f (- n 1) (remainder (* pow n) k))))))))) (define n!-k (lambda (n) (let* ([fst (n!-mod (- n 5) n)]) (remainder (* 9 fst) n)))) (define prime-vec (eular-filter 100000000)) (define prime-len (vector-length prime-vec)) (time (let pro ([i 2][sum 0]) (cond ((= i 9592) sum) (else (pro (+ i 1) (+ sum (n!-k (vector-ref prime-vec i))))))) ) #| 25 2 .000013 480 168 3 1229 4 .05 2882332 9592 5 15.9219 226591981 78498 6 664579 7 5761455 8 |#
false
880e064611dde4cbb753deaa9ba90d515af6d5d9
ffb05b145989e01da075e2a607fb291955251f46
/artima/scheme/scheme12.ss
3c54ab60656b8a8faa3a1685c0e466f81a1c8f06
[]
no_license
micheles/papers
a5e7f2fa0cf305cd3f8face7c7ecc0db70ce7cc7
be9070f8b7e8192b84a102444b1238266bdc55a0
refs/heads/master
2023-06-07T16:46:46.306040
2018-07-14T04:17:51
2018-07-14T04:17:51
32,264,461
2
0
null
null
null
null
UTF-8
Scheme
false
false
13,503
ss
scheme12.ss
#| Are macros really useful? =================================================================== In this episode I discuss the utility of macros for enterprise programmers. Are macros "just syntactic sugar"? ---------------------------------------------------- .. image:: sugar.jpg There is a serious problem when teaching macros to beginners: the real power of macros is only seen when solving difficult problems, but you cannot use those problems as teaching examples. As a consequence, virtually all beginner's introductions to macros are dumbed down: usually they just show a few trivial examples about how to modify the Scheme syntax to resemble some other language. I did the same too. This way of teaching macros has two negative effects: 1. beginners are naturally inclined to pervert the language instead of learning it; 2. beginners can easily dismiss macros as mere syntactic sugar. The first effect is the most dangerous: the fact that you can implement a C-like ``for`` loop in Scheme does not mean that you should use it! I strongly believe that learning a language means learning its idioms: learning a new language means that you must change the way you think when writing code. In particular, in Scheme, you must get used to recursion and accumulators, not to imperative loops, there is no other way around. Actually, there are cases where perverting the language may have business sense. For instance, suppose you are translating a library from another language with a ``for`` loop to Scheme. If you want to spend a minimal effort in the translation and if for any reason you want to stay close to the original implementation (for instance, for simplifying maintenance), then it makes sense to leverage on the macro facility and to add the ``for`` loop to the language syntax. The problem is that it is very easy to abuse the mechanism. Generally speaking, the adaptibility of the Scheme language is a double-edged sword. There is no doubts that it increases the programmer expressivity, but it can also make programs more difficult to read. The language allow you to invent your own idioms that nobody else uses, but perhaps this is not such a good idea if you care about other people reading your code. For this reason macros in the Python community have always been viewed with suspicion: I am also pretty confident that they will never enter in the language. The second effect (dismissing macros) is less serious: lots of people understimate macros as mere syntactic sugar, by forgetting that all Turing complete languages differ solely on syntactic sugar. Moreover, thinking too much about the syntactic sugar aspect make them blind to others and more important aspects of macros: in particular, the fact that macros are actually *compilers*. That means that you can implement with macros both *compile time checks* (as I have stressed in `episode #10`_, when talking about guarded patterns) and *compile time computations* (I have not discussed this point yet) with substantial benefits for what concerns both the reliability and the performance of your programs. In `episode #11`_ I have already shown how you can use macros to avoid expensive function calls in benchmarks and the example generalizes to any other situations. In general, since macros allows you to customize the evaluation mechanism of the language, you can do with macros things which are impossible without them: such an example is the ``test`` macro discussed in `episode #11`_. I strongly suggest you to read the third comment to that episode, whereas it is argued that it is impossible to implement an equivalent functionality in Python. So, you should not underestimate the power of macros; on the other hand, you should also not underestimate the complexity of macros. Recently I have started a `thread on comp.lang.scheme`_ with 180+ messages about the issues I have encountered when porting my ``sweet-macros`` library between different Scheme implementations, and the thread ended up discussing a lot of hairy points about macros (expand-time vs run-time, multiple instantiation of modules, separate compilation, and all that). .. _thread on comp.lang.scheme: http://groups.google.com/group/comp.lang.scheme/browse_frm/thread/8927053ede92fd27?hl=en# About the usefulness of macros for application programmers ----------------------------------------------------------------------------- I am not an advocate of macros for enterprise programming. Actually, even ignoring the issue with macros, I cannot advocate Scheme for enterprise programming because of the lack of a standard library worth of its name. This was more of an issue with R5RS Scheme, but it is still a problem since Scheme has an extremely small standard library and no concept of *batteries included* à la Python. As a consequence, everybody has to invent its own collections of utilities, each collection a little bit different from the other. For instance, when I started learning Scheme I wrote a lot of utilities; later on, I discovered that I could find the same utilites, under different names and slightly different signatures, in various Scheme frameworks. This never happened to me in Python to the same extent, since the standard library is already coding in an uniform way most of the useful idioms, so that everybody uses the library and there is less need to reinvent the wheel. On the other hand, I am not a macro aficionado like Paul Graham, who says: *When there are patterns in source code, the response should not be to enshrine them in a list of "best practices," or to find an IDE that can generate them. Patterns in your code mean you are doing something wrong. You should write the macro that will generate them and call that instead.* I think Graham is right in the first part of its analysis, but not in the conclusion. I agree that patterns are a `code smell`_ and I think that they denote a lack in the language or in its standard library. On the other hand, the real solution for the enterprise programmer is not to write her own macro which nobody knows, but to have the feature included in the language by an authoritative source (for instance Guido van Rossum in the case of Python) so that *all* users of the language get the benefit in an uniform way. This happened recently in Python, with the ternary operator, with the ``try .. except .. finally`` statement, with the *with statement*, with extended generators and in many other cases. The Scheme way in which everybody writes his own language makes sense for the academic researcher, for the solitary hacker, or for very small team of programmers, but not for the enterprise. Notice that I am not talking about specialized newly invented constructs: I am talking about *patterns* and by definition, according to the GoF_, a pattern cannot be new, it must be a tried and tested solution to a common problem. If something is so common and well known to be a pattern, it also deserves to be in the standard library of the language, or in a standard framework. This works well for scripting languages, which have a fast evolution, and less well in languages designed by committee, where you can wait years and years for any modernization of the language/library (we all know Paul Graham is coming from Common Lisp, so his position is understandable). In my opinion - and your are free to disagree of course - the enterprise programmer is much better served by a language without macros but with a very complete library where all useful constructs have been codified already. After all, 99.9% of the times the enterprise programmer has to do with already solved problems: it is not by chance that frameworks are so used in the enterprise world. Notice that by "enterprise programmer" I mean the framework *user*, not the framework *writer*. Take my case for instance: at work I am doing some Web programming, and I just use one of the major Python web frameworks (there already too many of them!); I do quite of lot of interaction with databases, and I just use the standard or *de facto* standard drivers/libraries provided for the task at hand; I also do some scripting task: then I use the standard library a lot. For all the task I routinely perform at my day job macros would not help me a bit: after all Python has already many solutions to avoid boilerplate (decorators, metaclasses, etc.) and the need for macros is not felt. I admit that some times I wished for new constructs in Python: but usually it was just a matter of time and patience to get them in the language and while waiting I could always solve my problems anyway, maybe in a less elegant way. There are good use cases for macros, but there also plenty of workarounds for the average application programmer. For instance, a case where one could argue for macros, is when there are performance issues, since macros are able to lift computations from runtime to compile time, and they can be used for code optimization. However, even without macros, there is plenty of room for optimization in the scripting language world, which typically involve interfacing with C/C++. There are also various standard techniques for *code generation* in C, whereas C++ has the infamous *templates*: while those are solutions very much inferior to Scheme macros, they also have the enormous advantage of working with an enterprise-familiar technology, and you certainly cannot say that for Scheme. The other good use for macros is to implement compile time checks: compile time checks are a good thing, but in practice people have learned to live without them by relying on a good unit test coverage, which is needed anyway. On the other hand, one should not underestimate the downsides of macros. Evaluation of code defined inside of the macro body at compile time or suspension of evaluation therein leads often to bugs that are hard to track. The behaviour of the code is generally not easy to understand and debugging macros is no fun. That should explain why the current situation about Scheme in the enterprise world is as it is. It is also true that the enterprise programmer's job is sometimes quite boring, and you can risk brain atrophy, whereas for sure you will not incur in this risk if you keep reading my *Adventures* ;) You may look at this series as a cure against senility! .. _code smell: http://en.wikipedia.org/wiki/Code_smell .. _GoF: http://en.wikipedia.org/wiki/Design_Patterns Appendix: a Pythonic ``for`` loop ------------------------------------------------- In this appendix I will give the solution to the exercise suggested at the end of `episode #10`_, i.e. implementing a Python-like ``for`` loop. First of all, let me notice that Scheme already has the functionality of Python ``for`` loop (at least for lists) via the for-each_ construct:: > (for-each (lambda (x y) (display x) (display y)) '(a x 1) '(b y 2)) abxy12 The problem is that the syntax looks quite different from Python:: >>> for (x, y) in (("a", "b"), ("x", "y"), (1, 2)): ... sys.stdout.write(x); sys.stdout.write(y) One problem is that the order of the list is completely different, but this is easy to fix with a ``transpose`` function: $$TRANSPOSE (if you have read carefully `episode #8`_ you will notice the similarity between ``transpose`` and ``zip``). ``transpose`` works as follows:: > (transpose '((a b) (x y) (1 2))) ((a x 1) (b y 2)))) Then there is the issue of hiding the ``lambda`` form, but this is an easy job for a macro: $$FOR The important thing to notice in this implementation is the usage of a guard with an ``else`` clause: that allows to introduce two different behaviours for the macro at the same time. If the pattern variable ``el`` is an identifier, then ``for`` is converted into a simple ``for-each``:: > (for x in '(1 2 3) (display x)) 123 On the other hand, if the pattern variable ``el`` is a list of identifiers and ``lst`` is a list of lists, then the macro also reorganizes the arguments of the underlying ``for-each`` expression, so that ``for`` works as Python's ``for``:: > (for (x y) in '((a b) (x y) (1 2)) (display x) (display y)) abxy12 .. _for-each: http://www.r6rs.org/final/html/r6rs/r6rs-Z-H-14.html#node_idx_644 .. _episode #8: http://www.artima.com/weblogs/viewpost.jsp?thread=240793 .. _episode #10: http://www.artima.com/weblogs/viewpost.jsp?thread=240805 .. _episode #11: http://www.artima.com/weblogs/viewpost.jsp?thread=240833 |# (import (rnrs) (sweet-macros) (easy-test) (only (ikarus) void)) ;TRANSPOSE (define (transpose llist) ; llist is a list of lists (if (and (list? llist) (for-all list? llist)) (apply map list llist) (error 'transpose "Not a list of lists" llist))) ;END ;FOR (def-syntax for (syntax-match (in) (sub (for el in lst do something ...) #'(for-each (lambda (el) do something ...) lst) (identifier? #'el)) (sub (for (el ...) in lst do something ...) #'(apply for-each (lambda (el ...) do something ...) (transpose lst)) (for-all identifier? #'(el ...)) (syntax-violation 'for "Non identifier" #'(el ...) (remp identifier? #'(el ...)))) )) ;END (run (test "transpose" (transpose '((a b) (x y) (1 2))) '((a x 1) (b y 2))) (test "for1" (for x in '(1 2 3) (display x)) (void)) (test "for2" (for (x y) in '((a b) (x y) (1 2)) (display x) (display y)) (void))) ;(for (x 2) in '((a b) (x y) (1 2)) (display x) (display y))
false
4d7e55c995ff72a2763feca4d66ea2a3398481e1
694d57c3e512ce916269411b51adef23532420cd
/artificial_intelligence/AgentWorld/Agents/V3/main.scm
a0515cd53bb0a34ff1788c5bc65b6814fe663da8
[]
no_license
clovery410/mycode
5541c3a99962d7949832a0859f18819f118edfba
e12025e754547d18d5bb50a9dbe5e725fd03fd9c
refs/heads/master
2021-05-16T02:46:47.996748
2017-05-10T23:43:50
2017-05-10T23:43:50
39,235,141
1
1
null
null
null
null
UTF-8
Scheme
false
false
24,721
scm
main.scm
(load "factor.scm") ;; f1: is-stay ;; f2: is-turn ;; f3: is-move1 ;; f4: is-move2 ;; f5: is-move3 ;; f6: is-eat ;; f7: is-strongest-within-1 ;; f8: is-strongest-within-2 ;; f9: is-strongest-within-3 ;; f10: is-current-not-accessible ;; f11: is-left-hand-vege ;; f12: is-right-hand-vege ;; f13: is-left-side-has-vege ;; f14: is-right-side-has-vege ;; f15: is-straight-line-has-vege ;; f16: is-surround-by-predator ;; f17: is-not-running-away-underattack ;; f18: is-facing-predator-when-stay ;; f19: is-taking-action-underattack ;; f20: is-eating-front-vege-has-gain ;; f21: is-making-turn-facing-barrier ;; f22: is-turning-to-barrier ;; f23: is-making-turn-facing-predator ;; f24: is-making-turn-after-eating ;; f25: is-surround-by-vegetation ;; f26: is-nothing-to-eat ;; f27: is-escaping-mode (define (initialize-agent) "OK") (define left-corner '()) (define right-corner '()) ;;this function returns the smallest element in a given list (define (find-smallest alist) (if (null? (cdr alist)) (car alist) (if (< (car alist) (find-smallest (cdr alist))) (car alist) (find-smallest (cdr alist))))) ;;this function returns a biggest element in a given list (define (find-biggest alist) (if (null? (cdr alist)) (car alist) (if (> (car alist) (find-biggest (cdr alist))) (car alist) (find-biggest (cdr alist))))) ;;this fucntion takes in an index and a list, returns the corresponding element of that index (define (nth-item index nums) (if (= index 1) (car nums) (nth-item (- index 1) (cdr nums)))) ;;this function takes in an index n, a list and a value, replaces the nth element with the new value, then returns the new lsit. (define (replace-nth-item n items val) (if (= n 1) (cons val (cdr items)) (cons (car items) (replace-nth-item (- n 1) (cdr items) val)))) ;;this function returns a new list of the first n element in the input list (define (get-n-items alist n) (if (> n 0) (cons (car alist) (get-n-items (cdr alist) (- n 1))) '())) ;;this function takes in a list, a start position, and the total number to slice in that list, then returns a sublist, for example, (get-sublist '(1 2 3 4) 1 2) will return (1 2). (define (get-sublist alist start count) (if (> start 1) (get-sublist (cdr alist) (- start 1) count) (get-n-items alist count))) ;;this function get the corresponding content of a percept from x, y coordinates (define (get-location percept x y) (if (= y 1) (nth-item (+ x 2) (car percept)) (get-location (cdr percept) (+ x 1) (- y 1)))) ;;this function tell whether this location is an empty spot (define (is-empty? location) (if (equal? location 'empty) #t #f)) ;;this function tell whether a road (across y-axis) from lower-point to higher-point is empty (define (is-road-empty? percepts lower higher) (if (> lower higher) #t (let ((curr-location (get-location percepts 0 lower))) (if (is-empty? curr-location) (is-road-empty? percepts (+ lower 1) higher) #f)))) ;;this function tell whether this location is a barrier (define (is-barrier? location) (if (equal? location 'barrier) #t #f)) ;;this function tell whether this location is a vegetation or not (define (is-vegetation? location) (if (and (list? location) (= (length location) 3)) #t #f)) ;;this function get the current vegetable energy from a location (define (get-vegetation-energy location) (nth-item 3 location)) ;;this function tell whether this location is a predator or not (define (is-predator? location) (if (and (list? location) (= (length location) 2)) #t #f)) ;;this fucntion get the id of a predator from a location (define (get-predator-id location) (nth-item 2 location)) ;;this function tell whether this location is other agent or not (define (is-agent? location) (if (and (list? location) (= (length location) 4)) #t #f)) ;;this function calculate the log base 2 value of a number (define (log-base2 number) (/ (log number) (log 2))) ;;this function get the approximate energy level of an agent (define (get-agent-energy location) (expt 2 (nth-item 3 location))) ;;this function get the direction of an agent (define (get-agent-direction location) (nth-item 4 location)) ;;this function calculate the feature 10, is-current-not-accessible, yes return 1, no return 0 (define (is-current-not-accessible percepts x y) (let ((curr-location (get-location percepts x y))) (cond ((is-barrier? curr-location) 1) ((is-predator? curr-location) 1) ((is-vegetation? curr-location) 1) ((is-agent? curr-location) 1) (#t (if (= y 1) 0 (is-current-not-accessible percepts x (- y 1))))))) ;;this function return the new state after apply corresponding action (define (apply-action action state) (let ((x (nth-item 1 action)) (y (nth-item 2 action)) (dir (nth-item 3 action))) (cond ((equal? state "STAY") action) ((equal? state "MOVE-1") (cond ((equal? dir (quote N)) (replace-nth-item 2 action (+ y 1))) ((equal? dir (quote S)) (replace-nth-item 2 action (- y 1))) ((equal? dir (quote W)) (replace-nth-item 1 action (- x 1))) ((equal? dir (quote E)) (replace-nth-item 1 action (+ x 1))) (else #t))) ((equal? state "MOVE-2") (cond ((equal? dir (quote N)) (replace-nth-item 2 action (+ y 2))) ((equal? dir (quote S)) (replace-nth-item 2 action (- y 2))) ((equal? dir (quote W)) (replace-nth-item 1 action (- x 2))) ((equal? dir (quote E)) (replace-nth-item 1 action (+ x 2))) (else #t))) ((equal? state "MOVE-3") (cond ((equal? dir (quote N)) (replace-nth-item 2 action (+ y 3))) ((equal? dir (quote S)) (replace-nth-item 2 action (- y 3))) ((equal? dir (quote W)) (replace-nth-item 1 action (- x 3))) ((equal? dir (quote E)) (replace-nth-item 1 action (+ x 3))) (else #t))) ((equal? state "TURN-AROUND") (cond ((equal? dir (quote N)) (replace-nth-item 3 action 'S)) ((equal? dir (quote W)) (replace-nth-item 3 action 'E)) ((equal? dir (quote S)) (replace-nth-item 3 action 'N)) ((equal? dir (quote E)) (replace-nth-item 3 action 'W)) (else #t))) ((equal? state "TURN-LEFT") (cond ((equal? dir (quote N)) (replace-nth-item 3 action 'W)) ((equal? dir (quote W)) (replace-nth-item 3 action 'S)) ((equal? dir (quote S)) (replace-nth-item 3 action 'E)) ((equal? dir (quote E)) (replace-nth-item 3 action 'N)) (else #t))) ((equal? state "TURN-RIGHT") (cond ((equal? dir (quote N)) (replace-nth-item 3 action 'E)) ((equal? dir (quote W)) (replace-nth-item 3 action 'N)) ((equal? dir (quote S)) (replace-nth-item 3 action 'W)) ((equal? dir (quote E)) (replace-nth-item 3 action 'S)) (else #t))) (else #t)))) ;;this function determines whether the agent was attacked by predator in last turn (define (is-attacked? previous-events) (if (null? previous-events) #f (let ((curr-event (car previous-events))) (if (equal? (car curr-event) 'attacked-by) #t (is-attacked? (cdr previous-events)))))) ;;this function calculate the feature19, is-taking-action-underattack, yes reuturn 1, no return 0 (define (is-taking-action-underattack previous-events percepts moving-steps) (let ((step1 (get-location percepts 0 1)) (step2 (get-location percepts 0 2)) (step3 (get-location percepts 0 3))) (if (is-attacked? previous-events) (cond ((= moving-steps 1) (if (is-empty? step1) 1 0)) ((= moving-steps 2) (if (and (is-empty? step1) (is-empty? step2)) 1 0)) ((= moving-steps 3) (if (and (is-empty? step1) (is-empty? step2) (is-empty? step3)) 1 0)) (#t 0)) 0))) ;;this function calculate the feature17, is-not-running-away-underattack, yes return 1, no return 0 (define (is-not-running-away-underattack previous-events origin-state action) (if (and (is-attacked? previous-events) (is-empty? origin-state) (or (equal? action "STAY") (equal? action "TURN-LEFT") (equal? action "TURN-RIGHT") (equal? action "TURN-AROUND") (equal? action "EAT-PASSIVE") (equal? action "EAT-AGGRESSIVE"))) 1 0)) ;;this function calculate the feature18, is-facing-predator-when-stay, yes return 1, no return 0 (define (is-facing-predator-when-stay percepts) (if (is-predator? (get-location percepts 0 1)) 1 0)) ;;this function returns the damage level from is-attacked? (define (get-damage-level previous-events) (if (not (is-attacked? previous-events)) 0 (let ((curr-event (car previous-events))) (if (equal? (car curr-event) 'attacked-by) (nth-item 3 curr-event) (get-damage-level (cdr previous-events)))))) ;;this function determines whether the agent eat the vegetation in last turn (define (is-ate? previous-events) (if (null? previous-events) #f (let ((curr-event (car previous-events))) (if (equal? (car curr-event) 'ate) #t (is-ate? (cdr previous-events)))))) ;;this function determines whether the agent was fought by other agent in last turn (define (is-fought? previous-events) (if (null? previous-events) #f (let ((curr-event (car previous-events))) (if (equal? (car curr-event) 'fought) #t (is-fought? (cdr previous-events)))))) ;;this function tells whether a location is surrounded by predator (define (surround-by-predator? x y percepts) (if (= y 0) (or (is-predator? (get-location percepts 0 1)) (is-predator? left-corner) (is-predator? right-corner)) (or (is-predator? (get-location percepts x (+ y 1))) (is-predator? (get-location percepts (- x 1) y)) (is-predator? (get-location percepts (+ x 1) y))))) ;;this function calculate feature25, is-surround-by-vegetation, yes return 1, no return 0 (define (is-surround-by-vegetation x y percepts) (let ((above (get-location percepts x (+ y 1))) (left (get-location percepts (- x 1) y)) (right (get-location percepts (+ x 1) y))) (if (or (and (is-vegetation? above) (> (get-vegetation-energy above) 0)) (and (is-vegetation? left) (> (get-vegetation-energy left) 0)) (and (is-vegetation? right) (> (get-vegetation-energy right) ))) 1 0))) ;;this function returns #f if there is no other agents around a location or the agents all weaker than me, otherwise return #t (define (stronger-than-me? x y percepts my-energy) (let ((above (get-location percepts x (+ y 1))) (left (get-location percepts (- x 1) y)) (right (get-location percepts (+ x 1) y))) (or (and (is-agent? above) (> (get-agent-energy above) my-energy)) (and (is-agent? left) (> (get-agent-energy left) my-energy)) (and (is-agent? right) (> (get-agent-energy right) my-energy))))) ;;this function calculate feature7, is-strongest-within-1, yes return #t, no return #f (define (is-strongest-within-1 my-energy percepts) (let ((above1 (get-location percepts 0 2)) (above2 (get-location percepts 0 3)) (above3 (get-location percepts 0 4)) (left1 (get-location percepts -1 1)) (right1 (get-location percepts 1 1))) (and (or (not (is-agent? above1)) (> my-energy (get-agent-energy above1))) (or (not (is-agent? above2)) (> my-energy (get-agent-energy above2))) (or (not (is-agent? above3)) (> my-energy (get-agent-energy above3))) (or (not (is-agent? left1)) (> my-energy (get-agent-energy left1))) (or (not (is-agent? right1)) (> my-energy (get-agent-energy right1)))))) ;;this function calculate feature8, is-strongest-within-2, yes return #t, no return #f (define (is-strongest-within-2 my-energy percepts) (let ((above1 (get-location percepts 0 3)) (above2 (get-location percepts 0 4)) (above3 (get-location percepts 0 5)) (left1 (get-location percepts -1 2)) (left2 (get-location percepts -2 2)) (right1 (get-location percepts 1 2)) (right2 (get-location percepts 2 2))) (and (or (not (is-agent? above1)) (> my-energy (get-agent-energy above1))) (or (not (is-agent? above2)) (> my-energy (get-agent-energy above2))) (or (not (is-agent? above3)) (> my-energy (get-agent-energy above3))) (or (not (is-agent? left1)) (> my-energy (get-agent-energy left1))) (or (not (is-agent? left2)) (> my-energy (get-agent-energy left2))) (or (not (is-agent? right1)) (> my-energy (get-agent-energy right1))) (or (not (is-agent? right2)) (> my-energy (get-agent-energy right2)))))) ;;this function calculate feature9, is-strongest-within-3, yes return #t, no return #f (define (is-strongest-within-3 my-energy percepts) (let ((above1 (get-location percepts 0 4)) (above2 (get-location percepts 0 5)) (left1 (get-location percepts -1 3)) (left2 (get-location percepts -2 3)) (left3 (get-location percepts -3 3)) (right1 (get-location percepts 1 3)) (right2 (get-location percepts 2 3)) (right3 (get-location percepts 3 3))) (and (or (not (is-agent? above1)) (> my-energy (get-agent-energy above1))) (or (not (is-agent? above2)) (> my-energy (get-agent-energy above2))) (or (not (is-agent? left1)) (> my-energy (get-agent-energy left1))) (or (not (is-agent? left2)) (> my-energy (get-agent-energy left2))) (or (not (is-agent? left3)) (> my-energy (get-agent-energy left3))) (or (not (is-agent? right1)) (> my-energy (get-agent-energy right1))) (or (not (is-agent? right2)) (> my-energy (get-agent-energy right2))) (or (not (is-agent? right3)) (> my-energy (get-agent-energy right3)))))) ;;this function tells whether the straight line has vegetation (define (has-vegetation-this-line? percepts) (or (is-vegetation? (get-location percepts 0 1)) (is-vegetation? (get-location percepts 0 2)) (is-vegetation? (get-location percepts 0 3)) (is-vegetation? (get-location percepts 0 4)) (is-vegetation? (get-location percepts 0 5)))) ;;this function caculate the left corner gain, returns the vegetation energy level in last turn, if no vege, returns 0 (define (left-corner-gain left-corner) (cond ((null? left-corner) 0) ((is-vegetation? left-corner) (get-vegetation-energy left-corner)) (#t 0))) ;;this function calculate the right corner gain, returns the vegetation energy level in last turn, if no vege, returns 0 (define (right-corner-gain right-corner) (cond ((null? right-corner) 0) ((is-vegetation? right-corner) (get-vegetation-energy right-corner)) (#t 0))) ;;this function calculate the feature11, is-left-hand-vege (define (is-left-hand-vege left-corner) (if (> (left-corner-gain left-corner) 0) 1 0)) ;;this function calculate the feature12, is-right-hand-vege (define (is-right-hand-vege right-corner) (if (> (right-corner-gain right-corner) 0) 1 0)) ;;this function calculate the feature20, is-eating-front-vege-has-gain, yes return 1, no return 0 (define (is-eating-front-vege-has-gain percepts previous-events) (let ((front-location (get-location percepts 0 1))) (if (and (is-vegetation? front-location) (> (get-vegetation-energy front-location) (get-damage-level previous-events))) 1 0))) ;;this function calculate the feature26, is-nothing-to-eat, yes return 1, no return 0 (define (is-nothing-to-eat percepts) (let ((front-location (get-location percepts 0 1))) (if (and (is-vegetation? front-location) (> (get-vegetation-energy front-location) 0)) 0 1))) ;;this function calculate the feature27, is-escaping-mode, yes return 1, no return 0 (define (is-escaping-mode percepts previous-events steps) (if (and (is-attacked? previous-events) (is-road-empty? percepts 1 steps)) 1 0)) ;;this function calculate the score of stay (define (stay-score previous-events percepts) (let ((origin-state (get-location percepts 0 1))) (+ (* (is-not-running-away-underattack previous-events origin-state "STAY") w17) (* (is-current-not-accessible percepts 0 1) w10) (* (is-facing-predator-when-stay percepts) w18) (if (surround-by-predator? 0 0 percepts) w16 0) w1))) ;;this function calculate the score of turn left (define (turn-left-score previous-events percepts) (let* ((origin-state (get-location percepts 0 1)) (origin-left (get-location percepts -1 1))) (+ (if (is-barrier? origin-state) w21 0) (if (is-barrier? origin-left) w22 0) (if (surround-by-predator? 0 0 percepts) w16 0) (* (is-left-hand-vege left-corner) w11) (if (is-predator? origin-state) w23 0) (if (is-ate? previous-events) w24 0) (* (is-not-running-away-underattack previous-events origin-state "TURN-LEFT") w17) w2))) ;;this function calculate the score of turn right (define (turn-right-score previous-events percepts) (let* ((origin-state (get-location percepts 0 1)) (origin-right (get-location percepts 1 1))) (+ (if (is-barrier? origin-state) w21 0) (if (is-barrier? origin-right) w22 0) (if (surround-by-predator? 0 0 percepts) w16 0) (* (is-right-hand-vege right-corner) w12) (if (is-predator? origin-state) w23 0) (if (is-ate? previous-events) w24 0) (* (is-not-running-away-underattack previous-events origin-state "TURN-RIGHT") w17) w2))) ;;this function calculate the score of turn around (define (turn-around-score previous-events percepts) (let* ((origin-state (get-location percepts 0 1))) (+ (if (is-barrier? origin-state) w21 0) (if (surround-by-predator? 0 0 percepts) w16 0) (if (is-predator? origin-state) w23 0) (if (is-ate? previous-events) w24 0) (* (is-not-running-away-underattack previous-events origin-state "TURN-AROUND") w17) w2))) ;;this function calculate the score of move passive 1 (define (move-passive-1-score previous-events percepts) (let* ((origin-state (get-location percepts 0 1))) (+ (* (is-current-not-accessible percepts 0 1) w10) (if (surround-by-predator? 0 1 percepts) w16 0) (* (is-taking-action-underattack previous-events percepts 1) w19) (if (has-vegetation-this-line? percepts) w15 0) w3))) ;;this function calculate the score of move passive 2 (define (move-passive-2-score previous-events percepts) (let* ((origin-state (get-location percepts 0 1)) (origin-above-state (get-location percepts 0 2))) (+ (* (is-current-not-accessible percepts 0 2) w10) (if (surround-by-predator? 0 2 percepts) w16 0) (* (is-taking-action-underattack previous-events percepts 2) w19) (* (is-escaping-mode percepts previous-events 2) w27) (* (is-surround-by-vegetation 0 2 percepts) w25) (if (has-vegetation-this-line? percepts) w15 0) w4))) ;;this function calculate the score of move passive 3 (define (move-passive-3-score previous-events percepts) (let* ((origin-state (get-location percepts 0 1)) (origin-above-state (get-location percepts 0 2)) (origin-above2-state (get-location percepts 0 3))) (+ (* (is-current-not-accessible percepts 0 3) w10) (if (surround-by-predator? 0 3 percepts) w16 0) (* (is-taking-action-underattack previous-events percepts 3) w19) (* (is-escaping-mode percepts previous-events 3) w27) (* (is-surround-by-vegetation 0 3 percepts) w25) (if (has-vegetation-this-line? percepts) w15 0) w5))) ;;this function calculate the score of move aggressive 1 (define (move-aggressive-1-score current-energy previous-events percepts) (let* ((origin-state (get-location percepts 0 1))) (+ (* (is-current-not-accessible percepts 0 1) w10) (if (surround-by-predator? 0 1 percepts) w16 0) (* (is-taking-action-underattack previous-events percepts 1) w19) (if (has-vegetation-this-line? percepts) w15 0) (if (is-strongest-within-1 current-energy percepts) w7 0) w3))) ;;this function calculate the score of move aggressive 2 (define (move-aggressive-2-score current-energy previous-events percepts) (let* ((origin-state (get-location percepts 0 1)) (origin-above-state (get-location percepts 0 2))) (+ (* (is-current-not-accessible percepts 0 2) w10) (if (surround-by-predator? 0 2 percepts) w16 0) (* (is-taking-action-underattack previous-events percepts 2) w19) (* (is-escaping-mode percepts previous-events 2) w27) (* (is-surround-by-vegetation 0 2 percepts) w25) (if (has-vegetation-this-line? percepts) w15 0) (if (is-strongest-within-2 current-energy percepts) w8 0) w4))) ;;this function calculate the score of move aggressive 3 (define (move-aggressive-3-score current-energy previous-events percepts) (let* ((origin-state (get-location percepts 0 1)) (origin-above-state (get-location percepts 0 2)) (origin-above2-state (get-location percepts 0 3))) (+ (* (is-current-not-accessible percepts 0 3) w10) (if (surround-by-predator? 0 3 percepts) w16 0) (* (is-taking-action-underattack previous-events percepts 3) w19) (* (is-escaping-mode percepts previous-events 3) w27) (* (is-surround-by-vegetation 0 3 percepts) w25) (if (has-vegetation-this-line? percepts) w15 0) (if (is-strongest-within-3 current-energy percepts) w9 0) w5))) ;;this function calculate the score after passive eating (define (eat-passive-score previous-events percepts) (let ((origin-state (get-location percepts 0 1))) (+ (* (is-eating-front-vege-has-gain percepts previous-events) w20) (* (is-nothing-to-eat percepts) w26) (if (surround-by-predator? 0 0 percepts) w16 0) w6))) ;;this function calculate the score after aggressive eating (define (eat-aggressive-score current-energy previous-events percepts) (let ((origin-state (get-location percepts 0 1))) (+ (* (is-eating-front-vege-has-gain percepts previous-events) w20) (* (is-nothing-to-eat percepts) w26) (if (not (stronger-than-me? 0 1 percepts current-energy)) w7 0) (if (surround-by-predator? 0 0 percepts) w16 0) w6))) (define (choose-action current-energy previous-events percepts) (let* ((s-score (stay-score previous-events percepts)) (tr-score (turn-right-score previous-events percepts)) (tf-score (turn-left-score previous-events percepts)) (ta-score (turn-around-score previous-events percepts)) (mp1-score (move-passive-1-score previous-events percepts)) (mp2-score (move-passive-2-score previous-events percepts)) (mp3-score (move-passive-3-score previous-events percepts)) (ma1-score (move-aggressive-1-score current-energy previous-events percepts)) (ma2-score (move-aggressive-2-score current-energy previous-events percepts)) (ma3-score (move-aggressive-3-score current-energy previous-events percepts)) (ep-score (eat-passive-score previous-events percepts)) (ea-score (eat-aggressive-score current-energy previous-events percepts)) (max-score (find-biggest (list s-score tr-score tf-score ta-score mp1-score mp2-score mp3-score ma1-score ma2-score ma3-score ep-score ea-score)))) (cond ((equal? max-score s-score) "STAY") ((equal? max-score tr-score) (begin (set! left-corner (get-location percepts 1 1)) (set! right-corner '()) "TURN-RIGHT")) ((equal? max-score tf-score) (begin (set! left-corner '()) (set! right-corner (get-location percepts 1 1)) "TURN-LEFT")) ((equal? max-score ta-score) (let ((temp-left left-corner)) (begin (set! left-corner right-corner) (set! right-corner temp-left) "TURN-AROUND"))) ((equal? max-score mp1-score) (begin (set! left-corner (get-location percepts -1 1)) (set! right-corner (get-location percepts 1 1)) "MOVE-PASSIVE-1")) ((equal? max-score mp2-score) (begin (set! left-corner (get-location percepts -1 2)) (set! right-corner (get-location percepts 1 2)) "MOVE-PASSIVE-2")) ((equal? max-score mp3-score) (begin (set! left-corner (get-location percepts -1 3)) (set! right-corner (get-location percepts 1 3)) "MOVE-PASSIVE-3")) ((equal? max-score ma1-score) (begin (set! left-corner (get-location percepts -1 1)) (set! right-corner (get-location percepts 1 1)) "MOVE-AGGRESSIVE-1")) ((equal? max-score ma2-score) (begin (set! left-corner (get-location percepts -1 2)) (set! right-corner (get-location percepts 1 2)) "MOVE-AGGRESSIVE-2")) ((equal? max-score ma3-score) (begin (set! left-corner (get-location percepts -1 3)) (set! right-corner (get-location percepts 1 3)) "MOVE-AGGRESSIVE-3")) ((equal? max-score ep-score) "EAT-PASSIVE") ((equal? max-score ea-score) "EAT-AGGRESSIVE") (#f "STAY"))))
false
53c46c3833e193a590c0be56094cfeeee9501c66
f5083e14d7e451225c8590cc6aabe68fac63ffbd
/cs/01-Programming/cs61a/course/reader/logo.scm
d957e7fadfad5d9c72aa6720b9a62c58551fa6a7
[]
no_license
Phantas0s/playground
a362653a8feb7acd68a7637334068cde0fe9d32e
c84ec0410a43c84a63dc5093e1c214a0f102edae
refs/heads/master
2022-05-09T06:33:25.625750
2022-04-19T14:57:28
2022-04-19T14:57:28
136,804,123
19
5
null
2021-03-04T14:21:07
2018-06-10T11:46:19
Racket
UTF-8
Scheme
false
false
5,577
scm
logo.scm
;;; logo.scm part of programming project #4 ;;; Problem A1 make-line-obj (define (make-line-obj text) (error "make-line-obj not written yet!")) ;;; Problem A2 logo-type (define (logo-type val) (error "logo-type not written yet!")) (define (logo-print val) (logo-type val) (newline) '=no-value=) (define (logo-show val) (logo-print (list val))) ;;; Problem 4 variables (logo-meta.scm is also affected) (define (make env var val) (error "make not written yet!") '=no-value=) ;;; Here are the primitives RUN, IF, and IFELSE. Problem B2 provides ;;; support for these, but you don't have to modify them. (define (run env exp) (eval-line (make-line-obj exp) env)) (define (logo-if env t/f exp) (cond ((eq? t/f 'true) (eval-line (make-line-obj exp) env)) ((eq? t/f 'false) '=no-value=) (else (error "Input to IF not true or false " t/f)))) (define (ifelse env t/f exp1 exp2) (cond ((eq? t/f 'true) (eval-line (make-line-obj exp1) env)) ((eq? t/f 'false) (eval-line (make-line-obj exp2) env)) (else (error "Input to IFELSE not true or false " t/f)))) ;;; Problem B2 logo-pred (define (logo-pred pred) pred) ;; This isn't written yet but we fake it for now. ;;; Here is an example of a Scheme predicate that will be turned into ;;; a Logo predicate by logo-pred: (define (equalp a b) (if (and (number? a) (number? b)) (= a b) (equal? a b))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Stuff below here is needed for the interpreter to work but you ;;; ;;; don't have to modify anything or understand how they work. ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The Logo reader (define left-paren-symbol (string->symbol (make-string 1 #\( ))) (define right-paren-symbol (string->symbol (make-string 1 #\) ))) (define quote-symbol (string->symbol (make-string 1 #\" ))) (define (logo-read) (define lookahead #f) (define (logo-read-help depth) (define (get-char) (if lookahead (let ((char lookahead)) (set! lookahead #f) char) (let ((char (read-char))) (if (eq? char #\\) (list (read-char)) char)))) (define (quoted char) (if (pair? char) char (list char))) (define (get-symbol char) (define (iter sofar char) (cond ((pair? char) (iter (cons (car char) sofar) (get-char))) ((memq char '(#\space #\newline #\+ #\- #\* #\/ #\= #\< #\> #\( #\) #\[ #\] )) (set! lookahead char) sofar) (else (iter (cons char sofar) (get-char))) )) (string->word (list->string (reverse (iter '() char)))) ) (define (get-token space-flag) (let ((char (get-char))) (cond ((eq? char #\space) (get-token #t)) ((memq char '(#\+ #\* #\/ #\= #\< #\> #\( #\) )) (string->symbol (make-string 1 char))) ((eq? char #\-) (if space-flag (let ((char (get-char))) (let ((result (if (eq? char #\space) '- '=unary-minus=))) (set! lookahead char) result)) '-)) ((eq? char #\[) (logo-read-help (+ depth 1))) ((pair? char) (get-symbol char)) ((eq? char #\") (let ((char (get-char))) (if (memq char '(#\[ #\] #\newline)) (begin (set! lookahead char) quote-symbol) (string->symbol (word quote-symbol (get-symbol (quoted char))))))) (else (get-symbol char)) ))) (define (after-space) (let ((char (get-char))) (if (eq? char #\space) (after-space) char))) (let ((char (get-char))) (cond ((eq? char #\newline) (if (> depth 0) (set! lookahead char)) '()) ((eq? char #\space) (let ((char (after-space))) (cond ((eq? char #\newline) (begin (if (> depth 0) (set! lookahead char)) '())) ((eq? char #\]) (if (> depth 0) '() (error "Unexpected ]"))) (else (set! lookahead char) (let ((token (get-token #t))) (cons token (logo-read-help depth))))))) ((eq? char #\]) (if (> depth 0) '() (error "Unexpected ]"))) ((eof-object? char) char) (else (set! lookahead char) (let ((token (get-token #f))) (cons token (logo-read-help depth)) ))))) (logo-read-help 0)) ;;; Assorted stuff (define (make-logo-arith op) (lambda args (apply op (map maybe-num args)))) (define (maybe-num val) (if (word? val) (string->word (word->string val)) val)) (define tty-port (current-input-port)) (define (prompt string) (if (eq? (current-input-port) tty-port) (begin (display string) (flush)))) (define (meta-load fn) (define (loader) (let ((exp (logo-read))) (if (eof-object? exp) '() (begin (eval-line (make-line-obj exp) the-global-environment) (loader))))) (with-input-from-file (symbol->string fn) loader) '=no-value=)
false
96e5edfa6cb2115670e63a130e8ff830ebed74da
a7ac0478e702b487d7df3b4c0c8169de05859b10
/example03-buffersrc.scm
ab21e126a5d757f795cad2ac1f7b34da6b61cd74
[]
no_license
kristianlm/chicken-ffmpeg
621b12671e2acc771788abdc6498f3295b76c680
d12998fee26d597dde248d8949a5d4329bd379e3
refs/heads/master
2021-04-25T07:54:45.632116
2018-06-12T13:27:21
2018-06-12T13:27:21
122,211,369
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,044
scm
example03-buffersrc.scm
(use ffmpeg) (begin (define fg (make-flg)) (define in (make-flx fg "buffer" "in" "video_size=16x16:pix_fmt=gray8:time_base=1/1:pixel_aspect=1/1")) (define scale (make-flx fg "scale" "scale" "8x8")) (define out (make-flx fg "buffersink" "out")) (avfilter-link in 0 scale 0) (avfilter-link scale 0 out 0) (avfilter-graph-config fg)) (begin (define frame (make-frame width: 16 height: 16 format: 'gray8)) (frame-get-buffer frame 32) (frame-make-writable frame) ;; TODO: implement frame-data-set! (av-buffersrc-add-frame in frame)) (begin (define png (make-codecx (find-encoder "png") width: 8 height: 8 pix-fmt: 'gray8 time-base: (vector 1 1))) (avcodec-open png #f) (define frame (av-buffersink-get-frame out)) (print "got frame " frame) (avcodec-send-frame png frame) (define pkt (avcodec-receive-packet png)) (with-output-to-file "/tmp/out.png" (lambda () (display (blob->string (u8vector->blob/shared (packet-data pkt)))))))
false
ebaad0ac51acf5d1cd856069b47e2e8384fb5a94
08d40276b8048e4d6f24de5c49f286d2a30ea006
/clos/std-protocols/initialize.sc
9213d6b56581e212384ddb36412df3d49979a9e8
[]
no_license
theschemer/clos
9261911ddef62d85652fd14dc86b6f1f449a9394
da7ca347a140fa3d7e2a7b187e47b749dc9e3cd4
refs/heads/master
2018-12-05T21:30:27.486069
2018-09-11T19:46:15
2018-09-11T19:46:15
115,925,034
13
5
null
2018-01-01T14:41:31
2018-01-01T14:41:31
null
UTF-8
Scheme
false
false
4,326
sc
initialize.sc
; ************************************************************************* ; Copyright (c) 1992 Xerox Corporation. ; All Rights Reserved. ; ; Use, reproduction, and preparation of derivative works are permitted. ; Any copy of this software or of any derivative work must include the ; above copyright notice of Xerox Corporation, this paragraph and the ; one after it. Any distribution of this software or derivative works ; must comply with all applicable United States export control laws. ; ; This software is made available AS IS, and XEROX CORPORATION DISCLAIMS ; ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE ; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ; PURPOSE, AND NOTWITHSTANDING ANY OTHER PROVISION CONTAINED HEREIN, ANY ; LIABILITY FOR DAMAGES RESULTING FROM THE SOFTWARE OR ITS USE IS ; EXPRESSLY DISCLAIMED, WHETHER ARISING IN CONTRACT, TORT (INCLUDING ; NEGLIGENCE) OR STRICT LIABILITY, EVEN IF XEROX CORPORATION IS ADVISED ; OF THE POSSIBILITY OF SUCH DAMAGES. ; ************************************************************************* ; ; port to R6RS -- 2007 Christian Sloma ; (library (clos std-protocols initialize) (export class-initialize generic-initialize method-initialize) (import (only (rnrs) define quote map lambda if list? list let* reverse cons car let set! + error) (clos private allocation) (clos private compat) (clos slot-access)) (define (class-initialize class-inst init-args compute-precedence-list compute-slots compute-getter-and-setter) (slot-set! class-inst 'direct-supers (get-arg 'direct-supers init-args)) (slot-set! class-inst 'direct-slots (map (lambda (slot) (if (list? slot) slot (list slot))) (get-arg 'direct-slots init-args))) (slot-set! class-inst 'definition-name (get-arg 'definition-name init-args #f)) (slot-set! class-inst 'precedence-list (compute-precedence-list class-inst)) (slot-set! class-inst 'slots (compute-slots class-inst)) (let* ((field-count 0) (field-inits '()) (allocator (lambda (init-fn) (let ((idx field-count)) (set! field-count (+ field-count 1)) (set! field-inits (cons init-fn field-inits)) (list (lambda (inst) (instance-ref inst idx)) (lambda (inst val) (instance-set! inst idx val)))))) (getters-and-setters (map (lambda (slot) (cons (car slot) (compute-getter-and-setter class-inst slot allocator))) (slot-ref class-inst 'slots)))) (slot-set! class-inst 'number-of-fields field-count) (slot-set! class-inst 'field-initializers (reverse field-inits)) (slot-set! class-inst 'getters-and-setters getters-and-setters))) (define (generic-initialize generic-inst init-args) (slot-set! generic-inst 'methods '()) (set-entity-print-name! generic-inst (get-arg 'definition-name init-args #f)) (set-instance-proc! generic-inst (lambda args (error 'generic "generic called without method installed")))) (define (method-initialize meth-inst init-args) (slot-set! meth-inst 'specializers (get-arg 'specializers init-args)) (slot-set! meth-inst 'qualifier (get-arg 'qualifier init-args 'primary)) (slot-set! meth-inst 'procedure (get-arg 'procedure init-args))) ) ;; library (clos std-protocols initialize)
false
9f0e031d41fa2d6658c0dc1b8747c80cbc52d9ba
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/sasm/parse/operand.scm
089949edd47d5a0b818c93ac69cea4272c14affd
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
1,180
scm
operand.scm
(need sasm/parse/syntax) (need sasm/sasm-ast) (define (sasm-parse-operand expression) (sasm-parse-by-case expression (sasm-syntax-case :pattern (?? ,sasm-parse-lvalue-operand operand) :rewrite (operand) operand) (sasm-syntax-case :pattern (?? ,sasm-parse-constant-operand constant) :rewrite (constant) constant) (sasm-syntax-case :pattern (label (,symbol? symbol-name)) :rewrite (symbol-name) (sasm-ast-node <label-constant-operand> (:label-value symbol-name) (:referenced-symbol symbol-name) (:resolved-symbol #f))) (sasm-syntax-case :pattern (result . (?? ,sasm-parse-operation operation)) :rewrite (operation) (sasm-ast-node <nested-operation-operand> (:operation operation))) (sasm-syntax-case :pattern (symconst (,symbol? symconst-name)) :rewrite (symconst-name) (sasm-ast-node <symbolic-constant-operand> (:symconst-name symconst-name) (:referenced-symconst-symbol symconst-name) (:resolved-symconst #f))) ))
false
85634a0ac56dd1dba3b5f22b33b37c86725248df
b83ef8d27287a1a6655a2e8e6f37ca2daf5820b7
/examples/gtk/gtk-hello.scm
6e0fc1b352802702c03f56464c38e059fe509492
[ "MIT" ]
permissive
Hamayama/c-wrapper-mg
5fd8360bb83bbf6a3452c46666bd549a3042da1f
d011d99dbed06f2b25c016352f41f8b29badcb1a
refs/heads/master
2021-01-18T22:43:46.179694
2020-11-10T12:05:38
2020-11-10T12:37:30
23,728,504
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,373
scm
gtk-hello.scm
(use c-wrapper) (c-load "gtk/gtk.h" :cppflags-cmd "pkg-config gtk+-2.0 --cflags-only-I" :cflags-cmd "pkg-config gtk+-2.0 --cflags-only-other" :libs-cmd "pkg-config gtk+-2.0 --libs" :import '(gtk_init gtk_window_new GTK_WINDOW_TOPLEVEL gtk_signal_connect gtk_main_quit gtk_container_set_border_width gtk_button_new_with_label gtk_container_add gtk_widget_show gtk_main NULL) ;; :import '(#/^gtk_/i NULL) :compiled-lib "gtklib") (define (main args) (let ((argc (make <c-int>))) (gtk_init (ptr argc) (make-null-ptr))) (let1 window (gtk_window_new GTK_WINDOW_TOPLEVEL) (gtk_signal_connect window "destroy" (lambda _ (format #t "Destroying\n") (gtk_main_quit) NULL) (make-null-ptr)) (gtk_container_set_border_width window 10) (let1 button (gtk_button_new_with_label "Hello world") (gtk_signal_connect button "clicked" (lambda _ (format #t "Hello world\n") NULL) (make-null-ptr)) (gtk_container_add window button) (gtk_widget_show button) (gtk_widget_show window) )) (gtk_main) 0)
false
23cbf2bfff4f11a0fe77cf17c1ba2fe811ea650f
f59b3ca0463fed14792de2445de7eaaf66138946
/section-5/5_22.scm
bdf9e2a5d196c3dba172403ad2b6f4d61848aaf8
[]
no_license
uryu1994/sicp
f903db275f6f8c2da0a6c0d9a90c0c1cf8b1e718
b14c728bc3351814ff99ace3b8312a651f788e6c
refs/heads/master
2020-04-12T01:34:28.289074
2018-06-26T15:17:06
2018-06-26T15:17:06
58,478,460
0
1
null
2018-06-20T11:32:33
2016-05-10T16:53:00
Scheme
UTF-8
Scheme
false
false
1,831
scm
5_22.scm
(load "./register") (define (append x y) (if (null? x) y (cons (car x) (append (cdr x) y)))) (define append-machine (make-machine '(continue x y x-tmp result) (list (list 'null? null?) (list 'cons cons) (list 'car car) (list 'cdr cdr)) '(controller (assign continue (label done)) append-loop (test (op null?) (reg x)) (branch (label append-null)) (save continue) (assign continue (label after-append)) (save x) (assign x (op cdr) (reg x)) (goto (label append-loop)) append-null (assign result (reg y)) (goto (reg continue)) after-append (restore x) (restore continue) (assign x-tmp (op car) (reg x)) (assign result (op cons) (reg x-tmp) (reg result)) (goto (reg continue)) done))) (set-register-contents! append-machine 'x '(1 2)) (set-register-contents! append-machine 'y '(3 4)) (start append-machine) (print (get-register-contents append-machine 'result)) (define (append! x y) (set-cdr! (last-pair x) y) x) (define (last-pair x) (if (null? (cdr x)) x (last-pair (cdr x)))) (define append!-machine (make-machine '(continue x y cdr-tmp) (list (list 'null? null?) (list 'set-cdr! set-cdr!) (list 'cdr cdr)) '(controller (assign continue (label append!-done)) (save x) last-pair (assign cdr-tmp (op cdr) (reg x)) (test (op null?) (reg cdr-tmp)) (branch (label pair-null)) (assign x (op cdr) (reg x)) (goto (label last-pair)) pair-null (assign x (op set-cdr!) (reg x) (reg y)) (goto (reg continue)) append!-done (restore x) ))) (set-register-contents! append!-machine 'x '(1 2)) (set-register-contents! append!-machine 'y '(3 4)) (start append!-machine) (print (get-register-contents append!-machine 'x))
false
0a1bd11ef4eb455ee3df3338e8b882c3aa7f1356
bf317e4573c4b7d0dad3ece436c55c26bd282caf
/ext/crypto/math/ec.scm
55823e01191ae53456edbd9399b4292c44cd158d
[ "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
permissive
wolfhesse/sagittarius-scheme
6c44693402cf360bae0309cfcd0fcc351bfc0471
74744751250330ef5d99ac2b3cc83b9ee0e2654b
refs/heads/master
2021-01-12T04:11:25.875532
2016-12-27T09:32:28
2016-12-27T09:32:28
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
8,560
scm
ec.scm
;;; -*- mode: scheme; coding: utf-8 -*- ;;; ;;; ec.scm - Elliptic curve ;;; ;; this library provides 3 things ;; - curve parameters ;; - constructors (ec point and curve) ;; - and arithmetic procedure for ec points ;; ;; there are 2 curves used, one is Fp and other one is F2m. ;; Fp is ;; y^2 = x^3 + ax + b (mod p) ;; F2m is ;; y^2 + xy = x^3 + ax^2 + b (mod p) #!core (library (math ec) (export make-ec-point ec-point-add ec-point-twice ec-point-negate ec-point-sub ec-point-mul ;; NIST parameters P-192 P-224 ec-parameter? ec-parameter-curve ) (import (core) (core base) (core errors) (core syntax) (core inline) (sagittarius)) ;; modular arithmetic ;; these are needed on for Fp ;; a + b (mod p) (define (mod-add a b p) (mod (+ a b) p)) ;; a - b (mod p) (define (mod-sub a b p) (mod (- a b) p)) ;; a * b (mod p) (define (mod-mul a b p) (mod (* a b) p)) ;; a / b (mod p) (define (mod-div a b p) (mod (* a (mod-inverse b p)) p)) ;; a^2 (mod p) (define (mod-square a p) (mod-expt a 2 p)) ;; -a (mod p) (define (mod-negate a p) (mod (- a) p)) ;; mod-inverse is defined in (sagittarius) ;; mod-expt is defined in (sagittarius) ;; to make constant foldable, we use vectors to represent ;; data structure ;;; ;; EC Curve ;; curve is a vector which contains type and parameters ;; for the curve. ;; make my life easier (define-syntax define-vector-type (lambda (x) (define (order-args args fs) (map (lambda (a) (cond ((memp (lambda (f) (bound-identifier=? a f)) fs) => car) (else (syntax-violation 'define-vector-type "unknown tag" a)))) args)) (define (generate-accessor k acc) ;; starting from 1 because 0 is type tag (let loop ((r '()) (i 1) (acc acc)) (syntax-case acc () ((name rest ...) (with-syntax ((n (datum->syntax k i))) (loop (cons #'(define (name o) (vector-ref o n)) r) (+ i 1) #'(rest ...)))) (() r)))) (syntax-case x () ((k type (ctr args ...) pred (field accessor) ...) (and (identifier? #'pred) (identifier? #'type) (identifier? #'ctr)) (with-syntax (((ordered-args ...) (order-args #'(args ...) #'(field ...))) ((acc ...) (generate-accessor #'k #'(accessor ...)))) #'(begin (define (ctr args ...) (vector 'type ordered-args ...)) (define (pred o) (and (vector? o) (= (vector-length o) (+ (length #'(field ...)) 1)) (eq? (vector-ref o 0) 'type))) acc ...)))))) (define-vector-type fp-curve (make-fp-curve q a b) fp-curve? (q fp-curve-q) (a fp-curve-a) (b fp-curve-b)) ;; Fp curve ;;(define (make-fp-curve q a b) (vector 'fp q a b)) ;; TODO F2m curve (define (make-f2m-curve m k1 k2 k3 a b n h) (error 'make-f2m-curve "not supported yet")) (define (%curve? o type) (and (vector? o) (not (zero? (vector-length o))) (eq? (curve-type o) type))) (define (f2m-curve? o) (%curve? o 'f2m)) (define (ec-curve=? a b) (equal? a b)) ;; EC point (define-vector-type ec-point (make-ec-point curve x y) %ec-point? (curve ec-point-curve) (x ec-point-x) (y ec-point-y)) (define (infinity-point curve) (make-ec-point curve #f #f)) ;; we don't check x and y, these can be #f for infinite point (define (ec-point? o) (and (%ec-point? o) (ec-point-curve o))) (define (ec-point-infinity? p) (or (not (ec-point-x p)) (not (ec-point-y p)))) (define (ec-point=? a b) (equal? a b)) (define (ec-point-twice x) (define (fp-ec-point-twice x) (let* ((xx (ec-point-x x)) (xy (ec-point-y x)) (curve (ec-point-curve x)) (p (fp-curve-q curve)) ;; gamma = ((xx^2)*3 + curve.a)/(xy*2) (gamma (mod-div (mod-add (mod-mul (mod-square xx p) 3 p) (fp-curve-a curve) p) (mod-mul xy 2 p) p)) ;; x3 = gamma^2 - x*2 (x3 (mod-sub (mod-square gamma p) (mod-mul xx 2 p) p)) ;; y3 = gamma*(xx - x3) - xy (y3 (mod-sub (mod-mul gamma (mod-sub xx x3 p) p) xy p))) (make-ec-point curve x3 y3))) (define (f2m-ec-point-twice x) (error 'ec-point-twice "not supported yet" x)) (cond ((ec-point-infinity? x) x) ((zero? (ec-point-y x)) (infinity-point (ec-point-curve x))) (else (if (fp-curve? (ec-point-curve x)) (fp-ec-point-twice x) (f2m-ec-point-twice x))))) (define (ec-point-add x y) (define (fp-ec-point-add x y) (let* ((xx (ec-point-x x)) (xy (ec-point-y x)) (yx (ec-point-x y)) (yy (ec-point-y y)) (curve (ec-point-curve y)) ;; if the curve are the same then p are the same (p (fp-curve-q curve)) ;; gamma = (yy - xy)/(yx-xx) (gamma (mod-div (mod-sub yy xy p) (mod-sub yx xx p) p)) ;; x3 = gamma^2 - xx - yx (x3 (mod-sub (mod-sub (mod-square gamma p) xx p) yx p)) ;; y3 = gamma*(xx - x3) - xy (y3 (mod-sub (mod-mul gamma (mod-sub xx x3 p) p) xy p))) (make-ec-point curve x3 y3))) (define (f2m-ec-point-add x y) (error 'ec-point-add "not supported yet" x y)) (cond ((not (ec-curve=? (ec-point-curve x) (ec-point-curve y))) (error 'ec-point-add "attempt to adding differenct curve point" x y)) ((ec-point-infinity? x) y) ((ec-point-infinity? y) x) ((= (ec-point-x x) (ec-point-x y)) (if (= (ec-point-y x) (ec-point-y y)) (ec-point-twice x) (infinity-point (ec-point-curve x)))) (else (if (fp-curve? (ec-point-curve x)) (fp-ec-point-add x y) (f2m-ec-point-add x y))))) (define (ec-point-negate x) (let ((curve (ec-point-curve x))) (if (fp-curve? curve) (make-ec-point curve (ec-point-x x) (mod-negate (ec-point-y x) (fp-curve-q curve))) (error 'ec-point-negate "not supported yet")))) (define (ec-point-sub x y) (cond ((not (ec-curve=? (ec-point-curve x) (ec-point-curve y))) (error 'ec-point-add "attempt to adding differenct curve point" x y)) ((ec-point-infinity? y) x) (else ;; add -y (ec-point-add x (ec-point-negate y))))) ;; http://en.wikipedia.org/wiki/Non-adjacent_form ;; this is probably super slow but for now... (define (ec-point-mul p k) (unless (integer? k) (error 'ec-point-mul "integer required for k" k)) (let ((h (* k 3)) (neg (ec-point-negate p))) (let loop ((R p) (i (- (bitwise-length h) 2))) (if (zero? i) R (let ((R (ec-point-twice R)) (hbit? (bitwise-bit-set? h i))) (if (eqv? hbit? (bitwise-bit-set? k i)) (loop R (- i 1)) (loop (ec-point-add R (if hbit? p neg)) (- i 1)))))))) ;;;; ;;; Parameters ;; Parameter contains followings ;; - curve ;; - base point x y (as ec-point) ;; - Order q of the point G (and of the elliptic curve group E) ;; - h = (l - 1) / 160 where l is bit length of prime p ;; - seed (define (ec-parameter? o) (and (vector? o) (= (vector-length o) 6) (eq? (vector-ref o 0) 'ec-parameter))) (define (ec-parameter-curve o) (vector-ref o 1)) ;; from https://www.nsa.gov/ia/_files/nist-routines.pdf ;; http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf (define-constant P-192 (let ((curve (make-fp-curve #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC #x64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1))) `#(ec-parameter ,curve ,(make-ec-point curve #x188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012 #x07192B95FFC8DA78631011ED6B24CDD573F977A11E794811) #xFFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831 1 ;; (div (- 192 1) 160) ;;3045AE6FC8422F64ED579528D38120EAE12196D5 #vu8(#x30 #x45 #xAE #x6F #xC8 #x42 #x2F #x64 #xED #x57 #x95 #x28 #xD3 #x81 #x20 #xEA #xE1 #x21 #x96 #xD5)))) (define-constant P-224 (let ((curve (make-fp-curve #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001 #xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE #xB4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4))) `#(ec-parameter ,curve ,(make-ec-point curve #xB70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21 #xBD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34) #xFFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D 1 ;; (div (- 224 1) 160) ;; BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5 #vu8(#xBD #x71 #x34 #x47 #x99 #xD5 #xC7 #xFC #xDC #x45 #xB5 #x9F #xA3 #xB9 #xAB #x8F #x6A #x94 #x8B #xC5)))) )
true
cb428c2cb86e60390b1efdbdb1482d7f525f68df
b8eb3fdd0e4e38a696c4013a8f91054df3f75833
/scheme/strlib.ss
8a29273a00988c53bb5f469b65a24e5803d133f2
[ "Zlib" ]
permissive
lojikil/digamma
952a7bdf176227bf82b3583020bc41764b12d906
61c7ffdc501f207a84e5d47157c3c84e5882fa0d
refs/heads/master
2020-05-30T07:11:20.716792
2016-05-11T11:32:15
2016-05-11T11:32:15
58,539,277
6
3
null
null
null
null
UTF-8
Scheme
false
false
1,445
ss
strlib.ss
;; The begining of a string library ;; to be 100% honest, this actually would work with most types ;; of sequences, so long as the elements can be eq?'d effectively (def (in-string? c str (start 0)) (if (>= start (length str)) #f (if (eq? c (nth str start)) #t (in-string? c str (+ start 1))))) (def (string-split-charset str sepset (start 0) (offset 0)) (cond (>= offset (length str)) (cons (cslice str start offset) '()) (in-string? (nth str offset) sepset) (cons (cslice str start offset) (string-split-charset str sepset (+ offset 1) (+ offset 1))) else (string-split-charset str sepset start (+ offset 1)))) (def (string-join l i (acc '())) (if (empty? (cdr l)) (apply string-append (append acc (list (car l)))) (string-join (cdr l) i (append acc (list (car l) i))))) (def (string-reverse s offset nu ) (cond (< offset 0) (begin (display (format "nu == ~a\n" nu)) (if (eq? nu '()) (display "nu is null\n") (display "nu isn't null\n")) (list nu)) (>= offset (length s)) (begin (display "in offset overflow\n") s) (eq? nu '()) (begin (display "In nu init\n") (string-reverse s (- (length s) 1) (make-string (length s)))) else (begin (display (format "In begin; offset == ~a; nu == ~a\n" offset nu)) (cset! nu offset (nth s offset)) (string-reverse s (- offset 1) nu))))
false
a2ea7807a954a6c13ee4839fa211796f4b4061e4
4f17c70ae149426a60a9278c132d5be187329422
/scheme/r6rs/hashtables.ss
b85340ead43cb0dc4b59964bb85e1437799d6095
[]
no_license
okuoku/yuni-core
8da5e60b2538c79ae0f9d3836740c54d904e0da4
c709d7967bcf856bdbfa637f771652feb1d92625
refs/heads/master
2020-04-05T23:41:09.435685
2011-01-12T15:54:23
2011-01-12T15:54:23
889,749
2
0
null
null
null
null
UTF-8
Scheme
false
false
455
ss
hashtables.ss
(library (yuni scheme r6rs hashtables) (export make-eq-hashtable make-eqv-hashtable make-hashtable hashtable? hashtable-size hashtable-ref hashtable-set! hashtable-delete! hashtable-contains? hashtable-update! hashtable-copy hashtable-clear! hashtable-keys hashtable-entries hashtable-equivalence-function hashtable-hash-function hashtable-mutable? equal-hash string-hash string-ci-hash symbol-hash) (import (yuni scheme r6rs)))
false
6bd4f4921316ef1f76e8b782a3f2acc3e25550b1
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch3/exercise3-65.scm
54f5ff63c65bcf03d571fdc71dd7c8073610e99a
[]
no_license
da1/sicp
a7eacd10d25e5a1a034c57247755d531335ff8c7
0c408ace7af48ef3256330c8965a2b23ba948007
refs/heads/master
2021-01-20T11:57:47.202301
2014-02-16T08:57:55
2014-02-16T08:57:55
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
379
scm
exercise3-65.scm
;; 問題3.65 (load "./ch3/3-5-3_Exploiting_the_Stream_Paradigm.scm") (define (log-summands n) (cons-stream (/ 1.0 n) (stream-map - (log-summands (+ n 1))))) (define log-stream (partial-sums (log-summands 1))) (show-stream log-stream 0 10) (show-stream (euler-transform log-stream) 0 10) (show-stream (accelerate-sequence euler-transform log-stream) 0 10)
false
b4a2c378a464594f2621d22b2c8cf068509c6aec
6e359a216e1e435de5d39bc64e75998945940a8c
/productiter.scm
924a59031dda401c04d14bf03054c07ea51e111c
[]
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
176
scm
productiter.scm
(define (product term a next b) (define (product-iter a b result) (if (> a b) result (product-iter (next a) b (* (term a) result)))) (product-iter a b 1))
false
afc1ee60a9d69b5ed4c913d1db78e36609d962c7
5dfe2cdb9e9b80915a878154093bf073df904bf0
/chap25.scm
6f12255f29c537e7fb09bc9f7986ba7f6837e066
[]
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
30,056
scm
chap25.scm
(define (attach-tag type-tag contents) (cond ((number? contents) contents) (else (cons type-tag contents)))) (define (type-tag datum) (cond ((number? datum) 'scheme-number) ((pair? datum) (car datum)) (else (error "Bad tagged datum: TYPE-TAG" datum)))) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cdr datum)) (else (error "Bad tagged datum: CONTENTS" datum)))) (define name-list '()) (define (make-sig op tags) (list op tags)) (define (sig-op sig) (car sig)) (define (sig-tags sig) (cadr sig)) (define (make-fn-entry sig fn) (list sig fn)) (define (fn-entry-sig entry) (car entry)) (define (fn-entry-fn entry) (cadr entry)) (define (get op tags) (define (get-helper sig name-list) (if (null? name-list) #f (if (equal? (fn-entry-sig (car name-list)) sig) (fn-entry-fn (car name-list)) (get-helper sig (cdr name-list))))) (get-helper (make-sig op tags) name-list)) (define (put op tags fn) ; Constructs a new name-table with the fn included (define (put-helper sig name-list) (cond ((null? name-list) (list (make-fn-entry (make-sig op tags) fn))) ((equal? sig (fn-entry-sig (car name-list))) (cons (make-fn-entry sig fn) (cdr name-list))) (else (cons (car name-list) (put-helper sig (cdr name-list)))))) (set! name-list (put-helper (make-sig op tags) name-list))) (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 (add x y) (apply-generic 'add x y)) (define (sub x y) (apply-generic 'sub x y)) (define (mul x y) (apply-generic 'mul x y)) (define (div x y) (apply-generic 'div x y)) (define (equ? x y) (apply-generic 'equ? x y)) (define (=zero? x) (apply-generic '=zero? x)) (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (= x y))) (put '=zero? '(scheme-number) (lambda (x) (= x 0))) (put 'negate '(scheme-number) (lambda (x) (- x))) (put 'make 'scheme-number (lambda (x) (tag x))) 'done) (install-scheme-number-package) (define (make-scheme-number n) ((get 'make 'scheme-number) n)) (define (install-integer-package) ; Defined as a list to avoid casting reals to integers (define (make-int x) (list (floor x))) (define (int-value x) (car x)) (define (tag x) (attach-tag 'integer x)) (put 'add '(integer integer) (lambda (x y) (make-int (+ (int-value x) (int-value y))))) (put 'sub '(integer integer) (lambda (x y) (make-int (- (int-value x) (int-value y))))) (put 'mul '(integer integer) (lambda (x y) (make-int (* (int-value x) (int-value y))))) (put 'div '(integer integer) (lambda (x y) (make-int (floor (/ (int-value x) (int-value y)))))) (put 'equ? '(integer integer) (lambda (x y) (= (int-value x) (int-value y)))) (put '=zero? '(integer) (lambda (x) (= (int-value x) (make-int 0)))) (put 'negate '(integer) (lambda (x) (make-int (- (value x))))) (put 'make 'integer (lambda (x) (tag (make-int x)))) (put 'value 'integer (lambda (x) (int-value x))) 'done) (install-integer-package) (define (make-integer n) ((get 'make 'integer) n)) (define (value x) ((get 'value 'integer) x)) (define (install-rational-package) ;; internal procedures (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (equ?-rat x y) (and (= (numer x) (numer y)) (= (denom x) (denom y)))) (define (=zero? x) (= (numer x) 0)) ;; interface to rest of the system (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'equ? '(rational rational) (lambda (x y) (equ?-rat x y))) (put '=zero? '(rational) (lambda (x) (=zero? x))) (put 'negate '(rational) (lambda (x) (tag (make-rat (- (numer x)) (denom x))))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put 'numer 'rational numer) (put 'denom 'rational denom) 'done) (install-rational-package) (define (make-rational n d) ((get 'make 'rational) n d)) (define (install-rectangular-package) ;; internal procedures (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)))) ;; interface to the rest of the system (define (tag x) (attach-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) (install-rectangular-package) (define (install-polar-package) ;; internal procedures (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))) ;; interface to the rest of the system (define (tag x) (attach-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) (install-polar-package) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) (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 (install-complex-package) ;; imported procedures from rectangular ;; and polar packages (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) ;; internal procedures (define (add-complex z1 z2) (make-from-real-imag (+ (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)))) (define (equ?-complex z1 z2) (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2)))) (define (=zero?-complex z) ; Could probably just use equ?-complex here. (and (= (real-part z) 0) (= (imag-part z) 0))) (define (negate-complex z) (make-from-real-imag (- (real-part z)) (- (imag-part z)))) ;; interface to rest of the system (define (tag z) (attach-tag 'complex z)) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'equ? '(complex complex) (lambda (z1 z2) (equ?-complex z1 z2))) (put '=zero? '(complex) (lambda (x) (=zero?-complex x))) (put 'negate '(complex) (lambda (x) (negate-complex x))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'real-part '(complex) real-part) (put 'imag-part '(complex) imag-part) (put 'magnitude '(complex) magnitude) (put 'angle '(complex) angle) 'done) (install-complex-package) (define (make-complex-from-real-imag x y) ((get 'make-from-real-imag 'complex) x y)) (define (make-complex-from-mag-ang r a) ((get 'make-from-mag-ang 'complex) r a)) ; Being tricksy and reusing the global table. (define (put-coercion from to fn) (put to from fn)) (define (get-coercion from to) (get to from)) (put-coercion 'scheme-number 'rational (lambda (int) (make-rational (contents int) 1))) ; Coercing version, 2.81 (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)) (if (= (length args) 2) (let ((type1 (car type-tags)) (type2 (cadr type-tags)) (a1 (car args)) (a2 (cadr args))) (if (not (= type1 type2)) (let ((t1->t2 (get-coercion type1 type2)) (t2->t1 (get-coercion type2 type1))) (cond (t1->t2 (apply-generic op (t1->t2 a1) a2)) (t2->t1 (apply-generic op a1 (t2->t1 a2))) (else (error "No method for these types" (list op type-tags))))) (error "No method for these types" (list op type-tags)))) (error "No method for these types" (list op type-tags))))))) (define (all x) (cond ((null? x) #t) ((car x) (all (cdr x))) (else #f))) ; Coercing version, 2.82 (define (get-coercions type-tags to-type) (let ((coercions (map (lambda (from-type) (if (eq? from-type to-type) (lambda (x) x) (get-coercion from-type to-type))) type-tags))) (if (all coercions) coercions #f))) (define (apply-coercions coercions args) (if (null? coercions) '() (cons ((car coercions) (car args)) (apply-coercions (cdr coercions) (cdr args))))) (define (repeat x n) (cond ((< n 1) '()) (else (cons x (repeat x (- n 1)))))) (define (apply-generic op . args) (define (try-coercions type-tags to-try) (if (null? to-try) (error "No method for these types" (list op type-tags)) (let ((coercions (get-coercions type-tags (car to-try)))) (if coercions (let ((proc (get op (repeat (car to-try) (length args))))) (if proc (apply proc (map contents (apply-coercions coercions args))) (try-coercions type-tags (cdr to-try)))) (try-coercions type-tags (cdr to-try)))))) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (try-coercions type-tags type-tags))))) ; 2.83 (define (install-raise-package) (put 'raise '(integer) (lambda (x) (make-rational (value x) 1))) (put 'raise '(rational) (lambda (x) (make-scheme-number (/ (numer x) (denom x) 1.0)))) (put 'raise '(scheme-number) (lambda (x) (make-complex-from-real-imag x 0))) 'done) (install-raise-package) (define (raise x) (apply-generic 'raise x)) ; 2.84 (define (install-level-package) (put 'level 'integer 1.0) (put 'level 'rational 2.0) (put 'level 'scheme-number 3.0) (put 'level 'complex 4.0) (put 'level 'polynomial 5.0) 'done) (install-level-package) (define (level x) (get 'level (type-tag x))) (define (raise-to x target-level) (cond ((= (level x) target-level) x) ((< (level x) target-level) (raise-to (raise x) target-level)) (else (error "LEVEL IS ALREADY HIGHER" (list (level x) target-level))))) (define (apply-generic op . args) (define (apply-helper op args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (let ((levels (map level args))) (if (apply = levels) (error "No method for these types or raised: APPLY-GENERIC" (list op type-tags)) (let ((max-level (apply max levels))) (let ((raised-args (map (lambda (arg) (raise-to arg max-level)) args))) (apply-helper op raised-args))))))))) (apply-helper op args)) ;2.85 (define (install-project-package) (put 'project 'rational (lambda (x) (make-integer (floor (/ (numer x) (denom x)))))) (put 'project 'scheme-number (lambda (x) (make-rational (floor (* 1000000 x)) 1000000))) (put 'project 'complex (lambda (x) (real-part x))) 'done) (install-project-package) (define (drop x) (let ((project (get 'project (type-tag x)))) (if project (let ((projected (project (contents x)))) (if (equ? x (raise projected)) (drop projected) x)) x))) ;2.86 (define (square x) (mul x x)) (define (install-rectangular-package) ;; internal procedures (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) (square-root (add (square (real-part z)) (square (imag-part z))))) (define (angle z) (arctangent (imag-part z) (real-part z))) (define (make-from-mag-ang r a) (cons (mul r (cosine a)) (mul r (sine a)))) ;; interface to the rest of the system (define (tag x) (attach-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) (install-rectangular-package) (define (install-polar-package) ;; internal procedures (define (magnitude z) (car z)) (define (angle z) (cdr z)) (define (make-from-mag-ang r a) (cons r a)) ; Cosine and sine are defined below (define (real-part z) (mul (magnitude z) (cosine (angle z)))) (define (imag-part z) (mul (magnitude z) (sine (angle z)))) (define (make-from-real-imag x y) (cons (square-root (add (square x) (square y))) (arctangent y x))) ;; interface to the rest of the system (define (tag x) (attach-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) (install-polar-package) (define (install-trig-package) (put 'sin 'scheme-number (lambda (x) (sin x))) (put 'cos 'scheme-number (lambda (x) (cos x))) (put 'atan 'scheme-number (lambda (x y) (atan x y))) (put 'sqrt 'scheme-number (lambda (x) (sqrt x))) 'done) (install-trig-package) (define (sine x) ((get 'sin 'scheme-number) (raise-to x (level 0)))) (define (cosine x) ((get 'cos 'scheme-number) (raise-to x (level 0)))) (define (arctangent x y) ((get 'atan 'scheme-number) (raise-to x (level 0)) (raise-to y (level 0)))) (define (square-root x) ((get 'sqrt 'scheme-number) (raise-to x (level 0)))) ;2.5.3 (define (install-polynomial-package) ;; internal procedures ;; representation of poly (define (make-poly variable term-list) (cons variable term-list)) (define (variable p) (car p)) (define (term-list p) (cdr p)) (define (variable? x) (symbol? x)) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2))) (define (add-terms L1 L2) (cond ((empty-termlist? L1) L2) ((empty-termlist? L2) L1) (else (let ((t1 (first-term L1)) (t2 (first-term L2))) (cond ((> (order t1) (order t2)) (adjoin-term t1 (add-terms (rest-terms L1) L2))) ((< (order t1) (order t2)) (adjoin-term t2 (add-terms L1 (rest-terms L2)))) (else (adjoin-term (make-term (order t1) (add (coeff t1) (coeff t2))) (add-terms (rest-terms L1) (rest-terms L2))))))))) (define (add-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (add-terms (term-list p1) (term-list p2))) (error "Polys not in same var: ADD-POLY" (list p1 p2)))) (define (mul-terms L1 L2) (if (empty-termlist? L1) (the-empty-termlist) (add-terms (mul-term-by-all-terms (first-term L1) L2) (mul-terms (rest-terms L1) L2)))) (define (mul-term-by-all-terms t1 L) (if (empty-termlist? L) (the-empty-termlist) (let ((t2 (first-term L))) (adjoin-term (make-term (+ (order t1) (order t2)) (mul (coeff t1) (coeff t2))) (mul-term-by-all-terms t1 (rest-terms L)))))) (define (mul-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (mul-terms (term-list p1) (term-list p2))) (error "Polys not in same var: MUL-POLY" (list p1 p2)))) (define (div-term t1 t2) (make-term (- (order t1) (order t2)) (div (coeff t1) (coeff t2)))) (define (div-terms dividend-terms divisor-terms) (if (empty-termlist? dividend-terms) (list (the-empty-termlist) (the-empty-termlist)) (let ((dividend-first (first-term dividend-terms)) (divisor-first (first-term divisor-terms))) (if (< (order dividend-first) (order divisor-first)) (list (the-empty-termlist) dividend-terms) (let ((term-quotient (div-term dividend-first divisor-first))) (let ((new-dividend (sub-terms dividend-terms (mul-term-by-all-terms term-quotient divisor-terms)))) (let ((rest-of-result (div-terms new-dividend divisor-terms))) (list (adjoin-term term-quotient (car rest-of-result)) (cadr rest-of-result))))))))) (define (div-poly p1 p2) (cond ((not (same-variable? (variable p1) (variable p2))) (error "Polys not in same var: DIV-POLY" (list p1 p2))) ((=zero?-poly p2) (error "Divide by zero error.")) (else (make-poly (variable p1) (car (div-terms (term-list p1) (term-list p2))))))) (define (negate-terms terms) (if (empty-termlist? terms) (the-empty-termlist) (let ((term (first-term terms))) (adjoin-term (make-term (order term) (negate (coeff term))) (negate-terms (rest-terms terms)))))) (define (negate-poly p) (make-poly (variable p) (negate-terms (term-list p)))) (define (sub-terms L1 L2) (add-terms L1 (negate-terms L2))) (define (sub-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (sub-terms (term-list p1) (term-list p2))) (error "Polys not in same var: ADD-POLY" (list p1 p2)))) (define (=zero?-poly p) (empty-termlist? (term-list p))) (define (integerizing-factor p-terms q-terms) (let ((p-term (first-term p-terms)) (q-term (first-term q-terms))) (let ((c (coeff q-term)) (o-p (order p-term)) (o-q (order q-term))) ; c must be an integer (if (integer? c) (expt c (- (+ 1 o-p) o-q)) (error "TRIED TO INTEGERIZE NON-INT COEFF: " c))))) (define (gcd-terms t1 t2) (if (empty-termlist? t2) t1 (let ((factor-list (make-termlist (list (list 0 (integerizing-factor t1 t2)))))) (gcd-terms t2 (cadr (div-terms (mul-terms t1 factor-list) (mul-terms t2 factor-list))))))) (define (gcd-poly p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (gcd-terms (term-list p1) (term-list p2))) (error "Polys not in same var: GCD-POLY" (list p1 p2)))) ;; interface to rest of the system (define (tag p) (attach-tag 'polynomial p)) (put 'add '(polynomial polynomial) (lambda (p1 p2) (tag (add-poly p1 p2)))) (put 'sub '(polynomial polynomial) (lambda (p1 p2) (tag (sub-poly p1 p2)))) (put 'mul '(polynomial polynomial) (lambda (p1 p2) (tag (mul-poly p1 p2)))) (put 'div '(polynomial polynomial) (lambda (p1 p2) (tag (div-poly p1 p2)))) (put '=zero? '(polynomial) (lambda (p) (=zero?-poly p))) (put 'negate '(polynomial) (lambda (x) (tag (negate-poly x)))) (put 'greatest-common-divisor '(polynomial polynomial) (lambda (p1 p2) (tag (gcd-poly p1 p2)))) (put 'make 'polynomial (lambda (var terms) (tag (make-poly var terms)))) 'done) (install-polynomial-package) (define (make-polynomial var terms) ((get 'make 'polynomial) var terms)) ; 2.88, negate dispersed throughout (define (negate x) (apply-generic 'negate x)) ; 2.90 (define (install-dense-termlist-package) (define (adjoin-term term term-list) (define (add-zeroes lst num) (if (> num 0) (add-zeroes (cons 0 lst) (- num 1)) lst)) (if (=zero? (coeff term)) term-list (let ((delta (- (order term) (length term-list)))) (if (< delta 0) (error "Tried to adjoin a term with an order lower than highest order term.") (cons (coeff term) (add-zeroes term-list delta )))))) (define (the-empty-termlist) '()) (define (first-term term-list) (make-term (length (cdr term-list)) (car term-list))) (define (rest-terms term-list) (define (skip-zeroes lst) (cond ((null? lst) '()) ((=zero? (car lst)) (skip-zeroes (cdr lst))) (else lst))) (skip-zeroes (cdr term-list))) (define (empty-termlist? term-list) (null? term-list)) (define (tag term-list) (attach-tag 'dense-termlist term-list)) ; Public API (put 'adjoin-term-fn '(dense-termlist) (lambda (term-list) (lambda (term) (tag (adjoin-term term term-list))))) (put 'the-empty-termlist 'dense-termlist (lambda () (tag (the-empty-termlist)))) (put 'first-term '(dense-termlist) (lambda (term-list) (first-term term-list))) (put 'rest-terms '(dense-termlist) (lambda (term-list) (tag (rest-terms term-list)))) (put 'empty-termlist? '(dense-termlist) (lambda (term-list) (empty-termlist? term-list))) (put 'make 'dense-termlist (lambda (term-list) (tag term-list))) 'done) (install-dense-termlist-package) (define (install-sparse-termlist-package) (define (adjoin-term term term-list) (if (=zero? (coeff term)) term-list (cons term term-list))) (define (the-empty-termlist) '()) (define (first-term term-list) (car term-list)) (define (rest-terms term-list) (cdr term-list)) (define (empty-termlist? term-list) (null? term-list)) (define (make-term order coeff) (list order coeff)) (define (order term) (car term)) (define (coeff term) (cadr term)) (define (tag term-list) (attach-tag 'sparse-termlist term-list)) ; Public API ; cheat and return a term-adding fn so the type-list is nicer (put 'adjoin-term-fn '(sparse-termlist) (lambda (term-list) (lambda (term) (tag (adjoin-term term term-list))))) (put 'the-empty-termlist 'sparse-termlist (lambda () (tag (the-empty-termlist)))) (put 'first-term '(sparse-termlist) (lambda (term-list) (first-term term-list))) (put 'rest-terms '(sparse-termlist) (lambda (term-list) (tag (rest-terms term-list)))) (put 'empty-termlist? '(sparse-termlist) (lambda (term-list) (empty-termlist? term-list))) (put 'make 'sparse-termlist (lambda (term-list) (tag term-list))) 'done) (install-sparse-termlist-package) ;; representation of terms and term lists (define (make-term order coeff) (list order coeff)) (define (order term) (car term)) (define (coeff term) (cadr term)) (define (adjoin-term term term-list) ; Cheat here by having 'adjoin-term-fn return a lambda that adds terms ((apply-generic 'adjoin-term-fn term-list) term)) (define (the-empty-termlist) ((get 'the-empty-termlist 'dense-termlist))) (define (first-term term-list) (apply-generic 'first-term term-list)) (define (rest-terms term-list) (apply-generic 'rest-terms term-list)) (define (empty-termlist? term-list) (apply-generic 'empty-termlist? term-list)) (define (make-termlist term-list) ((get 'make 'sparse-termlist) term-list)) ;; Skipping 2.92 for now :P (define (install-generic-rational-package) ;; internal procedures (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (greatest-common-divisor n d))) (cons (div n g) (div d g)))) (define (add-rat x y) (make-rat (add (mul (numer x) (denom y)) (mul (numer y) (denom x))) (mul (denom x) (denom y)))) (define (sub-rat x y) (make-rat (sub (mul (numer x) (denom y)) (mul (numer y) (denom x))) (mul (denom x) (denom y)))) (define (mul-rat x y) (make-rat (mul (numer x) (numer y)) (mul (denom x) (denom y)))) (define (div-rat x y) (make-rat (mul (numer x) (denom y)) (mul (denom x) (numer y)))) (define (equ?-rat x y) (and (equ? (numer x) (numer y)) (equ? (denom x) (denom y)))) (define (=zero?-rat x) (=zero? (numer x))) ;; interface to rest of the system (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'equ? '(rational rational) (lambda (x y) (equ?-rat x y))) (put '=zero? '(rational) (lambda (x) (=zero?-rat x))) (put 'negate '(rational) (lambda (x) (tag (make-rat (negate (numer x)) (denom x))))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put 'numer 'rational numer) (put 'denom 'rational denom) 'done) (install-generic-rational-package) (define (greatest-common-divisor a b) (apply-generic 'greatest-common-divisor a b))
false
80ead86f6dc9fbcb06d3a28b1f37bc459952496f
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch2/exercise2-71.scm
68c24361d32d1147644baf483b500a0223cc729a
[]
no_license
da1/sicp
a7eacd10d25e5a1a034c57247755d531335ff8c7
0c408ace7af48ef3256330c8965a2b23ba948007
refs/heads/master
2021-01-20T11:57:47.202301
2014-02-16T08:57:55
2014-02-16T08:57:55
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
329
scm
exercise2-71.scm
;; 問題2.71 ; n=5 ; 1,2,4,8,16,32 (load "./ch2/exercise2-69.scm") (define pairs '((a 1) (b 2) (c 4) (d 8) (e 16) (f 32))) (generate-huffman-tree pairs) (define pairs '((a 1) (b 2) (c 4) (d 8) (e 16) (f 32) (g 64) (h 128) (i 256) (j 512) (k 1024))) (generate-huffman-tree pairs) ; 最高頻度は1bit ; 最低頻度はnbit
false
6675caa1adfb122a250cecec77a874592cafa384
3686e1a62c9668df4282e769220e2bb72e3f9902
/ex3.17.scm
b1beddeedb3af0123d2ace2b5f9d6f550f861dee
[]
no_license
rasuldev/sicp
a4e4a79354495639ddfaa04ece3ddf42749276b5
71fe0554ea91994822db00521224b7e265235ff3
refs/heads/master
2020-05-21T17:43:00.967221
2017-05-02T20:32:06
2017-05-02T20:32:06
65,855,266
0
0
null
null
null
null
UTF-8
Scheme
false
false
584
scm
ex3.17.scm
(define (count-pairs x) (define (new-set initial-elements) (define (add x) (let ((is-x-new (not (pair? (memq x initial-elements))))) (if is-x-new (set! initial-elements (cons x initial-elements))) is-x-new ) ) add ) (define add-to-set (new-set '())) (define (count-iter x) (if (not (pair? x)) 0 (if (add-to-set x) (+ (count-iter (car x)) (count-iter (cdr x)) 1 ) 0 ) ) ) (count-iter x) ) (count-pairs '(a b c)) (define x '(a b)) (define last (cdr x)) (set-cdr! last x) (count-pairs x)
false
856fe42b819e5e6b022af698edf95fd424c1cfcd
4478a6db6f759add823da6436842ff0b1bf82aa8
/bloom/bloom.scm
6790a5331efe10b7ca51619bfa871505dfd0fbb1
[]
no_license
gaborpapp/LDS-fluxus
2c06508f9191d52f784c2743c4a92e8cadf116ea
44d90d9f1e3217b3879c496b2ddd4d34237935d1
refs/heads/master
2016-09-05T13:29:09.695559
2013-04-05T05:33:10
2013-04-05T05:33:10
7,058,302
1
1
null
null
null
null
UTF-8
Scheme
false
false
891
scm
bloom.scm
(require "bloom.ss") (clear) (set-camera-transform (mtranslate #(0 0 -10))) (define p (build-pixels 1024 1024 #t)) (define loc (with-pixels-renderer p (build-locator))) (with-pixels-renderer p (hint-sphere-map) (texture (load-texture "fluxus-icon.png")) (clip 1 20) (for ([i (in-range 180)]) (with-primitive (build-cube) (colour (hsv->rgb (vector (rndf) .4 1))) (translate (vmul (srndvec) 7)) (rotate (vmul (crndvec) 180)) (recalc-normals 0) (parent loc)))) (with-primitive p (scale 0)) (with-primitive (build-plane) (scale #(21 17 1)) (texture (pixels->texture p)) (bloom .5 (with-primitive p (vector (pixels-width) (pixels-height))))) (define (loop) (with-pixels-renderer p (with-primitive loc (rotate (vector 0 .2 0))))) (every-frame (loop))
false
f29cd71ddc1ed7542a7b40c7a686bc008df8d31b
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/10-tables/table2list.scm
9ff3ab4c983606d79ce7378a6990e8f89419f240
[ "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
1,620
scm
table2list.scm
(include "#.scm") (for-each (lambda (t) ;; Primitive keys (define prim-keys-a (list 1 2 #t #f #!void '() 'symbol '|special symbol| '|123|)) (define prim-keys-b (list 1 2 #t #f #!void '() 'symbol '|special symbol| '|123|)) ;; Object keys (define str "key") (define bignum 12893187263876213876213876128736498328443298679821739812739832879) (define flonum 77.77) (define ratnum 1/3) (define cpxnum +1.0-i) (define table-key (make-table)) (define fct-key (lambda (x) x)) (define keyword keyword:) (define uninterned-symbol (string->uninterned-symbol "unintered-symbol")) (define uninterned-keyword (string->uninterned-keyword "unintered-keyword")) (define obj-keys (list str bignum flonum ratnum cpxnum table-key fct-key prim-keys-a uninterned-symbol uninterned-keyword)) (for-each (lambda (key) (table-set! t key key)) (append prim-keys-a obj-keys)) (let ((lst (table->list t))) (check-= (length lst) (table-length t)) (for-each (lambda (key) (cond ((assoc key lst) => (lambda (pair) (check-eq? key (car pair)) (check-eq? key (cdr pair)))) (else (check-true #f)))) (append prim-keys-b obj-keys)))) (list (make-table) (make-table weak-keys: #t) (make-table weak-values: #t) (make-table weak-keys: #t weak-values: #t) (make-table test: eq?) (make-table test: eq? weak-keys: #t) (make-table test: eq? weak-values: #t) (make-table test: eq? weak-keys: #t weak-values: #t)))
false
86a6c95a46c359fd98f1c7deb0df8e93d70f55cc
2b0dc0760baad4405f64b424345381f688173281
/compiler/src/main/scheme/libraries/llambda/match.scm
4261224de703ace74fb93b186c117f5d4985b5e1
[ "Apache-2.0" ]
permissive
abduld/llambda
f2e7daf0c9a302dafa29a2d4067bfae6d1ec8317
17e53a5ec15f2b09f2eb3304151af3dbbcfd7f32
refs/heads/master
2023-04-12T23:59:17.462698
2015-10-24T04:51:25
2015-10-24T04:51:25
45,697,748
0
0
NOASSERTION
2023-04-04T01:11:51
2015-11-06T17:50:04
Scala
UTF-8
Scheme
false
false
413
scm
match.scm
(define-library (llambda match) (import (llambda internal primitives)) (export match match-lambda) (begin ; This is analogous to (case-lambda) except it matches a single passed value (define-syntax match-lambda (syntax-rules () ((match-lambda clause ...) (lambda (val) (match val clause ...)))))))
true
a8a5c7da632b32c3d32322e668b1e3730fb79b77
b3049fd33f4b3d340d6414081243b5a904befe2f
/tests/tests.scm
102c80beafbb1cc3a65ec8ad9939c182c8d12c58
[ "BSD-2-Clause" ]
permissive
dleslie/monad-egg
4f89853a9e9eb03c1ac2b07e823a9faf3652e3ca
98d21d03243c6fdf9e29e82e81f111caa8616195
refs/heads/master
2020-03-26T17:49:17.996472
2020-03-22T03:35:38
2020-03-22T03:35:38
3,967,588
26
6
NOASSERTION
2020-03-22T03:37:48
2012-04-08T23:22:27
Scheme
UTF-8
Scheme
false
false
6,708
scm
tests.scm
(import chicken.string) (import srfi-1) (import test) (import monad) (define (run-tests) (test-group "Identity" (test "Unit" '() (do/m <id> (return '()))) (test "Bind" '(a) (do/m <id> (x <- 'a) (return `(,x)))) (test-error "Fail" (do/m <id> (fail)))) (test-group "Maybe" (test "Unit" '(Just Second) (do/m <maybe> (if #t (return 'First) (fail)) (return 'Second))) (test "Bind" 'Nothing (do/m <maybe> (x <- (fail)) (if #t x (return 'First)) (return 'Second))) (test "Fail" 'Nothing (do/m <maybe> (fail)))) (test-group "List" (test "Unit" '(1) (do/m <list> (return 1))) (test "Bind" '((1 a) (1 b) (2 a) (2 b)) (do/m <list> (x <- '(1 2)) (y <- '(a b)) (return `(,x ,y)))) (test-error "Fail" (do/m <list> (fail)))) (test-group "State" (test "Unit" '(1 . #f) ((do/m <state> (return 1)) #f)) (test "Bind" '(Positive . 1) ((do/m <state> (x <- (/m get)) (if (> x 0) (return 'Positive) (return 'Negative))) 1)) (test "Gets" '(Positive . -1) ((do/m <state> (x <- (/m! gets (lambda (value) (+ value 2)))) (if (> x 0) (return 'Positive) (return 'Negative))) -1)) (test "Modify" '(Positive . 1) ((do/m <state> (/m! modify (lambda (value) (+ value 2))) (x <- (/m get)) (if (> x 0) (return 'Positive) (return 'Negative))) -1)) (test "Put" '(Positive . 99) ((do/m <state> (/m! put 99) (x <- (/m get)) (if (> x 0) (return 'Positive) (return 'Negative))) -1)) (test-error "Fail" (do/m <state> (fail)))) (test-group "Reader" (test "Unit" 1 ((do/m <reader> (return 1)) 2)) (test "Bind" 1 ((do/m <reader> (x <- (/m ask)) (return x)) 1)) (test-error "Fail" ((do/m <reader> (fail)) 1)) (test "Asks" 2 ((do/m <reader> (x <- (/m! asks (lambda (v) (+ v 1)))) (return x)) 1)) (test "Local" 1 ((do/m <reader> (/m! local (lambda (v) (+ v 1)) (/m ask)) (x <- (/m ask)) (return x)) 1))) (test-group "Writer" (test "Unit" '(hello) (do/m <writer> (return 'hello))) (test "Bind" '((hello world)) (do/m <writer> (x <- (return 'hello)) (return (list x 'world)))) (test-error "Fail" (do/m <writer> (fail))) (test "Tell" '(() hello world) (do/m <writer> (x <- (return 'hello)) (/m! tell x) (/m! tell 'world))) (test "Listen" '((() hello test world) hello test world) (let ((other-writer (do/m <writer> (/m! tell 'hello) (/m! tell 'test) (/m! tell 'world)))) (do/m <writer> (x <- (/m! listen other-writer)) (return x)))) (test "Listens" '((() arf arf arf) hello test world) (let ((other-writer (do/m <writer> (/m! tell 'hello) (/m! tell 'test) (/m! tell 'world)))) (do/m <writer> (x <- (/m! listens (lambda (l) (map (lambda (s) 'arf) l)) other-writer)) (return x)))) (test "Pass" '(() "(1 2 3)") (let ((other-writer (do/m <writer> (/m! tell '(1 2 3)) (return (/m! tell (lambda (l) (map ->string l))))))) (do/m <writer> (/m! pass other-writer)))) (test "Censor" '(() "(1 2 3)") (let ((other-writer (do/m <writer> (/m! tell '(1 2 3))))) (do/m <writer> (/m! censor (lambda (l) (map ->string l)) other-writer))))) )
false
3ec371a5c7c33f98daff64ecd66cc98e5e189c90
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 5/5.4/5.25.scm
b2e63b07b2a6de634cb2287c2da66d1a19502346
[]
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
187
scm
5.25.scm
#lang planet neil/sicp ;; Skipping this exercise ;; However Skanev has a solution here (if you are interested) ;; https://github.com/skanev/playground/blob/master/scheme/sicp/05/25.scm
false
d82dff1d2996644aeda840e9141a498f581a93c0
74d2f4ec77852839450ab8563971a5e0f615c019
/chapter_03/chapter_3_3_4/simulate.scm
c5e249edf5f7bd7c1996b28f30b15f01d9aff5cf
[]
no_license
wangoasis/sicp
b56960a0c3202ce987f176507b1043ed632ed6b3
07eaf8d46f7b8eae5a46d338a4608d8e993d4568
refs/heads/master
2021-01-21T13:03:11.520829
2016-04-22T13:52:15
2016-04-22T13:52:15
53,835,426
0
0
null
null
null
null
UTF-8
Scheme
false
false
747
scm
simulate.scm
( define ( after-delay delay action ) ( add-to-agenda! ( + delay ( current-time the-agenda ) ) action the-agenda ) ) ( define ( propagate ) ( if ( empty-agenda? the-agenda ) 'done ( let ( ( first-item ( first-agenda-item the-agenda ) ) ) ( first-item ) ( remove-first-agenda-item! the-agenda ) ( propagate ) ) ) ) ( define ( probe name wire ) ( add-action! wire ( lambda () ( newline ) ( display name ) ( display " time: " ) ( display ( current-time the-agenda ) ) ( display " new value: " ) ( display ( get-signal wire ) ) ( newline ) ) ) )
false
ec7891fa75b6283f43c99d61bd0bcdd6f05e699c
b49e6c2edc0c5323f326e045c2a9fc769ba74778
/2.27.ss
701e48b7003b58ada00fd2fd2620b0fcc8028661
[]
no_license
plotgeek/SICP
73d0109d37ca5f9ac2e98d847ecf633acb371021
e773a8071ae2fae768846a2b295b5ed96b019f8d
refs/heads/master
2023-03-09T18:50:54.195426
2012-08-14T10:18:59
2012-08-14T10:18:59
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
101
ss
2.27.ss
(define (deep-reverse list) (reverse (map reverse list))) (define x (list (list 1 2) (list 3 4)))
false
690cf0452ae423cf53621c7d3005ac5fc865a614
ae4938300d7eea07cbcb32ea4a7b0ead9ac18e82
/utils/printf/compat.ikarus.ss
8f47120aa1eb82a4c4712d6d5c0721ae174fb626
[]
no_license
keenbug/imi-libs
05eb294190be6f612d5020d510e194392e268421
b78a238f03f31e10420ea27c3ea67c077ea951bc
refs/heads/master
2021-01-01T19:19:45.036035
2012-03-04T21:46:28
2012-03-04T21:46:28
1,900,111
0
1
null
null
null
null
UTF-8
Scheme
false
false
82
ss
compat.ikarus.ss
#!r6rs (library (imi utils printf compat) (export printf) (import (ikarus)))
false
be92b2474a32b0fa9fa33c8879369f5b49557166
6fe3cf1c6fabcf6020aae0df8154b1d3ffb334b1
/cogen-typesig.scm
4e959750b1f3ebdc23915e86f375ed5413adc527
[]
no_license
tonyg/pgg
bd4eae9196abcca94f316e0198408b9bd90a7820
1625eba59e529b92572cb51b3749015e793d3563
refs/heads/master
2020-06-04T04:30:57.758708
2012-04-11T01:11:50
2012-04-11T01:11:50
3,988,925
5
0
null
null
null
null
WINDOWS-1252
Scheme
false
false
5,408
scm
cogen-typesig.scm
;;; cogen-typesig.scm ;;; copyright © 1996, 1997, 1998, 1999, 2000 by Peter Thiemann ;;; non-commercial use is free as long as the original copright notice ;;; remains intact ;;; type declarations (define (process-type-declarations def-type*) (let loop ((def-type* def-type*) (symtab '())) (if (pair? def-type*) (let ((def (car def-type*)) (def-type* (cdr def-type*))) (case (car def) ((define-type) (loop def-type* (cons (one-deftype def) symtab))) ((define-primitive) (loop def-type* (cons (one-defop def) symtab))) ((define-memo) (loop def-type* (cons (one-defmemo def) symtab))) ((define-data) (loop def-type* (append (one-defdata def) symtab))) (else (error "illegal declaration" (car def))))) symtab))) ;;; process (defdata t (c1 s11 ... s1n) ... (cm sm1 ... smn)) ;;; a constructor description for ci is a list ;;; (t np nc nt) ;;; where np = sum of # args of c[1] ... c[i-1] ;;; nc = # args of c[i] ;;; nt = sum of # args of c[1] ... c[m] ;(define (desc-type desc) (list-ref desc 0)) ;(define (desc-np desc) (list-ref desc 1)) ;(define (desc-nc desc) (list-ref desc 2)) ;(define (desc-nt desc) (list-ref desc 3)) (define (get-nc ctor) (- (length ctor) 1)) (define (get-nt ctors) (apply + (map get-nc ctors))) (define (one-defdata dc) (let* ((type-name (cadr dc)) (rest (cddr dc)) (hidden (and (pair? rest) (eq? (car rest) 'hidden))) (ctors (if hidden (cdr rest) rest)) (nt (get-nt ctors))) (let loop ((ctors ctors) (np 0)) (if (null? ctors) '() (let* ((ctor (car ctors)) (nc (get-nc ctor))) (append (one-ctor (list type-name (car ctor) np nc nt hidden) ctor) (loop (cdr ctors) (+ np nc)))))))) (define (one-ctor desc ctor) (let* ((the-ctor (car ctor)) (the-test (string->symbol (string-append (symbol->string the-ctor) "?"))) (selectors (cdr ctor))) (cons (list the-ctor (scheme->abssyn-make-ctor1 desc) (length selectors)) (cons (list the-test (annMakeTest1 the-ctor desc) 1) (let loop ((selectors selectors) (i 1)) (if (null? selectors) '() (cons (list (car selectors) (annMakeSel1 the-ctor desc i) 1) (loop (cdr selectors) (+ i 1))))))))) ;;; process (define-type (P B1 ... Bn) B0) (define (one-deftype dt) (let ((template (cadr dt)) (result-type (caddr dt))) (list (car template) scheme->abssyn-make-call (length (cdr template))))) ;;; process (define-primitive ...) ;;; accepts the following syntax for definitions of primitive operators ;;; D ::= (define-primitive O T [dynamic|error|opaque|apply|pure|0|1|2|...]) (define (one-defop dt) (let* ((op-name (cadr dt)) (op-type (caddr dt)) (op-optional (cdddr dt)) (op-option (and (pair? op-optional) (car op-optional))) (op-apair (assoc op-option wft-property-table)) ;defined in cogen-eq-flow (st-entry (list op-name ((if (or (eq? op-option 'apply) (number? op-option)) annMakeOp1 annMakeOpCoerce) (eq? op-option 'pure) ;opacity (if (number? op-option) op-option (and op-apair (cdr op-apair))) ;property (a function) #f (parse-type op-type)) ;type -1 ;;(length op-rand-types) ))) st-entry)) ;;; (define-memo M level [active]) ;;; - M name of the function ;;; - level binding time of the memoization point ;;; - active memo point is active in specializations with level >= active ;;; if active is 'deferred (verbatim!) ;;; then make a deferred memoization point (define (one-defmemo dm) (let* ((memo-name (cadr dm)) (memo-level (caddr dm)) (active-level (if (pair? (cdddr dm)) (cadddr dm) 0)) (memo-type (if (number? active-level) '(all t t) '(all t (-> b (-> b b t) t))))) (list memo-name (annMakeOp1 #t (wft-make-memo-property memo-level active-level) (bta-make-memo-postprocessor memo-level active-level) (parse-type memo-type)) 1))) ;;; T ::= (all TV T) | (rec TV T) | (TC T*) | TV ;;; TV type variable (must be bound by rec or all) ;;; TC type constructor ;;; abstract syntax: (define-record primop (op-name op-type op-prop)) (define-record type-app (tcon types)) (define-record type-rec (tvar type)) (define-record type-all (tvar type)) (define-record type-var (tvar)) ;;; typical type: (-> b b b) interprets as (b b) -> b (define parse-type (lambda (texp) (and (not (eq? texp '-)) (let loop ((texp texp) (tenv the-empty-env)) (cond ((pair? texp) (if (member (car texp) '(all rec)) (let ((tvar (cadr texp))) ((if (equal? (car texp) 'rec) make-type-rec make-type-all) tvar (loop (caddr texp) (extend-env tvar (make-type-var tvar) tenv)))) (make-type-app (car texp) (map (lambda (texp) (loop texp tenv)) (cdr texp))))) (else (apply-env tenv texp (lambda () (make-type-app texp '()))))))))) ;;; a constructor description for ci is a list ;;; (t ctor np nc nt) ;;; where np = sum of # args of c[1] ... c[i-1] ;;; nc = # args of c[i] ;;; nt = sum of # args of c[1] ... c[m] (define (desc-type desc) (list-ref desc 0)) (define (desc-ctor desc) (list-ref desc 1)) (define (desc-np desc) (list-ref desc 2)) (define (desc-nc desc) (list-ref desc 3)) (define (desc-nt desc) (list-ref desc 4)) (define (desc-hidden desc) (list-ref desc 5))
false
1cb020a786ac48714e1886c915f1e18d4ff5349f
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/bridge/dd.ss
df50cb162e628b0d0f2cbfb249b490366d5a76ec
[]
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
210
ss
dd.ss
(module dd mzscheme ;;; the double-dummy solver. (provide likely-declarer-tricks) (define (likely-declarer-tricks dealer trump-suit deck) (modulo (equal-hash-code (list dealer trump-suit deck)) 14)) )
false
914a6fd2c3b00c57845ef0c9fd9cca2934815278
03e4064a7a55b5d00937e74cddb587ab09cf7af9
/nscheme/include/write.scm
b288fdedc2b2795db4ca3165c2d347fffaf20b4b
[ "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
8,617
scm
write.scm
;; TODO: optional formatting styles? ;; quote/abbreviations, padding, packing, numeric formats/radixes/rounding ;; fine-grained writing styles? express write in terms of richer documents? (define (write v out (format-policy? #f)) (define (pr s) (port-put* out s)) (define (wr+:default x pos _ __) (pr " ") (wr x (+ pos 1) 0)) (define format-policy (match format-policy? (#f #f) ('pretty `(pretty 80)) ('bulky `(bulky 80)) (policy policy))) (define wr+ (match format-policy (#f wr+:default) (`(pretty ,width) (lambda (x pos indent s.indent) (pr "\n") (pr s.indent) (wr x indent indent))) (`(bulky ,width) (lambda (x pos indent s.indent) (define pos.after (+ pos (wunit-width x))) (define pos.1 (cond ((< width pos.after) (pr "\n") (pr s.indent) indent) (else (pr " ") (+ pos 1)))) (wr x pos.1 indent))))) (define width (match format-policy (#f #f) (`(pretty ,width) width) (`(bulky ,width) width))) (define (wunit-width x) (match x ;; TODO: do not use strings, use (byte)vectors ;; TODO: do not use string-length ((? string?) (string-length x)) ((vector w _ _ _) w))) (define (datum->wunit v) (define (bracket l r vs) (define xs (let loop ((vs vs)) (match vs ('() '()) (`(,v . ,vs) (cons (datum->wunit v) (loop vs))) (v (list "." (datum->wunit v)))))) (vector (+ (string-length l) (string-length r) (foldl + 0 (map wunit-width xs)) (max 0 (- (length xs) 1))) l r xs)) (cond ((pair? v) (bracket "(" ")" v)) ((vector? v) (cond ((eqv? (vector-length v) 0) (pr "#()")) (else (bracket "#(" ")" (vector->list v))))) ((mvector? v) (cond ((eqv? (mvector-length v) 0) (pr "#m()")) (else (bracket "#m(" ")" (vector->list (mvector->vector v)))))) ((eq? #t v) "#t") ((eq? #f v) "#f") ((null? v) "()") ((procedure? v) "#<procedure>") (else (call-with-output-string (lambda (out) (define (pr s) (port-put* out s)) (cond ((number? v) (write-number v out)) ((symbol? v) (write-symbol v out)) ((string? v) (write-string v out)) (else (pr "#<unknown>")))))))) (define (wr x pos indent.0) (match x ((? string?) (pr x) (+ pos (string-length x))) ((vector w.full l r xs) (define w.l (string-length l)) (define w.r (string-length r)) (define pos.0 (+ pos w.l)) (define indent (+ indent.0 w.l)) (pr l) (define pos.1 (match xs ('() pos.0) (`(,x . ,xs) (foldl (if (and width (<= (+ pos w.full) width)) (lambda (x pos) (wr+:default x pos 0 "")) (let ((s.indent (string-append* (make-list indent " ")))) (lambda (x pos) (wr+ x pos indent s.indent)))) (wr x pos.0 indent) xs)))) (pr r) (+ pos.1 w.r)))) (wr (datum->wunit v) 0 0)) (define (write-string v out) (define (pr s) (port-put* out s)) (pr "\"") (for-each (lambda (c) (pr (case/char c ("\"" "\\\"") ("\\" "\\\\") ("\a" "\\a") ("\b" "\\b") ("\e" "\\e") ("\f" "\\f") ("\n" "\\n") ("\r" "\\r") ("\t" "\\t") ("\v" "\\v") (else (if (or (unicode-control? c) (unicode-vspace? c)) (string-append "\\u" (number->string c) ";") (utf8->string (bytevector c))))))) (string->unicodes v)) (pr "\"")) (define write-symbol (let* ((punc? (cset "\\\"#'(),;[]`{}")) (bad-symbol? (lambda (c) (or (unicode-space? c) (punc? c))))) (lambda (v out) (define (pr s) (port-put* out s)) (define s (symbol->string v)) (cond ((eq? v '|.|) (pr "|.|")) ((string->number s) (pr "|") (pr s) (pr "|")) (else (define cs (string->unicodes s)) (define bad? (ormap bad-symbol? cs)) (when bad? (pr "|")) (for-each (lambda (c) (cond ((eqv? c (char "|")) (when bad? (pr "|")) (pr "\\|") (when bad? (pr "|"))) (else (pr (utf8->string (u8*->bytevector (unicode->utf8 c))))))) cs) (when bad? (pr "|"))))))) ;; TODO: reduce dependency on exact->inexact and inexact->exact ;; manipulate floating point representation directly via: ;; (real->floating-point-bytes x 8) ;; (floating-point-bytes->real bs) (define (write-number n out) (define (pr s) (port-put* out s)) (define (pr-digit d) (port-put out (+ d (char "0")))) (define (pr-nat n) (if (eqv? n 0) (pr "0") (let loop ((n n) (ds '())) (if (> n 0) (loop (quotient n 10) (cons (remainder n 10) ds)) (for-each pr-digit ds))))) (define (pr-int n) (cond ((< n 0) (pr "-") (pr-nat (- n))) (else (pr-nat n)))) (define (larger-log10 n) (cond ((< n 1) 0) (else (define ~e (inexact->exact (truncate (log n 10)))) (define ~p (expt 10 ~e)) (cond ((< n (/ ~p 10)) (- ~e 1)) ((< n ~p ) ~e ) (else (+ ~e 1)))))) (define (pr-float n.inexact) (define n (inexact->exact n.inexact)) (define (finish rdigits e) (define ds (reverse rdigits)) (if (and (eqv? 0 (car ds)) (< 0 e)) (finish.1 (cdr ds) (- e 1)) (finish.1 ds e))) (define (finish.1 digits e) (define (pr-dec digits e?) (pr-digit (car digits)) (cond ((null? (cdr digits)) (unless e? (pr ".") (pr-digit 0))) (else (pr ".") (for-each pr-digit (cdr digits))))) (define (pr-exp digits e) (pr-dec digits #t) (pr "e") (pr-int e)) (cond ((<= #e1e10 n ) (pr-exp digits e)) ((< 0 n #e1e-3) (let loop ((digits digits) (e e)) (if (eqv? 0 (car digits)) (loop (cdr digits) (- e 1)) (pr-exp digits e)))) (else (let loop ((ds digits) (e e)) (define digits (if (null? ds) '(0) ds)) (cond ((<= e 0) (pr-dec digits #f)) (else (pr-digit (car digits)) (loop (cdr digits) (- e 1)))))))) (define e (larger-log10 n)) (define e10 (expt 10 e)) (define m (/ n e10)) (let loop ((m m) (approx 0) (scale e10) (rdigits '())) (define d (truncate m)) (define a+d (+ approx (* d scale))) (define a+d+1 (+ approx (* (+ d 1) scale))) (define a+d=? (eqv? (exact->inexact a+d ) n.inexact)) (define a+d+1=? (eqv? (exact->inexact a+d+1) n.inexact)) (cond ((and a+d=? (or (not a+d+1=?) (<= (- n a+d) (- a+d+1 n)))) (finish (cons d rdigits) e)) ( a+d+1=? (finish (cons (+ d 1) rdigits) e)) (else (loop (* (- m d) 10) a+d (/ scale 10) (cons d rdigits)))))) (cond ((not (real? n)) (define i (imag-part n)) (write-number (real-part n) out) (when (and (<= 0 i) (not (eqv? i +inf.0))) (pr "+")) (write-number i out) (pr "i")) ((eqv? n +inf.0) (pr "+inf.0")) ((eqv? n -inf.0) (pr "-inf.0")) ((eqv? n +nan.0) (pr "+nan.0")) ((inexact? n) (when (or (< n 0) (equal? n -0.0)) (pr "-")) (pr-float (abs n))) ((integer? n) (pr-int n)) (else (pr-int (numerator n)) (pr "/") (pr-nat (denominator n))))) (define (number->string n) (call-with-output-string (lambda (out) (write-number n out)))) ;; TODO: format, fprintf
false
3e06dcf1df830dd90fa61455a0efd98ef7dd01b1
6b288a71553cf3d8701fe7179701d100c656a53c
/s/print.ss
af8fb379c046f73c92683b5b10f8ac3205cd61f4
[ "Apache-2.0" ]
permissive
cisco/ChezScheme
03e2edb655f8f686630f31ba2574f47f29853b6f
c048ad8423791de4bf650fca00519d5c2059d66e
refs/heads/main
2023-08-26T16:11:15.338552
2023-08-25T14:17:54
2023-08-25T14:17:54
56,263,501
7,763
1,410
Apache-2.0
2023-08-28T22:45:52
2016-04-14T19:10:25
Scheme
UTF-8
Scheme
false
false
52,591
ss
print.ss
;;; print.ss ;;; Copyright 1984-2017 Cisco Systems, Inc. ;;; ;;; Licensed under the Apache License, Version 2.0 (the "License"); ;;; you may not use this file except in compliance with the License. ;;; You may obtain a copy of the License at ;;; ;;; http://www.apache.org/licenses/LICENSE-2.0 ;;; ;;; Unless required by applicable law or agreed to in writing, software ;;; distributed under the License is distributed on an "AS IS" BASIS, ;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;;; See the License for the specific language governing permissions and ;;; limitations under the License. (begin (eval-when (compile) (define-constant cycle-node-max 1000) (define-syntax decr (lambda (x) (syntax-case x () ((_ x) (identifier? #'x) #'(and x (fx- x 1)))))) (define-syntax limit? (syntax-rules () ((_ x) (eq? x 0)))) ) ;eval-when ;;; $make-graph-env is shared with pretty.ss (define $make-graph-env) (define record-writer (let ([rw-ht #f] [cache '()]) (case-lambda [(rtd) (define default-record-writer (lambda (x p wr) (let ([rtd ($record-type-descriptor x)]) (cond ; keep in sync with wrhelp [(record-type-opaque? rtd) (fprintf p "#<~a>" (csv7:record-type-name rtd))] [(record-type-descriptor? x) (fprintf p "#<record type ~:s>" (record-type-uid x))] [(record-constructor-descriptor? x) (fprintf p "#<record constructor descriptor>")] [else (display "#[" p) ; we use write instead of wr here so that the field doesn't get ; a reference (#n#) when print-graph is true. (write (or (record-reader rtd) (record-type-uid rtd)) p) (do ([flds (csv7:record-type-field-names rtd) (cdr flds)] [i 0 (+ i 1)]) ((null? flds)) (write-char #\space p) (wr ((csv7:record-field-accessor rtd i) x) p)) (write-char #\] p)])))) (unless (record-type-descriptor? rtd) ($oops 'record-writer "~s is not a record-type descriptor" rtd)) (if rw-ht (or (eq-hashtable-ref rw-ht rtd #f) (let ([proc (or (let f ([rtd rtd]) (let ([rtd (record-type-parent rtd)]) (and rtd (or (eq-hashtable-ref rw-ht rtd #f) (f rtd))))) default-record-writer)]) ; cache the derived entry (eq-hashtable-cell rw-ht rtd proc) (set! cache (weak-cons rtd cache)) proc)) default-record-writer)] [(rtd proc) (unless (record-type-descriptor? rtd) ($oops 'record-writer "~s is not a record-type descriptor" rtd)) (unless (or (procedure? proc) (eq? proc #f)) ($oops 'record-writer "~s is not a procedure" proc)) (unless rw-ht (set! rw-ht (make-weak-eq-hashtable))) ; remove derived entries for rtd and any of its children (set! cache (let f ([cache cache]) (cond [(null? cache) '()] [(eq? (car cache) #!bwp) (f (cdr cache))] [(let g ([x (car cache)]) (and x (or (eq? x rtd) (g (record-type-parent x))))) (eq-hashtable-delete! rw-ht (car cache)) (f (cdr cache))] [else (weak-cons (car cache) (f (cdr cache)))]))) (let ([a (eq-hashtable-cell rw-ht rtd proc)]) (unless (eq? (cdr a) proc) (set-cdr! a proc)))]))) (let () (define black-hole '#0=#0#) (define hashable? (lambda (x) (if ($immediate? x) (eq? x black-hole) (and ($object-in-heap? x) (or (pair? x) (vector? x) (box? x) (and ($record? x) (not (eq? x #!base-rtd))) (fxvector? x) (string? x) (bytevector? x) (gensym? x)))))) (define bit-sink (let ([bsp #f]) (define make-bit-sink-port (lambda () (define handler (message-lambda (lambda (msg . args) ($oops 'bit-sink-port "operation ~s not handled" msg)) [(block-write p s n) (void)] [(clear-output-port p) (set-textual-port-output-index! p 0)] [(close-port p) (set-textual-port-output-size! p 0) (mark-port-closed! p)] [(flush-output-port p) (set-textual-port-output-index! p 0)] [(port-name p) "bit-sink port"] [(write-char c p) (set-textual-port-output-index! p 0)])) (make-output-port handler (make-string 1024)))) (lambda () (or bsp (let ([p (make-bit-sink-port)]) (set! bsp p) p))))) (define (graph-env x lev len) ;; NOTE: if used as is in fasl.ss, fasl.ss will have to play ;; $last-new-vector-element game. ;; $make-graph-env takes an object, a print level, and a print ;; length, and returns a procedure whose first argument is a ;; message, one of 'tag, 'tag?, or 'count. If the message is ;; 'tag, one of #f, (mark . <n>), or (ref . <n>) is returned if ;; the second argument needs no tag, a mark tag, or a reference ;; tag. If the message is 'tag?, #f is returned iff the second ;; argument needs no tag. If the message is 'count, the number ;; of items needing tags is returned. (let ([ht (make-eq-hashtable)] [count 0]) (let find-dupls ([x x] [lev lev] [lslen len]) (when (and (hashable? x) (not (limit? lev))) (let ([a (eq-hashtable-cell ht x 'first)]) (case (cdr a) [(first) (set-cdr! a #f) (cond [(pair? x) (unless (limit? lslen) (find-dupls (car x) (decr lev) len) (find-dupls (cdr x) lev (decr lslen)))] [(vector? x) (unless (fx= (vector-length x) 0) (let ([m (if (print-vector-length) ($last-new-vector-element vector-length vector-ref x) (fx- (vector-length x) 1))] [lev (decr lev)]) (let f ([i 0] [veclen len]) (unless (or (fx> i m) (limit? veclen)) (find-dupls (vector-ref x i) lev len) (f (fx+ i 1) (decr veclen))))))] [(and ($record? x) (not (eq? x #!base-rtd))) (when (print-record) ((record-writer ($record-type-descriptor x)) x (bit-sink) (lambda (x p) (unless (and (output-port? p) (textual-port? p)) ($oops 'write "~s is not a textual output port" p)) (find-dupls x (decr lev) len))))] [(box? x) (find-dupls (unbox x) (decr lev) len)] [(eq? x black-hole) (find-dupls x (decr lev) len)])] [(#f) (set! count (fx+ count 1)) (set-cdr! a #t)])))) (and (not (fx= count 0)) (let ([next -1]) (case-lambda [(msg x) (case msg [(tag) (and (hashable? x) (let ([a (eq-hashtable-cell ht x #f)]) (case (cdr a) [(#f) #f] [(#t) (set! next (fx+ next 1)) (set-cdr! a `(ref . ,next)) `(mark . ,next)] [else (cdr a)])))] [(tag?) (eq-hashtable-ref ht x #f)])] [(msg) (case msg [(count) count])]))))) (define (really-cyclic? x lev len) (define cyclic? (lambda (x curlev lstlen) (if ($immediate? x) (if (eq? x black-hole) (not lev) #f) (and ($object-in-heap? x) (cond [(pair? x) (cyclic-structure? x curlev lstlen cyclic-pair?)] [(vector? x) (cyclic-structure? x curlev 0 cyclic-vector?)] [(and ($record? x) (not (eq? x #!base-rtd))) (and (print-record) (cyclic-structure? x curlev lstlen (lambda (x curlev lstlen) (call/cc (lambda (k) ((record-writer ($record-type-descriptor x)) x (bit-sink) (lambda (x p) (unless (and (output-port? p) (textual-port? p)) ($oops 'write "~s is not a textual output port" p)) (if (cyclic? x (fx+ curlev 1) 0) (k #t)))) #f)))))] [(box? x) (cyclic-structure? x curlev 0 cyclic-box?)] [else #f]))))) (define cyclic-structure? (let ([ht (make-eq-hashtable)]) (lambda (x curlev lstlen sub-cyclic?) (and (not (eq? curlev lev)) (let ([a (eq-hashtable-cell ht x #f)]) (let ([oldlev (cdr a)]) (if oldlev (or (not (if (= oldlev curlev) len lev)) (sub-cyclic? x curlev lstlen)) (begin (set-cdr! a curlev) (or (sub-cyclic? x curlev lstlen) (begin (set-cdr! a #f) #f)))))))))) (define cyclic-pair? (lambda (x curlev lstlen) (and (not (eq? lstlen len)) (or (cyclic? (car x) (fx+ curlev 1) 0) (cyclic? (cdr x) curlev (fx+ lstlen 1)))))) (define cyclic-vector? (lambda (x curlev lstlen) (let ([n (vector-length x)] [curlev (fx+ curlev 1)]) (let across ([i (fx- (if len (fxmin len n) n) 1)]) (and (fx>= i 0) (or (cyclic? (vector-ref x i) curlev 0) (across (fx- i 1)))))))) (define cyclic-box? (lambda (x curlev lstlen) (cyclic? (unbox x) (fx+ curlev 1) 0))) (cyclic? x 0 0) ) (define maybe-cyclic? ;; brain damaged---can go essentially forever on very large trees ;; should keep separate count, lev, and len variables (lambda (x lev len) (let down ([x x] [xlev (if lev (fxmin lev (constant cycle-node-max)) (constant cycle-node-max))]) (cond [(fx= xlev 0) (or (not lev) (fx> lev (constant cycle-node-max)))] [($immediate? x) (if (eq? x black-hole) (not lev) #f)] [else (and ($object-in-heap? x) (cond [(pair? x) (let across ([x x] [xlen (if len (fxmin len (constant cycle-node-max)) (constant cycle-node-max))]) (cond [(fx= xlen 0) (or (not len) (fx> len (constant cycle-node-max)))] [(pair? x) (or (down (car x) (fx- xlev 1)) (across (cdr x) (fx- xlen 1)))] [else (down x (fx- xlev 1))]))] [(vector? x) (let ([n (vector-length x)]) (let across ([i (fx- (if len (fxmin len n) n) 1)]) (and (fx>= i 0) (or (down (vector-ref x i) (fx- xlev 1)) (across (fx- i 1))))))] [(and ($record? x) (not (eq? x #!base-rtd))) (and (print-record) (call/cc (lambda (k) ((record-writer ($record-type-descriptor x)) x (bit-sink) (lambda (x p) (unless (and (output-port? p) (textual-port? p)) ($oops 'write "~s is not a textual output port" p)) (if (down x (fx- xlev 1)) (k #t)))) #f)))] [(box? x) (down (unbox x) (fx- xlev 1))] [else #f]))])))) (set! $make-graph-env (lambda (who x lev len) (and (if ($immediate? x) (eq? x black-hole) (and ($object-in-heap? x) (or (pair? x) (vector? x) (box? x) (and ($record? x) (not (eq? x #!base-rtd)))))) (or (print-graph) (and (not (and lev len)) (maybe-cyclic? x lev len) (really-cyclic? x lev len) (begin (warningf who "cycle detected; proceeding with (print-graph #t)") #t))) (graph-env x lev len)))) ) ;;; $last-new-vector-element is shared with read.ss and pretty.ss (define $last-new-vector-element ; assumes vector has at least one element (lambda (vlen vref x) (let ([n (vlen x)]) (let ([y (vref x (fx- n 1))]) (do ([i (fx- n 2) (fx- i 1)]) ((or (fx< i 0) (not (eqv? y (vref x i)))) (fx+ i 1))))))) ;;; $flonum->digits is exported to allow us to play around with formatted IO #| (flonum->digits <flonum> <output radix> <mode> <position>) <flonum> is the number you want to convert to digits. <output radix> is the radix (usually 10) that you want the output digits to be in <mode> is one of: 'normal: this is used for "free format" printing. In normal mode, the digits produced are the minimum number needed to reproduce the internal representation. In this case, <position> is ignored (pass in zero). 'absolute: this is for fixed-format floating point notation. In this case, digit production is cut off (with appropriate rounding) at position <position>. Negative values of <position> specify positions to the right of the radix point; positive values specify positions to the left. 'relative: this is for fixed-format exponential notation. In this case, digit production is cut off (with appropriate rounding) at position <position> relative to the first digit. <position> must be negative. Return Value: In any of the modes, you receive an infinite list consisting of * the sign represented by 1 for + and -1 for - * the exponent * the significant digits w/o trailing zeros * a (possibly empty) sequence of -1's, and * a (possibly empty) sequence of -2's. The -1's should be printed as zeros if you need them; a -1 digit is equivalent to zero except that it is not necessary to print it to fully specify the number. The -2's should be printed as hash marks (#) or something similar; a -2 digit carries no information whatsoever, i.e., once you start getting -2 digits, all precision is gone. For normalized IEEE 64-bit floats, -2 digits won't appear until after 15 or so other digits. For denormalized floats, -2 digits may appear much sooner (perhaps even starting with the second digit). Positive floating point zero returns with (1 0 -1 ...). Negative floating point returns with (1 0 -1 ...). |# (define $flonum->digits) (let () (define terminator-1 '#1=(-1 . #1#)) (define terminator-2 '#2=(-2 . #2#)) (define invlog2of ;; must be accurate to several decimal places (let ([v (let ([ln2 (log 2)]) (let f ([n 36] [ls '()]) (if (fx= n 1) (list->vector ls) (f (fx- n 1) (cons (/ ln2 (log n)) ls)))))]) (lambda (x) (vector-ref v (fx- x 2))))) (define exptt (let ([v (let f ([k 325] [ls '()]) (if (fx< k 0) (list->vector ls) (f (fx- k 1) (cons (expt 10 k) ls))))]) (lambda (ob k) (if (and (fx= ob 10) (fx<= 0 k 320)) (vector-ref v k) (expt ob k))))) (define dragon4 ;; ob is the base of the output representation ;; e is the exponent of the floating point number ;; f is the significand of the floating point number ;; p is the precision of the floating point number ;; cutoffmode is one of normal (no cutoff), absolute (for fixed ;; formats), or relative (for fixed exponential formats) ;; initialcutoffplace is the digit position where cutoff should occur ;; (in radix-ob digits) ;; when cutoffmode is relative, initialcutoffplace must be negative ;; internally, ruf, cop, r, s, m+, m- are roundupflag, cutoffplace, ;; R, S, M+, M- from original algorithm (lambda (e f p ob cutoffmode initialcutoffplace) (define estimate (lambda (r s m- m+ ruf) (let ([k (fx1+ (exact (floor (- (* (fx+ (integer-length f) e -1) (invlog2of ob)) 1e-10))))]) (cond [(> k 0) (let ([scale (exptt ob k)]) (fixup k r (* s scale) m- m+ ruf))] [(< k 0) (let* ([scale (exptt ob (fx- k))] [m- (* m- scale)]) (fixup k (* r scale) s m- (and m+ (ash m- 1)) ruf))] [else (fixup k r s m- m+ ruf)])))) (define fixup (lambda (k r s m- m+ ruf) (if ((if ruf >= >) (+ r (or m+ m-)) s) (cutoffadjust0 (fx+ k 1) r (* s ob) m- m+ ruf) (cutoffadjust0 k r s m- m+ ruf)))) (define cutoffadjust0 (lambda (k r s m- m+ ruf) (case cutoffmode [(normal) (generate0 k r s m- m+ ruf #f)] [(absolute) (cutoffadjust k r s m- m+ ruf (fx- initialcutoffplace k))] [(relative) (when (fx>= initialcutoffplace 0) ($oops '$flonum->digits "nonnegative relative cutoffplace ~s" initialcutoffplace)) (cutoffadjust k r s m- m+ ruf initialcutoffplace)] [else ($oops '$flonum->digits "invalid cutoffmode ~s" cutoffmode)]))) (define cutoffadjust (lambda (k r s m- m+ ruf a) (let ([y (/ (if (fx>= a 0) (* s (exptt ob a)) (/ s (exptt ob (fx- a)))) 2)]) (if (> y m-) (if (ratnum? y) (let* ([d (denominator y)] [r (* r d)] [s (* s d)] [m- (numerator y)] [m+ (and m+ (let ([new-m+ (* m+ d)]) (if (> new-m+ m-) new-m+ #f)))] [ruf (or ruf (not m+))]) (fixup2 k r s m- m+ ruf (fx+ k a))) (let* ([m- y] [m+ (and m+ (if (> m+ y) m+ #f))] [ruf (or ruf (not m+))]) (fixup2 k r s m- m+ ruf (fx+ k a)))) (generate0 k r s m- m+ ruf (fx+ k a)))))) (define fixup2 (lambda (k r s m- m+ ruf cop) (if ((if ruf >= >) (+ r (or m+ m-)) s) (cutoffadjust0 (fx+ k 1) r (* s ob) m- m+ ruf) (generate0 k r s m- m+ ruf cop)))) (define generate0 (lambda (k r s m- m+ ruf cop) (let ([k (fx- k 1)]) (cons k (generate k r s m- m+ ruf cop))))) (define generate (lambda (k r s m- m+ ruf cop) (let* ([rob (* r ob)] [q-r ($quotient-remainder rob s)] [u (car q-r)] [r (cdr q-r)] [m- (* m- ob)] [m+ (and m+ (ash m- 1))] [low ((if ruf <= <) r m-)] [high ((if ruf >= >) (+ r (or m+ m-)) s)]) (if (and (not low) (not high)) (cons u (generate (fx- k 1) r s m- m+ ruf cop)) (let ([d (cond [(and low (not high)) u] [(and high (not low)) (fx+ u 1)] [(< (ash r 1) s) u] [else (fx+ u 1)])]) (cond [(not cop) (cons d terminator-1)] [(fx< k cop) terminator-1] [(fx= k cop) (cons d terminator-1)] [else (cons d (if (fx= d u) (generate1 k (+ r (or m+ m-)) s cop) (generate1 k (- (+ r (or m+ m-)) s) s cop)))])))))) ; delta may be zero, in which case all digits are significant, ; even if we've been asked for 1,000,000 of them. This is due to ; our definition of (in)significant: "a digit is insignificant when ; it and all digits after it can be replaced by any base-B digits ; without altering the value of the number when input. In other ; words, a digit is insignificant if incrementing the preceding ; digit does not cause the number to fall outside the rounding ; range of v." For 1e23, which falls exactly midway between two ; fp numbers and reads as the next one down due to "unbiased rounding", ; if we add even a single 1 digit way down, we're pushed to the next ; higher (when read). For example: ; 100000000000000000000000.000000000000000000000000000000000000001 ; reads as 1.0000000000000001e23. We probably don't get into this ; situation unless ruf is allowed to be true for absolute and relative ; modes below, since with ruf false, we won't try to print a number that ; is exactly half way between two floating-point numbers. (define generate1 (lambda (k delta s cop) (if (>= delta s) terminator-2 (let ([rest (let ([k (fx- k 1)]) (if (fx= k cop) terminator-1 (generate1 k (* delta ob) s cop)))]) (if (eq? rest terminator-1) rest (cons -1 rest)))))) ; we restrict ruf = true to cutoffmode normal so that we don't end ; up in the situation described above where delta is zero and we ; show an indefinite number of digits as significant. (let ([b (and (fx> e -1074) (= f 4503599627370496))] [ruf (and (eq? cutoffmode 'normal) (even? f))]) (if (fx>= e 0) (let* ([r (ash f (if b (fx+ e 2) (fx+ e 1)))] [m- (ash 1 e)] [m+ (and b (ash m- 1))] [s (if b 4 2)]) (estimate r s m- m+ ruf)) (let* ([r (ash f (if b 2 1))] [s (ash 1 (if b (fx- 2 e) (fx- 1 e)))] [m+ (and b 2)]) (estimate r s 1 m+ ruf)))))) (set! $flonum->digits (lambda (x ob cutoffmode initialcutoffplace) (let ([dx (if (flonum? x) (decode-float x) x)]) (let ([f (vector-ref dx 0)] [e (vector-ref dx 1)] [s (vector-ref dx 2)]) (cons s (if (= f 0) (cons 0 terminator-1) (dragon4 e f 53 ob cutoffmode initialcutoffplace))))))) ) (define $write-pretty-quick) (define write) (define display) (let () (define digit-char-table "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") (define-syntax digit->char (syntax-rules () ((_ d) (string-ref digit-char-table d)))) (define wr (lambda (x r lev len d? env p) (let ([a (and env (env 'tag x))]) (if (not a) (wrhelp x r lev len d? env p) (record-case a [(mark) n (write-char #\# p) (wrfixits n 10 p) (write-char #\= p) (wrhelp x r lev len d? env p)] [(ref) n (write-char #\# p) (wrfixits n 10 p) (write-char #\# p)]))))) (define wrhelp (lambda (x r lev len d? env p) (define void? (lambda (x) (eq? x (void)))) (define black-hole? (lambda (x) (eq? x '#3=#3#))) (define base-rtd? (lambda (x) (eq? x #!base-rtd))) (if-feature pthreads (begin (define $condition? thread-condition?) (define $condition-name condition-name) (define $mutex? mutex?) (define $mutex-name mutex-name)) (begin (define $condition? (lambda (x) #f)) (define $condition-name (lambda (x) #f)) (define $mutex? (lambda (x) #f)) (define $mutex-name (lambda (x) #f)))) (cond [($immediate? x) (type-case x [(fixnum?) (wrfixnum x r d? p)] [(null?) (display-string "()" p)] [(boolean?) (display-string (if x "#t" "#f") p)] [(char?) (if d? (write-char x p) (wrchar x p))] [(eof-object?) (display-string "#!eof" p)] [(bwp-object?) (display-string "#!bwp" p)] [($unbound-object?) (display-string "#<unbound object>" p)] [(void?) (display-string "#<void>" p)] [(black-hole?) (wrblack-hole x r lev len d? env p)] [else (display-string "#<garbage>" p)])] [($object-in-heap? x) (type-case x [(symbol?) (cond [d? (display-string (symbol->string x) p)] [(gensym? x) (case (print-gensym) [(#f) (wrsymbol (symbol->string x) p)] [(pretty) (display-string "#:" p) (wrsymbol (symbol->string x) p)] [(pretty/suffix) (let ((uname (gensym->unique-string x))) (define string-prefix? (lambda (x y) (let ([n (string-length x)]) (and (fx<= n (string-length y)) (let prefix? ([i 0]) (or (fx= i n) (and (char=? (string-ref x i) (string-ref y i)) (prefix? (fx+ i 1))))))))) (wrsymbol (symbol->string x) p) (display-string "." p) (if (and $session-key (string-prefix? $session-key uname)) (display-string (substring uname (string-length $session-key) (string-length uname)) p) (wrsymbol uname p #t)))] [else (let ((uname (gensym->unique-string x))) (display-string "#{" p) (wrsymbol (symbol->string x) p) (display-string " " p) (wrsymbol uname p) (display-string "}" p))])] [else (wrsymbol (symbol->string x) p)])] [(pair?) (wrpair x r lev len d? env p)] [(string?) (if d? (display-string x p) (wrstring x p))] [(vector?) (wrvector vector-length vector-ref #f x r lev len d? env p)] [(fxvector?) (wrvector fxvector-length fxvector-ref "vfx" x r lev len d? env p)] [(bytevector?) (wrvector bytevector-length bytevector-u8-ref "vu8" x r lev len d? env p)] [(flonum?) (wrflonum #f x r d? p)] ; catch before record? case [($condition?) (cond (($condition-name x) => (lambda (name) (display-string "#<condition " p) (wrsymbol (symbol->string name) p) (write-char #\> p))) (else (display-string "#<condition>" p)))] [($mutex?) (cond (($mutex-name x) => (lambda (name) (display-string "#<mutex " p) (wrsymbol (symbol->string name) p) (write-char #\> p))) (else (display-string "#<mutex>" p)))] [(base-rtd?) (display-string "#!base-rtd" p)] [($record?) (if (print-record) (if (limit? lev) (display-string "#[...]" p) ((record-writer ($record-type-descriptor x)) x p (lambda (x p) (unless (and (output-port? p) (textual-port? p)) ($oops 'write "~s is not a textual output port" p)) (wr x r (decr lev) len d? env p)))) (let ([rtd ($record-type-descriptor x)]) (cond ; keep in sync with default-record-writer [(record-type-opaque? rtd) (display-string "#<" p) (display-string (csv7:record-type-name rtd) p) (display-string ">" p)] [(record-type-descriptor? x) (display-string "#<record type " p) (wrsymbol (symbol->string (record-type-uid x)) p) (display-string ">" p)] [(record-constructor-descriptor? x) (display-string "#<record constructor descriptor>" p)] [else (display-string "#<record of type " p) (display-string (csv7:record-type-name rtd) p) (display-string ">" p)])))] [(bignum?) (wrbignum x r d? p)] [(ratnum?) (wrratnum x r d? p)] [($inexactnum?) (wrinexactnum x r d? p)] [($exactnum?) (wrexactnum x r d? p)] [(box?) (wrbox x r lev len d? env p)] [(procedure?) (if ($continuation? x) (wrcontinuation x p) (wrprocedure x p))] [(port?) (wrport x p)] [($code?) (wrcode x p)] [($tlc?) (display-string "#<tlc>" p)] [(thread?) (wrthread x p)] [($rtd-counts?) (display-string "#<rtd-counts>" p)] [else (display-string "#<garbage>" p)])] [else (display-string "#<foreign>" p)]))) (module (wrprocedure wrcode) (include "types.ss") (define wrcodename (lambda (x p) (cond [(let ([s ($code-name x)]) (and (string? s) s)) => (lambda (s) (write-char #\space p) (display-string s p))]) (cond [(let ([info ($code-info x)]) (and (code-info? info) (code-info-src info))) => (lambda (src) (fprintf p " at ~a:~a" (path-last (source-file-descriptor-name (source-sfd src))) (if (source-2d? src) (format "~a.~a" (source-2d-line src) (source-2d-column src)) (source-bfp src))))]))) (define wrprocedure (lambda (x p) (display-string "#<procedure" p) (wrcodename ($closure-code x) p) (write-char #\> p))) (define wrcode (lambda (x p) (display-string "#<code" p) (wrcodename x p) (write-char #\> p)))) (define wrthread (lambda (x p) (display-string "#<thread " p) (let ([n (with-tc-mutex (let ([tc ($thread-tc x)]) (and (not (eq? tc 0)) ($tc-field 'threadno tc))))]) (if n (if (fixnum? n) (wrfixnum n 10 #t p) (wrbignum n 10 #t p)) (display "destroyed" p))) (write-char #\> p))) (define wrcontinuation (lambda (x p) (cond [(eq? x $null-continuation) (display-string "#<null continuation>" p)] [(= ($continuation-stack-length x) (constant unscaled-shot-1-shot-flag)) (display-string "#<shot one-shot continuation>" p)] [else (display-string "#<" p) (unless (= ($continuation-stack-length x) ($continuation-stack-clength x)) (display-string "one-shot " p)) (let ([code ($continuation-return-code x)]) (if ($system-code? code) (display-string "system continuation" p) (display-string "continuation" p)) (let ([s ($code-name code)]) (when (string? s) (display-string " in " p) (display-string s p))) (write-char #\> p))]))) (define wrblack-hole (lambda (x r lev len d? env p) (if (limit? lev) (display-string "..." p) (wr x r (decr lev) len d? env p)))) (define wrbox (lambda (x r lev len d? env p) (display-string "#&" p) (if (limit? lev) (display-string "..." p) (wr (unbox x) r (decr lev) len d? env p)))) (define wrpair (lambda (x r lev len d? env p) (define inheap-pair? (lambda (x) ; safe to do pair? check first here since pair is a primary type, ; hence pair? won't deference the possibly bogus foreign pointer (and (pair? x) ($object-in-heap? x)))) (define abbreviations '((quote . "'") (quasiquote . "`") (unquote . ",") (unquote-splicing . ",@") (syntax . "#'") (quasisyntax . "#`") (unsyntax . "#,") (unsyntax-splicing . "#,@"))) (cond [(and d? (inheap-pair? (cdr x)) (null? (cddr x)) (assq (car x) abbreviations)) => (lambda (a) (display-string (cdr a) p) (wr (cadr x) r lev len d? env p))] [else (write-char #\( p) (if (limit? lev) (display-string "..." p) (let loop ([x x] [n len]) (if (limit? n) (display-string "..." p) (begin (wr (car x) r (decr lev) len d? env p) (cond [(and (inheap-pair? (cdr x)) (or d? (not env) (not (env 'tag? (cdr x))))) (write-char #\space p) (loop (cdr x) (decr n))] [(null? (cdr x))] [else (display-string " . " p) (wr (cdr x) r (decr lev) len d? env p)]))))) (write-char #\) p)]))) (define wrvector (lambda (vlen vref prefix x r lev len d? env p) (let ([size (vlen x)] [pvl (and (not d?) (print-vector-length))]) (write-char #\# p) (when pvl (wrfixits size 10 p)) (when prefix (display-string prefix p)) (write-char #\( p) ;) (if (and (limit? lev) (not (fx= size 0))) (display-string "..." p) (unless (fx= size 0) (let ([last (if pvl ($last-new-vector-element vlen vref x) (fx- size 1))]) (let loop ([i 0] [n len]) (if (limit? n) (display-string "..." p) (begin (wr (vref x i) r (decr lev) len d? env p) (unless (fx= i last) (write-char #\space p) (loop (fx+ i 1) (decr n))))))))) ;( (write-char #\) p)))) (define wrport (lambda (x p) (let ([name (port-name x)]) (display-string "#<" p) (when (binary-port? x) (display-string "binary " p)) (if (input-port? x) (if (output-port? x) (display-string "input/output port" p) (display-string "input port" p)) (if (output-port? x) (display-string "output port" p) (display-string "port" p))) (when (and (string? name) (not (eqv? name ""))) (write-char #\space p) (display-string name p)) (write-char #\> p)))) (define wrfixits (case-lambda [(n r p) (cond [(fx< n r) (write-char (digit->char n) p)] [else (wrfixits (fx/ n r) r p) (write-char (digit->char (fxremainder n r)) p)])] [(n r d p) (cond [(fx< n r) (do ([d d (fx- d 1)]) ((fx<= d 1)) (write-char #\0 p)) (write-char (digit->char n) p)] [else (wrfixits (fx/ n r) r (fx- d 1) p) (write-char (digit->char (fxremainder n r)) p)])])) (define wrfixits-negative ;; would be (wrfixits (fx- -n) r p) except that (- -n) may not be a ;; fixnum, e.g., for n = (most-negative-fixnum) in two's complement (lambda (-n r p) (cond [(fx> -n (fx- r)) (write-char (digit->char (fx- -n)) p)] [else (wrfixits-negative (fx/ -n r) r p) (write-char (digit->char (fx- (remainder -n r))) p)]))) (define wrbigits (let () ; divide-and-conquer, treating bignum as two ``big base'' bigits ; first base must be >= sqrt(n); base i+1 must be >= sqrt(base i) ; last base must be <= most-positive-fixnum (define largest-fixnum-big-base (let ([v (make-vector 37)]) (do ([b 2 (fx+ b 1)]) ((fx= b 37) v) (vector-set! v b (let f ([bb b] [d 1]) (let ([bb^2 (* bb bb)]) (if (fixnum? bb^2) (f bb^2 (* d 2)) (cons (cons bb d) '())))))))) (define (big-bases n r) (let ([iln/2 (bitwise-arithmetic-shift-right (+ (bitwise-length n) 1) 1)]) (let f ([bb* (vector-ref largest-fixnum-big-base r)]) (let ([bb (caar bb*)]) (if (> (bitwise-length bb) iln/2) bb* (f (cons (cons (* bb bb) (* (cdar bb*) 2)) bb*))))))) (lambda (n r p) (let f ([n n] [d 0] [bb* (big-bases n r)]) (cond [(fixnum? n) (wrfixits n r d p)] [(> (caar bb*) n) (f n d (cdr bb*))] [else (let ([hi.lo ($quotient-remainder n (caar bb*))]) (f (car hi.lo) (- d (cdar bb*)) (cdr bb*)) (f (cdr hi.lo) (cdar bb*) (cdr bb*)))]))))) (define wrradix (lambda (r p) (case r [(16) (display-string "#x" p)] [(8) (display-string "#o" p)] [(2) (display-string "#b" p)] [else (write-char #\# p) (wrfixits r 10 p) (write-char #\r p)]))) (define wrinexactnum (lambda (x r d? p) (let ([x1 ($inexactnum-real-part x)] [x2 ($inexactnum-imag-part x)]) (wrflonum #f x1 r d? p) (wrflonum #t x2 r #t p) (write-char #\i p)))) (define wrexactnum (lambda (x r d? p) (let ([x1 ($exactnum-real-part x)] [x2 ($exactnum-imag-part x)]) (wrhelp x1 r #f #f d? #f p) (unless (< x2 0) (write-char #\+ p)) (wrhelp x2 r #f #f #t #f p) (write-char #\i p)))) (define wrratnum (lambda (x r d? p) (let ([n (numerator x)] [d (denominator x)]) (if (fixnum? n) (wrfixnum n r d? p) (wrbignum n r d? p)) (write-char #\/ p) (if (fixnum? d) (wrfixits d r p) (wrbigits d r p))))) (define wrbignum (lambda (x r d? p) (unless (or (fx= r 10) d?) (wrradix r p)) (wrbigits (if (< x 0) (begin (write-char #\- p) (- x)) x) r p))) (define wrfixnum (lambda (x r d? p) (unless (or (fx= r 10) d?) (wrradix r p)) (if (fx< x 0) (begin (write-char #\- p) (wrfixits-negative x r p)) (wrfixits x r p)))) (define wrflonum (let () (define flonum-digit->char (lambda (n) (string-ref "#00123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" (fx+ n 2)))) (define free-format (lambda (e s p) (when (fx< e 0) (write-char #\0 p) (write-char #\. p) (let loop ([e e]) (when (fx< e -1) (write-char #\0 p) (loop (fx+ e 1))))) (let loop ([u (car s)] [s (cdr s)] [e e]) (write-char (flonum-digit->char u) p) (when (fx= e 0) (write-char #\. p)) (let ([u (car s)]) (when (or (fx>= u 0) (fx>= e 0)) (loop u (cdr s) (fx- e 1))))))) (define free-format-exponential (lambda (e s r p) (write-char (flonum-digit->char (car s)) p) (let ([s (cdr s)]) (unless (fx< (car s) 0) (write-char #\. p)) (let loop ([s s]) (let ([u (car s)]) (unless (fx< u 0) (write-char (flonum-digit->char u) p) (loop (cdr s)))))) (write-char #\e p) (wrfixnum e r #t p))) (define display-precision (lambda (m p) (write-char #\| p) (if (fixnum? m) (wrfixits m 10 p) (wrbigits m 10 p)))) (lambda (force-sign x r d? p) ;;; R4RS & IEEE-1178 technically demand radix 10, but screw 'em (if (exceptional-flonum? x) (if ($nan? x) (display-string "+nan.0" p) (if (fl> x 0.0) (display-string "+inf.0" p) (display-string "-inf.0" p))) (let ([dx (decode-float x)]) (unless (or (fx= r 10) d?) (wrradix r p)) (let ([ls ($flonum->digits dx r 'normal 0)]) (let ([s (car ls)] [e (cadr ls)] [ls (cddr ls)]) (if (fx< s 0) (write-char #\- p) (when force-sign (write-char #\+ p))) (if (or (fx> r 10) (fx< -4 e 10)) (free-format e ls p) (free-format-exponential e ls r p)))) (cond [(print-precision) => (lambda (m) (if (and (fixnum? m) (fx< m 53)) (display-precision (fxmax m (integer-length (vector-ref dx 0))) p) (display-precision m p)))] [else (let ([m (integer-length (vector-ref dx 0))]) (when (fx< 0 m 53) (display-precision m p)))])))))) (define wrchar (lambda (x p) (define (r6rs-char-name x) (cond [(assq x '((#\nul . nul) (#\alarm . alarm) (#\backspace . backspace) (#\tab . tab) (#\newline . newline) (#\vtab . vtab) (#\page . page) (#\return . return) (#\esc . esc) (#\space . space) (#\delete . delete))) => cdr] [else #f])) (display-string "#\\" p) (cond [(if (print-char-name) (char-name x) (r6rs-char-name x)) => (lambda (name) (display-string (symbol->string name) p))] [(or (char<=? #\x21 x #\x7e) (and (print-unicode) (char>=? x #\x80) (not (char=? x #\nel)) (not (char=? x #\ls)))) (write-char x p)] [else (write-char #\x p) (wrfixits (char->integer x) 16 p)]))) (define wrstring (lambda (x p) (write-char #\" p) (let ([n (string-length x)]) (do ([i 0 (fx+ i 1)]) ((fx= i n)) (let ([c (string-ref x i)]) (cond [(memv c '(#\" #\\)) (write-char #\\ p) (write-char c p)] [(or (char<=? #\x20 c #\x7e) (and (print-unicode) (char>=? c #\x80) (not (char=? c #\nel)) (not (char=? c #\ls)))) (write-char c p)] [else (case c [(#\bel) (write-char #\\ p) (write-char #\a p)] [(#\backspace) (write-char #\\ p) (write-char #\b p)] [(#\newline) (write-char #\\ p) (write-char #\n p)] [(#\page) (write-char #\\ p) (write-char #\f p)] [(#\return) (write-char #\\ p) (write-char #\r p)] [(#\tab) (write-char #\\ p) (write-char #\t p)] [(#\vt) (write-char #\\ p) (write-char #\v p)] [else (write-char #\\ p) (write-char #\x p) (wrfixits (char->integer c) 16 p) (write-char #\; p)])])))) (write-char #\" p))) (module (wrsymbol) ; this is like the one used in read, but has no eof clause (define-syntax state-case (lambda (x) (define state-case-test (lambda (cvar k) (with-syntax ((cvar cvar)) (syntax-case k (-) (char (char? (datum char)) #'(char=? cvar char)) ((char1 - char2) (and (char? (datum char1)) (char? (datum char2))) #'(char<=? char1 cvar char2)) (predicate (identifier? #'predicate) #'(predicate cvar)))))) (define state-case-help (lambda (cvar clauses) (syntax-case clauses (else) (((else exp1 exp2 ...)) #'(begin exp1 exp2 ...)) ((((k ...) exp1 exp2 ...) . more) (with-syntax (((test ...) (map (lambda (k) (state-case-test cvar k)) #'(k ...))) (rest (state-case-help cvar #'more))) #'(if (or test ...) (begin exp1 exp2 ...) rest))) (((k exp1 exp2 ...) . more) (with-syntax ((test (state-case-test cvar #'k)) (rest (state-case-help cvar #'more))) #'(if test (begin exp1 exp2 ...) rest)))))) (syntax-case x () ((_ cvar more ...) (identifier? #'cvar) (state-case-help #'cvar #'(more ...)))))) (define (print-hex-char c p) (write-char #\\ p) (write-char #\x p) (wrfixits (char->integer c) 16 p) (write-char #\; p)) (define (s0 s p n) (let ([c (string-ref s 0)]) (state-case c [((#\a - #\z) (#\A - #\Z) #\* #\= #\< #\> #\/ #\! #\$ #\% #\& #\: #\? #\^ #\_ #\~) (write-char c p)] [(#\.) (if (and (fx= n 3) (char=? (string-ref s 1) #\.) (char=? (string-ref s 2) #\.)) (write-char #\. p) (print-hex-char c p))] [(#\-) (if (or (fx= n 1) (char=? (string-ref s 1) #\>)) (write-char #\- p) (print-hex-char c p))] [(#\+) (if (fx= n 1) (write-char #\+ p) (print-hex-char c p))] [$constituent? (if (print-unicode) (write-char c p) (print-hex-char c p))] [else (print-hex-char c p)])) (s1 s p n 1)) (define (s1 s p n i) (unless (fx= i n) (let ([c (string-ref s i)]) (state-case c [((#\a - #\z) (#\A - #\Z) #\- #\? (#\0 - #\9) #\* #\! #\= #\> #\< #\$ #\% #\& #\/ #\: #\^ #\_ #\~ #\+ #\. #\@) (write-char c p)] [$constituent? (if (print-unicode) (write-char c p) (print-hex-char c p))] [$subsequent? (if (print-unicode) (write-char c p) (print-hex-char c p))] [else (print-hex-char c p)])) (s1 s p n (fx+ i 1)))) (define extended-identifier? (let () (define-syntax state-machine (lambda (x) (syntax-case x () ((_k start-state (name def (test e) ...) ...) (with-implicit (_k s i n) ; support num4 kludge #'(let () (define name (lambda (s i n) (if (= i n) def (let ([g (string-ref s i)]) (state-machine-help (s i n) g (test e) ... ))))) ... (lambda (string) (start-state string 0 (string-length string))))))))) (define-syntax state-machine-help (syntax-rules (else to skip) [(_ (s i n) c [test (skip to x)] more ...) (state-machine-help (s i n) c [test (x s i n)] more ...)] [(_ (s i n) c [test (to x)] more ...) (state-machine-help (s i n) c [test (x s (fx+ i 1) n)] more ...)] [(_ (s i n) c [else e]) e] [(_ (s i n) c [test e] more ...) (if (state-machine-test c test) e (state-machine-help (s i n)c more ...))])) (define-syntax state-machine-test (syntax-rules (-) [(_ c (char1 - char2)) (char<=? char1 c char2)] [(_ c (e1 e2 ...)) (or (state-machine-test c e1) (state-machine-test c e2) ...)] [(_ c char) (char=? c char)])) (state-machine start (start #f ; start state [((#\a - #\z) (#\A - #\Z)) (to sym)] [(#\- #\+) (to num1)] [(#\* #\= #\> #\<) (to sym)] [(#\0 - #\9) (to num4)] [#\. (to num2)] [(#\{ #\}) (to brace)] [else (skip to sym)]) (num1 #t ; seen + or - [(#\0 - #\9) (to num4)] [#\. (to num3)] [(#\i #\I) (to num5)] [else (skip to sym)]) (num2 #f ; seen . [(#\0 - #\9) (to num4)] [else (skip to sym)]) (num3 #f ; seen +. or -. [(#\0 - #\9) (to num4)] [else (skip to sym)]) (num4 #f ; seen digit, +digit, -digit, or .digit [else ; kludge (if (number? ($str->num s n 10 #f #f)) ; grabbing private s and n #f (sym s i n))]) ; really (skip to sym) (num5 #f ; bars: seen +i, -i, +I, or -I [else (skip to sym)]) (sym #t ; safe symbol [((#\a - #\z) (#\A - #\Z) #\- #\? (#\0 - #\9) #\* #\! #\= #\> #\< #\+ #\/) (to sym)] [((#\nul - #\space) #\( #\) #\[ #\] #\{ #\} #\" #\' #\` #\, #\; #\" #\\ #\|) #f] [else (to sym)]) (brace #t ; { or } [else #f])))) (define wrsymbol (case-lambda [(s p) (wrsymbol s p #f)] [(s p tail?) (let ([n (string-length s)]) (if tail? (s1 s p n 0) (if (fx= n 0) (display-string "||" p) (if (and (print-extended-identifiers) (extended-identifier? s)) (display-string s p) (s0 s p n)))))]))) (set! $write-pretty-quick (lambda (x lev len env p) (wrhelp x (print-radix) lev len #f env p))) (let () (define (do-write x p who) (when (port-closed? p) ($oops who "not permitted on closed port ~s" p)) (let ([lev (print-level)] [len (print-length)]) (let ([env ($make-graph-env who x lev len)]) (wr x (print-radix) lev len #f env p)))) (set-who! write (case-lambda [(x p) (unless (and (output-port? p) (textual-port? p)) ($oops 'write "~s is not a textual output port" p)) (do-write x p who)] [(x) (do-write x (current-output-port) who)])) (set-who! put-datum (lambda (p x) (unless (and (output-port? p) (textual-port? p)) ($oops who "~s is not a textual output port" p)) (do-write x p who)))) (let () (define (do-display x p who) (when (port-closed? p) ($oops who "not permitted on closed port ~s" p)) (wr x (print-radix) #f #f #t #f p)) (set-who! display (case-lambda [(x p) (unless (and (output-port? p) (textual-port? p)) ($oops 'display "~s is not a textual output port" p)) (do-display x p who)] [(x) (do-display x (current-output-port) who)]))) ) ;let (define print-gensym ($make-thread-parameter #t (lambda (x) (if (memq x '(pretty pretty/suffix)) x (and x #t))))) (define print-record ($make-thread-parameter #t (lambda (x) (and x #t)))) (define print-graph ($make-thread-parameter #f (lambda (x) (and x #t)))) (define print-level ($make-thread-parameter #f (lambda (x) (unless (or (not x) (and (fixnum? x) (fx>= x 0))) ($oops 'print-level "~s is not a nonnegative fixnum or #f" x)) x))) (define print-length ($make-thread-parameter #f (lambda (x) (unless (or (not x) (and (fixnum? x) (fx>= x 0))) ($oops 'print-length "~s is not a nonnegative fixnum or #f" x)) x))) (define print-radix ($make-thread-parameter 10 (lambda (x) (unless (and (fixnum? x) (fx<= 2 x 36)) ($oops 'print-radix "~s is not between 2 and 36" x)) x))) (define print-brackets ($make-thread-parameter #t (lambda (x) (and x #t)))) (define print-unicode ($make-thread-parameter #t (lambda (x) (and x #t)))) (define print-char-name ($make-thread-parameter #f (lambda (x) (and x #t)))) (define print-vector-length ($make-thread-parameter #f (lambda (x) (and x #t)))) (define print-extended-identifiers ($make-thread-parameter #f (lambda (x) (and x #t)))) (define print-precision ($make-thread-parameter #f (lambda (x) (unless (or (not x) (and (fixnum? x) (fx> x 0)) (and (bignum? x) ($bigpositive? x))) ($oops 'print-precision "~s is not a positive exact integer or #f" x)) x))) )
true
e2767f492a182aa937adad11cb8ab26a589346c5
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/cl/clchap7b.scm
1ebe5ac208698f0814c96434c3a4a3cb5c191ae7
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
4,390
scm
clchap7b.scm
;;; ******** ;;; ;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt, ;;; Beranek and Newman Inc. ;;; ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice and this permission appear in all copies and in ;;; supporting documentation, and that the name Bolt, Beranek and Newman ;;; Inc. not be used in advertising or publicity pertaining to distribution ;;; of the software without specific, written prior permission. In ;;; addition, BBN makes no respresentation about the suitability of this ;;; software for any purposes. It is provided "AS IS" without express or ;;; implied warranties including (but not limited to) all implied warranties ;;; of merchantability and fitness. In no event shall BBN be liable for any ;;; special, indirect or consequential damages whatsoever resulting from ;;; loss of use, data or profits, whether in an action of contract, ;;; negligence or other tortuous action, arising out of or in connection ;;; with the use or performance of this software. ;;; ;;; ******** ;;; ;;; ;; Chapter 7 -- Control Structure (proclaim '(insert-touches nil)) (export '(tagbody prog prog* go values values-list multiple-value-list multiple-value-call multiple-value-prog1 multiple-value-bind multiple-value-setq catch unwind-protect throw)) ;;prog and prog* (boot-defmacro prog (vars &rest body) (prim-with-values (lambda () (parse-body-internal body *syntax-time-env* #f)) (lambda (code decls doc) `(block nil (let ,vars ,@decls (tagbody ,@code)))))) (boot-defmacro prog* (vars &rest body) (prim-with-values (lambda () (parse-body-internal body *syntax-time-env* #f)) (lambda (code decls doc) `(block nil (let* ,vars ,@decls (tagbody ,@code)))))) ;;7.9 Multiple Values (cl-define values prim-values) (cl-define values-list prim-values-list) (boot-defmacro multiple-value-list (form) `(prim-with-values (lambda () ,form) (lambda all all))) (def-special-form (multiple-value-call function . forms) `(apply ,function (append ,@((access mapcar ()) (lambda (form) `(multiple-value-list ,form)) forms)))) (def-special-form (multiple-value-prog1 form . forms) (let ((result (generate-uninterned-symbol 'mvprog1))) `(let ((,result (multiple-value-list ,form))) ,@forms (values-list ,result)))) (boot-defmacro multiple-value-bind (vars values-form &rest body) (let ((ignore (generate-uninterned-symbol 'mvbignore))) `(prim-with-values (lambda () ,values-form) (cl-lambda (&optional ,@vars &rest ,ignore) ,@body)))) (boot-defmacro multiple-value-setq (variables form) (let ((result (generate-uninterned-symbol 'mvsetq))) (let ((binding-list (labels ((make-binding-loop (n v) (if (null? v) '() (cons (car v) (cons (cons 'nth (list n result)) (make-binding-loop (1+ n) (cdr v))))))) (make-binding-loop 0 variables)))) `(let ((,result (multiple-value-list ,form))) (setq ,@binding-list) (car ,result))))) ;;7.10 Dynamic non-local exits (define *common-lisp-catch-throw-stack* '()) (def-special-form (catch tag . forms) (let ((cont (fundefsym (generate-uninterned-symbol 'catch-)))) `(cl-nr-call/cc;; This is the non-reenterant kind since (lambda (,cont);; catches are not reused. (values-list (fluid-let ((*common-lisp-catch-throw-stack* (cons (list ,tag ,cont) *common-lisp-catch-throw-stack*))) (multiple-value-list (progn ,@forms)))))))) (def-special-form (unwind-protect protected-form . cleanup-forms) `(values-list (dynamic-wind (lambda () #!null) (lambda () (multiple-value-list ,protected-form)) (lambda () ,@cleanup-forms)))) (def-special-form (throw tag form) (let ((assoc-tag (generate-uninterned-symbol 'assoc-tag)) (result (generate-uninterned-symbol 'throw-result))) `(let ((,assoc-tag (assq ,tag *common-lisp-catch-throw-stack*))) (if (null? ,assoc-tag) (error "Throw to unknown tag: ~a" ,tag) (let ((,result (multiple-value-list ,form))) (apply (second ,assoc-tag) ,result))))));; Apply the continuation to the values to be returned by the form.
false
ecab0ff64875adfb5d5c87f793bc29efa66b15ec
943e73b33b7bc61fee44808cbd18f91c7ed1db7a
/chicken-thread-object-inlines.scm
c4213ac6a0ca8baa0cdb68d0e310f5ce914e5c9f
[ "BSD-3-Clause" ]
permissive
opt9/chicken-scheme
a631d3fb455c61312e0c9d30d791c78a6d99a7f6
1eb14684c26b7c2250ca9b944c6b671cb62cafbc
refs/heads/master
2020-03-09T15:41:06.499607
2009-07-25T23:49:53
2009-07-25T23:49:53
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
7,884
scm
chicken-thread-object-inlines.scm
;;;; chicken-thread-object-primitive-inlines.scm ;;;; Kon Lovett, Jan '09 ; Usage ; ; (include "chicken-primitive-object-inlines") ; (include "chicken-thread-object-inlines") ;; Notes ; ; Provides inlines & macros for thread objects. Use of these procedures ; by non-core & non-core-extensions is highly suspect. Many of these routines ; are unsafe. ; ; In fact, any use is suspect ;-) ;;; Mutex object helpers: ;; Mutex layout: ; ; 0 Tag - 'mutex ; 1 Name (object) ; 2 Thread (thread or #f) ; 3 Waiting threads (FIFO list) ; 4 Abandoned? (boolean) ; 5 Locked? (boolean) ; 6 Specific (object) (define-inline (%mutex? x) (%structure-instance? x 'mutex) ) (define-inline (%mutex-name mx) (%structure-ref mx 1) ) (define-inline (%mutex-thread mx) (%structure-ref mx 2) ) (define-inline (%mutex-thread-set! mx th) (%structure-set!/mutate mx 2 th) ) (define-inline (%mutex-thread-clear! mx) (%structure-set!/immediate mx 2 #f) ) (define-inline (%mutex-waiters mx) (%structure-ref mx 3) ) (define-inline (%mutex-waiters-set! mx wt) (%structure-set!/mutate mx 3 wt) ) (define-inline (%mutex-waiters-empty? mx) (%null? (%mutex-waiters mx)) ) (define-inline (%mutex-waiters-empty! mx) (%structure-set!/immediate mx 3 '()) ) (define-inline (%mutex-waiters-add! mx th) (%mutex-waiters-set! mx (%append! (%mutex-waiters mx) (%cons th '()))) ) (define-inline (%mutex-waiters-delete! mx th) (%mutex-waiters-set! mx (%delq! th (%mutex-waiters mx))) ) (define-inline (%mutex-waiters-pop! mx) (let* ([wt (%mutex-waiters mx)] [top (%car wt)]) (%mutex-waiters-set! mx (%cdr wt)) top ) ) (define-inline (%mutex-abandoned? mx) (%structure-ref mx 4) ) (define-inline (%mutex-abandoned-set! mx f) (%structure-set!/immediate mx 4 f) ) (define-inline (%mutex-locked? mx) (%structure-ref mx 5) ) (define-inline (%mutex-locked-set! mx f) (%structure-set!/immediate mx 5 f) ) (define-inline (%mutex-specific mx) (%structure-ref mx 6) ) (define-inline (%mutex-specific-set! mx x) (%structure-set!/mutate mx 6 x) ) ;;; Thread object helpers: ;; Thread layout: ; ; 0 Tag - 'thread ; 1 Thunk (procedure) ; 2 Results (list-of object) ; 3 State (symbol) ; 4 Block-timeout (fixnum or #f) ; 5 State buffer (vector) ; 0 Dynamic winds (list) ; 1 Standard input (port) ; 2 Standard output (port) ; 3 Standard error (port) ; 4 Exception handler (procedure) ; 5 Parameters (vector) ; 6 Name (object) ; 7 Reason (condition of #f) ; 8 Mutexes (list-of mutex) ; 9 Quantum (fixnum) ; 10 Specific (object) ; 11 Block object (thread or (pair-of fd io-mode)) ; 12 Recipients (list-of thread) ; 13 Unblocked by timeout? (boolean) (define-inline (%thread? x) (%structure-instance? x 'thread) ) (define-inline (%thread-thunk th) (%structure-ref th 1) ) (define-inline (%thread-thunk-set! th tk) (%structure-set!/mutate th 1 tk) ) (define-inline (%thread-results th) (%structure-ref th 2) ) (define-inline (%thread-results-set! th rs) (%structure-set!/mutate th 2 rs) ) (define-inline (%thread-state th) (%structure-ref th 3) ) (define-inline (%thread-state-set! th st) (%structure-set!/mutate th 3 st) ) (define-inline (%thread-block-timeout th) (%structure-ref th 4) ) (define-inline (%thread-block-timeout-set! th to) (%structure-set!/immediate th 4 to) ) (define-inline (%thread-block-timeout-clear! th) (%thread-block-timeout-set! th #f) ) (define-inline (%thread-state-buffer th) (%structure-ref th 5) ) (define-inline (%thread-state-buffer-set! th v) (%structure-set!/mutate th 5 v) ) (define-inline (%thread-name th) (%structure-ref th 6) ) (define-inline (%thread-reason th) (%structure-ref th 7) ) (define-inline (%thread-reason-set! th cd) (%structure-set!/mutate th 7 cd) ) (define-inline (%thread-mutexes th) (%structure-ref th 8) ) (define-inline (%thread-mutexes-set! th wt) (%structure-set!/mutate th 8 wx) ) (define-inline (%thread-mutexes-empty? th) (%null? (%thread-mutexes th)) ) (define-inline (%thread-mutexes-empty! th) (%structure-set!/immediate th 8 '()) ) (define-inline (%thread-mutexes-add! th mx) (%thread-mutexes-set! th (%cons mx (%thread-mutexes th))) ) (define-inline (%thread-mutexes-delete! th mx) (%thread-mutexes-set! th (%delq! mx (%thread-mutexes th))) ) (define-inline (%thread-quantum th) (%structure-ref th 9) ) (define-inline (%thread-quantum-set! th qt) (%structure-set!/immediate th 9 qt) ) (define-inline (%thread-specific th) (%structure-ref th 10) ) (define-inline (%thread-specific-set! th x) (%structure-set!/mutate th 10 x) ) (define-inline (%thread-block-object th) (%structure-ref th 11) ) (define-inline (%thread-block-object-set! th x) (%structure-set!/mutate th 11 x) ) (define-inline (%thread-block-object-clear! th) (%structure-set!/immediate th 11 #f) ) (define-inline (%thread-recipients th) (%structure-ref th 12) ) (define-inline (%thread-recipients-set! th x) (%structure-set!/mutate th 12 x) ) (define-inline (%thread-recipients-empty? th) (%null? (%condition-variable-waiters th)) ) (define-inline (%thread-recipients-empty! th) (%structure-set!/immediate th 12 '()) ) (define-inline (%thread-recipients-add! th rth) (%thread-recipients-set! t (%cons rth (%thread-recipients t))) ) (define-inline (%thread-recipients-process! th tk) (let ([rs (%thread-recipients t)]) (unless (%null? rs) (for-each tk rs) ) ) (%thread-recipients-empty! t) ) (define-inline (%thread-unblocked-by-timeout? th) (%structure-ref th 13) ) (define-inline (%thread-unblocked-by-timeout-set! th f) (%structure-set!/immediate th 13 f) ) (define-inline (%thread-blocked-for-timeout? th) (and (%thread-block-timeout th) (not (%thread-block-object th))) ) (define-inline (%thread-blocked? th) (%eq? 'blocked (%thread-state th)) ) (define-inline (%thread-created? th) (%eq? 'created (%thread-state th)) ) (define-inline (%thread-ready? th) (%eq? 'ready (%thread-state th)) ) (define-inline (%thread-sleeping? th) (%eq? 'sleeping (%thread-state th)) ) (define-inline (%thread-suspended? th) (%eq? 'suspended (%thread-state th)) ) (define-inline (%thread-terminated? th) (%eq? 'terminated (%thread-state th)) ) (define-inline (%thread-dead? th) (%eq? 'dead (%thread-state th)) ) ;; Synonyms (define-inline (%current-thread) ##sys#current-thread ) ;;; Condition-variable object: ;; Condition-variable layout: ; ; 0 Tag - 'condition-variable ; 1 Name (object) ; 2 Waiting threads (FIFO list) ; 3 Specific (object) (define-inline (%condition-variable? x) (%structure-instance? x 'condition-variable) ) (define-inline (%condition-variable-name cv) (%structure-ref cv 1) ) (define-inline (%condition-variable-waiters cv) (%structure-ref cv 2) ) (define-inline (%condition-variable-waiters-set! cv x) (%structure-set!/mutate cv 2 x) ) (define-inline (%condition-variable-waiters-empty? cv) (%null? (%condition-variable-waiters cv)) ) (define-inline (%condition-variable-waiters-empty! cv) (%structure-set!/immediate cv 2 '()) ) (define-inline (%condition-variable-waiters-add! cv th) (%condition-variable-waiters-set! cv (%append! (%condition-variable-waiters cv) (%cons th '()))) ) (define-inline (%condition-variable-waiters-delete! cv th) (%condition-variable-waiters-set! cv (%delq! th (%condition-variable-waiters cv))) ) (define-inline (%condition-variable-waiters-pop! mx) (let* ([wt (%condition-variable-waiters mx)] [top (%car wt)]) (%condition-variable-waiters-set! mx (%cdr wt)) top ) ) (define-inline (%condition-variable-specific cv) (%structure-ref cv 3) ) (define-inline (%condition-variable-specific-set! cv x) (%structure-set!/mutate cv 3 x) )
false
d1f7a663a1b18c8d0e0cff2c2cf9d734a7a894ef
29b17c2b8d6983198caf5e620dae0da98610b2a6
/Compiler/optimize-known-call.ss
03eaf506a6e4703407adfb5076371fa8cd34694a
[]
no_license
daaasbu/Scheme-Compiler-x86
ec3f4cd3e2c94c965c0e53ebb45e1a41627dc090
df971488bbac985479b2d2a516e3f9e566892c61
HEAD
2016-09-06T08:28:51.083237
2015-03-14T03:08:13
2015-03-14T03:08:13
32,192,637
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,260
ss
optimize-known-call.ss
(library (Compiler optimize-known-call) (export optimize-known-call) (import (chezscheme) (source-grammar) (Framework helpers) (Framework nanopass)) (define-pass optimize-known-call : LconvertClosures (orig) -> LconvertClosures () (definitions (define uv->label (lambda (sym) (let* ((name (extract-root sym)) (num (extract-suffix sym)) (str (string-append name "$" num)) (l (string->symbol str))) l))) ) #| (find-vars : Expr (x bound*) -> Expr () [,l `,l] [(letrec ([,l0* (lambda (,uv0* ...) (bind-free (,uv2 ,uv2* ...) ,expr0))] ...) (closures ((,uv1* ,l1* ,uv** ...) ...) ,expr1)) (let ((bound1* (append uv1* l1* uv**))) `(letrec ([,l0* (lambda (,uv0* ...) ,(find-vars expr0 bound1*))] ...) (closures ((,uv1* ,l1* ,uv** ...) ...) ,(find-vars expr1 bound1*))))] [,uv `,uv] [(let ([,uv* ,[find-vars : expr* bound* -> expr*]] ...) ,[find-vars : expr bound* -> expr]) `(let ([,uv* ,expr*] ...) ,expr)] [(quote ,i) `(quote ,i)] [(if ,[find-vars : expr0 bound* -> expr0] ,[find-vars : expr1 bound* -> expr1] ,[find-vars : expr2 bound* -> expr2]) `(if ,expr0 ,expr1 ,expr2)] [(begin ,[find-vars : expr* bound* -> expr*] ... ,[find-vars : expr bound* -> expr]) `(begin ,expr* ... ,expr)] [(,prim ,[find-vars : expr* bound* -> expr*] ...) `(prim ,expr* ...) ] [(call ,expr ,[find-vars : expr* bound* -> expr*] ...) (if (and (uvar? expr) (memq expr bound*)) `(call ,(uv->label expr) ,expr*) `(call ,expr ,expr* ...))]) |# (Expr : Expr (x bound*) -> Expr () [(letrec ([,l0* (lambda (,uv0* ...) (bind-free (,uv2 ,uv2* ...) ,expr0*))] ...) (closures ((,uv1* ,l1* ,uv** ...) ...) ,expr1)) `(letrec ([,l0* (lambda (,uv0* ...) (bind-free (,uv2 ,uv2* ...) ,(map (lambda (x) (Expr x (append uv1* bound*))) expr0*)))] ...) (closures ((,uv1* ,l1* ,uv** ...) ...) ,(Expr expr1 (append uv1* bound*))))] [(call ,uv ,expr* ...) (if (memq uv bound*) `(call ,(uv->label uv) ,(map (lambda (x) (Expr x bound*)) expr*) ...) `(call ,uv ,(map (lambda (x) (Expr x bound*)) expr*) ...))]) (Expr orig '()) ) )
false
f79f7d245faf2ce44a08db3c7a5674e1c366623d
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Data/system/data/odbc/odbc-category-attribute.sls
2f2699cfb117bb9dd8fbab323828d90c889bdd0d
[]
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
591
sls
odbc-category-attribute.sls
(library (system data odbc odbc-category-attribute) (export new is? odbc-category-attribute? category) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Data.Odbc.OdbcCategoryAttribute a ...))))) (define (is? a) (clr-is System.Data.Odbc.OdbcCategoryAttribute a)) (define (odbc-category-attribute? a) (clr-is System.Data.Odbc.OdbcCategoryAttribute a)) (define-field-port category #f #f (property:) System.Data.Odbc.OdbcCategoryAttribute Category System.String))
true
e2b1e3c21d7f0404a4bf2c36b95d827680d40422
46244bb6af145cb393846505f37bf576a8396aa0
/sicp/3_26.scm
e26a3fc83f5e40b2e86d97623520e298c02300e1
[]
no_license
aoeuidht/homework
c4fabfb5f45dbef0874e9732c7d026a7f00e13dc
49fb2a2f8a78227589da3e5ec82ea7844b36e0e7
refs/heads/master
2022-10-28T06:42:04.343618
2022-10-15T15:52:06
2022-10-15T15:52:06
18,726,877
4
3
null
null
null
null
UTF-8
Scheme
false
false
670
scm
3_26.scm
; Exercise 3.26. To search a table as implemented above, one needs to scan ; through the list of records. This is basically the unordered list representation of section 2.3.3. ; For large tables, it may be more efficient to ; structure the table in a different manner. Describe a table implementation where the (key, value) ; records are organized using a binary tree, assuming that keys can be ordered in some way ; (e.g., numerically or alphabetically). (Compare exercise 2.66 of chapter 2.) ; Answer ; to do this, You have to write a ``red-black tree``, which is introduced in chapteer 13, ; Introduction to Algorithms, and I'll do that when I'm reading that book.
false
9f1f3c9e92bbbfa718e80359f95e1913fd5a396f
077d3f3eb1b85df9980141becd8b876aaf9bf561
/lib/for-almost-up-to.scm
0e2a9d62e9b912173d29ec0fc8e35363e6268b8a
[ "MIT" ]
permissive
lyp-packages/chtab
f2d398d8ceeff134eb03d0fb11a6d93bb49ab87e
0c59bac6d1e7b49d59a6ca855ef3c97fa1537ac6
refs/heads/master
2021-01-11T20:53:22.437178
2017-01-17T09:14:21
2017-01-17T09:14:21
79,204,692
0
0
null
null
null
null
UTF-8
Scheme
false
false
319
scm
for-almost-up-to.scm
(define-module (scm for-almost-up-to) #:use-syntax (ice-9 syncase) #:export-syntax (for)) ; usage: (for i almost-up-to 10 (begin (display i)(newline))) displays #s from 0 to 9 (define-syntax for (syntax-rules (almost-up-to) ((for xy1 almost-up-to xy2 xy-rest)(do ((xy1 0 (1+ xy1)))((= xy1 xy2)) xy-rest))))
true
1aadc0ad7199f8bc6a585474f7d5290fb7e18dc5
fc070119c083d67c632e3f377b0585f77053331e
/exercises/02/factorial-iter.scm
06a3e26a1ddd26b319448d8afbecc237a3b9804e
[]
no_license
dimitaruzunov/fp-2018
abcd90396e9e8b73efe4e2b8a0634866948269a8
f75f0cd009cc7f41ce55a5ec71fb4b8eadafc4eb
refs/heads/master
2020-03-31T11:01:55.426456
2019-01-08T20:22:16
2019-01-08T20:22:16
152,160,081
9
3
null
null
null
null
UTF-8
Scheme
false
false
606
scm
factorial-iter.scm
(require rackunit rackunit/text-ui) (define (factorial-iter n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) (define factorial-iter-tests (test-suite "Tests for factorial-iter" (check = (factorial-iter 0) 1) (check = (factorial-iter 1) 1) (check = (factorial-iter 2) 2) (check = (factorial-iter 3) 6) (check = (factorial-iter 4) 24) (check = (factorial-iter 5) 120) (check = (factorial-iter 6) 720) (check = (factorial-iter 7) 5040))) (run-tests factorial-iter-tests)
false
7d9a487c9880ebf610143806aa0a50b60f2ca039
25a487e394b2c8369f295434cf862321c26cd29c
/lib/pikkukivi/commands/mount-nfs.sls
7b17d77d1fe6847c2d62022477cfc1056f900f71
[]
no_license
mytoh/loitsu
b11e1ed9cda72c0a0b0f59070c9636c167d01a2c
d197cade05ae4acbf64c08d1a3dd9be6c42aac58
refs/heads/master
2020-06-08T02:00:50.563515
2013-12-17T10:23:04
2013-12-17T10:23:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,308
sls
mount-nfs.sls
(library (pikkukivi commands mount-nfs) (export mount-nfs) (import (silta base) (silta cxr) (silta write) (only (srfi :13 strings) string-join) (loitsu match) (mosh process)) (begin (define (mount-nfs args) (let ((disk (caddr args)) (user (cadddr args))) (match disk ; commands ("mypassport" (mount-mypassport)) ("deskstar" (mount-deskstar)) ("quatre" (mount-quatre user)) ("all" (mount-mypassport) (mount-deskstar) (mount-quatre user))))) (define mount (lambda (src dest) (display (string-append "mounting " src)) (newline) (call-process (string-join `("sudo" "mount" "-v" "-o" "soft" ,src ,dest))))) (define (mount-mypassport) (mount "quatrevingtdix:/Volumes/MyPassport" "/nfs/mypassport")) (define (mount-deskstar) (mount "quatrevingtdix:/Volumes/Deskstar" "/nfs/deskstar")) (define (mount-quatre user) (mount (string-append "quatrevingtdix:/Users/" user) "/nfs/quatre")) )) ;; vim:filetype=scheme
false
41c959a38a0c2b3295ccf520ae8c098eed3727a7
a9377d6da484ad6d7844a8d809af98ab6470dda3
/chaos/and-let-values.ss
a512c5f03d9e2a043111ec1bfd89751fbc5cb07e
[]
no_license
ChaosEternal/and-let-values
6871cf51ed86b765b1c017a754770d7e6508a5ec
b2e5924e9019178b6e44741dba518f4bea409f70
refs/heads/master
2021-01-20T10:13:32.802106
2017-05-08T08:48:29
2017-05-08T08:48:29
90,336,465
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,164
ss
and-let-values.ss
(library (chaos and-let-values) (export and-let*-values and-let*-values-check) (import (rnrs base) (rnrs (6))) (define-syntax and-let*-values (lambda (stx) (syntax-case stx (else) ((_ (?bind0 ?bind1 ...) ?body0 ... (else ?expr0 ...)) (syntax-case #'?bind0 () (((?b0 ?b1 ...) ?exp) (identifier? #'?b0) #`(let-values (?bind0) (if ?b0 (and-let*-values (?bind1 ...) ?body0 ...) (begin ?expr0 ...)))))) ((_ () ?body0 ... (else ?expr0 ...)) #'(begin ?body0 ...)) ((_ (?bind0 ...) ?body0 ...) #'(and-let*-values (?bind0 ...) ?body0 ... (else #f)))))) (define-syntax and-let*-values-check (lambda (stx) (syntax-case stx (else) ((kw (?bind0 ?bind1 ...) ?body0 ... (else ?expr0 ...)) (syntax-case #'?bind0 () (((?b0 ?b1 ...) ?exp) (let* ((?check-b0 (car (generate-temporaries (list #'?b0))))) #`(let-values (((#,?check-b0 ?b1 ...) ?exp)) (if (equal? #,?check-b0 ?b0) (kw (?bind1 ...) ?body0 ...) (begin ?expr0 ...))))))) ((_ () ?body0 ... (else ?expr0 ...)) #'(begin ?body0 ...)) ((kw (?bind0 ...) ?body0 ...) #'(kw (?bind0 ...) ?body0 ... (else #f)))))))
true
6dd0cdefc761fb8c6cf32b49c42aefbc00ffe858
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/mono-async-call.sls
3ed3d0aa7cbb4f30d9fd57e66379cecd98d30dfc
[]
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
342
sls
mono-async-call.sls
(library (system mono-async-call) (export new is? mono-async-call?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.MonoAsyncCall a ...))))) (define (is? a) (clr-is System.MonoAsyncCall a)) (define (mono-async-call? a) (clr-is System.MonoAsyncCall a)))
true
2fb90a1bf036101f625abbbabff48d326f876f96
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/sitelib/rfc/jrd.scm
49935c057839ea73e24d7593dc035eaae4cb7fd7
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
4,650
scm
jrd.scm
;;; -*- mode:scheme; coding:utf-8; -*- ;;; ;;; rfc/jrd.scm - The JSON Resource Descriptor ;;; ;;; Copyright (c) 2017 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; reference: ;; - https://tools.ietf.org/html/rfc7033 ;; NB: this may be use for WebFinger which is defined in the same ;; RFC as JRD (more precisely, JRD is just an extraction of the ;; RFC) (library (rfc jrd) (export json-string->jrd jrd->json-string <jrd> jrd? make-jrd jrd-subject jrd-aliases jrd-properties jrd-links <jrd:link> jrd:link? make-jrd:link jrd:link-rel jrd:link-type jrd:link-href jrd:link-titles jrd:link-properties <jrd:property> jrd:property? make-jrd:property jrd:property-name jrd:property-value <jrd:title> jrd:title? make-jrd:title jrd:title-language jrd:title-title ) (import (rnrs) (text json) (text json object-builder)) (define-record-type (<jrd:property> make-jrd:property jrd:property?) (fields (immutable name jrd:property-name) (immutable value jrd:property-value))) (define-record-type (<jrd> make-jrd jrd?) (fields (immutable subject jrd-subject) (immutable aliases jrd-aliases) (immutable properties jrd-properties) (immutable links jrd-links))) (define-record-type (<jrd:title> make-jrd:title jrd:title?) (fields (immutable language jrd:title-language) (immutable title jrd:title-title))) (define-record-type (<jrd:link> make-jrd:link jrd:link?) (fields (immutable rel jrd:link-rel) (immutable type jrd:link-type) (immutable href jrd:link-href) (immutable titles jrd:link-titles) (immutable properties jrd:link-properties))) (define (->properties json) (define (->property kv) (make-jrd:property (car kv) (cdr kv))) (map ->property (vector->list json))) (define (->titles json) (define (->title kv) (make-jrd:title (car kv) (cdr kv))) (map ->title (vector->list json))) (define jrd-builder (json-object-builder (make-jrd "subject" (? "aliases" '() (@ list)) (? "properties" '() ->properties) (? "links" '() (@ list (make-jrd:link "rel" (? "type" #f) (? "href" #f) (? "titles" '() ->titles) (? "properties" '() ->properties))))))) (define (json-string->jrd json-string) (json-string->object json-string jrd-builder)) (define (properties->json props) (define (property->json prop) (cons (jrd:property-name prop) (jrd:property-value prop))) (list->vector (map property->json props))) (define (titles->json titles) (define (title->json title) (cons (jrd:title-language title) (jrd:title-title title))) (list->vector (map title->json titles))) (define jrd-serializer (json-object-serializer (("subject" jrd-subject) (? "aliases" '() jrd-aliases (->)) (? "properties" '() jrd-properties properties->json) (? "links" '() jrd-links (-> (("rel" jrd:link-rel) (? "type" #f jrd:link-type) (? "href" #f jrd:link-href) (? "titles" '() jrd:link-titles titles->json) (? "properties" '() jrd:link-properties properties->json))))))) (define (jrd->json-string jrd) (object->json-string jrd jrd-serializer)) )
false
8e907a26957340129589a84e9eff9f10c33b454f
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/boot/lib/scmlib.scm
7dc2bc6600fa5909b18cd505e177faeac4adb10f
[ "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
34,770
scm
scmlib.scm
;; for a bit of better performance (define (hashtable-for-each proc ht) (unless (procedure? proc) (assertion-violation 'hashtable-for-each (wrong-type-argument-message "procedure" proc 1))) (unless (hashtable? ht) (assertion-violation 'hashtable-for-each (wrong-type-argument-message "hashtable" ht 2))) (let ((itr (%hashtable-iter ht)) (eof (cons #t #t))) (let loop () (let-values (((k v) (itr eof))) (unless (eq? k eof) (proc k v) (loop)))))) (define (hashtable-map proc ht) (unless (procedure? proc) (assertion-violation 'hashtable-map (wrong-type-argument-message "procedure" proc 1))) (unless (hashtable? ht) (assertion-violation 'hashtable-map (wrong-type-argument-message "hashtable" ht 2))) (let ((itr (%hashtable-iter ht)) (eof (cons #t #t))) (let loop ((r '())) (let-values (((k v) (itr eof))) (if (eq? k eof) r (loop (cons (proc k v) r))))))) (define (hashtable-fold kons ht knil) (unless (procedure? kons) (assertion-violation 'hashtable-fold (wrong-type-argument-message "procedure" proc 1))) (unless (hashtable? ht) (assertion-violation 'hashtable-fold (wrong-type-argument-message "hashtable" ht 2))) (let ((itr (%hashtable-iter ht)) (eof (cons #t #t))) (let loop ((r knil)) (let-values (((k v) (itr eof))) (if (eq? k eof) r (loop (kons k v r))))))) (define (hashtable->alist ht) (hashtable-map cons ht)) (define (unique-id-list? lst) (and (list? lst) (not (let loop ((lst lst)) (and (pair? lst) (or (not (variable? (car lst))) (id-memq (car lst) (cdr lst)) (loop (cdr lst)))))))) #;(define (any pred ls) (if (pair? ls) (if (pred (car ls)) (car ls) (any pred (cdr ls))) #f)) (define (call-with-values producer consumer) (receive vals (producer) (apply consumer vals))) ;; print (define (print . args) (for-each display args) (newline)) (define (fold proc seed lst1 . lst2) (if (null? lst2) (let loop ((lis lst1) (knil seed)) (if (null? lis) knil (loop (cdr lis) (proc (car lis) knil)))) (let loop ((lis (apply list-transpose* lst1 lst2)) (knil seed)) (if (null? lis) knil (loop (cdr lis) (apply proc (append (car lis) (list knil)))))))) ;; from Ypsilon (define (wrong-type-argument-message expect got . nth) (if (null? nth) (format "expected ~a, but got ~a" expect got) (format "expected ~a, but got ~a, as argument ~a" expect got (car nth)))) ;; From Gauche ;; we don't define SRFI-43 vector-map/vector-for-each here ;; so make those tabulate/update! internal define for better performance. (define (vector-map proc vec . more) (define (vector-tabulate len proc) (let loop ((i 0) (r '())) (if (= i len) (list->vector (reverse! r)) (loop (+ i 1) (cons (proc i) r))))) (if (null? more) (vector-tabulate (vector-length vec) (lambda (i) (proc (vector-ref vec i)))) (let ((vecs (cons vec more))) (vector-tabulate (apply min (map vector-length vecs)) (lambda (i) (apply proc (map (lambda (v) (vector-ref v i)) vecs))))))) (define (vector-map! proc vec . more) (define (vector-update! vec len proc) (let loop ((i 0)) (if (= i len) vec (begin (vector-set! vec i (proc i)) (loop (+ i 1)))))) (if (null? more) (vector-update! vec (vector-length vec) (lambda (i) (proc (vector-ref vec i)))) (let ((vecs (cons vec more))) (vector-update! vec (apply min (map vector-length vecs)) (lambda (i) (apply proc (map (lambda (v) (vector-ref v i)) vecs))))))) (define (vector-for-each proc vec . more) (if (null? more) (let ((len (vector-length vec))) (let loop ((i 0)) (unless (= i len) (proc (vector-ref vec i)) (loop (+ i 1))))) (let* ((vecs (cons vec more)) (len (apply min (map vector-length vecs)))) (let loop ((i 0)) (unless (= i len) (apply proc (map (lambda (v) (vector-ref v i)) vecs)) (loop (+ i 1))))))) ;; same as vector-for-each (define (string-for-each proc str . more) (if (null? more) (let ((len (string-length str))) (let loop ((i 0)) (unless (= i len) (proc (string-ref str i)) (loop (+ i 1))))) (let* ((strs (cons str more)) (len (apply min (map string-length strs)))) (let loop ((i 0)) (unless (= i len) (apply proc (map (lambda (s) (string-ref s i)) strs)) (loop (+ i 1))))))) ;;;; ;; from SRFI-13 ;;; (string-join string-list [delimiter grammar]) => string ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Paste strings together using the delimiter string. ;;; ;;; (join-strings '("foo" "bar" "baz") ":") => "foo:bar:baz" ;;; ;;; DELIMITER defaults to a single space " " ;;; GRAMMAR is one of the symbols {prefix, infix, strict-infix, suffix} ;;; and defaults to 'infix. ;;; ;;; I could rewrite this more efficiently -- precompute the length of the ;;; answer string, then allocate & fill it in iteratively. Using ;;; STRING-CONCATENATE is less efficient. (define (string-join strings :optional (delim " ") (grammar 'infix)) (define (buildit lis final) (let recur ((lis lis)) (if (pair? lis) (cons delim (cons (car lis) (recur (cdr lis)))) final))) (unless (string? delim) (error 'string-join "Delimiter must be a string" delim)) (cond ((pair? strings) (string-concatenate (case grammar ((infix strict-infix) (cons (car strings) (buildit (cdr strings) '()))) ((prefix) (buildit strings '())) ((suffix) (cons (car strings) (buildit (cdr strings) (list delim)))) (else (error 'string-join "Illegal join grammar" grammar string-join))))) ((not (null? strings)) (error 'string-join "STRINGS parameter not list." strings string-join)) ((eq? grammar 'strict-infix) (error 'string-join "Empty list cannot be joined with STRICT-INFIX grammar." string-join)) (else ""))) ; Special-cased for infix grammar. ;;;; ;; from Ypsilon ;; from srfi-1 start (define (null-list? l) (cond ((pair? l) #f) ((null? l) #t) (else (assertion-violation 'null-list? "argument out of domain" l)))) (define (split-at x k) (or (integer? k) (assertion-violation 'split-at (wrong-type-argument-message "integer" k 2))) (let recur ((lis x) (k k) (r '())) (cond ((zero? k) (values (reverse! r) lis)) ((null? lis) (error 'split-at "given list it too short")) (else (recur (cdr lis) (- k 1) (cons (car lis) r)))))) (define (find pred list) (cond ((find-tail pred list) => car) (else #f))) (define (find-tail pred list) (or (procedure? pred) (assertion-violation 'find-tail (wrong-type-argument-message "procedure" pred 2))) (let lp ((list list)) (and (not (null? list)) (if (pred (car list)) list (lp (cdr list)))))) (define (assoc x lis . =) (or (list? lis) (assertion-violation 'assoc (wrong-type-argument-message "list" lis 2))) (if (null? =) (assoc x lis equal?) (find (lambda (entry) ((car =) x (car entry))) lis))) (define (member x lis . =) (if (null? =) (member x lis equal?) (find-tail (lambda (y) ((car =) x y)) lis))) (define (delete x lis . =) (if (null? =) (delete x lis equal?) (filter (lambda (y) (not ((car =) x y))) lis))) (define (delete! x lis . =) (if (null? =) (delete x lis equal?) (filter! (lambda (y) (not ((car =) x y))) lis))) (define (reduce f ridentity lis) (or (procedure? f) (assertion-violation 'reduce (wrong-type-argument-message "procedure" = 1))) (if (null? lis) ridentity (fold f (car lis) (cdr lis)))) (define (lset-union = . lists) (or (procedure? =) (assertion-violation 'lset-union (wrong-type-argument-message "procedure" = 1))) (reduce (lambda (lis ans) ; Compute ANS + LIS. (cond ((null? lis) ans) ; Don't copy any lists ((null? ans) lis) ; if we don't have to. ((eq? lis ans) ans) (else (fold (lambda (elt ans) (if (exists (lambda (x) (= x elt)) ans) ans (cons elt ans))) ans lis)))) '() lists)) (define (lset-intersection = lis1 . lists) (or (procedure? =) (assertion-violation 'lset-intersection (wrong-type-argument-message "procedure" = 1))) (let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals. (cond ((exists null? lists) '()) ; Short cut ((null? lists) lis1) ; Short cut (else (filter (lambda (x) (for-all (lambda (lis) (member x lis =)) lists)) lis1))))) (define (lset-difference = lis1 . lists) (or (procedure? =) (assertion-violation 'lset-difference (wrong-type-argument-message "procedure" = 1))) (let ((lists (filter pair? lists))) ; Throw out empty lists. (cond ((null? lists) lis1) ; Short cut ((memq lis1 lists) '()) ; Short cut (else (filter (lambda (x) (for-all (lambda (lis) (not (member x lis =))) lists)) lis1))))) (define (take lis k) (or (integer? k) (assertion-violation 'take (wrong-type-argument-message "integer" k 2))) (let recur ((lis lis) (k k)) (if (zero? k) '() (cons (car lis) (recur (cdr lis) (- k 1)))))) (define (drop lis k) (or (integer? k) (assertion-violation 'drop (wrong-type-argument-message "integer" k 2))) (let iter ((lis lis) (k k)) (if (zero? k) lis (iter (cdr lis) (- k 1))))) (define list-head take) ;;;; ;; standard libraries ;; 1 Unicode ;; 1.1 characters (define (make-ci-comparison = foldcase) (lambda (e1 e2 . rest) (let loop ((e1 (foldcase e1)) (e2 (foldcase e2)) (e* rest)) (and (= e1 e2) (or (null? e*) (loop e2 (foldcase (car e*)) (cdr e*))))))) (define char-ci=? (make-ci-comparison char=? char-foldcase)) (define char-ci<? (make-ci-comparison char<? char-foldcase)) (define char-ci>? (make-ci-comparison char>? char-foldcase)) (define char-ci<=? (make-ci-comparison char<=? char-foldcase)) (define char-ci>=? (make-ci-comparison char>=? char-foldcase)) ;; 1.2 strings (define string-ci=? (make-ci-comparison string=? string-foldcase)) (define string-ci<? (make-ci-comparison string<? string-foldcase)) (define string-ci>? (make-ci-comparison string>? string-foldcase)) (define string-ci<=? (make-ci-comparison string<=? string-foldcase)) (define string-ci>=? (make-ci-comparison string>=? string-foldcase)) ;; 2 Bytevectors ;; 2.4 operations on integers of arbitary size ;; from Ypsilon ;; we can't use macro in this file so expand by hand!! ;;(define-syntax div256 ;; (syntax-rules () ;; ((_ x) (bitwise-arithmetic-shift x -8)))) ;; ;;(define-syntax mod256 ;; (syntax-rules () ;; ((_ x) (bitwise-and x 255)))) ;; ;; This moved to (rnrs bytevectors) ;;(define-syntax endianness ;; (syntax-rules (big little native) ;; ((_ big) 'big) ;; ((_ little) 'little) ;; ((_ native) (native-endianness)))) (define (bytevector-uint-ref bv index endien size) (cond ((eq? endien 'big) (let ((end (+ index size))) (let loop ((i index) (acc 0)) (if (>= i end) acc (loop (+ i 1) (+ (* 256 acc) (bytevector-u8-ref bv i))))))) ((eq? endien 'little) (let loop ((i (+ index size -1)) (acc 0)) (if (< i index) acc (loop (- i 1) (+ (* 256 acc) (bytevector-u8-ref bv i)))))) (else (assertion-violation 'bytevector-uint-ref (format "expected endianness, but got ~s, as argument 3" endien) (list bv index endien size))))) (define (bytevector-sint-ref bv index endien size) (cond ((eq? endien 'big) (if (> (bytevector-u8-ref bv index) 127) (- (bytevector-uint-ref bv index endien size) (expt 256 size)) (bytevector-uint-ref bv index endien size))) ((eq? endien 'little) (if (> (bytevector-u8-ref bv (+ index size -1)) 127) (- (bytevector-uint-ref bv index endien size) (expt 256 size)) (bytevector-uint-ref bv index endien size))) (else (assertion-violation 'bytevector-uint-ref (format "expected endianness, but got ~s, as argument 3" endien) (list bv index endien size))))) (define (bytevector-uint-set! bv index val endien size) (cond ((= val 0) (let ((end (+ index size))) (let loop ((i index)) (cond ((>= i end) (undefined)) (else (bytevector-u8-set! bv i 0) (loop (+ i 1))))))) ((< 0 val (expt 256 size)) (cond ((eq? endien 'big) (let ((start (- (+ index size) 1))) (let loop ((i start) (acc val)) (cond ((< i index) (undefined)) (else ;; mod256 -> bitwise-and (bytevector-u8-set! bv i (bitwise-and acc 255)) ;; div256 -> bitwise-arithmetic-shift (loop (- i 1) (bitwise-arithmetic-shift acc -8))))))) ((eq? endien 'little) (let ((end (+ index size))) (let loop ((i index) (acc val)) (cond ((>= i end) (undefined)) (else ;; mod256 -> bitwise-and (bytevector-u8-set! bv i (bitwise-and acc 255)) ;; div256 -> bitwise-arithmetic-shift (loop (+ i 1) (bitwise-arithmetic-shift acc -8))))))))) (else (assertion-violation 'bytevector-uint-set! (format "value out of range, ~s as argument 3" val) (list bv index val endien size)))) (undefined)) (define (bytevector-sint-set! bv index val endien size) (let* ((p-bound (expt 2 (- (* size 8) 1))) (n-bound (- (+ p-bound 1)))) (if (< n-bound val p-bound) (if (>= val 0) (bytevector-uint-set! bv index val endien size) (bytevector-uint-set! bv index (+ val (expt 256 size)) endien size)) (assertion-violation 'bytevector-sint-set! (format "value out of range, ~s as argument 3" val) (list bv index val endien size)))) (undefined)) (define (bytevector->uint-list bv endien size) (let loop ((i (- (bytevector-length bv) size)) (acc '())) (if (> i -1) (loop (- i size) (cons (bytevector-uint-ref bv i endien size) acc)) (if (= i (- size)) acc (assertion-violation 'bytevector->uint-list (format "expected appropriate element size as argument 3, but got ~s" size) (list bv endien size)))))) (define (bytevector->sint-list bv endien size) (let loop ((i (- (bytevector-length bv) size)) (acc '())) (if (> i -1) (loop (- i size) (cons (bytevector-sint-ref bv i endien size) acc)) (if (= i (- size)) acc (assertion-violation 'bytevector->sint-list (format "expected appropriate element size as argument 3, but got ~s" size) (list bv endien size)))))) (define (uint-list->bytevector lst endien size) (let ((bv (make-bytevector (* size (length lst))))) (let loop ((i 0) (lst lst)) (cond ((null? lst) bv) (else (bytevector-uint-set! bv i (car lst) endien size) (loop (+ i size) (cdr lst))))))) (define (sint-list->bytevector lst endien size) (let ((bv (make-bytevector (* size (length lst))))) (let loop ((i 0) (lst lst)) (cond ((null? lst) bv) (else (bytevector-sint-set! bv i (car lst) endien size) (loop (+ i size) (cdr lst))))))) ;; 3 list utilities (define (for-all pred lst1 . lst2) (define (for-all-n pred list-of-lists) (let ((argc (length list-of-lists))) (define (collect-cdr lst) (let loop ((lst lst)) (cond ((null? lst) '()) ((null? (cdar lst)) (loop (cdr lst))) (else (cons (cdar lst) (loop (cdr lst))))))) (define (collect-car lst) (let loop ((lst lst)) (cond ((null? lst) '()) ((pair? (car lst)) (cons (caar lst) (loop (cdr lst)))) (else (assertion-violation 'for-all (format "traversal reached to non-pair element ~s" (car lst)) list-of-lists))))) (let loop ((head (collect-car list-of-lists)) (rest (collect-cdr list-of-lists))) (or (= (length head) argc) (assertion-violation 'for-all "expected same length chains of pairs" list-of-lists)) (if (null? rest) (apply pred head) (and (apply pred head) (loop (collect-car rest) (collect-cdr rest))))))) (define (for-all-n-quick pred lst) (or (null? lst) (let loop ((head (car lst)) (rest (cdr lst))) (if (null? rest) (apply pred head) (and (apply pred head) (loop (car rest) (cdr rest))))))) (define (for-all-1 pred lst) (cond ((null? lst) #t) ((pair? lst) (let loop ((head (car lst)) (rest (cdr lst))) (cond ((null? rest) (pred head)) ((pair? rest) (and (pred head) (loop (car rest) (cdr rest)))) (else (and (pred head) (assertion-violation 'for-all (format "traversal reached to non-pair element ~s" rest) (list pred lst))))))) (else (assertion-violation 'for-all (format "expected chain of pairs, but got ~a, as argument 2" lst) (list pred lst))))) (cond ((null? lst2) (for-all-1 pred lst1)) ((apply list-transpose+ lst1 lst2) => (lambda (lst) (for-all-n-quick pred lst))) (else (for-all-n pred (cons lst1 lst2))))) (define (exists pred lst1 . lst2) (define (exists-1 pred lst) (cond ((null? lst) #f) ((pair? lst) (let loop ((head (car lst)) (rest (cdr lst))) (cond ((null? rest) (pred head)) ((pred head)) ((pair? rest) (loop (car rest) (cdr rest))) (else (assertion-violation 'exists (format "traversal reached to non-pair element ~s" rest) (list pred lst)))))) (else (assertion-violation 'exists (format "expected chain of pairs, but got ~a, as argument 2" lst) (list pred lst))))) (define (exists-n-quick pred lst) (and (pair? lst) (let loop ((head (car lst)) (rest (cdr lst))) (if (null? rest) (apply pred head) (or (apply pred head) (loop (car rest) (cdr rest))))))) (define (exists-n pred list-of-lists) (let ((argc (length list-of-lists))) (define (collect-cdr lst) (let loop ((lst lst)) (cond ((null? lst) '()) ((null? (cdar lst)) (loop (cdr lst))) (else (cons (cdar lst) (loop (cdr lst))))))) (define (collect-car lst) (let loop ((lst lst)) (cond ((null? lst) '()) ((pair? (car lst)) (cons (caar lst) (loop (cdr lst)))) (else (assertion-violation 'exists (format "traversal reached to non-pair element ~s" (car lst)) list-of-lists))))) (let loop ((head (collect-car list-of-lists)) (rest (collect-cdr list-of-lists))) (or (= (length head) argc) (assertion-violation 'exists "expected same length chains of pairs" list-of-lists)) (if (null? rest) (apply pred head) (or (apply pred head) (loop (collect-car rest) (collect-cdr rest))))))) (cond ((null? lst2) (exists-1 pred lst1)) ((apply list-transpose+ lst1 lst2) => (lambda (lst) (exists-n-quick pred lst))) (else (exists-n pred (cons lst1 lst2))))) (define (filter pred lst) (let loop ((lst lst) (acc '())) (cond ((null? lst) (reverse! acc)) ((pred (car lst)) (loop (cdr lst) (cons (car lst) acc))) (else (loop (cdr lst) acc))))) ;; from SRFI-1, reference implementation (define (filter! pred lis) (let lp ((ans lis)) (cond ((null? ans) ans) ; Scan looking for ((not (pred (car ans))) (lp (cdr ans))) ; first cons of result. ;; ANS is the eventual answer. ;; SCAN-IN: (CDR PREV) = LIS and (CAR PREV) satisfies PRED. ;; Scan over a contiguous segment of the list that ;; satisfies PRED. ;; SCAN-OUT: (CAR PREV) satisfies PRED. Scan over a contiguous ;; segment of the list that *doesn't* satisfy PRED. ;; When the segment ends, patch in a link from PREV ;; to the start of the next good segment, and jump to ;; SCAN-IN. (else (letrec ((scan-in (lambda (prev lis) (if (pair? lis) (if (pred (car lis)) (scan-in lis (cdr lis)) (scan-out prev (cdr lis)))))) (scan-out (lambda (prev lis) (let lp ((lis lis)) (if (pair? lis) (if (pred (car lis)) (begin (set-cdr! prev lis) (scan-in lis (cdr lis))) (lp (cdr lis))) (set-cdr! prev lis)))))) (scan-in ans (cdr ans)) ans))))) (define (partition pred lst) (let loop ((lst lst) (acc1 '()) (acc2 '())) (cond ((null? lst) (values (reverse! acc1) (reverse! acc2))) ((pred (car lst)) (loop (cdr lst) (cons (car lst) acc1) acc2)) (else (loop (cdr lst) acc1 (cons (car lst) acc2)))))) (define (map proc lst1 . lst2) (if (null? lst2) (let loop ((xs lst1) (r '())) (cond ((pair? xs) (loop (cdr xs) (cons (proc (car xs)) r))) ((null? xs) (reverse! r)) (else (assertion-violation 'map (wrong-type-argument-message "proper list" lst1 2) (list proc lst1 lst2))))) (let loop ((xs (apply list-transpose* lst1 lst2)) (r '())) (cond ((pair? xs) (loop (cdr xs) (cons (apply proc (car xs)) r))) ((null? xs) (reverse! r)) (else (assertion-violation 'map (wrong-type-argument-message "proper list" lst1 2) (list proc lst1 lst2))))))) (define (for-each proc lst1 . lst2) (if (null? lst2) (let loop ((xs lst1)) (cond ((pair? xs) (proc (car xs)) (loop (cdr xs))) ((null? xs) (undefined)) (else (assertion-violation 'for-each (wrong-type-argument-message "proper list" lst1 2) (list proc lst1 lst2))))) (let loop ((xs (apply list-transpose* lst1 lst2))) (cond ((pair? xs) (apply proc (car xs)) (loop (cdr xs))) ((null? xs) (undefined)) (else (assertion-violation 'for-each (wrong-type-argument-message "proper list" lst1 2) (list proc lst1 lst2))))))) ;; it's used very often in the boot code so put it here (define (filter-map proc lst1 . lst2) (unless (procedure? proc) (assertion-violation 'filter-map (wrong-type-argument-message "procedure" proc 1) (list proc lst1 lst2))) (if (null? lst2) (let loop ((lst lst1) (r '())) (cond ((null? lst) (reverse! r)) ((pair? lst) (cond ((proc (car lst)) => (lambda (x) (loop (cdr lst) (cons x r)))) (else (loop (cdr lst) r)))) (else (assertion-violation 'filter-map (wrong-type-argument-message "proper list" lst1 2) (list proc lst1 lst2))))) (let loop ((xs (apply list-transpose* lst1 lst2)) (r '())) (cond ((null? xs) (reverse! r)) ((pair? xs) (cond ((apply proc (car xs)) => (lambda (x) (loop (cdr xs) (cons x r)))) (else (loop (cdr xs) r)))) (else (assertion-violation 'map (wrong-type-argument-message "proper list" lst1 2) (list proc lst1 lst2))))))) (define (fold-left proc seed lst1 . lst2) (if (null? lst2) (let loop ((lis lst1) (knil seed)) (if (null? lis) knil (loop (cdr lis) (proc knil (car lis))))) (let loop ((lis (apply list-transpose* lst1 lst2)) (knil seed)) (if (null? lis) knil (loop (cdr lis) (apply proc knil (car lis))))))) ;; tail recursive version (define (fold-right proc seed lst1 . lst2) (if (null? lst2) (let loop ((lis (reverse lst1)) (result seed)) (if (null? lis) result (loop (cdr lis) (proc (car lis) result)))) (let loop ((lis (reverse! (apply list-transpose* lst1 lst2))) (knil seed)) (if (null? lis) knil (loop (cdr lis) (apply proc (append! (car lis) (list knil)))))))) ;;(define (fold-right proc seed lst1 . lst2) ;; (if (null? lst2) ;; (let loop ((lis lst1)) ;; (if (null-list? lis) ;; seed ;; (proc (car lis) (loop (cdr lis))))) ;; (let loop ((lis (apply list-transpose* lst1 lst2)) (knil seed)) ;; (if (null-list? lis) ;; knil ;; (apply proc (append! (car lis) (list (loop (cdr lis) knil)))))))) (define (remp pred lst) (let loop ((lst lst) (r '())) (cond ((null? lst) (reverse! r)) ((pred (car lst)) (loop (cdr lst) r)) (else (loop (cdr lst) (cons (car lst) r)))))) (define (remove obj lst) (let loop ((lst lst) (r '())) (cond ((null? lst) (reverse! r)) ((equal? (car lst) obj) (loop (cdr lst) r)) (else (loop (cdr lst) (cons (car lst) r)))))) (define (remv obj lst) (let loop ((lst lst) (r '())) (cond ((null? lst) (reverse! r)) ((eqv? (car lst) obj) (loop (cdr lst) r)) (else (loop (cdr lst) (cons (car lst) r)))))) (define (remq obj lst) (let loop ((lst lst) (r '())) (cond ((null? lst) (reverse! r)) ((eq? (car lst) obj) (loop (cdr lst) r)) (else (loop (cdr lst) (cons (car lst) r)))))) (define (memp proc lst) (cond ((null? lst) #f) ((proc (car lst)) lst) (else (memp proc (cdr lst))))) (define (assp proc lst) (cond ((null? lst) #f) ((proc (caar lst)) (car lst)) (else (assp proc (cdr lst))))) ;;;; ;; 4 Sorting ;; The algorithm is from SBCL (define (list-sort proc lst) (define (merge-list! proc head lst1 lst2 tail) (let loop () (cond ((proc (car lst2) (car lst1)) ;; we can't use macro so duplicate it! (set-cdr! tail lst2) (set! tail lst2) (let ((rest (cdr lst2))) (cond ((null? rest) (set-cdr! lst2 lst1) (cdr head)) (else (set! lst2 rest) (loop))))) (else (set-cdr! tail lst1) (set! tail lst1) (let ((rest (cdr lst1))) (cond ((null? rest) (set-cdr! lst1 lst2) (cdr head)) (else (set! lst1 rest) (loop)))))))) (define (fast-merge-list! proc try? head lst1 tail1 lst2 tail2 rest) (if try? (cond ((not (proc (car lst2) (car tail1))) (set-cdr! tail1 lst2) (values lst1 tail2 rest)) ((proc (car tail2) (car lst1)) (set-cdr! tail2 lst1) (values lst2 tail1 rest)) (else (values (merge-list! proc head lst1 lst2 head) (if (null? (cdr tail1)) tail1 tail2) rest))) (values (merge-list! proc head lst1 lst2 head) (if (null? (cdr tail1)) tail1 tail2) rest))) (define (do-sort lst size head) (define (recur lst size) (cond ((= size 1) (let ((h (list (car lst)))) (values h h (cdr lst)))) ((= size 2) (let* ((a (car lst)) (ad (cadr lst)) (h (if (proc ad a) (list ad a) (list a ad)))) (values h (cdr h) (cddr lst)))) (else (let ((half (div size 2))) (receive (lst1 tail1 rest) (recur lst half) (receive (lst2 tail2 rest) (recur rest (- size half)) (fast-merge-list! proc (>= size 8) head lst1 tail1 lst2 tail2 rest))))))) (receive (lst tail size) (recur lst size) lst)) (define (divide lst) (let loop ((acc 1) (lst lst)) (cond ((null? (cdr lst)) (values acc '())) (else (if (proc (car lst) (cadr lst)) (loop (+ acc 1) (cdr lst)) (values acc (cdr lst))))))) (unless (procedure? proc) (assertion-violation 'list-sort (wrong-type-argument-message "procedure" proc 1))) (if (null? lst) lst (receive (n lst2) (divide lst) (if (null? lst2) lst (let* ((head (cons '() '())) (r (do-sort lst2 (length lst2) head))) (merge-list! proc head (list-head lst n) r head)))))) (define (vector-sort proc vect :optional (start 0) (maybe-end #f)) (define len (vector-length vect)) (define end (or maybe-end len)) ;; TODO should we expose this? (define (vector-copy! src src-from dst dst-from size) (if (<= dst-from src-from) (do ((i 0 (+ i 1)) (s src-from (+ s 1)) (d dst-from (+ d 1))) ((= i size) dst) (vector-set! dst d (vector-ref src s))) (do ((i 0 (+ i 1)) (s (+ src-from size) (- s 1)) (d (+ dst-from size) (- d 1))) ((= i size) dst) (vector-set! dst d (vector-ref src s))))) (when (or (negative? start) (negative? end)) (assertion-violation 'vector-sort! "start and end must be positive" start vect)) (when (or (> start len) (> end len)) (assertion-violation 'vector-sort! "out of range" (list (list start end) len) vect)) (when (> start end) (assertion-violation 'vector-sort! "start is greater than end" (list start end) vect)) (let* ((lst (vector->list vect start end)) (lst2 (list-sort proc lst))) (cond ((eq? lst lst2) vect) ((= (- end start) len) (list->vector lst2)) (else (let ((v (make-vector len))) (vector-copy! vect 0 v 0 start) (do ((i start (+ i 1)) (l lst2 (cdr l))) ((null? l)) (vector-set! v i (car l))) (vector-copy! vect end v end (- len end))))))) (define (vector-sort! proc vect :optional (start 0) (maybe-end #f)) (define len (vector-length vect)) (define end (or maybe-end len)) (when (or (negative? start) (negative? end)) (assertion-violation 'vector-sort! "start and end must be positive" start vect)) (when (or (> start len) (> end len)) (assertion-violation 'vector-sort! "out of range" (list (list start end) len) vect)) (when (> start end) (assertion-violation 'vector-sort! "start is greater than end" (list start end) vect)) (let* ((n (- end start)) (work (make-vector (+ (div n 2) 1)))) (define (simple-sort! first last) (let loop1 ((i first)) (cond ((< i last) (let ((m (vector-ref vect i)) (k i)) (let loop2 ((j (+ i 1))) (cond ((<= j last) (if (proc (vector-ref vect j) m) (begin (set! m (vector-ref vect j)) (set! k j))) (loop2 (+ j 1))) (else (vector-set! vect k (vector-ref vect i)) (vector-set! vect i m) (loop1 (+ i 1)))))))))) (define (sort! first last) (cond ((> (- last first) 10) (let ((middle (div (+ first last) 2))) (sort! first middle) (sort! (+ middle 1) last) (let loop ((i first) (p2size 0)) (cond ((> i middle) (let loop ((p1 (+ middle 1)) (p2 0) (p3 first)) (cond ((and (<= p1 last) (< p2 p2size)) (cond ((proc (vector-ref work p2) (vector-ref vect p1)) (vector-set! vect p3 (vector-ref work p2)) (loop p1 (+ p2 1) (+ p3 1))) (else (vector-set! vect p3 (vector-ref vect p1)) (loop (+ p1 1) p2 (+ p3 1))))) (else (let loop ((s2 p2)(d3 p3)) (cond ((< s2 p2size) (vector-set! vect d3 (vector-ref work s2)) (loop (+ s2 1) (+ d3 1))))))))) (else (vector-set! work p2size (vector-ref vect i)) (loop (+ i 1) (+ p2size 1))))))) (else (simple-sort! first last)))) ;; the end is exclusive (sort! start (- end 1)))) ;;;; ;; 8 I/O ;; 8.2.6 input port and output port ;; from Ypsilon (define (call-with-port port proc) (receive args (proc port) (close-port port) (apply values args))) ;; 8.2.10 output port (define (open-bytevector-output-port . maybe-transcoder) (when (> (length maybe-transcoder) 1) (assertion-violation 'open-bytevector-output-port (format "wrong number of argument: expected between 0 and 1, but got ~a" (length maybe-transcoder)) maybe-transcoder)) (let ((transcoder (if (null? maybe-transcoder) #f (car maybe-transcoder)))) (let* ((port (open-output-bytevector transcoder)) (proc (lambda () (extract-output-bytevector port)))) (values port proc)))) (define (open-string-output-port) (let* ((port (open-output-string)) (proc (lambda () (extract-output-string port)))) (values port proc))) (define (call-with-bytevector-output-port proc . maybe-transcoder) (receive (port extractor) (apply open-bytevector-output-port maybe-transcoder) (proc port) (extractor))) (define (call-with-string-output-port proc) (receive (port extractor) (open-string-output-port) (proc port) (extractor))) ;;;;; ;; 13 hashtable ;; 13.3 inspection (define (hashtable-equivalence-function ht) (or (hashtable? ht) (assertion-violation 'hashtable-equivalence-function (wrong-type-argument-message "hashtable" ht))) (case (hashtable-type ht) ((eq) eq?) ((eqv) eqv?) ((equal) equal?) ((string) string=?) ((general) (hashtable-compare ht)))) (define (hashtable-hash-function ht) (or (hashtable? ht) (assertion-violation 'hashtable-hash-function (wrong-type-argument-message "hashtable" ht))) (case (hashtable-type ht) ((eq) #f) ((eqv) #f) ((equal) equal-hash) ((string) string-hash) ((general) (hashtable-hasher ht)))) ;;;; end of file ;; Local Variables: ;; coding: utf-8-unix ;; End:
true
b516be0daa98cee53d3952710d1e9642b7184980
a0c856484b0cafd1d7c428fb271a820dd19be577
/lab10/ex8.ss
a851353fcd8e007c6c91ca77b6a701fe523044cd
[]
no_license
ctreatma/scheme_exercises
b13ba7743dfd28af894eb54429297bad67c14ffa
94b4e8886b2500a7b645e6dc795c0d239bf2a3bb
refs/heads/master
2020-05-19T07:30:58.538798
2012-12-03T23:12:22
2012-12-03T23:12:22
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
654
ss
ex8.ss
(require "tree.ss") (define traverse-q (lambda (tree leaf-visitor) (let try ([tree-list (list tree)] [q (lambda () 'done)]) (if (null? tree-list) q (let* ([current (car tree-list)] [rest (cdr tree-list)] [new-q (try rest q)]) (if (leaf-node? current) (leaf-visitor current new-q) (try (interior-node-children current) new-q))))))) (define leaf-visitor-q (lambda (z q) (printf "~s~n" (leaf-node-value z)) q)) (define leaf-visitor-q1 (lambda (z q) (printf "~s~n" (leaf-node-value z)) q))
false
0181ef1b3a0ecb0a75e164556ffc2facb5a1ae20
f9e4062f24473a22bc9161d86f05ed49ed4e8080
/readline/trunk/readline.setup
6c353d108546c67dd028c31eb4177bb67a0280d5
[ "Apache-2.0" ]
permissive
hwinslow3/eggs
20cee88b249c2daa10760df3e8ca9b9d868c5752
dab1ca2c51f90f4714866e74c3a7f3ebe4b62535
refs/heads/master
2020-03-24T09:40:12.201125
2017-11-04T00:20:11
2017-11-04T00:20:11
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,357
setup
readline.setup
;;;; readline.setup -*- Scheme -*- ;;;; vim:ft=scheme: (use files) ;; get environment CFLAGS bindings (define old-files (append (filter (lambda (y) (or (string-suffix? ".o" y) (string-suffix? ".out" y))) (find-files "./")) '("readline-test" "readline.c"))) ;; cleans up from previous builds (do ((lst old-files (cdr lst))) ((null? lst)) (display (string-append "rm -f " (car lst))) (newline) (delete-file* (car lst))) (define-syntax compile/error ;; Required for Chicken < 4.6, which calls (reset) on (compile) error. (syntax-rules () ((compile/error args ...) (let ((old-reset (reset-handler))) (parameterize ((reset-handler (lambda () (parameterize ((reset-handler old-reset)) (error 'compile "compilation error"))))) (compile args ...)))))) (define rl-extra-cflags (string-append "-C -D_GNU_SOURCE=1" " -C -std=gnu99" (let ((cflags (get-environment-variable "CFLAGS"))) (if (and cflags (not (string=? cflags ""))) (string-append " -C " (string-join (string-split cflags " ") " -C ")) "")) )) (define-syntax check-rllibs (syntax-rules () ((_ libs) (and (print "trying: " libs) (handle-exceptions e #f (compile/error readline-test.scm ,rl-extra-cflags ,libs)) libs)))) ;(define curry (lambda (f . c) (lambda x (apply f (append c x))))) #;(define rl-extralib (list-ref (list-index (lambda (y) (equal? #t y)) (list (check-rllibs " -lreadline") (check-rllibs " -lreadinline -lhistory") (check-rllibs " -lreadline -lncurses") (check-rllibs " -lreadline -lcurses") (check-rllibs " -lreadline -ltermcap") (check-rllibs " -lreadline -lhistory -lncurses") (check-rllibs " -lreadline -lhistory -lcurses") (check-rllibs " -lreadline -lhistory -ltermcap") (check-rllibs " -lreadline -lhistory -lncurses") (check-rllibs " -lreadline -lhistory -lcurses") (check-rllibs " -lreadline -lhistory -ltermcap"))))) (define rl-extralib (or (check-rllibs "-lreadline -lhistory -ltermcap") (check-rllibs "-lreadline -lhistory -lcurses") (check-rllibs "-lreadline -lhistory -lncurses") (check-rllibs "-lreadline -ltermcap") (check-rllibs "-lreadline -lcurses") (check-rllibs "-lreadline -lhistory") (check-rllibs "-lreadline -lncurses") (check-rllibs "-lreadline") (error (string-append "This extension requires GNU readline. GNU readline " "may be found at ftp://ftp.gnu.org/pub/gnu/readline\n" "For more information, please consult " "http://wiki.call-cc.org/egg/readline#installation-problems\n")))) (compile -s -O2 readline.scm ,rl-extra-cflags ,rl-extralib) (compile -c -O2 -d0 -j readline readline.scm -o readline-static.o -unit readline ,rl-extra-cflags ,rl-extralib) (compile -s -O2 -d0 readline.import.scm) (install-extension 'readline '("readline.so" "readline.import.so" "readline-static.o") `((version "4.1.3") (static "readline-static.o") (static-options ,rl-extralib)))
true
98045c0e631190f1ce846a5e10105b701407d79e
de21ee2b90a109c443485ed2e25f84daf4327af3
/exercise/section3/3.60.scm
f9f05ebc5533ca39f04c36d594a4c6932da37a20
[]
no_license
s-tajima/SICP
ab82518bdc0551bb4c99447ecd9551f8d3a2ea1d
9ceff8757269adab850d01f238225d871748d5dc
refs/heads/master
2020-12-18T08:56:31.032661
2016-11-10T11:37:52
2016-11-10T11:37:52
18,719,524
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,394
scm
3.60.scm
;= Question ============================================================================= ; ; 問題 3.60 ; ; 問題3.59のように係数のストリームとして表現したべき級数で, ; 級数の加算がadd-streamsで実装してある. 級数の乗算の次の手続きの定義を完成せよ. ; ; (define (mul-series s1 s2) ; (cons-stream ⟨??⟩ (add-streams ⟨??⟩ ⟨??⟩))) ; ; この手続きは問題3.59の級数を使い, sin2x + cos2 x = 1を確認することでテスト出来る. ; ; ; ;= Prepared ============================================================================= (load "./stream.scm") (define (integers-starting-from n) (cons-stream n (integers-starting-from (+ n 1)))) (define integers (integers-starting-from 1)) ;= Answer =============================================================================== (define (mul-series s1 s2) (cons-stream (* (stream-car s1) (stream-car s2)) (add-streams (stream-map (lambda (x) (* (stream-car s1) x)) (stream-cdr s2)) (mul-series (stream-cdr s1) s2)))) ;= Test ================================================================================= (define a (mul-series integers integers)) (stream-head a 10)
false
f0bff0d8de327818a14d69fb2563aa1583376431
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/depends/matpak.sls
de8611bfccac8f6a1ab19a385834792cee206d66
[ "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
5,266
sls
matpak.sls
#!r6rs (library (depends matpak) (export ws-invert-matrix) (import (except (rnrs (6)) error) (ws common)) ;; This matrix code is lifted from the web. ; Found at: http://www.cap-lore.com/MathPhys/Field/ (define matpak (lambda (zero zer? one fa fs fm fi) (letrec ((tf (lambda (x zp) (if (null? x) (zp (list one)) (if (zer? (caar x)) (let ((z (tf (cdr x) zp))) (cons (car z) (cons (car x) (cdr z)))) x)))) (tr (trnxx zero zer?)) (sm (lambda (s a)(map (lambda (w) (fm s w)) a))) (fms (lambda (a s b) (if (null? a) (sm (fs zero s) b) (if (null? b) a (cons (fs (car a) (fm s (car b))) (fms (cdr a) s (cdr b))))))) (deter (lambda (a) (letrec ((p #f) (tf (lambda (x) (if (null? x) (list one) (if (zer? (caar x)) (let ((z (tf (cdr x)))) (set! p (not p)) (cons (car z) (cons (car x) (cdr z)))) x))))) (let inx ((d one)(a a)) (if (null? a) (if p (fs zero d) d) (let* ((A (tf a)) (i (fi (caar A))) (b (map (lambda (z) (fm z i)) (cdar A)))) (inx (fm (caar A) d) (map (lambda (x w) (fms x w b)) (map cdr (cdr A)) (map car (cdr A)))))))))) (inv (lambda (a nxp) (let ol ((ut (let inx ((a (let pad ((x a)(e (list one))) (if (null? x) '() (cons (let ap ((z (car x)) (ln a)) (if (null? ln) e (if (null? z) (cons zero (ap z (cdr ln))) (cons (car z)(ap (cdr z)(cdr ln)))))) (pad (cdr x) (cons zero e)))))) (np nxp)) (if (null? a) '() (let* ((A (tf a np)) (i (fi (caar A))) (b (map (lambda (z) (fm z i)) (cdar A)))) (cons b (inx (map (lambda (x w) (fms x w b)) (map cdr (cdr A)) (map car (cdr A))) (lambda (w) (np (cons (fs zero (ip w b)) w)))))))))) (if (null? ut) '() (cons (let eg ((top (car ut))(bod (cdr ut))) (if (null? bod) top (eg (fms (cdr top) (car top) (car bod))(cdr bod)))) (ol (cdr ut))))))) (ip (lambda (x y)(if (or (null? x) (null? y)) zero (fa (fm (car x)(car y)) (ip (cdr x)(cdr y)))))) (mp (lambda (a b)(let ((b (tr b))) (map (lambda(x) (map (lambda (y) (ip x y)) b)) a))))) (values mp inv ip tr deter)))) (define (trnxx zer zer?) (lambda (x) (if (null? x) '() (let ((z ((trnxx zer zer?) (cdr x)))) (let m ((u (car x))(v z)) (if (null? u) (map (lambda (q) (if (null? q) '() (cons zer q))) v) (if (null? v) (let y ((q u)) (if (null? q) '() (let ((p (y (cdr q)))) (if (and (null? p) (zer? (car q))) '() (cons (if (zer? (car q)) '() (list (car q))) p))))) (cons (cons (car u)(car v)) (m (cdr u)(cdr v)))))))))) (define our-exit (let* ((s (cons 0 0)) (z (call-with-current-continuation (lambda (e) (cons s e))))) (if (and (pair? z) (eq? (car z) s)) (cdr z) our-exit))) (define mer (lambda (x) (let ((r (call-with-current-continuation (lambda(d) (cons #f (lambda(y) (d (cons #t y)))))))) (if (car r) (begin (write (list "MatrixException:" x (cdr r))) (newline) (our-exit 0)) (cdr r))))) (define cc (mer "Singular:")) (define-values (mp inv ip tr deter) (matpak 0 zero? 1 + - * (lambda (x)(/ 1 x)))) (define (ws-invert-matrix mat) (list->vector (map list->vector (inv (map vector->list (vector->list mat)) cc)))) ) ;; End module ;(require matpak) #; (call-with-values (lambda () ; Here we supply matpak with the field goodies the rationals. (matpak 0 zero? 1 + - * (lambda (x)(/ 1 x)))) (lambda (matm matinv ip tr det) ; A test matrix inversion with rational arithmetic. (let* ((a '((0 2 4 5) (3 4 5 -2) (7 6 5 3) (4 6 5 7))) (b (matinv a cc))) (list b (matm a b)(matinv b cc))))) #; (ws-invert-matrix (ws-invert-matrix #(#(0 2 4 5) #(3 4 5 -2) #(7 6 5 3) #(4 6 5 7))))
false
5733108c41f17e76c6dc317fde66680c24ee9fb7
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec4/sec4.3.2-Examples-of-Nondeterministic-Programs.scm
9f8d1483cdd8be51cf2ef4c6421abcd8e971b30d
[]
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
6,876
scm
sec4.3.2-Examples-of-Nondeterministic-Programs.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 4.3.2. 非決定性プログラムの例 (load "./sec4.3-nondeterministic") (driver-loop) ;;; driver-loopを起動した後に定義する. >>> ココカラ (define (require p) (if (not p) (amb))) (define (an-element-of items) (require (not (null? items))) (amb (car items) (an-element-of (cdr items)))) ;; amb使えば論理パズル解けるよー (ええからはよ実装せえや) ;; 問題を論理的に書き下せる時点で解けとるようなもんやん (define (multiple-dwelling) (let ((baker (amb 1 2 3 4 5)) (cooper (amb 1 2 3 4 5)) (fletcher (amb 1 2 3 4 5)) (miller (amb 1 2 3 4 5)) (smith (amb 1 2 3 4 5))) (require (distinct? (list baker cooper fletcher miller smith))) (require (not (= baker 5))) (require (not (= cooper 1))) (require (not (= fletcher 5))) (require (not (= fletcher 1))) (require (> miller cooper)) (require (not (= (abs (- smith fletcher)) 1))) (require (not (= (abs (- fletcher cooper)) 1))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith)))) ;; multiple-dwellingを動かすにはdistinct?の実装が必要 (define (distinct? items) (cond ((null? items) true) ((null? (cdr items)) true) ((member (car items) (cdr items)) false) (else (distinct? (cdr items))))) ;;;; Amb-Eval input: ;(multiple-dwelling) ;;;; Starting a new problem ;;;; Amb-Eval value ;((baker 3) (cooper 2) (fletcher 4) (miller 5) (smith 1)) ;; => q4.38.scm, q4.39.scm, q4.40.scm, q4.41.scm, q4.42.scm, q4.43.scm, q4.44.scm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; 自然言語の構文解析 ;;; ;; (ええからはよ実装せえや) ;; 品詞に分解 (define nouns '(noun student professor cat class)) (define verbs '(verbs studies lectures eats sleeps)) (define articles '(articles the a)) ;; 道具箱 -- parseを定義するまで (define (parse-sentence) (list 'sentence (parse-noun-phrase) (parse-word verbs))) (define (parse-noun-phrase) (list 'noun-phrase (parse-word articles) (parse-word nouns))) (define (parse-word word-list) (require (not (null? *unparsed*))) (require (memq (car *unparsed*) (cdr word-list))) (let ((found-word (car *unparsed*))) (set! *unparsed* (cdr *unparsed*)) (list (car word-list) found-word))) ;; こうやって使う (define *unparsed* '()) (define (parse input) (set! *unparsed* input) (let ((sent (parse-sentence))) (require (null? *unparsed*)) sent)) ;; sample: The cat eats を構文解析する ;(parse '(the cat eats)) ;; => (sentence (noun-phrase (articles the) (noun cat)) (verbs eats)) ;; 探索とバックトラックは複雑な文法を扱うとき本当に有効である(ええからはよ実装せえや) (define prepositions '(prep for to in by with)) (define (parse-prepositional-phrase) (list 'prep-phrase (parse-word prepositions) (parse-noun-phrase))) (define (parse-sentence) (list 'sentence (parse-noun-phrase) (parse-verb-phrase))) ;; ようやくamb出てきた (define (parse-verb-phrase) (define (maybe-extend verb-phrase) (amb verb-phrase (maybe-extend (list 'verb-phrase verb-phrase (parse-prepositional-phrase))))) (maybe-extend (parse-word verbs))) ;; ついでに名刺句の定義を改善する (define (parse-simple-noun-phrase) (list 'simple-noun-phrase (parse-word articles) (parse-word nouns))) (define (parse-noun-phrase) (define (maybe-extend noun-phrase) (amb noun-phrase (maybe-extend (list 'noun-phrase noun-phrase (parse-prepositional-phrase))))) (maybe-extend (parse-simple-noun-phrase))) ;; <<< ココマデ driver-loop 内で評価する ;; ここまでやると, 以下のような複雑な文を解析できる(うれしげに言うとらんと実装せえっちゅうに) (parse '(the student with the cat sleeps in the class)) ;; => (sentence (noun-phrase (simple-noun-phrase (articles the) (noun student)) (prep-phrase (prep with) (simple-noun-phrase (article the) (noun cat)))) (verb-phrase (verb sleeps) (prep-phrase (prep in) (simple-noun-phrase (article the) (noun class))))) ;; the student with ... 実際の出力結果 {{{ ; ;;; Amb-Eval input: ; (parse '(the student with the cat sleeps in the class)) ; ; ;;; Starting a new problem ; ; ;;; Amb-Eval value ; (sentence (noun-phrase (simple-noun-phrase (articles the) (noun student)) (prep-phrase (prep with) (simple-noun-phrase (articles the) (noun cat)))) (verb-phrase (verbs sleeps) (prep-phrase (prep in) (simple-noun-phrase (articles the) (noun class))))) ; }}} ;; 別の例 (parse '(the professor lectures to the student with the cat)) ;; => (sentence (simple-noun-phrase (article the) (noun professor)) (verb-phrase (verb-phrase (verb lectures) (prep-phrase (prep to) (simple-noun-phrase (article the) (noun student)))) (prep-phrase (prep with) (simple-noun-phrase (article the) (noun cat))))) ;; => 再実行 (sentence (simple-noun-phrase (article the) (noun professor)) (verb-phrase (verb lectures) (prep-phrase (prep to) (noun-phrase (simple-noun-phrase (article the) (noun student)) (prep-phrase (prep with) (simple-noun-phrase (article the) (noun cat))))))) ;; the professor lectures ... 実際の出力結果 {{{ ; ;;; Amb-Eval input: ; (parse '(the professor lectures to the student with the cat)) ; ; ;;; Starting a new problem ; ;;; Amb-Eval value ; (sentence (simple-noun-phrase (articles the) (noun professor)) (verb-phrase (verb-phrase (verbs lectures) (prep-phrase (prep to) (simple-noun-phrase (articles the) (noun student)))) (prep-phrase (prep with) (simple-noun-phrase (articles the) (noun cat))))) ; ; ;;; Amb-Eval input: ; try-again ; ;;; Amb-Eval value ; (sentence (simple-noun-phrase (articles the) (noun professor)) (verb-phrase (verbs lectures) (prep-phrase (prep to) (noun-phrase (simple-noun-phrase (articles the) (noun student)) (prep-phrase (prep with) (simple-noun-phrase (articles the) (noun cat))))))) ; ; ;;; Amb-Eval input: ; try-again ; ;;; There are no more values of ; (parse '(the professor lectures to the student with the cat)) ;}}} ;; => q4.45.scm, q4.46.scm, q4.47.scm, q4.48.scm, q4.49.scm
false
a3d2ff60aa1a0d53303631c44822ab25cbe25cad
be06d133af3757958ac6ca43321d0327e3e3d477
/format/format.scm
08fa50bee3e77c2557e725b16939c680f2db72b9
[]
no_license
aoyama-val/scheme_practice
39ad90495c4122d27a5c67d032e4ab1501ef9c15
f133d9326699b80d56995cb4889ec2ee961ef564
refs/heads/master
2020-03-13T12:14:45.778707
2018-04-26T07:12:06
2018-04-26T07:12:06
131,115,150
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,134
scm
format.scm
; printfみたいなもの (define (format f . args) (let loop ((i 0) (arg-i 0) (ret "")) (if (>= i (string-length f)) ret (cond ((equal? (string-ref f i) #\%) (let ((arg (list-ref args arg-i))) (loop (+ i 2) (+ arg-i 1) (string-append ret (cond ((string? arg) arg) ((number? arg) (number->string arg)) ((char? arg) (list->string (list arg))) (else "unknown type")))))) (else (loop (+ i 1) arg-i (string-append ret (list->string (list (string-ref f i)))))))))) (display (format "%s = %d %c\n" "hoge" 123 #\H)) ; C#方式 (define (format2 f . args) (let loop ((i 0) (ret f)) (if (>= i (length args)) ret (loop (+ i 1) (regexp-replace-all (string->regexp (string-append "\\{" (number->string (+ i 1)) "\\}")) ret (list-ref args i)))))) (display (format2 "{1} = {2}\nagain {1} = {2}\n" "foo" "bar")) (display (apply format2 '("{1} = {2}\nagain {1} = {2}\n" "foo" "bar")))
false
c906910a70f2c571d1cce562e0afcdec83319690
b2dc5cb7275421d81152cc0df41f09f7b1a0f742
/examples/plato/apps/repl/meta.scm
948c74fec8330843618033d5f598f2ea168d0610
[]
no_license
ktakashi/sagittarius-paella
d330d6d0b7b19e395687d469e5fe6b81c6014563
9f4e6ee17d44cdd729d7f2ceccf99aac9d98da4c
refs/heads/master
2021-01-19T21:09:36.784683
2019-04-05T13:55:36
2019-04-05T13:55:36
37,460,489
7
0
null
null
null
null
UTF-8
Scheme
false
false
46
scm
meta.scm
;; auto generated stub ((handler "repl.scm"))
false
ed1d017c36b26a56652906a3672a49fe1e564a58
bdfa935097ef39f66c7f18856accef422ef39128
/parts/qa0/tree/scheme/cfold.ss
5f19d81c33fcb4f7bd3613364ae6420413054de6
[ "MIT" ]
permissive
djm2131/qlua
213f5ed4b692b1b03d2ff1a78d09ea9d2d9fe244
737bfe85228dac5e9ae9eaab2b5331630703ae73
refs/heads/master
2020-04-18T15:01:06.117689
2019-02-06T15:23:27
2019-02-06T15:23:27
162,349,914
0
0
null
null
null
null
UTF-8
Scheme
false
false
23,854
ss
cfold.ss
;; Constant folding #fload "sfc.sf" #fload "common.sf" #fload "error.ss" #fload "basis.ss" #fload "ast.ss" #fload "parser.ss" #fload "cenv.ss" ;; ;; (provide fold-constants/env) ;; (define (fold-constants/env ast machine real) (define fresh-param-reg (let ([*param-count* 0]) (lambda () (let ([n *param-count*]) (set! *param-count* (+ n 1)) (gen-reg 'p n))))) (define (ce-start-env machine real) (let* ([env (ce-empty-env)] [env (machine env)] [env (ce-bind env 'proc-prefix "qop_")] [env (ce-bind env 'proc-infix "mdwf")] [env (ce-bind env 'proc-suffix "")] [env (ce-add-qcd-type env 'Fermion-double "struct FermionD" '*colors* '*fermion-dim* 'complex-double)] [env (ce-add-qcd-type env 'Fermion-float "struct FermionF" '*colors* '*fermion-dim* 'complex-float)] [env (ce-add-qcd-type env 'Staggered-Fermion-double "struct StaggeredFermionD" '*colors* 1 'complex-double)] [env (ce-add-qcd-type env 'Staggered-Fermion-float "struct StaggeredFermionF" '*colors* 1 'complex-float)] [env (ce-add-qcd-type env 'Projected-Fermion-double "struct ProjectedFermionD" '*colors* '*projected-fermion-dim* 'complex-double)] [env (ce-add-qcd-type env 'Projected-Fermion-float "struct ProjectedFermionF" '*colors* '*projected-fermion-dim* 'complex-float)] [env (ce-add-qcd-matrix-type env 'SU-n-double "struct SUnD" '*colors* 1 'complex-double)] [env (ce-add-qcd-matrix-type env 'SU-n-float "struct SUnF" '*colors* 1 'complex-float)] [env (ce-add-qcd-matrix-type env 'Clover-double "struct CloverD" '*clovers* 2 'complex-double)] [env (ce-add-qcd-matrix-type env 'Clover-float "struct CloverF" '*clovers* 2 'complex-float)] [env (case real [(double) (let* ([env (ce-bind env 'prec-letter "d")] [env (ce-add-alias env 'REAL 'double)] [env (ce-add-alias env 'COMPLEX 'complex-double)] [env (ce-add-alias env 'VECTOR 'vector-double)] [env (ce-add-alias env 'Fermion 'Fermion-double)] [env (ce-add-alias env 'Staggered-Fermion 'Staggered-Fermion-double)] [env (ce-add-alias env 'Projected-Fermion 'Projected-Fermion-double)] [env (ce-add-alias env 'SU-n 'SU-n-double)] [env (ce-add-alias env 'Clover 'Clover-double)]) env)] [(float) (let* ([env (ce-bind env 'prec-letter "f")] [env (ce-add-alias env 'REAL 'float)] [env (ce-add-alias env 'COMPLEX 'complex-float)] [env (ce-add-alias env 'VECTOR 'vector-float)] [env (ce-add-alias env 'Fermion 'Fermion-float)] [env (ce-add-alias env 'Staggered-Fermion 'Staggered-Fermion-float)] [env (ce-add-alias env 'Projected-Fermion 'Projected-Fermion-float)] [env (ce-add-alias env 'SU-n 'SU-n-float)] [env (ce-add-alias env 'Clover 'Clover-float)]) env)] [else (ic-error 'cfold "Bad value of REAL: ~a" real)])] [env (ce-add-const env '*mdwf-start-sum-dimension* mdwf-start-sum-dimension)] [env (ce-add-const env '*mdwf-start-sum-direction* mdwf-start-sum-direction)]) (let loop ([env env] [p* mdwf-basis]) (cond [(null? p*) env] [else (loop (ce-bind env (caar p*) (cdar p*)) (cdr p*))])))) (define (cf-decl ast out* env) (variant-case ast [qa0-alias (old-name new-name) (cf-alias old-name new-name out* env)] [qa0-const (name value) (cf-const name value out* env)] [qa0-struct (name c-name field-name* field-type* field-c-name*) (cf-struct name c-name field-name* field-type* field-c-name* out* env)] [qa0-array (name c-name base-name size) (cf-array name c-name base-name size out* env)] [qa0-proc (attr* name arg-name* arg-type* arg-c-name* arg-c-type* code*) (cf-proc attr* name arg-name* arg-type* arg-c-name* arg-c-type* code* out* env)] [qa0-repeat-list (id value* body*) (cf-repeat-list id value* body* out* env)] [qa0-repeat-range (id low high body*) (cf-repeat-range id low high body* out* env)] [qa0-macro-def (id) (cf-macro-def ast id out* env)] [qa0-name-prefix (name) (cf-name-prefix ast name out* env)] [qa0-name-infix (name) (cf-name-infix ast name out* env)] [qa0-name-suffix (name) (cf-name-suffix ast name out* env)] [qa0-verbose () (cf-verbose ast out* env)])) (define (cf-macro-def ast id out* env) (values out* (ce-add-macro env id ast))) (define (cf-name-prefix ast name out* env) (values out* (ce-bind env 'proc-prefix name))) (define (cf-name-infix ast name out* env) (values out* (ce-bind env 'proc-infix name))) (define (cf-name-suffix ast name out* env) (values out* (ce-bind env 'proc-suffix name))) (define (cf-alias old new out* env) (values out* (ce-add-alias env new old))) (define (cf-const name value out* env) (let ([v (cf-eval-const value env)]) (values out* (ce-add-const env name v)))) (define (cf-struct name c-name field-name* field-type* field-c-name* out* env) (let ([name (cf-eval-param name env)] [c-name (cf-eval-param c-name env)] [field-name* (cf-eval-param* field-name* env)] [field-type* (cf-eval-param* field-type* env)] [field-c-name* (cf-eval-param* field-c-name* env)]) (values (cons (make-qa0-struct name c-name field-name* field-type* field-c-name*) out*) (ce-add-struct env name c-name field-name* field-type*)))) (define (cf-array name c-name base size out* env) (let ([size (cf-eval-const size env)] [name (cf-eval-param name env)] [c-name (cf-eval-param c-name env)] [base (cf-eval-param base env)]) (values (cons (make-qa0-array name c-name base (cf-rewrap size)) out*) (ce-add-array env name c-name base size)))) (define (cf-proc attr* name arg-name* arg-type* arg-c-name* arg-c-type* code* out* env) (values (cons (make-qa0-proc (cf-attr* attr* env) (cf-eval-param name env) (cf-eval-param* arg-name* env) (cf-eval-param* arg-type* env) (cf-eval-param* arg-c-name* env) (cf-eval-param* arg-c-type* env) (cf-block code* env)) out*) env)) (define (cf-repeat-list id value* body* out* env) (let loop-values ([value* (cf-eval-param* value* env)] [out* out*]) (cond [(null? value*) (values out* env)] [else (let ([env-x (ce-add-param env id (car value*))]) (let loop-body ([body* body*] [out* out*]) (cond [(null? body*) (loop-values (cdr value*) out*)] [else (loop-body (cdr body*) (cf-repeat (car body*) out* env-x))])))]))) (define (cf-repeat-range id low high body* out* env) (let ([low (cf-eval-const low env)] [high (cf-eval-const high env)]) (let loop-values ([i low] [out* out*]) (cond [(>= i high) (values out* env)] [else (let ([env-x (ce-add-param env id i)]) (let loop-body ([body* body*] [out* out*]) (cond [(null? body*) (loop-values (+ i 1) out*)] [else (loop-body (cdr body*) (cf-repeat (car body*) out* env-x))])))])))) (define (cf-repeat ast out* env) (let-values* ([(out* env) (variant-case ast [qa0-proc (attr* name arg-name* arg-type* arg-c-name* arg-c-type* code*) (cf-proc attr* name arg-name* arg-type* arg-c-name* arg-c-type* code* out* env)] [qa0-repeat-list (id value* body*) (cf-repeat-list id value* body* out* env)] [qa0-repeat-range (id low high body*) (cf-repeat-range id low high body* out* env)])]) out*)) (define (cf-verbose ast out* env) (values (cons ast out*) env)) (define (cf-attr attr env) (variant-case attr [qa0-attr (name value*) (make-qa0-attr (cf-eval-param name env) (cf-eval-param* value* env))])) (define (cf-attr* attr* env) (map (lambda (attr) (cf-attr attr env)) attr*)) (define (cf-block code* env) (reverse (cf-code* code* '() env))) (define (cf-code* code* out* env) (let loop ([code* code*] [out* out*]) (cond [(null? code*) out*] [else (loop (cdr code*) (cf-code (car code*) out* env))]))) (define (cf-code code out* env) (variant-case code [qa0-operation (attr* name output* input*) (cf-operation attr* name output* input* out* env)] [qa0-load (attr* type output addr*) (cf-load attr* type output addr* out* env)] [qa0-store (attr* type addr* value) (cf-store attr* type addr* value out* env)] [qa0-loop (attr* var low high code*) (cf-loop attr* var low high code* out* env)] [qa0-if (var true-code* false-code*) (cf-if var true-code* false-code* out* env)] [qa0-macro-call (id arg*) (cf-macro-call id arg* out* env)] [qa0-macro-list (id value* code*) (cf-macro-list id value* code* out* env)] [qa0-macro-range (id low high code*) (cf-macro-range id low high code* out* env)])) (define (cf-if var true* false* out* env) (let ([var (cf-input var env)]) (variant-case var [c-expr-number (number) (if (zero? number) (cf-code* false* out* env) (cf-code* true* out* env))] [reg (name) (cons (make-qa0-if var (cf-block true* env) (cf-block false* env)) out*)]))) (define (cf-operation attr* name output* input* out* env) (cons (make-qa0-operation (cf-attr* attr* env) (cf-eval-param name env) (cf-output* output* env) (cf-input* input* env)) out*)) (define (cf-load attr* type output addr* out* env) (cons (make-qa0-load (cf-attr* attr* env) (cf-type type env) (cf-output output env) (cf-addr* addr* env)) out*)) (define (cf-store attr* type addr* value out* env) (cons (make-qa0-store (cf-attr* attr* env) (cf-type type env) (cf-addr* addr* env) (cf-input value env)) out*)) (define (cf-loop attr* var low high code* out* env) (cons (make-qa0-loop (cf-attr* attr* env) (make-reg (cf-eval-param (reg->name var) env)) (cf-input low env) (cf-input high env) (cf-block code* env)) out*)) (define (cf-macro-call id p* out* env) (let ([vv (cf-eval-mname id env)]) (variant-case (ce-lookup-x env 'macro vv "Macro call of ~a (~a)" vv id) [qa0-macro-def (arg* code*) (if (not (= (length arg*) (length p*))) (s-error "Macro call ~a expects ~a arguments" (list* 'macro id p*) (length arg*))) (let-values* ([(env v*) (ne-start* env arg* p* env '())] [(env v*) (ne-mcode* env code* v*)]) (let loop ([out* out*] [code* code*]) (cond [(null? code*) out*] [else (loop (cf-code (car code*) out* env) (cdr code*))])))]))) (define (ne-start* env a* p* ine v*) (cond [(null? p*) (values env v*)] [else (let-values* ([(env v*) (ne-start env (car a*) (car p*) ine v*)]) (ne-start* env (cdr a*) (cdr p*) ine v*))])) (define (ne-start env a p ine v*) (let ([p (cf-param p ine)]) (variant-case p [reg (name) (let ([a (user-reg a)]) (values (ce-add-param env a name) (cons a v*)))] [else (values (ce-add-param env a p) (cons a v*))]))) (define (ne-mcode* env code* v*) (cond [(null? code*) (values env v*)] [else (let-values* ([(env v*) (ne-mcode env (car code*) v*)]) (ne-mcode* env (cdr code*) v*))])) (define (ne-mcode env code v*) (variant-case code [qa0-operation (output* input*) (let-values* ([(env v*) (ne-input* env input* v*)]) (ne-output* env output* v*))] [qa0-load (output addr*) (let-values* ([(env v*) (ne-addr* env addr* v*)]) (ne-output env output v*))] [qa0-store (addr* value) (let-values* ([(env v*) (ne-input env value v*)]) (ne-addr* env addr* v*))] [qa0-loop (var low high code*) (let-values* ([(env v*) (ne-output env var v*)] [(env v*) (ne-input env low v*)] [(env v*) (ne-input env high v*)]) (ne-mcode* env code* v*))] [qa0-if (var true-code* false-code*) (let-values* ([(env v*) (ne-output env var v*)] [(env v*) (ne-mcode* env true-code* v*)]) (ne-mcode* env false-code* v*))] [qa0-macro-call (arg*) (ne-marg* env arg* v*)] [qa0-macro-list (id code*) (let-values* ([(env v*) (ne-mcode* env code* v*)]) (ne-mvar env id v*))] [qa0-macro-range (id code*) (let-values* ([(env v*) (ne-mcode* env code* v*)]) (ne-mvar env id v*))])) (define (ne-input* env input* v*) (cond [(null? input*) (values env v*)] [else (let-values* ([(env v*) (ne-input env (car input*) v*)]) (ne-input* env (cdr input*) v*))])) (define (ne-input env input v*) (variant-case input [reg (name) (if (memq name v*) (values env v*) (values (ne-add-binding env name) (cons name v*)))] [else (values env v*)])) (define (ne-output* env output* v*) (ne-input* env output* v*)) (define (ne-output env output v*) (ne-input env output v*)) (define (ne-addr* env addr* v*) (ne-input* env addr* v*)) (define (ne-marg* env arg* v*) (ne-input* env arg* v*)) (define (ne-mvar env var v*) (ne-input env var v*)) (define (ne-add-binding env name) (ce-add-param env name (fresh-param-reg))) (define (cf-macro-list id value* code* out* env) (let loop ([value* (cf-eval-param* value* env)] [out* out*]) (cond [(null? value*) out*] [else (let ([env-x (ce-add-param env id (car value*))]) (loop (cdr value*) (cf-code* code* out* env-x)))]))) (define (cf-macro-range id low high code* out* env) (let ([low (cf-eval-const low env)] [high (cf-eval-const high env)]) (let loop ([i low] [out* out*]) (cond [(>= i high) out*] [else (loop (+ i 1) (cf-code* code* out* (ce-add-param env id i)))])))) (define (cf-input* input* env) (map (lambda (in) (cf-input in env)) input*)) (define (cf-input input env) (variant-case input [reg (name) (make-reg (cf-eval-param name env))] [else (cf-rewrap (cf-eval-const input env))])) (define (cf-param input env) (variant-case input [reg (name) (make-reg (cf-eval-param name env))] [c-expr-macro (name) (let ([t (ce-lookup-x env 'type name "Macro binding of ~a" name)]) (case t [(macro) name] [(param) (ce-lookup-x env 'param name "Macro arg binding of ~a" name)] [else (ic-error 'cf-param "??? name ~a, type ~a" name t)]))] [else (cf-reparam (cf-eval-const input env))])) (define (cf-addr* addr* env) (cf-input* addr* env)) (define (cf-output* output* env) (map (lambda (out) (cf-output out env)) output*)) (define (cf-output output env) (variant-case output [reg (name) (make-reg (cf-eval-param name env))])) (define (cf-rewrap c) (cond [(number? c) (make-c-expr-number c)] [(string? c) (make-c-expr-string c)] [(symbol? c) (make-c-expr-quote c)] [else (ic-error 'cfold "Unexpected computed constant is ~a" c)])) (define (cf-reparam c) (cond [(number? c) c] [(string? c) c] [(symbol? c) c] [else (ic-error 'cf-reparam "c=~a" c)])) (define (cf-type type env) (let ([type (cf-eval-param type env)]) (ce-search-x env 'aliased-to type (lambda (x) x) (lambda () type)))) (define (cf-eval-const const env) (variant-case const [c-expr-quote (literal) literal] [c-expr-op (name c-expr*) (cx-const-op name c-expr* env)] [c-expr-string (string) string] [c-expr-number (number) number] [c-expr-id (id) (let ([t (ce-lookup-x env 'type id "Type of ~a" id)] [v (cf-eval-id id env)]) (cond [(number? v) v] [(string? v) v] [else (ce-search-x env 'const v (lambda (x) x) (lambda () v))]))])) (define (cx-const-op name expr* env) (define (check-id-arg v) (variant-case v [c-expr-id () #t] [else (s-error "Expecting id, found ~a" v)])) (define (check-id-arg* arg* len) (if (not (and (list? arg*) (= (length arg*) len))) (s-error "Expecting a list of ~a arguments, found ~a" len arg*) (let loop ([arg* arg*]) (cond [(null? arg*) #t] [else (check-id-arg (car arg*)) (loop (cdr arg*))])))) (define (get-id v env) ; for types and fields (variant-case v [c-expr-id (id) (cf-eval-param id env)])) (define (compute-arith* v-0 op1 op+) (let ([arg* (map (lambda (arg) (cf-eval-const arg env)) expr*)]) (cond [(zero? (length arg*)) v-0] [(= 1 (length arg*)) (op1 (car arg*))] [else (let loop ([arg* (cddr arg*)] [v (op+ (car arg*) (cadr arg*))]) (cond [(null? arg*) v] [else (loop (cdr arg*) (op+ v (car arg*)))]))]))) (define (compute-arith2 op) (let ([arg* (map (lambda (arg) (cf-eval-const arg env)) expr*)]) (if (not (= (length arg*) 2)) (s-error "Expecting a list of 2, found ~a" arg*)) (map check-number-arg arg*) (op (car arg*) (cadr arg*)))) (define (check-number-arg arg) (if (not (number? arg)) (s-error "A number is expected, found ~a" arg))) (define (compute-equal) (or (null? expr*) (let loop ([v (cf-eval-const (car expr*) env)] [arg* (cdr expr*)]) (cond [(null? arg*) 1] [(equal? v (cf-eval-const (car arg*) env)) (loop v (cdr arg*))] [else 0])))) (define (compute-shift) (cond [(not (= (length expr*) 2)) (s-error "Bad number of args for shift")] [else (let ([v (cf-eval-const (car expr*) env)] [s (cf-eval-const (cadr expr*) env)]) (check-number-arg v) (check-number-arg s) (let loop ([v v] [s s]) (cond [(zero? s) v] [(positive? s) (loop (* v 2) (- s 1))] [else (loop (quotient v 2) (+ s 1))])))])) (define (compute-not) (if (not (= (length expr*) 1)) (s-error "Bad number of arguments for not")) (if (zero? (cf-eval-const (car expr*) env)) 1 0)) (define (compute-or) (let loop ([arg* expr*]) (cond [(null? arg*) 0] [(not (zero? (cf-eval-const (car arg*) env))) 1] [else (loop (cdr arg*))]))) (define (compute-and) (let loop ([arg* expr*]) (cond [(null? arg*) 1] [(zero? (cf-eval-const (car arg*) env)) 0] [else (loop (cdr arg*))]))) (let ([v name]) ; ([v (cf-eval-param name env)]) (case v [(size-of align-of) (check-id-arg* expr* 1) (let ([type (get-id (car expr*) env)]) (ce-lookup env (list name type) "Computing (~a ~a)" name type))] [(offset-of) (check-id-arg* expr* 2) (let ([type (get-id (car expr*) env)] [field (get-id (cadr expr*) env)]) (ce-lookup env (list name type field) "Computing (~a ~a ~a)" name type field))] ;; for sfc [(+) (compute-arith* 0 (lambda (x) x) (lambda (a b) (+ a b)))] [(-) (compute-arith* 0 (lambda (x) (- x)) (lambda (a b) (- a b)))] [(*) (compute-arith* 1 (lambda (x) x) (lambda (a b) (* a b)))] [(/) (compute-arith2 quotient)] [(=) (compute-equal)] [(shift) (compute-shift)] [(and) (compute-and)] [(or) (compute-or)] [(not) (compute-not)] [else (s-error "Unexpected constant operation ~a (~a)" name v)]))) (define (cf-eval-param* param* env) (map (lambda (p) (cf-eval-param p env)) param*)) (define (cf-eval-param param env) (ce-search-x env 'param param (lambda (p) p) (lambda () param))) (define (cf-eval-id id env) (ce-search-x env 'type id (lambda (t) (case t [(param) (ce-lookup-x env 'param id "ICE in cf-eval-id/param")] [(const) (ce-lookup-x env 'const id "ICE in cf-eval-id/const")] [else id])) (lambda () id))) (define (cf-eval-mname param env) (ce-search-x env 'param param (lambda (p) (cf-eval-mname p env)) (lambda () param))) (variant-case ast [qa0-top (decl*) (let loop ([in* decl*] [out* '()] [env (ce-start-env machine real)]) (cond [(null? in*) (values (make-qa0-top (reverse out*)) env)] [else (let-values* ([(out* env) (cf-decl (car in*) out* env)]) (loop (cdr in*) out* env))]))]))
false
ad7dc517e1e3ad58d9b5bfbc4804c14081dcf663
486987d683c996171c3d52f4466574f60ad451be
/finalize.scm
0f3f35a7716b5a0a855f108645592a4a34476f8a
[]
no_license
drcz/cowgirl-or-invader
5ea3a35ee7631b642830eccda686ebe0257f4fa3
d56944ed80b527675166377edc03952488173f53
refs/heads/master
2016-08-11T09:52:18.737877
2016-01-15T16:33:36
2016-01-15T16:33:36
49,728,137
1
0
null
null
null
null
UTF-8
Scheme
false
false
4,047
scm
finalize.scm
;;; basic new blockmap extraction from the closed process tree: (define (rm-trans-label conf) (if (eq? (car conf) 'TRANSIT) (cdr conf) conf)) (define (tree->blockmap tree) (cons (cons (rm-trans-label (get-label-of tree)) (get-content-of tree)) (append-map tree->blockmap (get-children-of tree)))) ;;; change (pp . store) labels into symbols: (define (massage blockmap) (let* ((old-keys (map car blockmap)) (new-keys (map (lambda (k) ; blee, gensym is impure! (gensym (cond-expand (gambit (car k)) (guile-2 (symbol->string (car k)))))) old-keys)) (mapping (map cons old-keys new-keys))) (let loop ((bm blockmap)) (if (null? bm) '() (let* ((cur-node (car bm)) (old-label (car cur-node)) (old-block (cdr cur-node)) (new-label (lookup old-label mapping)) (new-block (massage-labels-in old-block mapping))) (cons (cons new-label new-block) (loop (cdr bm)))))))) (define (massage-labels-in block mapping) (match block [(('let v e) . block) `((let ,v ,e) . ,(massage-labels-in block mapping))] [(('return e)) block] [(('goto l)) `((goto ,(lookup l mapping)))] [(('if e l1 l2)) `((if ,e ,(lookup l1 mapping) ,(lookup l2 mapping)))])) ;;; convert CVARs and TVARS into symbols (define (mvars->symbols-in-program blockmap) (map (lambda (entry) (cons (car entry) (mvars->symbols-in-block (cdr entry)))) blockmap)) (define (mvars->symbols-in-block block) (match block [(('return e)) `((return ,(mvars->symbols-in-expr e))) ] [(('let mv e) . block) `((let ,(mvar->symbol mv) ,(mvars->symbols-in-expr e)) . ,(mvars->symbols-in-block block))] [(('if e l1 l2)) `((if ,(mvars->symbols-in-expr e) ,l1 ,l2))] [(('goto l)) `((goto ,l))])) (define (mvars->symbols-in-expr e) (match e [(? ground-sex? g) g] [('CVAR n) (mvar->symbol e)] [('TVAR n) (mvar->symbol e)] [(op e) `(,op ,(mvars->symbols-in-expr e))] [(op e1 e2) `(,op ,(mvars->symbols-in-expr e1) ,(mvars->symbols-in-expr e2))])) (define (mvar->symbol mvar) (string->symbol (string-append (if (eq? (car mvar) 'CVAR) "x" "t") (number->string (cadr mvar))))) ;;; compressing trivial transitions... (define (compress-transitions blockmap init-pp) (let ((jumpcounts (build-jumpinfo blockmap init-pp))) (let loop ((pend `(,(caar blockmap))) (res '())) (if (null? pend) (reverse res) (let* ((cur-label (car pend)) (pend (cdr pend))) (if (lookup cur-label res) (loop pend res) (let* ((cur-block (lookup cur-label blockmap)) (new-block (let compress ((block cur-block)) (match block [(('let v e) . block) `((let ,v ,e) . ,(compress block))] [(('return e)) `((return ,e))] [(('if e l1 l2)) `((if ,e ,l1 ,l2))] [(('goto l)) (if (> 1 (lookup l jumpcounts)) `((goto ,l)) (compress (lookup l blockmap)))]))) (children (get-jumps-from new-block)) (res `((,cur-label . ,new-block) . ,res)) (pend (append children pend))) (loop pend res)))))))) ;; for every pp, count number of jumps to it (from gotos and ifs): (define (count-occurences x xs) (cond ((null? xs) 0) ((equal? x (car xs)) (+ 1 (count-occurences x (cdr xs)))) (else (count-occurences x (cdr xs))))) (define (build-jumpinfo blockmap init-pp) (let* ((all-pps (map car blockmap)) (all-blocks (map cdr blockmap)) (all-jumps (append-map get-jumps-from all-blocks)) (pps-jumpcounts (map (lambda (pp) (count-occurences pp all-jumps)) all-pps)) (jump-info (map cons all-pps pps-jumpcounts))) ;;; now the init-pp is called once more, ;;; when the program starts... (update init-pp (+ 1 (lookup init-pp jump-info)) jump-info))) ;;; all together... (define (finalize tree) (mvars->symbols-in-program (massage (compress-transitions (tree->blockmap tree) (get-label-of tree)))))
false
6130691bfa5f65048809e1e3cb4a7eaf01050f7a
32b2a5a524695c0499f205a9ed8a1d32fc9f0c41
/simple/simple.scm
1296d20db8a3324353374800db86c7e2108b73e1
[]
no_license
NalaGinrut/simple
df4edec127991efc9753fe4a28df2b5db0565c43
b87870d2542208172b38464787bd83316408aedd
refs/heads/master
2020-05-19T20:49:30.558141
2018-07-07T08:26:13
2018-07-07T08:26:13
18,797,363
1
1
null
null
null
null
UTF-8
Scheme
false
false
3,553
scm
simple.scm
;; Copyright (C) 2014 ;; "Mu Lei" known as "NalaGinrut" <[email protected]> ;; This file is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; This file is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. (define-module (language simple simple) #:use-module (system base lalr) #:use-module (language tree-il) #:use-module (ice-9 and-let-star) #:use-module (ice-9 match) #:export (make-simple-tokenizer make-parser compile-tree-il)) ;; Two helper macros to create the token struct for returning (define-syntax-rule (port-source-location port) (make-source-location (port-filename port) (port-line port) (port-column port) (false-if-exception (ftell port)) #f)) (define-syntax-rule (return port category value) (make-lexical-token category (port-source-location port) value)) (define (is-whitespace? c) (char-set-contains? char-set:whitespace c)) (define (is-number? c) (char-set-contains? char-set:hex-digit c)) ;; operators, in this simple case, we just have four operators (define (is-op? c) (string-contains "+-*/" (string c))) (define (is-delimiter? c) (or (eof-object? c) (string-contains " +-*/;\n" (string c)))) (define (get-number port) (let lp((c (peek-char port)) (ret '())) (cond ((is-delimiter? c) ; encounter delimiter, finish to read a number ;; convert to a number representation (string->number (list->string (reverse ret)))) (else (read-char port) ; next char (lp (peek-char port) (cons c ret)))))) (define (get-op port) (string->symbol (string (read-char port)))) (define (next-token port) (let ((c (peek-char port))) (cond ((or (eof-object? c) (char=? c #\nl)) ; end of line, or end src '*eoi*) ; return '*eoi* because LALR module need it ((is-whitespace? c) (read-char port) (next-token port)) ; skip white space ((is-number? c) (return port 'number (get-number port))) ((is-op? c) (return port (get-op port) #f)) (else (read-char port) (next-token port))))) (define (make-simple-tokenizer port) (lambda () (next-token port))) (define (make-parser) (lalr-parser (number + - * /) ;;((number #;(left: + -) #;(left: * /)) (program (exp) : $1 (*eoi*) : (call-with-input-string "" read)) ; *eof-object* (exp (exp + term) : `(+ ,$1 ,$3) (exp - term) : `(- ,$1 ,$3) (term) : $1) (term (term * factor) : `(* ,$1 ,$3) (term / factor) : `(/ ,$1 ,$3) (factor) : $1) (factor (number) : `(number ,$1)))) (define (compile-tree-il exp env opts) (values (parse-tree-il (comp exp '())) env env)) (define (comp src e) (and-let* (((supports-source-properties? src)) (loc (source-property src 'loc))) (format (current-error-port) "LOC [~a]: ~a\n" loc src)) (match src (('number x) `(const ,x)) ((op x y) `(call (primitive ,op) ,(comp x e) ,(comp y e))) ((h t ...) (comp h e)))) ;; for driver glr
true
1ed1f2447dbe2814a308f6d8701278756c393cdd
d8d4bcb61e4af58a86fd1a02503e608b03d8c89f
/sitelib/errata/message.scm
23e07de2cb56e6982dafe7e9f5706db8d0843fc7
[ "BSD-2-Clause" ]
permissive
tabe/errata
b81cbb66b86e3bc1aaae4814b32ef03bfc5ed52e
23b30c26b59d6b049a198788fbce37049ad02e3f
refs/heads/master
2020-05-03T01:45:39.955636
2010-08-19T02:32:49
2010-08-19T02:32:49
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
16,335
scm
message.scm
(library (errata message) (export) (import (only (lunula gettext) gettext)) (gettext ;; fields (new-account-nick (en "nick") (ja "ニックネーム")) (new-account-name (en "name") (ja "名前")) (new-account-password (en "password") (ja "パスワード")) (new-account-password-re (en "password-re") (ja "パスワード(再入力)")) (new-account-mail-address (en "mail address") (ja "メールアドレス")) (account-to-modify-name (en "name") (ja "名前")) (account-to-modify-mail-address (en "mail address") (ja "メールアドレス")) (account-to-modify-password (en "current password") (ja "現在のパスワード")) (account-to-login-nick (en "nick") (ja "ニックネーム")) (account-to-login-password (en "password") (ja "パスワード")) (forgotten-account-mail-address (en "mail address") (ja "メールアドレス")) (password-reset-password (en "new password") (ja "新しいパスワード")) (password-reset-password-re (en "new password-re") (ja "新しいパスワード(再入力)")) (occurrence-to-add-page (en "Page") (ja "ページ")) (occurrence-to-add-position (en "Position") (ja "位置")) (password-to-modify-current-password (en "current password") (ja "現在のパスワード")) (password-to-modify-new-password (en "new password") (ja "新しいパスワード")) (password-to-modify-new-password-re (en "new password-re") (ja "新しいパスワード(再入力)")) (preference-to-edit-gravatar (en "Gravatar") (ja "Gravatar")) (preference-to-edit-report-format (en "Report format") (ja "報告の書式")) (confirmation-ok (en "OK?") (ja "OK?")) (new-exlibris-title (en "title") (ja "タイトル")) (new-exlibris-isbn (en "ISBN") (ja "ISBN")) (revision-name (en "name") (ja "名前")) (revision-revised-at (en "revised at") (ja "改訂日時")) (review-body (en "Body") (ja "レビュー本文")) (quotation-page (en "Page") (ja "ページ")) (quotation-position (en "Position") (ja "位置")) (quotation-body (en "Quotation's Body") (ja "引用本文")) (quotation-font-face (en "Font Face") (ja "書体")) (correction-body (en "Correction's Body") (ja "訂正本文")) (correction-font-face (en "Font Face") (ja "書体")) (report-to-modify-subject (en "Subject") (ja "題名")) (report-to-modify-page (en "Page") (ja "ページ")) (report-to-modify-position (en "Position") (ja "位置")) (report-to-modify-quotation-body (en "Quotation's Body") (ja "引用本文")) (report-to-modify-quotation-font-face (en "Quotation's Font Face") (ja "引用本文の書体")) (report-to-modify-correction-body (en "Correction's Body") (ja "訂正本文")) (report-to-modify-correction-font-face (en "Correction's Font Face") (ja "訂正本文の書体")) (report-by-manued-subject (en "Subject") (ja "題名")) (report-by-manued-page (en "Page") (ja "ページ")) (report-by-manued-position (en "Position") (ja "位置")) (report-by-manued-body (en "Body in Manued format") (ja "引用と訂正(Manued)")) (report-by-manued-quotation-font-face (en "Quotation's Font Face") (ja "引用本文の書体")) (report-by-manued-correction-font-face (en "Correction's Font Face") (ja "訂正本文の書体")) (acknowledgement-sign (en "Sign") (ja "引用部分が誤りだということに")) (acknowledgement-comment (en "Comment") (ja "コメント")) (agreement-comment (en "Comment") (ja "コメント")) ;; messages (password-is-blank (en "password is blank.") (ja "パスワードが空です。")) (password-too-short (en "password is too short.") (ja "パスワードが短いです。")) (password-too-long (en "password is too long.") (ja "パスワードが規定の長さを超えています。")) (password-differs-from-re (en "The first password differs from the second.") (ja "パスワードが再入力したものと異なります。")) (nick-is-blank (en "nick is blank.") (ja "ニックネームが空です。")) (nick-too-long (en "nick is too long.") (ja "ニックネームが規定の長さを超えています。")) (nick-already-used (en "nick is already used.") (ja "ニックネームは既に使用されています。")) (nick-invalid-char (en "nick contains invalid characters.") (ja "ニックネームに使えない文字が含まれています。")) (name-is-blank (en "name is blank.") (ja "名前が空です。")) (name-too-long (en "name is too long.") (ja "名前が規定の長さを超えています。")) (mail-address-is-blank (en "mail address is blank.") (ja "メールアドレスが空です。")) (mail-address-too-short (en "mail address is too short.") (ja "メールアドレスが規定の長さに達していません。")) (mail-address-too-long (en "mail address is too long.") (ja "メールアドレスが規定の長さを超えています。")) (does-not-exist (en "authentication failed.") (ja "認証に失敗しました。")) (invalid-report-format (en "invalid report format.") (ja "報告の書式に誤りがあります。")) (title-too-long (en "title is too long.") (ja "タイトルが規定の長さを超えています。")) (body-is-blank (en "body is blank.") (ja "本文が空です。")) (body-too-long (en "body is too long.") (ja "本文が規定の長さを超えています。")) (subject-is-blank (en "subject is blank.") (ja "題名が空です。")) (subject-too-long (en "subject is too long.") (ja "題名が規定の長さを超えています。")) (page-is-blank (en "page is blank.") (ja "ページが空です。")) (page-too-long (en "page is too long.") (ja "ページが規定の長さを超えています。")) (position-is-blank (en "position is blank.") (ja "位置が空です。")) (position-too-long (en "position is too long.") (ja "位置が規定の長さを超えています。")) (comment-is-blank (en "comment is blank.") (ja "コメントが空です。")) (comment-too-long (en "comment is too long.") (ja "コメントが規定の長さを超えています。")) (invalid-manued-format (en "Invalid Manued format.") (ja "Manued 書式に誤りがあります。")) (submit (en "submit") (ja "送信")) (cancel (en "cancel") (ja "キャンセル")) (hmm-an-error-occurred (en "Hmm ... an error occurred.") (ja "残念ながら ... エラーが発生しました。")) (you-have-already-logged-in (en "You have already logged in!") (ja "既にログインしています。")) (you-can-create-your-own-account (en "You can create your own account:") (ja "以下の情報を入力してアカウントを作成できます:")) (we-have-sent-confirmation-message-to-you (en "We have sent the confirmation message to you.") (ja "アカウント作成についての確認のメールを送信しました。作成を完了するにはメールの内容にしたがってください。")) (now-you-have-your-own-account (en "Now you have your own account!") (ja "アカウントができました。")) (your-account-has-been-updated (en "Your account has been updated.") (ja "アカウントが更新されました。")) (let-me-know-your-mail-address (en "Let me know your mail address:") (ja "アカウントのメールアドレスを入力してください:")) (we-have-sent-message-to-you (ja "We have sent the message to you.") (ja "メッセージをメールを送信しました。メールの内容にしたがってください。")) (specify-new-password (en "Specify new password:") (ja "新しいパスワードを指定してください:")) (your-password-updated (en "Your password has been updated.") (ja "パスワードが更新されました。")) (are-you-sure-to-cancel-account? (en "Are you sure to cancel your account?") (ja "アカウントを解除しますか?(アカウントを解除するとこれまでに登録されたデータが利用できなくなります。)")) (now-you-have-logged-in (en "Now you have logged in!") (ja "ログインしました。")) (now-you-have-logged-out (en "Now you have logged out!") (ja "ログアウトしました。")) (now-you-have-left-errata (en "Now you have left Errata. Thanks for your favor.") (ja "Errata のアカウントは解除されました。ご利用ありがとうございました。")) (of-course-we-know-you-are-kidding (en "Of course we know you are kidding :)") (ja "アカウントの解除をキャンセルしました。")) (your-preference-has-been-updated (en "Your preference has been updated.") (ja "設定が更新されました。")) (please-input-title-or-isbn (en "Please input title or ISBN.") (ja "タイトルまたは ISBN を入力してください。")) (please-check-isbn (en "Please check the ISBN.") (ja "ISBN を確認してください。")) (is-this-content-ok? (en "Is this content OK?") (ja "この内容でよろしいですか?")) (please-retry (en "Please check your input and retry.") (ja "入力内容を確認して再度入力してください。")) (specify-revision (en "Specify a concerned revision:") (ja "該当する改訂情報を指定してください:")) (choose-a-revision (en "Choose a concerned revision:") (ja "該当する改訂情報を選んでください:")) (or-specify-revision (en "Or, specify another revision:") (ja "もしくは、新たな改訂情報を指定してください:")) (do-you-want-to-make-exlibris-shared? (en "Do you want to make the exlibris shared?") (ja "この蔵書を公開しますか?(あとから公開/非公開にすることができます。)")) (where-do-you-find-the-same-body? (en "Where do you find the same body?: ") (ja "次と同じ内容が見つかった箇所を入力してください: ")) (are-you-sure-to-put-off-this-one? (en "Are you sure to put off this one?") (ja "この蔵書を書棚から外しますか?(書棚から外すと報告などの関連するデータも利用できなくなります。)")) (you-have-put-it-off (en "You have put it off.") (ja "この蔵書を書棚から外しました。")) (are-you-sure-to-hide-this-one? (en "Are you sure to hide this one?") (ja "この蔵書を隠しますか?(隠すと報告などの関連するデータが非公開になります。)")) (are-you-sure-to-drop-report? (en "Are you sure to drop report?") (ja "この報告を削除しますか?(報告を削除するとコメントなどの関連するデータも利用できなくなります。)")) (following-revisions-found (en "The following revisions are found:") (ja "以下の改訂情報が見つかりました:")) (bib-not-found (en "Bib not found.") (ja "書誌が見つかりませんでした。")) (ISBN (en "ISBN") (ja "ISBN")) (Revision (en "Revision") (ja "改訂情報")) (Review (en "Review") (ja "レビュー")) (Table (en "Table") (ja "正誤表")) (Detail (en "Detail") (ja "詳細")) (History (en "History") (ja "履歴")) (Quotation (en "Quotation") (ja "誤(引用)")) (Correction (en "Correction") (ja "正(訂正)")) (to-board (en "To Board") (ja "書誌一覧へ")) (to-desk (en "To Desk") (ja "デスクへ")) (to-detail (en "To Detail") (ja "詳細へ")) (to-shelf (en "To Shelf") (ja "書棚へ")) (to-table (en "To Table") (ja "正誤表へ")) (find-bib (en "Find Bib") (ja "書誌検索")) (drop-notification (en "Drop Notification") (ja "通知を削除")) (share-exlibris (en "Share Exlibris") (ja "共有する")) (hide-exlibris (en "Hide Exlibris") (ja "隠す")) (put-off (en "Put Off") (ja "外す")) (put-at-top (en "Put at Top") (ja "先頭に置く")) (edit-review (en "Edit") (ja "編集")) (new-report (en "New Report") (ja "新たに報告")) (modify-revision (en "Modify Revision") (ja "修正")) (import-bib (en "Import Bib") (ja "書棚にインポート")) (add-occurrence (en "Add occurrence") (ja "報告を追加")) (modify-report (en "Modify Report") (ja "報告を修正")) (drop-report (en "Drop Report") (ja "報告を削除")) (acknowledge (en "Acknowledge") (ja "引用に関してコメント")) (agree (en "Agree") (ja "訂正に同意")) (disagree (en "Disagree") (ja "訂正に反対")) (show-report-history (en "show report history") (ja "履歴を見る")) (recent-revisions (en "Recent revisions") (ja "新たに公開された改訂情報")) (recent-reviews (en "Recent reviews") (ja "新たに公開されたレビュー")) (recent-reports (en "Recent reports") (ja "新たに公開された報告")) (recent-acknowledgements (en "Recent acknowledgements") (ja "新たに公開されたコメント")) (recent-agreements (en "Recent agreements") (ja "新たに公開された同意")) ) )
false
446e4c314e9714eca36379982148561e6545162f
ffb05b145989e01da075e2a607fb291955251f46
/artima/scheme/scheme6.ss
9643953dc582ed1c8eeceffa94edf6912574ba10
[]
no_license
micheles/papers
a5e7f2fa0cf305cd3f8face7c7ecc0db70ce7cc7
be9070f8b7e8192b84a102444b1238266bdc55a0
refs/heads/master
2023-06-07T16:46:46.306040
2018-07-14T04:17:51
2018-07-14T04:17:51
32,264,461
2
0
null
null
null
null
UTF-8
Scheme
false
false
10,571
ss
scheme6.ss
#| The danger of benchmarks ========================================= Benchmarks are useful in papers and blog posts, as a good trick to attract readers, but you should never make the mistake of believing them: as Mark Twain would say, *there are lies, damned lies, and benchmarks*. The problem is not only that reality is different from benchmarks; the problem is that it is extremely easy to write a wrong benchmark or to give a wrong interpretation of it. In this episode I will show some of the dangers hidden under the factorial benchmark shown in the `previous episode`_, which on the surface looks trivial and unquestionable. If a benchmark so simple is so delicate, I leave to your imagination to figure out what may happen for complex benchmarks. The major advantage of benchmarks is that they make clear how wrong we are when we think that a solution is faster or slower than another solution. .. _previous episode: http://www.artima.com/weblogs/viewpost.jsp?thread=239699 Beware of wasted cycles ------------------------------------------------------------- .. image:: tartaruga.jpg An obvious danger of benchmarks is the issue of vasted cycles. Since usually benchmarks involve calling a function *N* times, the time spent in the loop must be subtracted from the real computation time. If the the computation is complex enough, usually the time spent in the loop is negligible with respect to the time spent in the computation. However, there are situations where this assumption is not true. In the factorial example you can measure the wasted cycles by subtracting from the total time the the time spent in the loop performing no operations (for instance by computing the factorial of zero, which contains no multiplications). On my MacBook the total time spent in order to compute the factorial of 7 for ten millions of times is 3.08 seconds, whereas the time spent to compute the factorial of zero is 0.23 seconds, i.e. fairly small but sensible. In the case of fast operations, the time spent in the loop can change completely the results of the benchmark. For instance, ``add1`` it is a function which increments a number by one and it is extremely fast. The time to sum 1+1 ten millions of times is 0.307 seconds:: > (time (call 10000000 add1 1)) running stats for (call 10000000 add1 1): no collections 307 ms elapsed cpu time, including 0 ms collecting 308 ms elapsed real time, including 0 ms collecting 24 bytes allocated If you measure the time spent in the loop and in calling the auxiliary function ``call``, by timing a ``do-nothing`` function, you will find a value of 0.214 seconds, i.e. 2/3 of the total time is wasted:: > (define (do-nothing x) x) > (time (call 10000000 do-nothing 1)) running stats for (call 10000000 do-nothing): no collections 214 ms elapsed cpu time, including 0 ms collecting 216 ms elapsed real time, including 0 ms collecting 16 bytes allocated Serious benchmarks must be careful in subtracting the wasted time correctly, if it is significant. The best thing is to reduce the wasted time. In a future episode we will consider this example again and we will see how to remove the time wasted in ``call`` by replacing it with a macro. Beware of cheats ----------------------------------------------------- .. image:: il+gatto+e+la+volpe.jpg The issue of wasted cycles is obvious enough; on the other hand, benchmarks are subject to less obvious effects. Here I will show a trick to improve dramatically the performance by cheating. Let us consider the factorial example, but using the Chicken Scheme compiler. Chicken works by compiling Scheme code into C code which is then compiled to machine code. Therefore, Chicken may leverage on all the dirty tricks on the underlying C compiler. In particular, Chicken exposes a benchmark mode where consistency checks are disabled and the ``-O3`` optiomization of gcc is enabled. By compiling the `factorial benchmark`_ in in this way you can get incredible performances:: $ csc -Ob fact.scm # csc = Chicken Scheme Compiler $ ./fact 7 ./fact 7 0.176 seconds elapsed 0 seconds in (major) GC 0 mutations 1 minor GCs 0 major GCs result:5040 We are *16* times faster than Ikarus and *173* times faster than Python! The only disadvantage is that the script does not work: when the factorial gets large enough (biggen than 2^31) Chicken (or better gcc) starts yielding meaningless values. Everything is fine until ``12!``:: $ ./fact 12 # this is smaller than 2^31, perfectly correct 0.332 seconds elapsed 0 seconds in (major) GC 0 mutations 1 minor GCs 0 major GCs result:479001600 Starting from ``13!`` you get a surprise:: $ ./fact 13 # the correct value is 6227020800, larger than 2^31 0.352 seconds elapsed 0 seconds in (major) GC 0 mutations 1 minor GCs 0 major GCs result:-215430144 You see what happens when you cheat? ;) Beware of naive optimization ------------------------------------------------------------- .. image:: exclamation-mark.jpg In this last section I will show a positive aspect of benchmarks: they may be usefully employed to avoid useless optimizations. Generally speaking, one should not try to optimize too much, since one could waste work and get the opposite effect, especially with modern compilers which are pretty smart. In order to give an example, suppose we want to optimize by hand the `factorial benchmark`_, by replacing the closure ``(call 10000000 (lambda () (fac n)))`` with the expression ``(call 10000000 fac n)``. In theory we would expect a performance improvement since we can skip an indirection level by calling directly ``fac`` instead of a closure calling ``fac``. Actually, this is what happens with: for ``n=7``, the program runs in 3.07 secondi with the closure and in 2.95 seconds without. In Chicken - I am using Chicken 2.732 here - instead, a disaster happens when the benchmark mode is turned on:: $ csc -Ob fact.scm $ ./fact 7 1.631 seconds elapsed 0.011 seconds in (major) GC 0 mutations 1881 minor GCs 23 major GCs result:5040 The program is nearly ten times slower! All the time is spent in the garbage collector. Notice that this behavior is proper of the benchmark mode: by compiling with the default options you will not see significant differences in the execution time, even if they are in any case much larger (7.07 seconds with the closure versus 6.88 seconds without). In other words, with the default option to use the closure has a little penalty, as you would expect, but in benchmark mode the closure improves the performance by ten times! I asked for an explation to Chicken's author, Felix Winkelmann, and here is what he said: *In the first case, the compiler can see that all references to fac are call sites: the value of "fac" is only used in positions where the compiler can be absolutely sure it is a call. In the second case the value of fac is passed to "call" (and the compiler is not clever enough to trace the value through the execution of "call" - this would need flow analysis). So in the first case, a specialized representation of fac can be used ("direct" lambdas, i.e. direct-style calls which are very fast).* *Compiling with "-debug o" and/or "-debug 7" can also be very instructive.* That should make clear that benchmarks are extremely delicate beasts, where (apparently) insignificant changes may completely change the numbers you get. So, beware of benchmarks, unless you are a compiler expert (and in that case you must be twice as careful! ;) .. _factorial benchmark: http://www.phyast.pitt.edu/~micheles/scheme/fact.scm Recursion vs iteration --------------------------------------------------------- Usually imperative languages do not support recursion too well, in the sense that they may have a *recursion limit*, as well as inefficiencies in the management of the stack. In such a languages it is often convenient to convert ricorsive problems into iterative problems. To this aim, it is convenient to rewrite first the recursive problem in tail call form, possibly by adding auxiliary variables working as accumulators. At this point, the rewritin as a ``while`` loop is trivial. For instance, implementing the factorial iteratively in Python has serious advantages: if you run the script :: # fact_it.py import sys, timeit def fact(x): acc = 1 while x > 0: acc *= x x -= 1 return acc if __name__ == '__main__': n = int(sys.argv[-1]) t = timeit.Timer('fact(%d)' % n, 'from fact_it import fact') print t.repeat(1, number=10000000) print fact(n) you will see a speed-up of circa 50% with respect to the recursive version for "small" numbers. Alternatively, you can get an iterative version of the factorial as ``reduce(operator.mul, range(1, n+1)``. This was suggested by Miki Tebeka in a comment to the previous episode and also gives a sensible speedup. However notice that ``reduce`` is not considered Pythonic and that Guido removed it from the builtins in Python 3.0 - you can find it in ``functools`` now. If you execute the equivalent Scheme code, :: (import (rnrs) (only (ikarus) time) (only (repeat) call)) (define (fac x acc) (if (= x 0) acc (fac (- x 1) (* x acc)))) (define n (string->number (car (reverse (command-line))))) (time (call 10000000 (lambda () (fac n 1)))) (display "result:") (display (fac n 1)) (newline) you will discover that it is slightly *slower* than the non tail-call version (the tail-call requires less memory to run, anyway). In any case we are an order of magnituder over Python efficiency. If we consider benchmarks strongly dependent on function call efficiency, like the `Fibonacci benchmark`_ of Antonio Cangiano, the difference between Python and Scheme is even greater: on my tests Ikarus is *thirty* times faster than Python. Other implementations of Scheme or other functional languages (ML, Haskell) can be even faster (I tried the SML/NJ implementation, which is *forty* times faster than Python 2.5). Of course those benchmarks have no meaning. With benchmarks one can prove that Python is faster than Python is faster than Fortran and C++ in matrix computations. If you do not believe it, please read this_ ;) .. _this: http://matrixprogramming.com/MatrixMultiply/ .. _Fibonacci benchmark: http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-python-away/ That's all folks, see you next episode! |#
false
f7aea0a61baffc9349aff3cce0f9f6fdb97894a6
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/swallowing_exceptions/wallowing_exceptions.ss
4615143c0e2eeb29a379e1aaf4f710ede981d52a
[]
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,057
ss
wallowing_exceptions.ss
#! /bin/sh #| Hey Emacs, this is -*-scheme-*- code! #$Id: v4-script-template.ss 6182 2009-11-10 04:59:27Z erich $ exec mzscheme -l errortrace --require "$0" --main -- ${1+"$@"} |# #lang scheme (require (planet schematics/schemeunit:3) (planet schematics/schemeunit:3/text-ui)) (define-syntax-rule (with-swallowed-exceptions exn-predicate body ...) (with-handlers ([exn-predicate (lambda (e) (printf "Swallowing an exception: ~a~%" (exn-message e)))]) body ...)) (define-syntax-rule (calm-loop generator-stuff exn-predicate body ...) (for generator-stuff (with-swallowed-exceptions exn-predicate body ...))) (define-struct (exn:bigfaterror exn:fail) () #:transparent) (define (process datum) (if (even? datum) (raise (make-exn:bigfaterror (format "I don't like even numbers like ~a" datum) (current-continuation-marks))) (format "~a is nice because it's even" datum))) (define (main . args) (calm-loop ([d (list 1 2 3 4 5)]) exn:bigfaterror? (display (process d)) (newline))) (provide main)
true
8455836528260bfbcc915169bd2462833270bb30
e870410f5d1d711825daab7a5cf7bb58fb1f973e
/tests/check.scm
b838bbb284aea675f01a9405cc39509591a8ef6c
[]
no_license
tali713/mit-scheme
bfe4fbe28a771519b0577ceece8610b32b70efe5
6c703a838081fe2418bc0dbfe003bdb429d8c479
refs/heads/master
2020-04-04T19:36:56.868928
2012-06-05T02:58:35
2012-06-05T02:58:35
6,101,800
8
5
null
null
null
null
UTF-8
Scheme
false
false
3,764
scm
check.scm
#| -*-Scheme-*- Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 Massachusetts Institute of Technology This file is part of MIT/GNU Scheme. MIT/GNU Scheme is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. MIT/GNU Scheme is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MIT/GNU Scheme; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. |# ;;;; Script to run the tests ;++ This whole script is a horrible kludge. Please rewrite it! (declare (usual-integrations)) ;;; Can't just look at */test-*.scm because not everything has been ;;; converted to use the automatic framework. (define known-tests '( ;++ Kludge to run the flonum cast tests interpreted and compiled -- ;++ the compiler has a bug with negative zero. "microcode/test-flonum-casts" "microcode/test-flonum-casts.scm" "microcode/test-flonum-casts.com" "microcode/test-lookup" ("runtime/test-char-set" (runtime character-set)) "runtime/test-division" "runtime/test-ephemeron" "runtime/test-floenv" "runtime/test-hash-table" "runtime/test-integer-bits" "runtime/test-process" "runtime/test-regsexp" ("runtime/test-wttree" (runtime wt-tree)) ;;"ffi/test-ffi" )) (with-working-directory-pathname (directory-pathname (current-load-pathname)) (lambda () (load "load") (for-each (lambda (entry) (receive (pathname environment) (if (pair? entry) (values (car entry) (->environment (cadr entry))) (values entry #!default)) (with-notification (lambda (output-port) (write-string "Run tests " output-port) (write pathname output-port) (if (not (default-object? environment)) (begin (write-string " in environment " output-port) (write (cond ((environment->package environment) => package/name) (else environment)) output-port)))) (lambda () (if (not (pathname-type pathname)) (with-working-directory-pathname (directory-pathname pathname) (lambda () ;++ Kludge around a bug in SF... (compile-file (file-pathname pathname) '() environment)))) (let* ((t (pathname-type pathname)) (p (if (and t (string=? "com" t) (eq? 'C microcode-id/compiled-code-type)) (pathname-new-type pathname "so") pathname))) (run-unit-tests p environment)))))) known-tests)))
false
58566a77f5fc88ef1526df6d39bcbb6434edff35
53cb8287b8b44063adcfbd02f9736b109e54f001
/prec/prec-parse.scm
9df06a6156a3d3075517739882086a7517c5fa0c
[]
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
8,070
scm
prec-parse.scm
;;; prec-parse.scm -- do precedence parsing of expressions and patterns ;;; ;;; author : John & Sandra ;;; date : 04 Feb 1992 ;;; ;;; ;;; ================================================================== ;;; Handling for pp-exp-list ;;; ================================================================== ;;; This function is called during the scope phase after all of the ;;; exps in a pp-exp-list have already been walked. Basically, the ;;; purpose is to turn the original pp-exp-list into something else. ;;; Look for the section cases first and treat them specially. ;;; Sections are handled by inserting a magic cookie (void) into the ;;; list where the `missing' operand of the section would be and then ;;; making sure the cookie stays at the top. ;;; Unary minus needs checking to avoid things like a*-a. (define (massage-pp-exp-list exps) (let* ((first-term (car exps)) (last-term (car (last exps))) (type (cond ((infix-var-or-con? first-term) 'section-l) ((infix-var-or-con? last-term) 'section-r) (else 'exp))) (exps1 (cond ((eq? type 'section-l) (cons (make void) exps)) ((eq? type 'section-r) (append exps (list (make void)))) (else exps))) (parsed-exp (parse-pp-list '#f exps1))) (if (eq? type 'exp) parsed-exp (if (or (not (app? parsed-exp)) (not (app? (app-fn parsed-exp)))) (begin (signal-section-precedence-conflict (if (eq? type 'section-l) first-term last-term)) (make void)) (let ((rhs (app-arg parsed-exp)) (op (app-fn (app-fn parsed-exp))) (lhs (app-arg (app-fn parsed-exp)))) (if (eq? type 'section-l) (if (void? lhs) (make section-l (op op) (exp rhs)) (begin (signal-section-precedence-conflict first-term) (make void))) (if (void? rhs) (make section-r (op op) (exp lhs)) (begin (signal-section-precedence-conflict last-term) (make void))))))))) ;;; ================================================================== ;;; Handling for pp-pat-list ;;; ================================================================== ;;; In this case, we have to do an explicit walk of the pattern looking ;;; at all of its subpatterns. ;;; ** This is a crock - the scope walker needs fixing. (define (massage-pattern pat) (cond ((is-type? 'as-pat pat) (setf (as-pat-pattern pat) (massage-pattern (as-pat-pattern pat))) pat) ((is-type? 'irr-pat pat) (setf (irr-pat-pattern pat) (massage-pattern (irr-pat-pattern pat))) pat) ((is-type? 'plus-pat pat) (setf (plus-pat-pattern pat) (massage-pattern (plus-pat-pattern pat))) pat) ((is-type? 'pcon pat) (when (eq? (pcon-con pat) *undefined-def*) (setf (pcon-con pat) (lookup-toplevel-name (pcon-name pat)))) (setf (pcon-pats pat) (massage-pattern-list (pcon-pats pat))) pat) ((is-type? 'list-pat pat) (setf (list-pat-pats pat) (massage-pattern-list (list-pat-pats pat))) pat) ((is-type? 'pp-pat-list pat) (parse-pp-list '#t (massage-pattern-list (pp-pat-list-pats pat)))) (else pat))) (define (massage-pattern-list pats) (map (function massage-pattern) pats)) ;;; ================================================================== ;;; Shared support ;;; ================================================================== ;;; This is the main routine. (define (parse-pp-list pattern? l) (mlet (((stack terms) (push-pp-stack '() l))) (pp-parse-next-term pattern? stack terms))) (define (pp-parse-next-term pattern? stack terms) (if (null? terms) (reduce-complete-stack pattern? stack) (let ((stack (reduce-stronger-ops pattern? stack (car terms)))) (mlet (((stack terms) (push-pp-stack (cons (car terms) stack) (cdr terms)))) (pp-parse-next-term pattern? stack terms))))) (define (reduce-complete-stack pattern? stack) (if (pp-stack-op-empty? stack) (car stack) (reduce-complete-stack pattern? (reduce-pp-stack pattern? stack)))) (define (reduce-pp-stack pattern? stack) (let ((term (car stack)) (op (cadr stack))) (if pattern? (cond ((pp-pat-plus? op) (let ((lhs (caddr stack))) (cond ((or (not (const-pat? term)) (and (not (var-pat? lhs)) (not (wildcard-pat? lhs)))) (signal-plus-precedence-conflict term) (cddr stack)) (else (cons (make plus-pat (pattern lhs) (k (integer-const-value (const-pat-value term)))) (cdddr stack)))))) ((pp-pat-negated? op) (cond ((const-pat? term) (let ((v (const-pat-value term))) (if (integer-const? v) (setf (integer-const-value v) (- (integer-const-value v))) (setf (float-const-numerator v) (- (float-const-numerator v))))) (cons term (cddr stack))) (else (signal-minus-precedence-conflict term) (cons term (cddr stack))))) (else (setf (pcon-pats op) (list (caddr stack) term)) (cons op (cdddr stack)))) (cond ((negate? op) (cons (**app (**var/def (core-symbol "negate")) term) (cddr stack))) (else (cons (**app op (caddr stack) term) (cdddr stack))))))) (define (pp-stack-op-empty? stack) (null? (cdr stack))) (define (top-stack-op stack) (cadr stack)) (define (push-pp-stack stack terms) (let ((term (car terms))) (if (or (negate? term) (pp-pat-negated? term)) (begin (when (and stack (stronger-op? (car stack) term)) (unary-minus-prec-conflict term)) (push-pp-stack (cons term stack) (cdr terms))) (values (cons term stack) (cdr terms))))) (define (reduce-stronger-ops pattern? stack op) (cond ((pp-stack-op-empty? stack) stack) ((stronger-op? (top-stack-op stack) op) (reduce-stronger-ops pattern? (reduce-pp-stack pattern? stack) op)) (else stack))) (define (stronger-op? op1 op2) (let ((fixity1 (get-op-fixity op1)) (fixity2 (get-op-fixity op2))) (cond ((> (fixity-precedence fixity1) (fixity-precedence fixity2)) '#t) ((< (fixity-precedence fixity1) (fixity-precedence fixity2)) '#f) (else (let ((a1 (fixity-associativity fixity1)) (a2 (fixity-associativity fixity2))) (if (eq? a1 a2) (cond ((eq? a1 'l) '#t) ((eq? a1 'r) '#f) (else (signal-precedence-conflict op1 op2) '#t)) (begin (signal-precedence-conflict op1 op2) '#t)))) ))) (define (get-op-fixity op) (cond ((var-ref? op) (pp-get-var-fixity (var-ref-var op))) ((con-ref? op) (pp-get-con-fixity (con-ref-con op))) ((pcon? op) (pp-get-con-fixity (pcon-con op))) ((or (negate? op) (pp-pat-negated? op)) (pp-get-var-fixity (core-symbol "-"))) ((pp-pat-plus? op) (pp-get-var-fixity (core-symbol "+"))) (else (error "Bad op ~s in pp-parse." op)))) (define (pp-get-var-fixity def) (if (eq? (var-fixity def) '#f) default-fixity (var-fixity def))) (define (pp-get-con-fixity def) (if (eq? (con-fixity def) '#f) default-fixity (con-fixity def))) ;;; Error handlers (define (signal-section-precedence-conflict op) (phase-error 'section-precedence-conflict "Operators in section body have lower precedence than section operator ~A." op)) (define (signal-precedence-conflict op1 op2) (phase-error 'precedence-conflict "The operators ~s and ~s appear consecutively, but they have the same~%~ precedence and are not either both left or both right associative.~% You must add parentheses to avoid a precedence conflict." op1 op2)) (define (signal-plus-precedence-conflict term) (phase-error 'plus-precedence-conflict "You need to put parentheses around the plus-pattern ~a~%~ to avoid a precedence conflict." term)) (define (signal-minus-precedence-conflict arg) (phase-error 'minus-precedence-conflict "You need to put parentheses around the negative literal ~a~%~ to avoid a precedence conflict." arg)) (define (unary-minus-prec-conflict arg) (recoverable-error 'minus-precedence-conflict "Operator ~A too strong for unary minus - add parens please!~%" arg))
false
3e1dd1b6a30ac877ef13ef3b279343859c6b4125
dff2c294370bb448c874da42b332357c98f14a61
/es-pipelines.scm
42274efdc3af7d271aa07859e0af3903041fd839
[ "BSD-2-Clause" ]
permissive
kdltr/hypergiant
caf14bbeac38b9d5b5713a19982b226082f3daad
ffaf76d378cc1d9911ad4de41f1d7219e878371e
refs/heads/master
2021-01-01T01:43:09.756174
2019-04-04T12:38:25
2019-04-04T12:38:25
239,126,881
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,163
scm
es-pipelines.scm
;;;; es-pipelines.scm ;;;; GL ES pipelines, conditionally imported by shaders.scm (define-pipeline mesh-pipeline ((#:vertex input: ((position #:vec3)) uniform: ((mvp #:mat4))) (define (main) #:void (set! gl:position (* mvp (vec4 position 1.0))))) ((#:fragment uniform: ((color #:vec3))) (define (main) #:void (set! gl:frag-color (vec4 color 1.0))))) (define-pipeline color-pipeline ((#:vertex input: ((position #:vec3) (color #:vec3)) uniform: ((mvp #:mat4)) output: ((c #:vec3))) (define (main) #:void (set! gl:position (* mvp (vec4 position 1.0))) (set! c color))) ((#:fragment input: ((c #:vec3))) (define (main) #:void (set! gl:frag-color (vec4 c 1.0))))) (define-pipeline texture-pipeline ((#:vertex input: ((position #:vec3) (tex-coord #:vec2)) uniform: ((mvp #:mat4)) output: ((tex-c #:vec2))) (define (main) #:void (set! gl:position (* mvp (vec4 position 1.0))) (set! tex-c tex-coord))) ((#:fragment input: ((tex-c #:vec2)) uniform: ((tex #:sampler-2d))) (define (main) #:void (set! gl:frag-color (texture-2d tex tex-c))))) (define-alpha-pipeline sprite-pipeline ((#:vertex input: ((position #:vec3) (tex-coord #:vec2)) uniform: ((mvp #:mat4)) output: ((tex-c #:vec2))) (define (main) #:void (set! gl:position (* mvp (vec4 position 1.0))) (set! tex-c tex-coord))) ((#:fragment input: ((tex-c #:vec2)) uniform: ((tex #:sampler-2d))) (define (main) #:void (set! gl:frag-color (texture-2d tex tex-c))))) (define-pipeline text-pipeline ((#:vertex input: ((position #:vec2) (tex-coord #:vec2)) uniform: ((mvp #:mat4)) output: ((tex-c #:vec2))) (define (main) #:void (set! gl:position (* mvp (vec4 position 0.0 1.0))) (set! tex-c tex-coord))) ((#:fragment input: ((tex-c #:vec2)) uniform: ((tex #:sampler-2d) (color #:vec3))) (define (main) #:void (let ((r #:float (field (texture-2d tex tex-c) r))) (set! gl:frag-color (vec4 color r))))))
false
cf8291376f3750ce98a27ece57fb1aa951ed721e
c42881403649d482457c3629e8473ca575e9b27b
/test/persistence.scm
09718f6b3bcecc0072cdbb2b6c7965eb4ee6fd4a
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
kahua/Kahua
9bb11e93effc5e3b6f696fff12079044239f5c26
7ed95a4f64d1b98564a6148d2ee1758dbfa4f309
refs/heads/master
2022-09-29T11:45:11.787420
2022-08-26T06:30:15
2022-08-26T06:30:15
4,110,786
19
5
null
2015-02-22T00:23:06
2012-04-23T08:02:03
Scheme
UTF-8
Scheme
false
false
52,608
scm
persistence.scm
;; -*- coding: utf-8; mode: scheme -*- ;; test kahua.persistence ;; Kahua.persistenceモジュールのテスト (use gauche.test) (use gauche.collection) (use file.util) (use util.list) ;; A hook to use this file for both stand-alone test and ;; DBI-backed-up test. (cond ((global-variable-bound? (current-module) '*dbname*) (rxmatch-if (#/^(\w+):/ *dbname*) (#f driver) (test-start #`"persistence/,|driver| (,|*dbname*|)") (test-start #`"persistence/efs (,|*dbname*|)"))) (else (error "You must define \*dbname\* for database name."))) (define-syntax with-clean-db (syntax-rules () ((_ (db dbpath) . body) (with-db (db dbpath) (kahua-db-purge-objs) . body)))) ;; ロードテスト: ;; kahua.persistentceがロードでき、またそのインタフェースに ;; 齟齬がないことを確認する。 (use kahua.persistence) (test-module 'kahua.persistence :bypass-arity-check '(read-kahua-instance)) ;;---------------------------------------------------------- ;; 基本的なテスト (test-section "database basics") ;; 存在しないデータベース名を与えてデータベースをオープンし、 ;; データベースが正しく作成されることを確認する。 (test* "creating database" '(#t #t #t #t) (with-db (db *dbname*) (cons (is-a? db <kahua-db>) (case (class-name (class-of db)) ((<kahua-db-fs> <kahua-db-efs>) (list (file-is-directory? (ref db 'real-path)) (file-is-regular? (ref db 'id-counter-path)) (file-is-regular? (ref db 'character-encoding-path)))) ((<kahua-db-mysql>) (list (and (dbi-do (ref db 'connection) "select class_name, table_name from kahua_db_classes") #t) (and-let* ((r (dbi-do (ref db 'connection) "select value from kahua_db_idcount")) (p (map (cut dbi-get-value <> 0) r))) (and (pair? p) (integer? (x->integer (car p))))) (and-let* ((r (dbi-do (ref db 'connection) "select value from kahua_db_classcount")) (p (map (cut dbi-get-value <> 0) r))) (and (pair? p) (integer? (x->integer (car p))))))) ((<kahua-db-postgresql>) (list (and (dbi-do (ref db 'connection) "select class_name, table_name from kahua_db_classes") #t) (and-let* ((r (dbi-do (ref db 'connection) "select count(*) from pg_class where relname='kahua_db_idcount' and relkind='S'")) (p (map (cut dbi-get-value <> 0) r))) (and (pair? p) (= (x->integer (car p)) 1))) (and-let* ((r (dbi-do (ref db 'connection) "select count(*) from pg_class where relname='kahua_db_classcount' and relkind='S'")) (p (map (cut dbi-get-value <> 0) r))) (and (pair? p) (= (x->integer (car p)) 1)))))) ))) ;; データベースがwith-dbの動的スコープ中で有効であり、 ;; その外で無効になることを確認する。 (test* "database activeness" '(#t #f) (receive (db active?) (with-db (db *dbname*) (values db (ref db 'active))) (list active? (ref db 'active)))) ;;---------------------------------------------------------- ;; インスタンス作成テスト (test-section "instances") ;; 新しい永続クラスを定義し、それが永続メタクラス<kahua-persistent-meta>に ;; 登録されていることを確認する。 (define-class <kahua-test> (<kahua-persistent-base>) ((quick :allocation :persistent :init-keyword :quick :init-value 'i) (quack :init-keyword :quack :init-value 'a) (quock :allocation :persistent :init-keyword :quock :init-value 'o)) :source-id "Rev 1") (define-method list-slots ((obj <kahua-test>)) (map (cut ref obj <>) '(%kahua-persistent-base::id quick quack quock))) (define (get-test-obj id) (find-kahua-instance <kahua-test> (format "~6,'0d" id))) (test* "metaclass stuff" (list #t <kahua-test>) (list (is-a? <kahua-test> <kahua-persistent-meta>) (find-kahua-class '<kahua-test>))) ;; 永続インスタンスを作成し、スロットが初期化されていること確認する。 (test* "creation (1)" '(1 ii aa "oo") (with-clean-db (db *dbname*) (list-slots (make <kahua-test> :quick 'ii :quack 'aa :quock "oo")))) ;; 再びトランザクションを開始し、先程作成した永続オブジェクトが得られる ;; ことを確認する。 (test* "read (1)" '(1 ii a "oo") (with-clean-db (db *dbname*) (list-slots (get-test-obj 1)))) ;; ひとつのトランザクションでの変更が、次のトランザクションにも保持されて ;; いることを確認する。 (test* "modify (1)" '(1 "II" a "oo") (begin (with-clean-db (db *dbname*) (set! (ref (get-test-obj 1) 'quick) "II")) (with-clean-db (db *dbname*) (list-slots (get-test-obj 1)))) ) ;; もう一つの永続インスタンスを作成し、変更が可能であることを確認する。 ;; また、その変更が先程作成した永続インスタンスには影響しないことを ;; 確認する。 (test* "creation (2)" '(2 hh bb "pp") (with-clean-db (db *dbname*) (list-slots (make <kahua-test> :quick 'hh :quack 'bb :quock "pp")))) (test* "modify (2)" '(2 "hh" a "PP") (begin (with-clean-db (db *dbname*) (set! (ref (get-test-obj 2) 'quick) "hh") (set! (ref (get-test-obj 2) 'quock) "PP")) (with-clean-db (db *dbname*) (list-slots (get-test-obj 2)))) ) (test* "read (1)" '(1 "II" a "oo") (with-clean-db (db *dbname*) (list-slots (get-test-obj 1)))) ;; 永続クラスの世代番号が正しく初期化されていること、すなわち ;; in-memory世代もin-db世代も0であることを確認する。 (test* "generation" '(0 0) (with-clean-db (db *dbname*) (list (ref <kahua-test> 'generation) (ref <kahua-test> 'persistent-generation)))) ;; オーバーライドを禁止したスロットをオーバーライドするクラスを定義してみる。 ;; エラーになるはず。 (test* "Final slot overriding: %kahua-persistent-base::id" *test-error* (eval '(define-class <kahua-violation-id> (<kahua-persistent-base>) ((%kahua-persistent-base::id :init-value 0))) (current-module))) (test* "Final slot overriding: %kahua-persistent-base::db" *test-error* (eval '(define-class <kahua-violation-db> (<kahua-persistent-base>) ((%kahua-persistent-base::db :init-value #f) (%kahua-persistent-base::id :init-value 0))) (current-module))) ;;---------------------------------------------------------- ;; トランザクションに関するテスト (test-section "transaction") ;; 永続インスタンス変更後にトランザクションをerrorで中断し、 ;; 再びトランザクションを開始して、永続インスタンスが変更されて ;; いないことを確認する。 (test* "abort transaciton" '(2 "hh" a "PP") (guard (e (else (with-clean-db (db *dbname*) (list-slots (get-test-obj 2))))) (with-clean-db (db *dbname*) (set! (ref (get-test-obj 2) 'quick) 'whoops) (error "abort!")))) ;; 永続インスタンス変更後に一度中間commitしてからまたインスタンスを ;; 変更し、トランザクションをerrorで中断する。 ;; 再びトランザクションを開始して、永続インスタンスが中間commitまでの ;; 変更を受け、それ以降の変更は受けていないことを確認する。 (test* "commit & abort" '(2 whoops a "PP") (guard (e (else (with-clean-db (db *dbname*) (list-slots (get-test-obj 2))))) (with-clean-db (db *dbname*) (set! (ref (get-test-obj 2) 'quick) 'whoops) (kahua-db-sync db) (set! (ref (get-test-obj 2) 'quock) 'whack) (error "abort!")))) ;;---------------------------------------------------------- ;; 永続オブジェクト間の参照に関するテスト (test-section "references") ;; 永続オブジェクトへの参照を別の永続オブジェクトのスロットにセットし、 ;; コミットできることを確認する。 (test* "reference write" #t (with-clean-db (db *dbname*) (set! (ref (get-test-obj 1) 'quick) (get-test-obj 2)) (is-a? (ref (get-test-obj 1) 'quick) <kahua-test>))) ;; 再びもとの永続オブジェクトを読み出し、参照先の永続オブジェクトも ;; 正しく読まれていることを確認する。 (test* "reference read" '(2 whoops a "PP") (with-clean-db (db *dbname*) (list-slots (ref (get-test-obj 1) 'quick)))) ;; ふたつの永続オブジェクトが相互に参照しあう構造を作成し、それが ;; コミットできることを確認する。 (test* "circular reference write" '(#t #t) (with-clean-db (db *dbname*) (set! (ref (get-test-obj 2) 'quick) (get-test-obj 1)) (list (eq? (get-test-obj 1) (ref (get-test-obj 2) 'quick)) (eq? (get-test-obj 2) (ref (get-test-obj 1) 'quick))))) ;; 作成した循環参照構造を再び読み出し、構造が正しく再現されている ;; ことを確認する。 (test* "circular reference read" '(#t #t) (with-clean-db (db *dbname*) (list (eq? (get-test-obj 1) (ref (get-test-obj 2) 'quick)) (eq? (get-test-obj 2) (ref (get-test-obj 1) 'quick))))) ;;---------------------------------------------------------- ;; クラス再定義 (test-section "class redefinition") ;(with-clean-db (db *dbname*) (kahua-db-purge-objs)) ;; 永続クラスを再定義する。スロットの変更点は以下の通り。 ;; Slot changes: ;; quick - no change (persistent) ;; quack - no change (transient) ;; muick - added (persistent) ;; quock - changed (persistent -> virtual) (define-class <kahua-test> (<kahua-persistent-base>) ((quick :allocation :persistent :init-keyword :quick :init-value 'i) (quack :init-keyword :quack :init-value 'a) (muick :allocation :persistent :init-keyword :muick :init-value 'm) (quock :allocation :virtual :slot-ref (lambda (o) (ref o 'quick)) :slot-set! (lambda (o v) #f)) ;; to vanish ) :source-id "Rev 2") ;; オブジェクトマネージャに、再定義されたクラスが登録されていることを確認。 (test* "redefining class" <kahua-test> (find-kahua-class '<kahua-test>)) ;; インスタンスが新しいクラスに対応してアップデートされることを確認する。 (test* "updating instance for new class" #t (with-db (db *dbname*) (eq? (ref (get-test-obj 1) 'quick) (ref (get-test-obj 1) 'quock)))) (test* "updating instance for new class" '(#t #t) (with-db (db *dbname*) (list (equal? (list-slots (ref (get-test-obj 1) 'quock)) (list-slots (get-test-obj 2))) (equal? (list-slots (ref (get-test-obj 2) 'quock)) (list-slots (get-test-obj 1)))))) ;; アップデートしたインスタンスに対する変更がデータベースに反映されることを ;; 確認する。 (test* "redefining class (write)" '("M" "M" "M") (with-clean-db (db *dbname*) (set! (ref (get-test-obj 1) 'muick) '("M" "M" "M")) (ref (get-test-obj 1) 'muick))) (test* "redefining class (read)" '("M" "M" "M") (with-clean-db (db *dbname*) (ref (get-test-obj 1) 'muick))) ;; 再定義した永続クラスの世代番号がインクリメントされていることを確認する。 (test* "generation" '(1 1) (with-clean-db (db *dbname*) (list (ref <kahua-test> 'generation) (ref <kahua-test> 'persistent-generation)))) ;;---------------------------------------------------------- ;; サブクラスのテスト (test-section "subclassing") ;(with-clean-db (db *dbname*) (kahua-db-purge-objs)) ;; 永続クラス<kahua-test>を継承したサブクラスを作成する。 (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") ;; this shadows parent's quock (quock :allocation :persistent :init-keyword :quock :init-value #f)) :source-id "Rev 3") (define-method list-slots ((obj <kahua-test-sub>)) (map (cut ref obj <>) '(%kahua-persistent-base::id quick quack woo boo quock))) (define-method key-of ((obj <kahua-test-sub>)) (string-append (ref obj 'woo) (ref obj 'boo))) ;; サブクラスの永続インスタンスが正しく作成され、継承されたスロット、 ;; 追加されたスロット、共にデータが永続化されることを確認する。 (test* "write" '(4 "quick" "quack" "woo" "boo" "quock") (with-clean-db (db *dbname*) (list-slots (make <kahua-test-sub> :quick "quick" :quack "quack" :woo "woo" :boo "boo" :quock "quock")))) (test* "read" '(4 "quick" a "woo" "boo" "quock") (with-clean-db (db *dbname*) (list-slots (find-kahua-instance <kahua-test-sub> "wooboo")))) (test* "write" '(5 i a "wooo" "booo" #f) (with-clean-db (db *dbname*) (list-slots (make <kahua-test-sub> :woo "wooo" :boo "booo")))) (test* "read" '(5 i a "wooo" "booo" #f) (with-clean-db (db *dbname*) (list-slots (find-kahua-instance <kahua-test-sub> "wooobooo")))) ;; 親クラスの永続インスタンスへの参照を含む構造を作成し、 ;; それがデータベースに反映されることを確認する。 (test* "reference to parent (write)" #t (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <kahua-test-sub> "wooboo") (set! (ref obj 'quick) (get-test-obj 1)) (eq? (ref obj 'quick) (get-test-obj 1))))) (test* "reference to parent (read)" #t (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <kahua-test-sub> "wooboo") (eq? (ref obj 'quick) (get-test-obj 1))))) ;; この子クラスの世代番号が初期化されていることを確認する。 (test* "generation" '(0 0) (with-clean-db (db *dbname*) (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation)))) ;;---------------------------------------------------------- ;; 永続オブジェクトコレクション<kahua-collection>に関するテスト (test-section "collection") ;; <kahua-test>永続クラス、および<kahua-test-sub>永続クラスから ;; そのクラスの永続インスタンスのコレクションが作成できることを ;; 確認する。 (test* "kahua-test" '(1 2) (sort (with-clean-db (db *dbname*) (map kahua-persistent-id (make-kahua-collection <kahua-test>))))) (test* "kahua-test-sub" '("woo" "wooo") (sort (with-clean-db (db *dbname*) (map (cut ref <> 'woo) (make-kahua-collection <kahua-test-sub>))))) (test* "kahua-test-sub w/ predicate" '("woo") (sort (with-clean-db (db *dbname*) (map (cut ref <> 'woo) (make-kahua-collection <kahua-test-sub> :predicate (lambda (obj) (string=? "woo" (ref obj 'woo)))))))) (test* "kahua-test-sub w/ keys" '(4 5) (sort (with-clean-db (db *dbname*) (map kahua-persistent-id (make-kahua-collection <kahua-test-sub> :keys '("wooboo" "wooobooo")))))) ;; This tests key-cache table initialization protocol ;; 永続コレクションの作成時に、in-memoryデータベースのインデックスハッシュが ;; 正しくセットアップされることを確認する。 (test* "kahua-test-sub" '((<kahua-test-sub> . "wooboo") (<kahua-test-sub> . "wooobooo")) (with-clean-db (db *dbname*) (make-kahua-collection <kahua-test-sub>) (sort (hash-table-keys (with-module kahua.persistence (key-cache-of db))) (lambda (a b) (string<? (cdr a) (cdr b)))))) ;; <kahua-test>と,そのsubclassである<kahua-test-sub>両者ともの ;; 永続インスタンスのコレクションを,<kahua-test>に対する ;; make-kahua-collectionを用いて作成できることを確認する. (test* "kahua-test-subclasses" '((1 . <kahua-test>) (2 . <kahua-test>) (4 . <kahua-test-sub>) (5 . <kahua-test-sub>)) (sort (with-clean-db (db *dbname*) (map (lambda (i) (cons (kahua-persistent-id i) (class-name (class-of i)))) (make-kahua-collection <kahua-test> :subclasses #t))) (lambda (a b) (< (car a) (car b))))) (define-class <hogehoge> (<kahua-persistent-base>) ((a :allocation :persistent :init-keyword :a))) (test* "make-kahua-collection / floating instance" 1 (with-clean-db (db *dbname*) (make <hogehoge> :a 'a) (size-of (make-kahua-collection <hogehoge>)))) (test* "make-kahua-collection / db instance" 1 (with-clean-db (db *dbname*) (size-of (make-kahua-collection <hogehoge>)))) ;;---------------------------------------------------------- ;; メタ情報履歴に関するテスト:永続クラスの変更をオブジェクトマネージャ ;; が認識し、世代番号を自動的に付与して管理していることを確認する。 (test-section "metainfo history") ;; Tests source-id change ;; スロット定義を変えずにsource-idだけを変えた永続クラスを再定義し、 ;; 永続クラスの世代番号が変化しないこと、変更したsource-idから世代番号への ;; マッピングが正しく設定されていることを確認する。 (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") ;; this shadows parent's quock (quock :allocation :persistent :init-keyword :quock :init-value #f)) :source-id "Rev 4") (test* "generation with source-id change" '("1B" 0 0 (0)) (with-clean-db (db *dbname*) (let1 ins (make <kahua-test-sub> :woo "1" :quick 'q1 :muick 'm1 :quock 'o1) (list (key-of ins) (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation) (assoc-ref (ref (ref <kahua-test-sub> 'metainfo) 'source-id-map) "Rev 4"))))) ;; さらに、Source-idを戻した永続クラスを再定義し、永続スロット以外の ;; 定義変更では永続クラスの世代番号が変化しないこと、およびSource-idから ;; 世代番号へのマッピングに齟齬がないことを確認する。 (define <kahua-test-sub-save> <kahua-test-sub>) (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") (bar :init-keyword :bar :init-value #f) ;; this shadows parent's quock (quock :allocation :persistent :init-keyword :quock :init-value #f)) :source-id "Rev 3") (test* "generation with source-id change (revert source-id)" '("2B" 0 0 (0)) (with-clean-db (db *dbname*) (let1 ins (make <kahua-test-sub> :woo "2") (list (key-of ins) (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation) (assoc-ref (ref (ref <kahua-test-sub> 'metainfo) 'source-id-map) "Rev 3"))))) ;; Source-idを保ったまま永続クラスのスロット定義を変更し、永続クラスの ;; 世代番号が変更されること、および当該source-idからの世代番号へのマップが ;; 複数世代に設定されることを確認する。 (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") (bar :allocation :persistent :init-keyword :bar :init-value #f) ;; this shadows parent's quock (quock :allocation :persistent :init-keyword :quock :init-value #f)) :source-id "Rev 3") (test* "generation with source-id change (update)" '(1 1 (1 0)) (with-clean-db (db *dbname*) (make <kahua-test-sub> :woo "3" :quick 'q3 :muick 'm3 :quock 'o3 :bar 'b3) (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation) (assoc-ref (ref (ref <kahua-test-sub> 'metainfo) 'source-id-map) "Rev 3")))) ;; 上記の定義を保ったまま永続クラスのsource-idを変更し、source-idから ;; 世代番号へのmany-to-manyのマッピングが正しく管理されていることを ;; 確認する。 (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") (bar :allocation :persistent :init-keyword :bar :init-value #f) ;; this shadows parent's quock (quock :allocation :persistent :init-keyword :quock :init-value #f)) :source-id "Rev 4") (test* "generation with source-id change (change source-id)" '(1 1 (1 0)) (with-clean-db (db *dbname*) (make <kahua-test-sub> :woo "4" :quock 'o4) (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation) (assoc-ref (ref (ref <kahua-test-sub> 'metainfo) 'source-id-map) "Rev 4")))) ;; 親の永続クラスを再定義することによって<kahua-test-sub>の自動再定義を ;; トリガし、その変更がデータベースのメタ情報履歴にも反映されることを ;; 確認する。 ;; slot change: drop muick. (define-class <kahua-test> (<kahua-persistent-base>) ((quick :allocation :persistent :init-keyword :quick :init-value 'i) ) :source-id "Rev 3") (test* "generation with source-id change (change parent)" '(2 2 (2 1 0)) (with-clean-db (db *dbname*) (make-kahua-collection <kahua-test-sub>) (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation) (assoc-ref (ref (ref <kahua-test-sub> 'metainfo) 'source-id-map) "Rev 4")))) ;; 次のテストのために、もう一世代変更しておく。 ;; (親クラスで削除されたスロットmuickを子クラスで復活) (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") (bee :allocation :persistent :init-keyword :boo :init-value 'bee) (muick :allocation :persistent :init-keyword :muick :init-value #f)) :source-id "Rev 5") (test* "generation with source-id change (change source-id again)" '(3 3 (3)) (with-clean-db (db *dbname*) (make <kahua-test-sub> :woo "5") (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation) (assoc-ref (ref (ref <kahua-test-sub> 'metainfo) 'source-id-map) "Rev 5")))) ;;---------------------------------------------------------- ;; インスタンスの世代間の変更に関するテスト:異なる世代の永続クラスで ;; 作成されたインスタンスにアクセスする際に、世代間の自動変換が行われる ;; ことを確認。以下のコメントでは、<kahua-test-sub>[n]で世代nの ;; <kahua-test-sub>クラスであることを表記する。 (test-section "instance translation") ;; テスト開始前に、現在の永続ストレージの内容を確認しておく。 ;; 永続クラス<kahua-test-sub>の変遷は以下の通りである。 ;; (世代[4]は以下のテスト中に定義される) ;; ;; generation [0] [1] [2] [3] [4] ;; ---------------------------------------------------------------- ;; p-slots quick quick quick quick ;; muick muick muick ;; woo woo woo woo woo ;; boo boo boo boo boo ;; quock quock quock quock ;; bar bar bar ;; bee bee ;; ;; source-id "Rev 3" "Rev 3" "Rev 4" "Rev 5" "Rev 6" ;; "Rev 4" "Rev 4" ;; ------------------------------------------------------- ;; ;; 現在の永続クラスの世代 ;; in-memory class: <kahua-test-sub>[3] ;; in-db class: <kahua-test-sub>[3] ;; 現在の永続インスタンスのin-dbの世代 ;; "wooboo" [0] ;; "woobooo" [0] ;; "1B" [0] ;; "2B" [0] ;; "3B" [1] ;; "4B" [1] ;; "5B" [3] ;; まず、<kahua-test-sub>[0]で作成された永続インスタンスを読み出し、 ;; それが<kahua-test-sub>[3]の構成にアップデートされていることを確認する。 (test* "translation [0]->[3]" '(:slots ((quick . q1) (muick . m1) (woo . "1") (boo . "B") (bee . beebee)) :hidden ((quock . o1)) :instance-generation 0) (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <kahua-test-sub> "1B") (set! (ref obj 'bee) 'beebee) (list :slots (map (lambda (s) (cons s (ref obj s))) '(quick muick woo boo bee)) :hidden (ref obj '%hidden-slot-values) :instance-generation (ref obj '%persistent-generation))))) ;; 一旦 <kahua-test-sub> の定義を世代[2]に戻し、インスタンス"1B"に ;; アクセス。世代[3]で削除されたスロットquockの値が復活していることを ;; 確認する。 (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") (bar :allocation :persistent :init-keyword :bar :init-value #f) ;; this shadows parent's quock (quock :allocation :persistent :init-keyword :quock :init-value #f)) :source-id "Rev 4") (test* "translation [3]->[2]" '(:class-generations (2 3) :slots ((quick . q1) (woo . "1") (boo . "B") (quock . o1) (bar . #t)) :hidden ((bee . beebee) (muick . m1)) :instance-generation 3) (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <kahua-test-sub> "1B") (set! (ref obj 'bar) #t) (list :class-generations (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation)) :slots (map (lambda (s) (cons s (ref obj s))) '(quick woo boo quock bar)) :hidden (ref obj '%hidden-slot-values) :instance-generation (ref obj '%persistent-generation))))) ;; 世代[1]のインスタンス"3B"にもアクセスし、それが世代[2]にアップデート ;; されることを確認する。 (test* "translation [1]->[2]" '(:class-generations (2 3) :slots ((quick . q3) (woo . "3") (boo . "B") (quock . o3) (bar . b3)) :instance-generation 1) (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <kahua-test-sub> "3B") (touch-kahua-instance! obj) (list :class-generations (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation)) :slots (map (lambda (s) (cons s (ref obj s))) '(quick woo boo quock bar)) :instance-generation (ref obj '%persistent-generation))))) ;; 再び<kahua-test-sub>の定義を世代[3]に戻し、インスタンス"1B", "3B"に ;; それぞれアクセスする。"1B"を世代[2]に戻した際に消えたスロット(bee)、 ;; 及び、"3B"を世代[2]に移行した際に消えたスロット (muick) が復活している ;; ことを確認する。また、各永続インスタンスの世代は最も進んだ世代のまま ;; (すなわち、"1B"では[3], "3B"では[2])であることを確認する。 (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") (bee :allocation :persistent :init-keyword :boo :init-value 'bee) (muick :allocation :persistent :init-keyword :muick :init-value #f)) :source-id "Rev 5") (test* "translation [2]->[3]" '(:class-generations (3 3) :slots (((quick . q1) (woo . "1") (boo . "B") (muick . m1) (bee . beebee)) ((quick . q3) (woo . "3") (boo . "B") (muick . m3) (bee . bee))) :instance-generation (3 2)) (with-clean-db (db *dbname*) (let1 objs (list (find-kahua-instance <kahua-test-sub> "1B") (find-kahua-instance <kahua-test-sub> "3B")) (for-each touch-kahua-instance! objs) (list :class-generations (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation)) :slots (map (lambda (obj) (map (lambda (s) (cons s (ref obj s))) '(quick woo boo muick bee))) objs) :instance-generation (map (cut ref <> '%persistent-generation) objs))))) ;; この段階での各インスタンスのin-dbの世代は次のようになっている。 ;; "wooboo" [0] ;; "wooobooo" [0] ;; "1B" [3] ;; "2B" [0] ;; "3B" [3] ;; "4B" [1] ;; "5B" [3] ;; 今度は<kahua-test-sub>の定義を世代[0]まで戻す。世代[0]および[3]の ;; 永続インスタンス複数を読み出し、全てがin-memoryでは世代[0]の ;; インスタンスになっていることを確認する。 (define-class <kahua-test> (<kahua-persistent-base>) ((quick :allocation :persistent :init-keyword :quick :init-value 'i) (quack :init-keyword :quack :init-value 'a) (muick :allocation :persistent :init-keyword :muick :init-value 'm) (quock :allocation :virtual :slot-ref (lambda (o) (ref o 'quick)) :slot-set! (lambda (o v) #f)) ) :source-id "Rev 2") (define-class <kahua-test-sub> (<kahua-test>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") ;; this shadows parent's quock (quock :allocation :persistent :init-keyword :quock :init-value #f)) :source-id "Rev 3") (test* "translation [0]->[0]" '(:class-generations (0 3) :slots (((woo . "woo") (boo . "boo") (muick . m) (quock . "quock")) ((woo . "wooo") (boo . "booo") (muick . m) (quock . Q))) :instance-generation (0 0)) (with-clean-db (db *dbname*) (let1 objs (list (find-kahua-instance <kahua-test-sub> "wooboo") (find-kahua-instance <kahua-test-sub> "wooobooo")) (set! (ref (cadr objs) 'quock) 'Q) (list :class-generations (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation)) :slots (map (lambda (obj) (map (lambda (s) (cons s (ref obj s))) '(woo boo muick quock))) objs) :instance-generation (map (cut ref <> '%persistent-generation) objs))))) (test* "translation [3]->[0]" '(:slots (((woo . "1") (boo . "B") (muick . m1) (quock . o1)) ((woo . "3") (boo . "B") (muick . m3) (quock . o3)) ((woo . "5") (boo . "B") (muick . #f) (quock . QQ))) :instance-generation (3 3 3)) (with-clean-db (db *dbname*) (let1 objs (list (find-kahua-instance <kahua-test-sub> "1B") (find-kahua-instance <kahua-test-sub> "3B") (find-kahua-instance <kahua-test-sub> "5B")) (set! (ref (caddr objs) 'quock) 'QQ) (list :slots (map (lambda (obj) (map (lambda (s) (cons s (ref obj s))) '(woo boo muick quock))) objs) :instance-generation (map (cut ref <> '%persistent-generation) objs))))) ;; 次いで、<kahua-test-sub>を再定義する。今度は<kahua-test>を ;; 継承しない。この定義が世代[4]となることを確認する。また、 ;; 各世代の永続インスタンスを読み込み、それらが新しい世代に ;; アップデートされていること、世代間のtranslationで消えたスロット ;; の値が失われていないこと、を確認する。 (define-class <kahua-test-sub> (<kahua-persistent-base>) ((woo :allocation :persistent :init-keyword :woo :init-value "W") (boo :allocation :persistent :init-keyword :boo :init-value "B") (quock :allocation :persistent :init-keyword :quock :init-value #f) (bar :allocation :persistent :init-keyword :bar :init-value #f) (bee :allocation :persistent :init-keyword :boo :init-value 'bee) ) :source-id "Rev 6") (test* "translation [0]->[4]" '(:class-generations (4 4) :slots (((woo . "woo") (boo . "boo") (quock . "quock") (bar . #f) (bee . bee)) ((woo . "wooo") (boo . "booo") (quock . Q) (bar . wooobooo) (bee . bee)) ((woo . "2") (boo . "B") (quock . #f) (bar . b2) (bee . bee))) :instance-generation (0 0 0)) (with-clean-db (db *dbname*) (let1 objs (list (find-kahua-instance <kahua-test-sub> "wooboo") (find-kahua-instance <kahua-test-sub> "wooobooo") (find-kahua-instance <kahua-test-sub> "2B")) (set! (ref (cadr objs) 'bar) 'wooobooo) (set! (ref (caddr objs) 'bar) 'b2) (list :class-generations (list (ref <kahua-test-sub> 'generation) (ref <kahua-test-sub> 'persistent-generation)) :slots (map (lambda (obj) (map (lambda (s) (cons s (ref obj s))) '(woo boo quock bar bee))) objs) :instance-generation (map (cut ref <> '%persistent-generation) objs))))) (test* "translation [1]->[4]" '(:slots ((woo . "4") (boo . "B") (quock . o4) (bar . b4) (bee . bee)) :instance-generation 1) (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <kahua-test-sub> "4B") (set! (ref obj 'bar) 'b4) (list :slots (map (lambda (s) (cons s (ref obj s))) '(woo boo quock bar bee)) :instance-generation (ref obj '%persistent-generation))))) (test* "translation [3]->[4]" '(:slots (((woo . "1") (boo . "B") (quock . o1) (bar . #t) (bee . beebee)) ((woo . "3") (boo . "B") (quock . o3) (bar . b3) (bee . bee)) ((woo . "5") (boo . "B") (quock . QQ) (bar . #f) (bee . bee))) :instance-generation (3 3 3)) (with-clean-db (db *dbname*) (let1 objs (list (find-kahua-instance <kahua-test-sub> "1B") (find-kahua-instance <kahua-test-sub> "3B") (find-kahua-instance <kahua-test-sub> "5B")) (for-each touch-kahua-instance! objs) (list :slots (map (lambda (obj) (map (lambda (s) (cons s (ref obj s))) '(woo boo quock bar bee))) objs) :instance-generation (map (cut ref <> '%persistent-generation) objs))))) ;; 上でアップデートした永続インスタンスのうち、変更を受けたか ;; touch-kahua-instance! で「触られた」もののみ、永続インスタンスの ;; 世代が更新されていることを確認する。 (test* "translation (instances' persistent generations)" '(("1B" . 4) ("2B" . 4) ("3B" . 4) ("4B" . 4) ("5B" . 4) ("wooboo" . 0) ("wooobooo" . 4)) (with-clean-db (db *dbname*) (sort (map (lambda (obj) (cons (key-of obj) (ref obj '%persistent-generation))) (make-kahua-collection <kahua-test-sub>)) (lambda (a b) (string<? (car a) (car b)))))) ;;---------------------------------------------------------- ;; トランザクション管理のテスト (test-section "transaction / default(read-only, no-sync)") (define-class <transaction-test-1> (<kahua-persistent-base>) ((a :init-value 0 :init-keyword :a :allocation :persistent))) (define-method key-of ((self <transaction-test-1>)) "key") (test "ref out of transaction" 1 (lambda () (let1 object (with-clean-db (db *dbname*) (make <transaction-test-1> :a 1)) (ref object 'a)))) (test "write in other transaction" #t (lambda () (with-clean-db (db *dbname*) (let1 object (find-kahua-instance <transaction-test-1> "key") (set! (ref object 'a) 2))) #t)) (test "check (write in other transaction" 2 (lambda () (with-clean-db (db *dbname*) (let1 object (find-kahua-instance <transaction-test-1> "key") (ref object 'a))))) (test "set! out of transaction" *test-error* (lambda () (let1 object (with-clean-db (db *dbname*) (make <transaction-test-1> :a 1)) (set! (ref object 'a) 1) #t))) (test-section "transaction / access denied") (define-class <transaction-test-2> (<kahua-persistent-base>) ((a :init-value 0 :init-keyword :a :allocation :persistent :out-of-transaction :denied))) (test "ref out of transaction" *test-error* (lambda () (let1 object (with-clean-db (db *dbname*) (make <transaction-test-2> :a 0)) (ref object 'a)))) (test "ref in other transaction" 1 (lambda () (let1 object (with-clean-db (db *dbname*) (make <transaction-test-2> :a 1)) (with-clean-db (db *dbname*) (ref object 'a))))) (test "set! out of transaction" *test-error* (lambda () (let1 object (with-clean-db (db *dbname*) (make <transaction-test-2> :a 0)) (set! (ref object 'a) 1)))) (test-section "transaction / read-only auto-sync") (define-class <transaction-test-3> (<kahua-persistent-base>) ((key :init-value #f :init-keyword :key :allocation :persistent) (a :init-value 0 :init-keyword :a :allocation :persistent)) :read-syncer :auto) (define-method key-of ((self <transaction-test-3>)) (ref self 'key)) (define (geto key) (with-clean-db (db *dbname*) (find-kahua-instance <transaction-test-3> key))) (test "ref out of transaction" 0 (lambda () (let1 object (with-clean-db (db *dbname*) (make <transaction-test-3> :key "0" :a 0)) (ref object 'a)))) (define (other-transaction num) (with-db (db *dbname*) (let1 object (geto "0") (set! (ref object 'a) num))) (sys-exit 0)) (test "write in other transaction" 1 (lambda () (let1 object (geto "0") (let1 pid (sys-fork) (if (= pid 0) (other-transaction 1) (begin (sys-waitpid pid) (with-db (db *dbname*) (ref object 'a)))))))) (test "overwrite object" 5 (lambda () (let1 object (geto "0") (let1 pid (sys-fork) (if (= pid 0) (other-transaction 2) (begin (sys-waitpid pid) (with-db (db *dbname*) (set! (ref object 'a) 5)) (with-db (db *dbname*) (ref object 'a)))))))) ; (test-section "transaction / read/write auto-sync") ; (define-class <transaction-test-4> (<kahua-persistent-base>) ; ((a :init-value 0 :init-keyword :a :allocation :persistent ; :out-of-transaction :read/write)) ; :read-syncer :auto ; :write-syncer :auto) ; (define-method key-of ((self <transaction-test-4>)) ; "key") ; (define object #f) ; (test* "make" #t ; (with-db (db *dbname*) ; (set! object (make <transaction-test-4> :a 0)) ; #t)) ; (test "write out of transaction" 1 ; (lambda () (set! (ref object 'a) 1) 1)) ; ;; トランザクション開始時にon-memory cacheがdbに書き込まれ ; ;; ることを確認する。 ; (test* "read in other transaction (auto synched: 1)" 1 ; (with-db (db *dbname*) ; (ref (find-kahua-instance <transaction-test-4> "key") 'a))) ; ;; 前トランザクションで書き込まれたデータを別トランザクション ; ;; にて読み出せることを確認する。 ; (test* "read in other transaction (auto synched: 2)" 1 ; (with-db (db *dbname*) (ref object 'a))) ;;---------------------------------------------------------- ;; unboundなスロットのテスト (test-section "unbound slot") (define-class <unbound-slot-class> (<kahua-persistent-base>) ((normal :allocation :persistent :init-value 'val) (unbound :allocation :persistent))) (define-method key-of ((self <unbound-slot-class>)) (x->string (ref self 'normal))) (test* "make unbound slot instance" '(val #f) (with-clean-db (db *dbname*) (let1 obj (make <unbound-slot-class>) (list (ref obj 'normal) (slot-bound? obj 'unbound) )))) (test* "check unbound slot" '(val #f) (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <unbound-slot-class> "val") (list (ref obj 'normal) (slot-bound? obj 'unbound) )))) ;;---------------------------------------------------------- ;; 初期化メソッドinitializeとpersistent-initialize methodのチェック (test-section "initialize and persistent-initialize method") (define-class <init-A> (<kahua-persistent-base>) ((base1 :allocation :persistent :init-value 0) (base2 :allocation :persistent :init-value 0) (key :init-value "a" :accessor key-of))) (define-method persistent-initialize ((obj <init-A>) initargs) (update! (ref obj 'base1) (cut + <> 1))) (define-method initialize ((obj <init-A>) initargs) (next-method) (update! (ref obj 'base2) (cut + <> 1))) (test* "make first instance" '(1 1) (with-clean-db (db *dbname*) (let1 obj (make <init-A>) (list (ref obj 'base1) (ref obj 'base2))))) (test* "find instance" '(1 2) (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <init-A> "a") (list (ref obj 'base1) (ref obj 'base2))))) ;;---------------------------------------------------------- ;; 永続クラス再定義のチェック (test-section "persistent class redefine") (define-class <redefine-A> (<kahua-persistent-base>) ((base :allocation :persistent :init-value 0) (key :init-value "a" :accessor key-of))) (define-class <redefine-B> (<kahua-persistent-base>) ((base :allocation :persistent :init-value 1) (key :init-value "b" :accessor key-of))) (define *id* #f) (define *id2* #f) (test* "make first instance(1)" 0 (with-db (db *dbname*) (let1 obj (make <redefine-A>) (set! *id* (kahua-persistent-id obj)) (ref obj 'base)))) (redefine-class! <redefine-A> <redefine-B>) (test* "redefine instance(1)" '(#f 0) (with-db (db *dbname*) (let* ((obj (find-kahua-instance <redefine-A> "a")) (base (ref obj 'base))) ; trigger instance update. (set! *id2* (kahua-persistent-id obj)) (list (eq? *id* (kahua-persistent-id obj)) base)))) (test* "find redefined instance(1)" '(#t 0) (with-clean-db (db *dbname*) (let1 obj (find-kahua-instance <redefine-B> "a") (list (eq? *id2* (kahua-persistent-id obj)) (ref obj 'base))))) (define-class <redefine-C> (<kahua-persistent-base>) ((base :allocation :persistent :init-value 0) (key :init-value "c" :accessor key-of))) (test* "make first instance(2)" 0 (with-db (db *dbname*) (let1 obj (make <redefine-C>) (set! *id* (kahua-persistent-id obj)) (ref obj 'base)))) (define-class <redefine-C> (<kahua-persistent-base>) ((base :allocation :persistent :init-value 1) (base2 :allocation :persistent :init-value 10) (key :init-value "c" :accessor key-of))) (test* "find redefined instance(2)" '(#t 0 10) (with-db (db *dbname*) (let1 obj (find-kahua-instance <redefine-C> "c") (list (eq? *id* (kahua-persistent-id obj)) (ref obj 'base) (ref obj 'base2))))) ;;---------------------------------------------------------- ;; 永続クラスと他のメタクラスを同時に使うチェック ;; 継承順序もチェック (test-section "useing other metaclass") (use gauche.mop.validator) (define-class <valid-A> (<kahua-persistent-base> <validator-mixin>) ((number :allocation :persistent :init-value "0" :validator (lambda (obj value) (if (not (string? value)) value (string->number value)))))) (define-class <valid-B> (<validator-mixin> <kahua-persistent-base>) ((string :allocation :persistent :init-value "0" :validator (lambda (obj value) (if (kahua-wrapper? value) value (x->string value)))))) (define-method key-of ((obj <valid-A>)) "valid-a") (define-method key-of ((obj <valid-B>)) "valid-b") (test* "make mixin instance" '(10 "(a b c)") (with-clean-db (db *dbname*) (let ((a-obj (make <valid-A>)) (b-obj (make <valid-B>))) (slot-set! a-obj 'number "10") (slot-set! b-obj 'string '(a b c)) (list (ref a-obj 'number) (ref b-obj 'string))))) (test* "find mixin instance" '(10 "(a b c)") (with-clean-db (db *dbname*) (let ((a-obj (find-kahua-instance <valid-A> "valid-a")) (b-obj (find-kahua-instance <valid-B> "valid-b"))) (list (ref a-obj 'number) (ref b-obj 'string))))) (test-section "big date") (define-class <big> (<kahua-persistent-base>) ((a :allocation :persistent))) (define-method key-of ((obj <big>)) "big") (test* "make big instance" 100000 (with-clean-db (db *dbname*) (let ((obj (make <big>))) (slot-set! obj 'a (make-string 100000 #\a)) (string-length (ref obj 'a))))) (test* "make big instance" 100000 (with-clean-db (db *dbname*) (let ((obj (find-kahua-instance <big> "big"))) (string-length (ref obj 'a))))) ;;---------------------------------------------------------- ;; オブジェクトの削除 (test-section "object deletion") ;; Fist: before commit. (define *key* #f) (with-clean-db (db *dbname*) (let* ((obj (car (map identity (make-kahua-collection <hogehoge>)))) (key (key-of obj))) (test* "before remove-kahua-instance" #f (removed? obj) eq?) (test* "remove-kahua-instance" (undefined) (remove-kahua-instance obj) eq?) (test* "after remove-kahua-instance" #t (removed? obj) eq?) (test* "find-kahua-instance" #f (find-kahua-instance <hogehoge> key) eq?) (test* "find-kahua-instance w/ #t" #t (and-let* ((o (find-kahua-instance <hogehoge> key #t))) (removed? o)) eq?) (test* "make-kahua-collection" '() (map identity (make-kahua-collection <hogehoge>)) eq?) (let1 l (map identity (make-kahua-collection <hogehoge> :include-removed-object? #t)) (test* "make-kahua-collection w/ :include-removed-object?" 1 (length l) =) (test* "it\'s removed?" #t (removed? (car l)) eq?)) (set! *key* key) )) ;; Second: after commit; (with-clean-db (db *dbname*) (let1 key *key* (test* "find-kahua-instance" #f (find-kahua-instance <hogehoge> key) eq?) (test* "find-kahua-instance w/ #t" #t (and-let* ((o (find-kahua-instance <hogehoge> key #t))) (removed? o)) eq?) (test* "make-kahua-collection" '() (map identity (make-kahua-collection <hogehoge>)) eq?) (let1 l (map identity (make-kahua-collection <hogehoge> :include-removed-object? #t)) (test* "make-kahua-collection w/ :include-removed-object?" 1 (length l) =) (test* "it\'s removed?" #t (removed? (car l)) eq?) ))) ;; Third: new object and remove it immediately (with-clean-db (db *dbname*) (let* ((obj (make <hogehoge> :a 'aa)) (key (key-of obj))) (test* "before remove-kahua-instance" #f (removed? obj) eq?) (test* "remove-kahua-instance" (undefined) (remove-kahua-instance obj) eq?) (test* "after remove-kahua-instance" #t (removed? obj) eq?) (test* "find-kahua-instance" #f (find-kahua-instance <hogehoge> key) eq?) (test* "find-kahua-instance w/ #t" #t (and-let* ((o (find-kahua-instance <hogehoge> key #t))) (removed? o)) eq?) (test* "make-kahua-collection" '() (map identity (make-kahua-collection <hogehoge>)) eq?) (let1 l (map identity (make-kahua-collection <hogehoge> :include-removed-object? #t)) (test* "make-kahua-collection w/ :include-removed-object?" 2 (length l) =)) (kahua-db-rollback db) (let1 l (map identity (make-kahua-collection <hogehoge> :include-removed-object? #t)) (test* "make-kahua-collection w/ :include-removed-object?" 1 (length l) =)) )) ;; Forth: reference to other objects (with-clean-db (db *dbname*) (let* ((l (map identity (make-kahua-collection <kahua-test>))) (obj (car l)) (key (key-of obj))) (test* "before remove-kahua-instance" #f (removed? (ref obj 'quick)) eq?) (test* "length of kahua-collection" 2 (length l) =) (test* "remove-kahua-instance" (undefined) (remove-kahua-instance (ref obj 'quick)) eq?) (test* "after remove-kahua-instance" #f (ref obj 'quick) eq?) (test* "length of kahua-collection" 1 (length (map identity (make-kahua-collection <kahua-test>))) =) )) (with-clean-db (db *dbname*) (let* ((l (map identity (make-kahua-collection <kahua-test>))) (obj (car l)) (key (key-of obj))) (test* "after remove-kahua-instance" #f (ref obj 'quick) eq?) (test* "length of kahua-collection" 1 (length (map identity (make-kahua-collection <kahua-test>))) =) )) (test-end)
true
25d0128a10e9ce296c35136c682b492e177f47e5
fae4190f90ada065bc9e5fe64aab0549d4d4638a
/typed-scheme-lti/optimize/csu660.ss
981ec813d5fa2e5b08fab17694948ec6ae033fcd
[]
no_license
ilya-klyuchnikov/old-typed-racket
f161481661a2ed5cfc60e268f5fcede728d22488
fa7c1807231f447ff37497e89b25dcd7a9592f64
refs/heads/master
2021-12-08T04:19:59.894779
2008-04-13T10:54:34
2008-04-13T10:54:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,978
ss
csu660.ss
(module csu660 mzscheme (require (lib "list.ss") (lib "etc.ss") (lib "trace.ss") "datatype.ss" "utils.ss") (provide ;; ========================================================================= ;; mzscheme - syntax requirements ; #%app #%datum #%top #;#%module-begin #;#%plain-module-begin #;#%top-interaction ;; make it possible to use additional modules ; require ;; --- basic scheme + - * / < <= = > >= abs acos add1 and andmap angle append arithmetic-shift asin assoc assq assv atan bitwise-and bitwise-ior bitwise-not bitwise-xor boolean? caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr car case cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr cdr ceiling complex? cond cos define denominator eq? equal? eqv? even? exact->inexact exact? exp expt floor format gcd imag-part inexact->exact inexact? integer? lcm length let let* list list* list-ref list-tail log magnitude map max member memq memv min modulo negative? not null null? number->string number? numerator odd? or ormap pair? positive? procedure? quasiquote quote quotient random rational? rationalize real-part real? remainder reverse round sin sqrt string string->number string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-length string-ref string<=? string<? string=? string>=? string>? string? sub1 substring symbol? tan truncate unquote unquote-splicing zero? ;; --- expose normal error error ;; --- advanced HOF apply lambda letrec ;; --- simple side effects display newline print printf write read-line sleep time begin begin0 for-each unless when ;; --- boxes box box? set-box! unbox ;; --- vectors make-vector list->vector vector? vector-ref ;; --- syntax define-syntax syntax-rules ;; --- used at the very end set! ;; ========================================================================= ;; list first second third fourth fifth sixth seventh eighth rest cons? empty empty? foldl foldr last-pair remove remq remv remove* remq* remv* memf assf filter sort ;; ========================================================================= ;; etc true false boolean=? symbol=? identity compose build-list build-vector ;; ========================================================================= ;; trace trace untrace ;; ========================================================================= ;; datatype ;define-type cases ;; ========================================================================= ;; utils (rename *if if) (rename *cons cons) (rename *list? list?) (rename cons cons*) ; make this available for lazy evaluators match number: integer: symbol: string: boolean: string->sexpr make-transformer test test-mode any? list-of sexp-of box-of union-of intersection-of false? true? ))
true
af20a2209442b0b8bfe931bae2099a2fee0e84ed
6488db22a3d849f94d56797297b2469a61ad22bf
/crc32/crc32.scm
d4e0d6ea6e4aa2ce298f68b434e79e59e43619bc
[]
no_license
bazurbat/chicken-eggs
34d8707cecbbd4975a84ed9a0d7addb6e48899da
8e741148d6e0cd67a969513ce2a7fe23241df648
refs/heads/master
2020-05-18T05:06:02.090313
2015-11-18T16:07:12
2015-11-18T16:07:12
22,037,751
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,016
scm
crc32.scm
(module crc32 (crc32 crc32-mid crc32-of-file) (import scheme chicken foreign) #> /* from RFC2083 */ /* Table of CRCs of all 8-bit messages. */ static uint32_t crc_table[256] = { 0UL, 1996959894UL, 3993919788UL, 2567524794UL, 124634137UL, 1886057615UL, 3915621685UL, 2657392035UL, 249268274UL, 2044508324UL, 3772115230UL, 2547177864UL, 162941995UL, 2125561021UL, 3887607047UL, 2428444049UL, 498536548UL, 1789927666UL, 4089016648UL, 2227061214UL, 450548861UL, 1843258603UL, 4107580753UL, 2211677639UL, 325883990UL, 1684777152UL, 4251122042UL, 2321926636UL, 335633487UL, 1661365465UL, 4195302755UL, 2366115317UL, 997073096UL, 1281953886UL, 3579855332UL, 2724688242UL, 1006888145UL, 1258607687UL, 3524101629UL, 2768942443UL, 901097722UL, 1119000684UL, 3686517206UL, 2898065728UL, 853044451UL, 1172266101UL, 3705015759UL, 2882616665UL, 651767980UL, 1373503546UL, 3369554304UL, 3218104598UL, 565507253UL, 1454621731UL, 3485111705UL, 3099436303UL, 671266974UL, 1594198024UL, 3322730930UL, 2970347812UL, 795835527UL, 1483230225UL, 3244367275UL, 3060149565UL, 1994146192UL, 31158534UL, 2563907772UL, 4023717930UL, 1907459465UL, 112637215UL, 2680153253UL, 3904427059UL, 2013776290UL, 251722036UL, 2517215374UL, 3775830040UL, 2137656763UL, 141376813UL, 2439277719UL, 3865271297UL, 1802195444UL, 476864866UL, 2238001368UL, 4066508878UL, 1812370925UL, 453092731UL, 2181625025UL, 4111451223UL, 1706088902UL, 314042704UL, 2344532202UL, 4240017532UL, 1658658271UL, 366619977UL, 2362670323UL, 4224994405UL, 1303535960UL, 984961486UL, 2747007092UL, 3569037538UL, 1256170817UL, 1037604311UL, 2765210733UL, 3554079995UL, 1131014506UL, 879679996UL, 2909243462UL, 3663771856UL, 1141124467UL, 855842277UL, 2852801631UL, 3708648649UL, 1342533948UL, 654459306UL, 3188396048UL, 3373015174UL, 1466479909UL, 544179635UL, 3110523913UL, 3462522015UL, 1591671054UL, 702138776UL, 2966460450UL, 3352799412UL, 1504918807UL, 783551873UL, 3082640443UL, 3233442989UL, 3988292384UL, 2596254646UL, 62317068UL, 1957810842UL, 3939845945UL, 2647816111UL, 81470997UL, 1943803523UL, 3814918930UL, 2489596804UL, 225274430UL, 2053790376UL, 3826175755UL, 2466906013UL, 167816743UL, 2097651377UL, 4027552580UL, 2265490386UL, 503444072UL, 1762050814UL, 4150417245UL, 2154129355UL, 426522225UL, 1852507879UL, 4275313526UL, 2312317920UL, 282753626UL, 1742555852UL, 4189708143UL, 2394877945UL, 397917763UL, 1622183637UL, 3604390888UL, 2714866558UL, 953729732UL, 1340076626UL, 3518719985UL, 2797360999UL, 1068828381UL, 1219638859UL, 3624741850UL, 2936675148UL, 906185462UL, 1090812512UL, 3747672003UL, 2825379669UL, 829329135UL, 1181335161UL, 3412177804UL, 3160834842UL, 628085408UL, 1382605366UL, 3423369109UL, 3138078467UL, 570562233UL, 1426400815UL, 3317316542UL, 2998733608UL, 733239954UL, 1555261956UL, 3268935591UL, 3050360625UL, 752459403UL, 1541320221UL, 2607071920UL, 3965973030UL, 1969922972UL, 40735498UL, 2617837225UL, 3943577151UL, 1913087877UL, 83908371UL, 2512341634UL, 3803740692UL, 2075208622UL, 213261112UL, 2463272603UL, 3855990285UL, 2094854071UL, 198958881UL, 2262029012UL, 4057260610UL, 1759359992UL, 534414190UL, 2176718541UL, 4139329115UL, 1873836001UL, 414664567UL, 2282248934UL, 4279200368UL, 1711684554UL, 285281116UL, 2405801727UL, 4167216745UL, 1634467795UL, 376229701UL, 2685067896UL, 3608007406UL, 1308918612UL, 956543938UL, 2808555105UL, 3495958263UL, 1231636301UL, 1047427035UL, 2932959818UL, 3654703836UL, 1088359270UL, 936918000UL, 2847714899UL, 3736837829UL, 1202900863UL, 817233897UL, 3183342108UL, 3401237130UL, 1404277552UL, 615818150UL, 3134207493UL, 3453421203UL, 1423857449UL, 601450431UL, 3009837614UL, 3294710456UL, 1567103746UL, 711928724UL, 3020668471UL, 3272380065UL, 1510334235UL, 755167117UL}; #if 0 /* Flag: has the table been computed? Initially false. */ static int crc_table_computed = 0; /* Make the table for a fast CRC. */ static void make_crc_table(void) { uint32_t c; int n, k; for (n = 0; n < 256; n++) { c = (uint32_t) n; for (k = 0; k < 8; k++) { if (c & 1) c = 0xedb88320L ^ (c >> 1); else c = c >> 1; } crc_table[n] = c; } crc_table_computed = 1; } #endif /* Update a running CRC with the bytes buf[0..len-1]--the CRC should be initialized to all 1's, and the transmitted value is the 1's complement of the final running CRC (see the crc() routine below). */ static uint32_t update_crc(uint32_t crc, uint8_t *buf, int len) { uint32_t c = crc; int n; /*if (!crc_table_computed) make_crc_table();*/ for (n = 0; n < len; n++) { c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8); } return c; } static uint32_t crc32_of(uint8_t *buf, int len, uint32_t crc) { return update_crc(crc ^ ~0U, buf, len) ^ ~0U; } static uint32_t crc32_at(uint8_t *buf, int start, int end, uint32_t crc) { return crc32_of((buf + start), end - start, crc); } static uint32_t crc32_of_file(const char* name) { FILE* fd = fopen(name, "rb"); if (!fd) { return ~0U; } size_t n; uint8_t buf[4096]; uint32_t crc = 0; while ((n = fread(buf, 1, sizeof(buf), fd)) > 0) { crc = crc32_of(buf,n,crc); } fclose(fd); return crc; } <# (define (crc32 str #!optional (len (##sys#size str)) (crc 0)) ((foreign-lambda unsigned-integer32 "crc32_of" nonnull-scheme-pointer int unsigned-integer32) str len crc)) (define (crc32-mid str #!optional (start 0) (end (##sys#size str)) (crc 0)) ((foreign-lambda unsigned-integer32 "crc32_at" nonnull-scheme-pointer int int unsigned-integer32) str start end crc)) (define (crc32-of-file name) ((foreign-lambda unsigned-integer32 "crc32_of_file" c-string) name)) );module
false
69adce9ae55fd28fa3042a13b4133943d6f0f9b5
fae4190f90ada065bc9e5fe64aab0549d4d4638a
/660-typed-scheme/private/resolve-type.ss
a6735b92acdddebf805123c83515e327cd2225a4
[]
no_license
ilya-klyuchnikov/old-typed-racket
f161481661a2ed5cfc60e268f5fcede728d22488
fa7c1807231f447ff37497e89b25dcd7a9592f64
refs/heads/master
2021-12-08T04:19:59.894779
2008-04-13T10:54:34
2008-04-13T10:54:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,398
ss
resolve-type.ss
#lang scheme/base (require "type-rep.ss" "type-name-env.ss" "tc-utils.ss" "type-utils.ss" mzlib/plt-match mzlib/trace) (provide resolve-name resolve-app needs-resolving? resolve-once) (define (resolve-name t) (match t [(Name: n) (lookup-type-name n)] [_ (int-err "resolve-name: not a name ~a" t)])) (define (resolve-app rator rands stx) (parameterize ([current-orig-stx stx]) (match rator [(Poly: _ _) (instantiate-poly rator rands)] [(Name: _) (resolve-app (resolve-name rator) rands stx)] [(Mu: _ _) (resolve-app (unfold rator) rands)] [(App: r r* s) (resolve-app (resolve-app r r* s) rands)] [_ (tc-error "resolve-app: not a proper operator ~a" rator)]))) (define (needs-resolving? t) (or (Mu? t) (App? t) (Name? t))) (define (resolve-once t) (match t [(Mu: _ _) (unfold t)] [(App: r r* s) (resolve-app r r* s)] [(Name: _) (resolve-name t)])) #| (define (resolve-tc-result tcr) (match tcr [(tc-result: t e1s e2s) (ret (resolve-type t) (map resolve-effect e1s) (map resolve-effect e2s))])) (define (resolve-effect* e) (effect-case resolve-type resolve-effect e)) (define (resolve-type* t) (define (int t) (type-case resolve-type t [#:Name stx (lookup-type-name stx)] [#:Poly #:matcher Poly: names body (make-Poly names (resolve-type body))] [#:Mu #:matcher Mu: name body (make-Mu name (resolve-type body))] [#:App rator rands stx (let ([rator (resolve-type rator)] [rands (map resolve-type rands)]) (unless (Poly? rator) (tc-error/stx stx "Cannot apply non-polymorphic type: ~a, arguments were: ~a" rator rands)) (instantiate-poly rator rands))])) (let loop ([t (int t)]) (if (or (Name? t) (App? t)) (loop (resolve-type t)) t))) (define table (make-hasheq)) (define (resolve-type t) (hash-ref table t (lambda () (let ([v (resolve-type* t)]) (hash-set! table t v) v)))) (define (resolve-effect t) (hash-ref table t (lambda () (let ([v (resolve-effect* t)]) (hash-table-set! table t v) v)))) ;(trace resolve-type) |#
false
52353425b5dc75e6ba41e29ca5f5afada4ba4a56
2020abc33d03e8d0b4f1a7b9f3a0ceaa62c1c423
/melt/page.scm
47ace5798a5c7b30b29055fa33adf9aa95ef5212
[ "BSD-3-Clause" ]
permissive
Memorytaco/Melt
c70fbbd06d1a2063955f2443f548796829834509
4691bdf1b1fca5efaa6778838164280a3e321201
refs/heads/master
2020-04-02T04:33:51.950914
2019-06-17T16:41:28
2019-06-17T16:41:28
154,022,571
0
0
null
2019-06-17T16:41:29
2018-10-21T15:21:53
Scheme
UTF-8
Scheme
false
false
1,027
scm
page.scm
(library (melt page) (export create-page compose create-writer page-list-query) (import (scheme) (melt srfi match) (melt parser sxml) (melt utils) (melt lib sxml) (melt lib file) (melt asset) (melt renderer) (melt structure)) (import type-page) (define (create-page meta cont comt) (make-page meta cont comt)) (define (compose page renderer-list) (let ((generate-sxml (page-cont page))) (generate-sxml page renderer-list))) (define (page-list-query key page-list) (if (null? page-list) #f (if (eq? key (page-meta (car page-list))) (car page-list) (page-list-query key (cdr page-list))))) ;; convert the sxml to html and write it to a file (define (create-writer output-file-name) (lambda (sxml) (let ((port (open-output-file output-file-name 'replace))) (sxml->html sxml port) (close-output-port port)))) )
false
50d3186f3dcf9e2702b84d440a15205571b667de
4f97d3c6dfa30d6a4212165a320c301597a48d6d
/cocoa/Barliman/mk-and-rel-interp/interp-dynamic.scm
7c26fac641d5bf509c8497acbe684ed7eb165491
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
michaelballantyne/Barliman
8c0b1ccbe5141347a304fe57dc9f85085aae9228
7a58671a85b82c05b364b60aa3a372313d71f8ca
refs/heads/master
2022-09-24T05:59:45.760663
2019-11-25T10:32:26
2019-11-25T10:32:26
268,399,942
0
0
MIT
2020-06-01T01:48:21
2020-06-01T01:48:20
null
UTF-8
Scheme
false
false
74
scm
interp-dynamic.scm
;; Dynamically-typed full miniScheme with match ;; TODO -- implement! :)
false
c2200679b33a56674de4568540e94c2b8c3c9ff9
ae8b793a4edd1818c3c8b14a48ba0053ac5d160f
/Applications/constrain.scm
50e6b7f29fe75ab55e9d3e74a753cbe54d8ff611
[]
no_license
experimentsin/telosis
e820d0752f1b20e2913f6f49c0e2a4023f5eda97
4b55140efa8fc732291d251f18f1056dc700442f
refs/heads/master
2020-04-19T08:32:05.037165
2013-07-13T18:59:36
2013-07-13T18:59:36
11,391,770
1
0
null
null
null
null
UTF-8
Scheme
false
false
2,127
scm
constrain.scm
(define-class <constrained-generic> (<generic>) ((pre-condition reader generic-pre-condition initform #f) (post-condition reader generic-post-condition initform #f)) initargs (pre-condition post-condition) metaclass <callable-class>) (define-method (compute-discriminating-function (gf <constrained-generic>) sig lookup methods) (let ((std (call-next-method)) (pre (generic-pre-condition gf)) (post (generic-post-condition gf))) ;; Preserve tail-calls when we can... (cond ((not (or pre post)) std) ((and pre post) (lambda args (unless (apply pre args) (telos-error "pre-condition not met" gf args)) (let ((res (apply std args))) (unless (apply post args) (telos-error "post-condition not met" gf args)) res))) (pre (lambda args (unless (apply pre args) (telos-error "pre-condition not met" gf args)) (apply std args))) (post (lambda args (let ((res (apply std args))) (unless (apply post args) (telos-error "post-condition not met" gf args)) res)))))) ;; e.g. ;; Type: (define-abstract-class <stack> (<object>) ()) (define-generic (empty-stack? (s <stack>))) (define-generic (push! val (s <stack>)) class <constrained-generic> post-condition (lambda (val s) (not (empty-stack? s)))) (define-generic (pop! (s <stack>)) class <constrained-generic> pre-condition (lambda (s) (not (empty-stack? s)))) ;; Imp: (define-class <working-stack> (<stack>) ((values accessor working-stack-values initform '())) constructor (make-working-stack)) (define-method (empty-stack? (s <working-stack>)) (null? (working-stack-values s))) (define-method (push! val (s <working-stack>)) (set-working-stack-values! s (cons val (working-stack-values s))) val) (define-method (pop! (s <working-stack>)) (let ((values (working-stack-values s))) (set-working-stack-values! s (rest values)) (first values))) ;; e.g. (define s (make-working-stack)) (push! 12 s) (pop! s) ;; => 12 ;; (pop! s) ;; would => constraint not met error.
false
cf0283ff6b8262b232db6ee38deaaeb299466118
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/old/main_chez.ss
4625981dbe4a40fed605284f3b4384cf568ec91d
[ "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
27,403
ss
main_chez.ss
;;;; main_chez.ss ;;;; Loads the regiment compiler in Chez Scheme. ;;;; NOTE: This file uses (include ...) rather than (load ...) ;;;; This basically inlines all the code in question into this file at compile time. ;;;; Thus, making a compiled copy of this file makes a compiled copy of the whole system. ;;;; HOWEVER: I broke this rule for things that depend on whether or not SWL is loaded. ;;;; TODO FIXME: I can also make this happen at compile time, via macros. ; ======================================================================= ;; Wipe *all* previous bindings before coming RELOADING the system. ;; [2006.02.28] Without this we get killed by the fact that we redefine "module". ;; This is *only* relevant if repeatedly loading regiment into a single REPL. (when (top-level-bound? 'REGIMENTD) (printf "WIPING previous bindings before reloading Regiment system.\n") (eval '(import scheme))) ;;; Compile-time configuration. ;;; ;;; This runs extra-early, when the file is compiled. <br> ;;; It sets up the location of the Regiment tree. <br> ;;; ;;; The Regiment compiler expects case-sensitive treatment of symbols: ;;; (But hopefully it should work either way, as long as its consistent. (eval-when (compile load eval) ;; We load this at compile time to figure out some of our ;; compilation options: (include "config.ss") ;;; TEMP TEMP TEMP TEMPTOGGLE: ;(compile-profile #t) ;; Note: this also bloats the code size. (case-sensitive #t) ;; For now let's just error if we have no dir: ; (if (not (getenv "REGIMENTD")) ; (error 'regiment "environment variable REGIMENTD was not set")) ;; This is a bit weird, ultimately the global param ;; REGIMENTD is the thing to look at, but we have some ;; issues with the order of evaluation/loading/binding ;; here, so first we bind this: (define-syntax default-regimentd (syntax-rules () [(_) (if (getenv "REGIMENTD") (getenv "REGIMENTD") (current-directory))])) (define default-source-directories (#%list ; (string-append (default-regimentd) "/src/chez") ; (string-append (default-regimentd) "/src/generic") (string-append (default-regimentd) "/src") ;"." ;; Alas this causes some problems currently... )) (source-directories default-source-directories) ;(optimize-level 0) ;0/1/2/3) ;; Currently [2005.10.20] optimize levels result in these times on unit tests: ;; 1: 29046 ms elapsed cpu time, including 9314 ms collecting ;; 2: 29365 ms elapsed cpu time, including 7988 ms collecting ;; 3: 25488 ms elapsed cpu time, including 8571 ms collecting ;; 3 with no debug mode! 13993 ms elapsed cpu time, including 3844 ms collecting ;; This makes our modules work properly in newer versions of Chez: ;; Otherwise we get unorder definitions, which breaks certain Regiment code. (if (top-level-bound? 'internal-defines-as-letrec*) (internal-defines-as-letrec* #t)) (define current_interpreter 'chezscheme) (define-top-level-value 'simulator-batch-mode #f) (define reg:set_opt_lvl! (lambda () (case (REGOPTLVL) [(0) ;; Disable source optimization altogether. (optimize-level 0) (run-cp0 (lambda (cp0 x) x))] [(2) (optimize-level 2)] [(3) (printf "Configuring compiler for full optimize mode. (UNSAFE)\n") ;; This configuration is for running extended simulation-experiments only: ;; REMEMBER to also disable IFDEBUG in constants.ss (define-top-level-value 'simulator-batch-mode #t) (optimize-level 3) (compile-compressed #f) (generate-inspector-information #f) ;; Messing with this didn't seem to help performance. #; (run-cp0 (lambda (cp0 x) (parameterize ([cp0-effort-limit 50000] ;; per-call inline effort, 200 default [cp0-score-limit 500] ;; per-call expansion allowance, 20 default [cp0-outer-unroll-limit 3]) ;; inline recursive? (let ((x (cp0 x))) (parameterize ( (cp0-effort-limit 0) ) (cp0 x))))))] [else (error 'regiment-compiler "bad setting for REGOPTLVL: <~s>" (REGOPTLVL))]))) (reg:set_opt_lvl!) ;; According to $REGOPTLVL ) ;; Trying to set the svn rev when the code is *compiled*: (define-syntax bind-svn-revision (lambda (x) (syntax-case x () [(_) (let () (define (system-to-str str) (let* ([pr (process str)] [in (car pr)] [out (cadr pr)] [id (caddr pr)]) (let ((p (open-output-string))) (let loop ((c (read-char in))) (if (eof-object? c) (begin (close-input-port in) (close-output-port out) (get-output-string p)) (begin (display c p) (loop (read-char in)))))))) (if (eq? (machine-type) 'i3nt) -9999 (and (zero? (system "which svn &> /dev/null")) (parameterize ([current-directory (string-append (default-regimentd) "/src")]) ;(printf"<<<<<<<<<<<READING SVN REV>>>>>>>>>>>>\n") (let ([rev (read (open-input-string (system-to-str "svn info | grep Revision | sed s/Revision://")))]) (with-syntax ([revis (datum->syntax-object #'_ rev)]) #'(define-top-level-value 'svn-revision (let ([x 'revis]) (if (number? x) x #f)))) ) ))))]))) (bind-svn-revision) ;====================================================================== ;;; Setup stuff. ;(include "./config.ss") ;; Need to do this for windows... haven't got a good system yet. (include "config.ss") ;; Set some Chez scheme parameters. (print-graph #t ) (print-gensym #f) ;(print-level 8) (print-level #f) ;20) (print-length #f) ;80) (print-vector-length #t) ;(pretty-maximum-lines 700) (pretty-maximum-lines #f) (pretty-line-length 150) (pretty-standard-indent 0) ;; Storing and then modifying the default break handler. ;; This is just a little hack to let us break "on" a value and then continue. ;; ...<removed>... ;; [2006.08.28] Nixing that hack. It's much better to just have our own inspect function: (define (inspect/continue x) (inspect x) x) ;; Debugging, find out where a spurious inspect is!! (define (debug-inspect x) (warning 'inspect "inspector called! ~s" x) (call/cc #%inspect)) #; (begin (optimize-level 0) (define-top-level-value 'inspect debug-inspect) (define-top-level-value 'inspect/continue debug-inspect)) ;; Because I run from command line, it helps to enter the inspector after an error. ;; First let's backup the existing error-handler: (unless (top-level-bound? 'default-error-handler) (define-top-level-value 'default-error-handler (error-handler))) (define inspector-error-handler (lambda (who msg . args) (call/cc (lambda (k) (parameterize ([error-handler default-error-handler] ;[current-directory (string-append (REGIMENTD) "/src/generic")] ) (fprintf (console-output-port) "~%Error~a: ~a.~%" (if who (format " in ~s" who) "") (parameterize ([print-level 3] [print-length 6]) (apply format msg args))) (when (and (top-level-bound? 'REGIMENT-BATCH-MODE) (top-level-value 'REGIMENT-BATCH-MODE)) (exit 1)) ;; Should only do this if we're running as a script. (fprintf (console-output-port) "Entering debugger to inspect current continuation, type 'q' to exit.\n") ;; [2008.03.30] Also reset the source-directories so Chez can find the code: (source-directories default-source-directories) ;; Set the current directory so that the inspector can find line numbers: (inspect k)))))) (error-handler inspector-error-handler) ;; A Chez hack to see all the source locations in a continuation. (define (continuation->sourcelocs k) (let loop ([depth 0] [ob (inspect/object k)]) (when (> (ob 'depth) 1) (call-with-values (lambda () (ob 'source-path)) (lambda args (when (= (length args) 3) ;; Success (apply printf "~a: File: ~a, line ~a char ~a\n" depth args) ))) (loop (add1 depth) (ob 'link))))) (define k->files continuation->sourcelocs) ;; This forces the output to standard error in spite the Scheme ;; parameters console-output-port and current-output-port. (define stderr (let ((buffer-size 1)) (let ((p (make-output-port 2 (make-string buffer-size)))) (set-port-output-size! p (- buffer-size 1)) p))) ;; This is an (attempted) hack for maintaining clean seperation between repeated loads. ;; ;; [2006.03.27] This doesn't work yet, repeated loads still allocate more memory. ;; Chez garbage collects compiled code, right? ;; Ahh, Chez doesn't collect space used by environments. ;; So I WOULD need that part that tries to wipe all the bindings. (define (wipe) ;; shorthand (define set-difference (lambda (set1 set2) (let loop ([set1 set1] [set2 set2]) (cond ((null? set1) '()) ((memq (car set1) set2) (loop (cdr set1) set2)) (else (cons (car set1) (loop (cdr set1) set2))))))) (time (begin (collect (collect-maximum-generation)) (let ([stats (statistics)]) (printf "Pre-wipe mem usage: ~:d\n" (- (sstats-bytes stats) (sstats-gc-bytes stats)))) (eval '(import scheme)) ;; This is a simple version: (for-each (lambda (s) (when (and (top-level-bound? s) (not (memq s '(wipe ;; Don't kill my little loading mechanism: ;bl2 bln __UTILSDIR __utilsdir )))) ;(printf "Killing ~s\n" s) (set-top-level-value! s #f))) (set-difference (environment-symbols (interaction-environment)) (environment-symbols (scheme-environment)))) (collect (collect-maximum-generation)) (let ([stats (statistics)]) (printf "Post-wipe mem usage: ~:d\n" (- (sstats-bytes stats) (sstats-gc-bytes stats))))))) ;; This wipes bindings and reloads. (define (reload) ;(define main (** (REGIMENTD) "/src/main_chez.ss")) (current-directory (REGIMENTD)) (current-directory "src") ;(wipe) ;(load main) (load "main_chez.ss") ) ;====================================================================== ;;; Print a banner message. ;(inspect (eval '(command-line-arguments))) ;(inspect (command-line)) ;(inspect (command-line-arguments)) (unless #f ;(inspect (member "-quiet" (command-line-arguments))) (fprintf stderr "Regiment: Loading ~a compiler in chezscheme~a...\n" (let ([ws #f] [reg #f]) (IFWAVESCOPE (set! ws #t) (set! reg #t)) (cond [(and ws reg) "ws+reg"] [ws "ws"] [reg "reg"])) (if (top-level-bound? 'regiment-origin) (format " (from ~a)" regiment-origin) "(LOADED VIA UNKNOWN METHOD!?)" ))) ;====================================================================== ;;; Begin loading files. First some setup stuff. (eval-when (compile load eval) (define-top-level-value 'pre-load-directory (current-directory)) (current-directory (string-append (default-regimentd) "/src/chez"))) (include "chez/match.ss") ;; Pattern matcher, dependency. (include "chez/rn-match.ss") ;; My version of the pattern matcher. ;; To completely DISABLE my new prototype matcher, uncomment this: ;; This may be useful for debugging, the iu-matcher gives better source locations. ;; (Note that rn-match increases compile times) (alias rn-match-bak rn-match) (alias rn-match iu-match) ;; TEMPTOGGLE ;; ;; [2007.04.19] Currently, just having rn-match in the type-checker ;; plus the static elaborator bloats the code size a noticable amount. ;; Import the IU matcher globally: (import iu-match) ;(import rn-match) ;; Can't yet use rn-match globally. ;; After this point, everything must use chez:module for native chez modules. ;; 'module' will become my chez/plt portable regiment modules. (eval-when (load eval) (include "chez/regmodule.ss") ;; Common module syntax. (import reg:module) ) ;====================================================================== ;;; Now begin loading Regiment/WaveScript proper. ;; Load this first. Widely visible constants/parameters. (include "chez/chez_constants.ss") ;; A global parameter that is the equivalent of the eponymous ;; environment var. Now that constants.ss is loaded we can set this. <br> ;; This uses the kinder behavior -- try the current directory. ;; (However, that's a bit irrelevent if an error was already signaled above.) (REGIMENTD (default-regimentd)) (if VERBOSE-LOAD (printf " Starting load...\n")) (IF_GRAPHICS (fprintf stderr "(Linking GUI code using SWL.)\n") (fprintf stderr "(No GUI available.)\n")) (flush-output-port stderr) ;====================================================================== ;; [2005.11.16] This is a nasty dependency, but I had to write the "sleep" function in C: ;; This tries to dynamically load the shared object the first time the function is called: (define (sleep t) (IF_GRAPHICS (thread-sleep t) ;; This uses the SWL thread library. (Not real OS threads.) (begin ;(printf "Dynamically loading usleep from shared library...\n")(flush-output-port (current-output-port)) (parameterize ((current-directory (string-append (REGIMENTD) "/src/"))) (if (not (file-exists? (format "build/~a/usleep_libc.so" (machine-type)))) ;; This even resorts to calling make to build the sleep object!! ;; This is kinda silly, and will cause a bunch of text to dump to stdout/err. (system "(cd C; make usleep_libc)")) (if (file-exists? (format "build/~a/usleep_libc.so" (machine-type))) ;(parameterize ((current-directory (format "chez/usleep/~a" (machine-type)))) (load (format "build/~a/usleep_libc.so" (machine-type))) ;; If that build failed and we still don't have it we have to throw an error: (define-top-level-value 'sleep (lambda args (error 'sleep "function not loaded from C shared object file."))))) (sleep t)))) ;; [2007.03.13] Haven't been using this recently, disabling it due to Windows incompatibility: ;; Only make a system call once to sync us with the outside world. ;(define current-time (seconds-since-1970)) ;====================================================================== (alias todo:common:load-source include) (define-syntax (common:load-source x) (syntax-case x () [(_ file) (let () (define (basename pathstr) ;; Everything after the last "#/" (define file (let loop ([ls (reverse! (string->list pathstr))]) (cond [(null? ls) ()] [(eq? (car ls) #\/) ()] [else (cons (car ls) (loop (cdr ls)))]))) (list->string (reverse! (cdr (or (memq #\. file) (cons #\. file)))))) ;; Make sure we put the *real* symbol include in there. ;; Having problems with this for some reason: (with-syntax ([incl (datum->syntax-object #'_ 'include)] [modname (datum->syntax-object #'_ (string->symbol (basename (datum file))))]) #'(begin (incl file) (import modname))) )])) ;;====================================================================================================;; ;;====================================================================================================;; ;;====================================================================================================;; ;; This loads the bulk of the source files. ;; This is a simple, lightweight object system: ;(include "../depends/bos/macros.scm") ;(include "../depends/bos/bos.scm") ;(include "../depends/bos/utilities.scm") (begin (todo:common:load-source "generic/util/reg_macros.ss") (import reg_macros) (todo:common:load-source "generic/util/hash.ss") (import hash) ;; TEMPORARY, used for "hash" function from slib. ;; Including full slib hash tables also... nesed equal?-based hashtabs sometime. (todo:common:load-source "generic/util/slib_hashtab.ss") (import (add-prefix slib_hashtab slib:)) (todo:common:load-source "chez/hashtab.ss") (import hashtab) ;; eq? based. (include "common_loader.ss") ;; [2007.12.28] Not sure what this is being used for: ;(todo:common:load-source "chez/pregexp.ss") (import pregexp_module) ;; For loading regiment source. Depends on desugar-pattern-matching: (todo:common:load-source "generic/compiler_components/source_loader.ss") (import source_loader) (todo:common:load-source "generic/passes/optimizations/smoosh-together.ss") (import smoosh-together) (todo:common:load-source "generic/passes/optimizations/rewrite_opts.ss") (import rewrite_opts) (todo:common:load-source "generic/passes/optimizations/data_reps.ss") (todo:common:load-source "generic/passes/normalize_source/resolve-varrefs.ss") (import resolve-varrefs) (todo:common:load-source "generic/passes/normalize_source/ws-label-mutable.ss") (import ws-label-mutable) (todo:common:load-source "generic/passes/normalize_source/rename-vars.ss") (import rename-vars) (todo:common:load-source "generic/passes/normalize_source/eta-primitives.ss") (import eta-primitives) (todo:common:load-source "generic/passes/normalize_source/desugar-misc.ss") (import desugar-misc) (todo:common:load-source "generic/passes/normalize_source/remove-unquoted-constant.ss") (import remove-unquoted-constant) ;(eval-when (compile eval load) (compile-profile #t)) (todo:common:load-source "generic/passes/static_elaborate/static-elaborate.ss") (import static-elaborate) (todo:common:load-source "generic/passes/normalize_query/reduce-primitives.ss") (import reduce-primitives) (todo:common:load-source "generic/passes/normalize_query/ws-remove-letrec.ss") (import ws-remove-letrec) (todo:common:load-source "generic/passes/static_elaborate/interpret-meta.ss") (import interpret-meta) ;(eval-when (compile eval load) (compile-profile #f)) (todo:common:load-source "generic/passes/static_elaborate/degeneralize-arithmetic.ss") (import degeneralize-arithmetic) (todo:common:load-source "generic/passes/static_elaborate/split-union-types.ss") (import split-union-types) (todo:common:load-source "generic/passes/static_elaborate/verify-elaborated.ss") (import verify-elaborated) (todo:common:load-source "generic/passes/optimizations/merge-iterates.ss") (import merge-iterates) (todo:common:load-source "generic/passes/optimizations/simple-merge-iterates.ss") (import simple-merge-iterates) (todo:common:load-source "generic/passes/wavescope_bkend/purify-iterate.ss") (import purify-iterate) (todo:common:load-source "generic/passes/wavescope_bkend/flatten-iterate-spine.ss") (import flatten-iterate-spine) (todo:common:load-source "generic/passes/wavescope_bkend/anihilate-higher-order.ss") (import anihilate-higher-order) (todo:common:load-source "generic/passes/normalize_query/remove-complex-constant.ss") (import remove-complex-constant) ; pass07_verify-stage2.ss (todo:common:load-source "generic/passes/normalize_query/uncover-free.ss") (import uncover-free) (todo:common:load-source "generic/passes/normalize_query/lift-letrec.ss") (import lift-letrec) (todo:common:load-source "generic/passes/normalize_query/lift-letrec-body.ss") (import lift-letrec-body) (todo:common:load-source "generic/passes/normalize_query/remove-complex-opera.ss") (import remove-complex-opera) ;(eval-when (compile eval load) (compile-profile #t)) (todo:common:load-source "generic/passes/normalize_query/ws-remove-complex-opera.ss") (import ws-remove-complex-opera) ;(eval-when (compile eval load) (compile-profile #f)) (todo:common:load-source "generic/passes/normalize_query/ws-lift-let.ss") (import ws-lift-let) (todo:common:load-source "generic/passes/normalize_query/ws-normalize-context.ss") (import ws-normalize-context) (todo:common:load-source "generic/passes/normalize_query/remove-lazy-letrec.ss") (import remove-lazy-letrec) (todo:common:load-source "generic/passes/normalize_query/verify-core.ss") (import verify-core) (IFWAVESCOPE (begin) (begin (todo:common:load-source "generic/passes/analyze_query/classify-names.ss") (import classify-names) (todo:common:load-source "generic/passes/analyze_query/add-heartbeats.ss") (import add-heartbeats) (todo:common:load-source "generic/passes/analyze_query/add-control-flow.ss") (import add-control-flow) (todo:common:load-source "generic/passes/analyze_query/add-places.ss") (import add-places) (todo:common:load-source "generic/passes/analyze_query/analyze-places.ss") (import analyze-places) (todo:common:load-source "generic/passes/analyze_query/resolve-fold-trees.ss") (import resolve-fold-trees) ;(todo:common:load-source "generic/pass18_add-routing.ss") (todo:common:load-source "generic/passes/deglobalize/deglobalize.ss") (import deglobalize) (todo:common:load-source "generic/passes/deglobalize/deglobalize2.ss") (import deglobalize2) (todo:common:load-source "generic/passes/deglobalize/deglobalize2_tmgen.ss") ;; Uses delazy-bindings: (todo:common:load-source "generic/passes/analyze_query/add-data-flow.ss") (import add-data-flow) ;(todo:common:load-source "generic/pass22_desugar-soc-return.ss") ;; TODO: Merge with pass22, besides this isn't really 26 anyway! (todo:common:load-source "generic/passes/tokmac_bkend/desugar-macros.ss") (import desugar-macros) (todo:common:load-source "generic/passes/tokmac_bkend/find-emittoks.ss") (import find-emittoks) (todo:common:load-source "generic/passes/tokmac_bkend/desugar-gradients.ss") (import desugar-gradients) ;(todo:common:load-source "generic/passes/tokmac_bkend/desugar-gradients_verbose.ss") ;(todo:common:load-source "generic/passes/tokmac_bkend/desugar-gradients_simple.ss") ;(todo:common:load-source "generic/passes/tokmac_bkend/desugar-gradients_ETX.ss") (todo:common:load-source "generic/passes/tokmac_bkend/desugar-let-stored.ss") (import desugar-let-stored) (todo:common:load-source "generic/passes/tokmac_bkend/rename-stored.ss") (import rename-stored) ;(todo:common:load-source "generic/pass24_analyze-calls.ss") ;(todo:common:load-source "generic/pass25_inline.ss") ;(todo:common:load-source "generic/pass26_prune-returns.ss") (todo:common:load-source "generic/passes/tokmac_bkend/cps-tokmac.ss") (import cps-tokmac) (todo:common:load-source "generic/passes/tokmac_bkend/sever-cont-state.ss") (import sever-cont-state) ;; (todo:common:load-source "generic/pass27.2_add-kclosure.ss") (todo:common:load-source "generic/passes/tokmac_bkend/closure-convert.ss") (import closure-convert) (todo:common:load-source "generic/passes/tokmac_bkend/inline-tokens.ss") (import inline-tokens) ;; This is out of use, but not deleted yet: (todo:common:load-source "generic/scrap/pass30_haskellize-tokmac.ss") (todo:common:load-source "generic/passes/nesc_bkend/flatten-tokmac.ss") (import flatten-tokmac) (todo:common:load-source "generic/passes/nesc_bkend/emit-nesc.ss") (import emit-nesc) )) ;; These are miscellaneous small passes used by wavescript: (todo:common:load-source "generic/passes/small-ws-passes.ss") (import small-ws-passes) ;; [2006.08.27] Now for the passes in the WaveScript branch: (todo:common:load-source "generic/passes/wavescope_bkend/reify-certain-types.ss") (import reify-certain-types) ;(eval-when (compile eval load) (compile-profile #t)) (todo:common:load-source "generic/passes/wavescope_bkend/type-annotate-misc.ss") (import type-annotate-misc) ;(eval-when (compile eval load) (compile-profile #f)) (todo:common:load-source "generic/passes/wavescope_bkend/convert-sums-to-tuples.ss") (import convert-sums-to-tuples) (todo:common:load-source "generic/passes/wavescope_bkend/nominalize-types.ss") (import nominalize-types) (todo:common:load-source "generic/passes/wavescope_bkend/emit-c.ss") (import emit-c) (todo:common:load-source "generic/passes/wavescope_bkend/insert-refcounts.ss") (import insert-refcounts) (todo:common:load-source "generic/util/bos_oop.ss") (import bos_oop) (todo:common:load-source "generic/passes/wavescope_bkend/emit-c2.ss") (import emit-c2) (todo:common:load-source "generic/passes/partition-graph.ss") (import partition-graph) (todo:common:load-source "generic/passes/analyze_data_rates/annotate-with-data-rates.ss") (import annotate-with-data-rates) (todo:common:load-source "generic/passes/wavescope_bkend/explicit-stream-wiring.ss") (import explicit-stream-wiring) ;(eval-when (compile eval load) (compile-profile #t)) (todo:common:load-source "generic/passes/ocaml_bkend/shared-emit-ml.ss") ;(import shared-emit-ml) (todo:common:load-source "generic/passes/ocaml_bkend/emit-caml.ss") (import emit-caml) (todo:common:load-source "generic/passes/mlton_bkend/emit-mlton.ss") (import emit-mlton) ;(eval-when (compile eval load) (compile-profile #f)) ;(load "../depends/slib/chez.init") ;(require 'tsort) ;; for the simulator: ;; Basic parallel computation (using engines): ;; [2006.02.28] These were used by simulator_nought, but are not used currently. (IF_GRAPHICS (load "chez/swl_flat_threads.ss") ;; uses swl threads instead (load "chez/flat_threads.ss")) ;; LAME: ;(if (top-level-bound? 'SWL-ACTIVE) (eval '(import flat_threads))) ;; If we're in SWL then load the GRAPHICS portion: ;; Disabled temporarily!: #; (when (top-level-bound? 'SWL-ACTIVE) (load "demo_display.ss") (load "chez/simulator_nought_graphics.ss")) (if VERBOSE-LOAD (printf " Now for main file.\n")) ;;; NOW INCLUDE THE (GENERIC) MAIN FILE: ;=============================================================================== (todo:common:load-source "main.ss") (if VERBOSE-LOAD (printf " Finished init routines in main file..\n")) ;;; TESTING FILES: ;=============================================================================== ;; [2006.04.18] This testing system isn't doing much for us currently ;; other than exercising our static elaborator. ;; TODO: Fold it into the unit tests. ;; ;; Driver depends on 'pass-list being defined. ;; Let's not waste load time on this... it's not used currently. (IFWAVESCOPE (begin) (begin (todo:common:load-source "generic/testing/driver.ss") (game-eval eval) (host-eval (lambda args 'unspecified)) (todo:common:load-source "generic/testing/tests_noclosure.ss") )) (todo:common:load-source "generic/testing/tests.ss") ;; [2006.04.18] This is pretty out of date as well: ;; Load the repl which depends on the whole compiler and simulator. (IFWAVESCOPE (begin) (todo:common:load-source "generic/scrap/repl.ss")) (todo:common:load-source "generic/shortcuts.ss") ) ;(ws-compiler-hooks `([verify-elaborated ,inspect] [insert-refcounts ,inspect])) ;; END COMMON LOADER ;;====================================================================================================;; ;;====================================================================================================;; ;;====================================================================================================;; ;; Open this up so we can read the global counters: (IFWAVESCOPE (begin) (import simulator_alpha_datatypes)) (if VERBOSE-LOAD (printf " Finished loading... \n")) (eval-when (compile load eval) (current-directory (top-level-value 'pre-load-directory))) ;; [2008.02.18] On the way out lets set this to something sane: ;(source-directories '(".")) (source-directories (cons "." (source-directories)))
true
789d07c80a2a6f3ff817df0619ce0ef76905fbd5
358b0f0efbdb9f081245b536c673648abbb6dc41
/well512.scm
9553e6e882c91ca807a5368b53b09bf646c391ac
[ "MIT" ]
permissive
diamond-lizard/srfi-27
edb34a5ab850bfdf342acab61f1b49b87875116a
d54fcd1916ddef175df1d3dda107b149737ce1ca
refs/heads/main
2023-01-13T00:50:41.260636
2020-11-16T17:18:46
2020-11-16T17:18:46
312,747,512
1
0
null
null
null
null
UTF-8
Scheme
false
false
7,311
scm
well512.scm
;;;; well512.scm ;;;; Kon Lovett, Nov '17 (module well512 (import scheme) (import (chicken base)) (;export make-random-source-well512) (import (except scheme <= inexact->exact exact->inexact number?)) (import scheme) (import (chicken base)) (import (chicken foreign)) (import srfi-4 random-source entropy-source (only srfi-27-numbers check-positive-integer random-large-integer random-large-real native-real-precision?)) #> /* ***************************************************************************** */ /* Copyright: Francois Panneton and Pierre L'Ecuyer, University of Montreal */ /* Makoto Matsumoto, Hiroshima University */ /* Notice: This code can be used freely for personal, academic, */ /* or non-commercial purposes. For commercial purposes, */ /* please contact P. L'Ecuyer at: [email protected] */ /* ***************************************************************************** */ #define R 16 typedef struct { unsigned int i; uint32_t *state; /*[R]*/ } WELL512aState; void InitWELLRNG512a( WELL512aState *well ) { well->i = 0; for (int j = 0; j < R; j++) well->state[j] = rand()^(rand()<<16)^(rand()<<31); } double WELLRNG512a( WELL512aState *well ) { # define W 32 # define P 0 # define M1 13 # define M2 9 # define M3 5 # define OFF( o ) ((well->i + (o)) & 0x0000000fU) # define V0 well->state[OFF( 0 )] # define VM1 well->state[OFF( M1 )] # define VM2 well->state[OFF( M2 )] # define VM3 well->state[OFF( M3 )] # define VRm1 well->state[OFF( 15 )] # define VRm2 well->state[OFF( 14 )] # define newV0 well->state[OFF( 15 )] # define newV1 well->state[OFF( 0 )] # define newVRm1 well->state[OFF( 14 )] # define MAT0POS( t, v ) (v^(v>>t)) # define MAT0NEG( t, v ) (v^(v<<(-(t)))) # define MAT3NEG( t, v ) (v<<(-(t))) # define MAT4NEG( t, b, v ) (v^((v<<(-(t))) & b)) # define FACT 2.32830643653869628906e-10 uint32_t z0 = VRm1; uint32_t z1 = MAT0NEG( -16, V0 ) ^ MAT0NEG( -15, VM1 ); uint32_t z2 = MAT0POS( 11, VM2 ); newV1 = z1 ^ z2; newV0 = MAT0NEG( -2, z0 ) ^ MAT0NEG( -18, z1 ) ^ MAT3NEG( -28, z2 ) ^ MAT4NEG(-5, 0xda442d24U, newV1 ); well->i = OFF( 15 ); C_return( ((double) well->state[OFF( 0 )]) * FACT ); # undef FACT # undef V0 # undef VM1 # undef VM2 # undef VM3 # undef VRm1 # undef VRm2 # undef newV0 # undef newV1 # undef newVRm1 # undef MAT0POS # undef MAT0NEG # undef MAT3NEG # undef MAT4NEG # undef OFF # undef W # undef P # undef M1 # undef M2 # undef M3 } //#undef R static void init_state( unsigned int *i, uint32_t *state ) { uint32_t wstate[R]; WELL512aState well; well.state = wstate; InitWELLRNG512a( &well ); *i = well.i; memcpy( state, wstate, sizeof wstate ); } static double uniformf64( unsigned int *i, uint32_t *state ) { WELL512aState well; well.i = *i; well.state = state; double res = WELLRNG512a( well ); *i = well.i; C_return( res ); } static uint32_t randomu32( unsigned int *i, uint32_t *state ) { C_return( (uint32_t) uniformf64( i, state ) ); } <# (define STATE-LENGTH (foreign-value "R" integer32)) (define init_state (foreign-lambda void "init_state" nonnull-u32vector unsigned-integer64)) (define well512-random-integer (foreign-lambda unsigned-integer32 "randomu32" nonnull-u32vector unsigned-integer32)) (define well512-random-real (foreign-lambda double "uniformf64" nonnull-u32vector)) ;;; ;; (define-constant maximum-unsigned-integer32-flonum 4294967295.0) (cond-expand (64bit (define-constant maximum-unsigned-integer32 4294967295) ) ;MAX (else ;32bit (define-constant maximum-unsigned-integer32 1073741823) ) ) ;32bit most-positive-fixnum ;; (define-constant fpMAX maximum-unsigned-integer32-flonum) ;2^32 - 1 (define-constant LOG2-PERIOD 250) (define eMAX (inexact->exact fpMAX)) ;Create a "bignum" if necessary (define-constant INITIAL-SEED maximum-unsigned-integer32) (define INTERNAL-ID 'well512) (define EXTERNAL-ID 'well512) ;; (define (make-state) (make-u32vector STATE-LENGTH)) (define (well512-initial-state) (let ((state (make-state))) (init_state state INITIAL-SEED) state ) ) (define (well512-unpack-state state) (cons EXTERNAL-ID (u32vector->list state)) ) (define (well512-pack-state external-state) (unless (well512-external-state? external-state) (error 'well512-pack-state "malformed state" external-state) ) (let ((state (make-state))) (do ((i 0 (fx+ i 1)) (ss (cdr external-state) (cdr ss)) ) ((null? ss) state) (let ((x (car ss))) (if (and (integer? x) (<= 0 x 4294967295)) (u32vector-set! state i x) (error 'well512-pack-state "illegal value" x) ) ) ) ) ) (define (well512-external-state? obj) (and (pair? obj) (eq? EXTERNAL-ID (car obj)) (fx= (fx+ STATE-LENGTH 1) (length obj)) ) ) (define (well512-randomize-state state entropy-source) (init_state state (exact->inexact (modulo (fpabs (entropy-source-f64-integer entropy-source)) fpMAX))) state ) (define (well512-pseudo-randomize-state i j) (let ((state (make-state))) (init_state state (exact->inexact (+ i j))) state ) ) (define (well512-random-large state n) (random-large-integer well512-random-integer state fpMAX eMAX n) ) (define (well512-random-real-mp state prec) (random-large-real well512-random-integer state fpMAX eMAX prec) ) ;;; (define (make-random-source-well512) (let ((state (well512-initial-state))) (*make-random-source ; make-random-source-well512 ; EXTERNAL-ID ; "Well's 512-bit Generator" ; LOG2-PERIOD ; fpMAX ; #f ; (lambda () (well512-unpack-state state) ) ; (lambda (new-state) (set! state (well512-pack-state new-state)) ) ; (lambda (entropy-source) (set! state (well512-randomize-state state entropy-source)) ) ; (lambda (i j) (set! state (well512-pseudo-randomize-state i j)) ) ; (lambda () (lambda (n) (check-positive-integer INTERNAL-ID n 'range) (cond-expand (64bit (cond ((and (fixnum? n) (<= n maximum-unsigned-integer32)) (well512-random-integer state n)) (else (well512-random-large state n) ) ) ) (else ;32bit (cond ((and (fixnum? n) (<= n maximum-unsigned-integer32)) (well512-random-integer state n)) ;'n' maybe bignum - must be convertable to "unsigned-integer32" ((<= n eMAX) (well512-random-integer state (exact->inexact n))) (else (well512-random-large state n) ) ) ) ) ) ) ; (lambda (prec) (cond ((native-real-precision? prec eMAX) (lambda () (well512-random-real state) ) ) (else (lambda () (well512-random-real-mp state prec) ) ) ) ) ) ) ) ;;; ;;; Module Init ;;; (register-random-source! INTERNAL-ID make-random-source-well512) ) ;module well512
false
d8f053ceede9e644e4756306a3de2562104cd05a
aa83a0110d917f0018e31e5144ead84ca08ba86b
/srfi/207/parse.scm
ca640f6bab5e5186b22d18f9e616123b0dbd5ba9
[]
permissive
Zipheir/srfi-207
2ff53642cd1a0e673083ae3b7c487e9c2aaddfda
bad4761a404cc9336ea6667f192285f5f7ccba35
refs/heads/master
2023-01-04T12:07:20.551279
2020-10-29T18:52:48
2020-10-29T18:52:48
297,557,032
0
0
MIT
2020-09-22T06:31:51
2020-09-22T06:31:50
null
UTF-8
Scheme
false
false
3,087
scm
parse.scm
;;; Simple parser for string-notated bytevectors. (define (parse prefix) (when prefix (consume-prefix)) (consume-quote) (let lp ((c (read-char))) (cond ((eof-object? c) (bytestring-error "unexpected EOF")) ((char=? c #\") (if #f #f)) ; terminating quote ((char=? c #\\) (let ((c* (read-char))) (cond ((eof-object? c*) (bytestring-error "incomplete escape sequence")) ((escape c*) => (lambda (b) (write-u8 b) (lp (read-char)))) (else (lp (read-char)))))) ((and (char>=? c #\space) (char<=? c #\~)) (write-u8 (char->integer c)) (lp (read-char))) (else (bytestring-error "invalid character" c))))) (define (consume-quote) (let ((c (read-char))) (cond ((eof-object? c) (bytestring-error "unexpected EOF")) ((char=? c #\") #t) (else (bytestring-error "invalid character (expected #\\\")" c))))) (define (consume-prefix) (let ((s (read-string 3))) (cond ((eof-object? s) (bytestring-error "unexpected EOF")) ((string=? s "#u8") #t) (else (bytestring-error "invalid bytestring prefix" s))))) (define (escape c) (case c ((#\a) 7) ((#\b) 8) ((#\t) 9) ((#\n) 10) ((#\r) 13) ((#\") 34) ((#\\) 92) ((#\|) 124) ((#\x) (parse-hex)) ((#\newline) (skip-horizontal-whitespace) #f) ; skip (else (cond ((char-whitespace? c) (skip-horizontal-whitespace) (skip-line-break) #f) (else (bytestring-error "invalid escaped character" c)))))) (define (parse-hex) (let* ((hex1 (read-char)) (hex2 (read-char))) (when (or (eof-object? hex1) (eof-object? hex2)) (bytestring-error "incomplete hexadecimal sequence")) (if (char=? hex2 #\;) (or (string->number (string hex1) 16) (bytestring-error "invalid hexadecimal sequence")) (let ((term (read-char))) (if (eqv? term #\;) (or (string->number (string hex1 hex2) 16) (bytestring-error "invalid hexadecimal sequence")) (bytestring-error "overlong or unterminated hexadecimal sequence")))))) (define (skip-line-break) (let ((c (read-char))) (unless (eqv? #\newline c) (bytestring-error "expected newline" c))) (skip-horizontal-whitespace)) (define (skip-horizontal-whitespace) (let lp ((c (peek-char))) (when (and (char-whitespace? c) (not (char=? c #\newline))) (read-char) (lp (peek-char))))) (define read-textual-bytestring (case-lambda ((prefix) (read-textual-bytestring prefix (current-input-port))) ((prefix in) (assume (boolean? prefix)) (call-with-port (open-output-bytevector) (lambda (out) (parameterize ((current-input-port in) (current-output-port out)) (parse prefix) (get-output-bytevector out)))))))
false
2d49367c182788992d3c0f76395396a15da48932
a6a1c8eb973242fd2345878e5a871a89468d4080
/2.69.scm
0ba001cdb75c6f187551e514ba53909898f8f7f9
[]
no_license
takkyuuplayer/sicp
ec20b6942a44e48d559e272b07dc8202dbb1845a
37aa04ce141530e6c9803c3c7122016d432e924b
refs/heads/master
2021-01-17T07:43:14.026547
2017-02-22T03:40:07
2017-02-22T03:40:07
15,771,479
1
1
null
null
null
null
UTF-8
Scheme
false
false
1,839
scm
2.69.scm
(use slib) (require 'trace) (define (make-leaf symbol weight) (list 'leaf symbol weight)) (define (leaf? object) (eq? (car object) 'leaf)) (define (symbol-leaf x) (cadr x)) (define (weight-leaf x) (caddr x)) (define (make-code-tree left right) (list left right (append (symbols left) (symbols right)) (+ (weight left) (weight right)))) (define (left-branch tree) (car tree)) (define (right-branch tree) (cadr tree)) (define (symbols tree) (if (leaf? tree) (list (symbol-leaf tree)) (caddr tree))) (define (weight tree) (if (leaf? tree) (weight-leaf tree) (cadddr tree))) (define (adjoin-set x set) (cond ((null? set) (list x)) ((< (weight x) (weight (car set))) (cons x set)) (else (cons (car set) (adjoin-set x (cdr set)))))) (define (make-leaf-set pairs) (if (null? pairs) '() (let ((pair (car pairs))) (adjoin-set (make-leaf (car pair) ; 記号 (cadr pair)) ; 頻度 (make-leaf-set (cdr pairs)))))) (define pairs (list '(A 4) '(B 2) '(C 1) '(D 1))) ;(print pairs) (define leaf-set (make-leaf-set pairs)) ;(print leaf-set) ;(print (make-code-tree (car leaf-set) (cadr leaf-set))) (define sample-tree (make-code-tree (make-leaf 'A 4) (make-code-tree (make-leaf 'B 2) (make-code-tree (make-leaf 'D 1) (make-leaf 'C 1))))) (print sample-tree) ; 2.69 (define (successive-merge leaf-set) (if (= (length leaf-set) 1) (car leaf-set) (let ((left (car leaf-set)) (right (cadr leaf-set)) (rest (cddr leaf-set))) (successive-merge (adjoin-set (make-code-tree left right) rest)) ))) ;(trace successive-merge) (print (successive-merge leaf-set))
false
46ed97570c3f30d7e1dc6843c5ea889c40642ccd
c22faca441eb0c96c35bd3f225dc8d4de8ba1b16
/lib/radix.scm
b75ea4f1e053f2372758c9562498434f69360632
[]
no_license
buhman/route-mux
30c783137fc0600c46d4d020f5e2a996497a5b85
3e8c470e5af671b382c56fd55a9b69bf880acfa2
refs/heads/master
2020-04-13T10:49:25.004039
2019-03-26T05:53:04
2019-03-26T05:53:04
163,154,310
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,906
scm
radix.scm
;; model (define-record-type node (make-node value edges) node? ;; any (value node-value (setter node-value)) ;; #(edge ...) (edges node-edges (setter node-edges))) (define-record-printer (node n out) (fprintf out "#,(node ~s ~s)" (node-value n) (node-edges n))) (define-record-type edge (make-edge label node) edge? ;; string (label edge-label (setter edge-label)) ;; node (node edge-node (setter edge-node))) (define-record-printer (edge e out) (fprintf out "#,(edge ~s ~s)" (edge-label e) (edge-node e))) (define (edge-match return edge key parent-node) (let* ((label (edge-label edge))) (if (not (string? label)) ;; this is a parameter edge; let the caller figure out what it wants to ;; do with this (return parent-node key 0 edge) ;; (let* ((prefix-length (string-prefix-length label key)) (suffix (substring/shared key prefix-length))) (cond ((= prefix-length (string-length label)) ;; complete match; continue to next node (call-with-values (lambda () (node-search (edge-node edge) suffix)) return)) ((< 0 prefix-length) ;; incomplete match; no better matches are possible (return parent-node suffix prefix-length edge)) (else ;; no match; there might be a better match #f)))))) (define (sorted-insert vec item cmp<) (vector-unfold (lambda (i found?) (cond (found? (values (vector-ref vec (- i 1)) #t)) ((and (not (= (vector-length vec) i)) (cmp< (vector-ref vec i) item)) (values (vector-ref vec i) #f)) (else (values item #t)))) (+ (vector-length vec) 1) #f)) (define (edge< a b) (string< (edge-label a) (edge-label b))) (define (sorted-edge-insert vec item) (sorted-insert vec item edge<)) ;; api (define (node-search node suffix) (if (= 0 (string-length suffix)) ;; empty suffix; no edges could possibly match (values node suffix 0 #f) ;; binary search edges (let ((edges (node-edges node))) (let loop ((last #f) (start 0) (end (vector-length edges))) (let ((index (quotient (+ start end) 2))) (if (or (= start end) (and last (= last index))) ;; none of the edges matched (values node suffix 0 #f) ;; (let ((edge (vector-ref edges index))) (call/cc (lambda (return) (edge-match return edge suffix node) (if (string< suffix (edge-label edge)) (loop index start index) (loop index index end))))))))))) (define (node-insert-at! parent-node new-suffix prefix-length common-edge value) (cond (common-edge ;; this is a partial match with a common edge (let ((common-prefix (substring (edge-label common-edge) 0 prefix-length)) (old-suffix (substring (edge-label common-edge) prefix-length)) (old-node (edge-node common-edge))) (set! (edge-node common-edge) (let ((edges (sorted-edge-insert (vector (make-edge old-suffix old-node)) (make-edge new-suffix (make-node value #()))))) (make-node #f edges))) (set! (edge-label common-edge) common-prefix))) ;; this parent-node is the same node as this key ((= 0 (string-length new-suffix)) (set! (node-value parent-node) value)) ;; this is a new edge for this parent-node (else (set! (node-edges parent-node) (sorted-edge-insert (node-edges parent-node) (make-edge new-suffix (make-node value #()))))))) (define (node-insert! root key value) (receive (parent-node new-suffix prefix-length common-edge) (node-search root key) (node-insert! parent-node new-suffix prefix-length common-edge value)))
false
006a8c02d8b728b7e0cb1c92a1c478372ce7298c
c9548b7e89f384fb53fc0d0a3c008d17416dd6c6
/src/contract-macros.scm
a7da330e435f4af8dd0bd16574839ab0435ab67c
[ "Zlib" ]
permissive
euccastro/sphere-energy
8c4a02632ea848569f9acfb2ecb6eda1e2db492b
e532a7274be2dbf54a62620b658564710354d469
refs/heads/master
2021-01-15T09:18:44.389023
2014-10-25T14:28:37
2014-10-25T14:28:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,032
scm
contract-macros.scm
;;; Copyright (c) 2012 by Álvaro Castro Castilla / Estevo Castro. All Rights Reserved. ;;; Basic contracts functionality ;;; Expand checks only if debug cond-expand feature is defined (cond-expand (debug ;;; Input only contracts (define-syntax define/i (syntax-rules () ((_ (?proc ?args ...) (?i-contracts ...) . ?exprs) (define (?proc ?args ...) (if (and (?i-contracts ?args) ...) (begin . ?exprs) (raise (list "input contracts not satisfied" ?proc))))))) ;;; Output only contracts (define-syntax define/o (syntax-rules () ((_ (?proc args ...) (?o-contracts ...) . ?exprs) (define (?proc args ...) (call-with-values (lambda () . ?exprs) (lambda vals (if (null? (cdr vals)) (let ((res (begin . ?exprs))) ; faster path (if (?o-contracts ... res) res (raise (list "output contracts not satisfied" ?proc)))) (let recur ((contr (list ?o-contracts ...)) (check-vals vals)) (cond ((and (null? contr) (not (null? check-vals))) (error "number of output contracts doesn't match the number of output values")) ((null? check-vals) (apply values vals)) (else (if ((car contr) (car check-vals)) (recur (cdr contr) (cdr check-vals)) (raise (list "output contracts not satisfied" ?proc))))))))))))) ;;; Input/output contracts (allows using -> as a separator as an alternate syntax) (define-syntax define/io (syntax-rules (->) ((_ (?proc ?args ...) ((?i-contracts ...) (?o-contracts ...)) . ?exprs) (define·io (?proc ?args ...) ((?i-contracts ...) -> (?o-contracts ...)) . ?exprs)) ((_ (?proc ?args ...) ((?i-contracts ...) -> (?o-contracts ...)) . ?exprs) (define (?proc ?args ...) (if (and (?i-contracts ?args) ...) (let ((res (begin . ?exprs))) (call-with-values (lambda () . ?exprs) (lambda vals (if (null? (cdr vals)) (let ((res (begin . ?exprs))) ; faster path (if (?o-contracts ... res) res (raise (list "output contracts not satisfied" ?proc)))) (let recur ((contr (list ?o-contracts ...)) (check-vals vals)) (cond ((and (null? contr) (not (null? check-vals))) (error "number of output contracts doesn't match the number of output values")) ((null? check-vals) (apply values vals)) (else (if ((car contr) (car check-vals)) (recur (cdr contr) (cdr check-vals)) (raise (list "output contracts not satisfied" ?proc)))))))))) (raise (list "input contracts not satisfied" ?proc)))))))) (else (define-syntax define/i (syntax-rules () ((_ (?def ...) (?i-contracts ...) ?exprs ...) (define (?def ...) ?exprs ...)))) (define-syntax define/o (syntax-rules () ((_ (?def ...) (?o-contracts ...) ?exprs ...) (define (?def ...) ?exprs ...)))) (define-syntax define/io (syntax-rules () ((_ (?def ...) ((?i-contracts ...) (?o-contracts ...)) ?exprs ...) (define (?def ...) ?exprs ...))))))
true
d26da2ddc7474ee93f41d91a5596f501ccccea50
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/random-scheme-stuff/moving-average.scm
ef77266db355bdbb96690ad0b6f0c74928f058fc
[]
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,064
scm
moving-average.scm
;; given a list of numbers, a procedure that takes N numeric ;; arguments, and N itself, return a list of numbers gotten by ;; applying the procedure many times -- first, to SEQ[0] through SEQ[N ;; - 1] inclusive, then to SEQ[1] through SEQ[N] inclusive, and so on, ;; up to and including SEQ[L - N] through SEQ[L - 1] inclusive, where ;; L is the length of the list SEQ. ;; You could figure a moving average like this: ;;(define (average . args) (/ (apply + args) (length args))) ;;(map-n average (list 1 2 3 4 5 6 7 8 9) 3) (require 'common-list-functions) (define (map-n proc seq n) (define (first-n n seq) (cond ((= n (length seq)) seq) ((< n (length seq)) (butnthcdr n seq)) (t (error "Bad argument to first-n" n seq)))) (if (or (not (list? seq)) (> n (length seq)) (not (procedure? proc))) (error "Bad args!")) (let loop ((seq seq) (results '())) (if (> n (length seq)) (reverse results) (loop (cdr seq) (cons (apply proc (first-n n seq)) results)))))
false
f881d2af7527e571c27a361185c85bea45f4f79a
3429e6ba407a54c5e815d3acf4288b829ba775d3
/misc.sld
7eeadbc96545fdcde2c9e7290787397e75da1758
[ "BSD-3-Clause" ]
permissive
markcol/praxis-prelude-r7rs
1aa9affc2c77ddcd2c2ede4e167e1fd77548d2ea
3c01884ba68f847a91106bf3b8387ede95a2fbcf
refs/heads/master
2020-05-29T15:06:47.092809
2016-06-08T05:46:03
2016-06-08T05:46:03
60,632,105
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,054
sld
misc.sld
;; -*- scheme -*- ;; From http://programmingpraxis.com/contents/standard-prelude/ (define-library (praxis misc) (import (scheme base)) (export box box! gensym permutations unbox ;; define-integrable define-macro aif awhen ;; provided by scheme base: when) (begin ;; Define-integrable is similar to define for procedure definitions ;; except that the code for the procedure is integrated (some people ;; would say inlined) whenever the procedure is called, eliminating ;; the function-call overhead associated with the procedure. Any ;; procedure defined with define-integrable must appear in the source ;; code before the first reference to the defined identifier. Lexical ;; scoping is preserved, macros within the body of the defined ;; procedure are expanded at the point of call, the actual parameters ;; to an integrated procedure are evaluated once and at the proper ;; time, integrable procedures may be used as first-class values, and ;; recursive procedures do not cause indefinite recursive expansion. ;; Define-integrable appears in Section 8.4 of R. Kent Dybvig’s book ;; The Scheme Programming Language: ;; (define-syntax (define-integrable x) ;; (define (make-residual-name name) ;; (datum->syntax-object name ;; (string->symbol ;; (string-append "residual-" ;; (symbol->string (syntax-object->datum name)))))) ;; (syntax-case x (lambda) ;; ((_ (name . args) . body) ;; (syntax (define-integrable name (lambda args . body)))) ;; ((_ name (lambda formals form1 form2 ...)) ;; (identifier? (syntax name)) ;; (with-syntax ((xname (make-residual-name (syntax name)))) ;; (syntax ;; (begin ;; (define-syntax (name x) ;; (syntax-case x () ;; (_ (identifier? x) (syntax xname)) ;; ((_ arg (... ...)) ;; (syntax ;; ((fluid-let-syntax ;; ((name (identifier-syntax xname))) ;; (lambda formals form1 form2 ...)) ;; arg (... ...)))))) ;; (define xname ;; (fluid-let-syntax ((name (identifier-syntax xname))) ;; (lambda formals form1 form2 ...))))))))) ;; Scheme provides hygienic macros (though syntax-case provides a way ;; to safely bend hygiene); Common Lisp, by comparison, provides ;; unhygienic macros. There are some circumstances where unhygienic ;; macros are more convenient than hygienic macros; Paul Graham ;; provides numerous examples in his book On Lisp. Define-macro ;; provides unhygienic macros for Scheme: ;; (define-syntax (define-macro x) ;; (syntax-case x () ;; ((_ (name . args) . body) ;; (syntax (define-macro name (lambda args . body)))) ;; ((_ name transformer) ;; (syntax ;; (define-syntax (name y) ;; (syntax-case y () ;; ((_ . args) ;; (datum->syntax-object ;; (syntax _) ;; (apply transformer ;; (syntax-object->datum (syntax args))))))))))) ;; The following examples are adapted from Graham’s book: ;; (define-macro (aif test-form then-else-forms) ;; `(let ((it ,test-form)) ;; (if it ,then-else-forms))) ;; (define-macro (awhen pred? . body) ;; `(aif ,pred? (begin ,@body))) ;; When a macro breaks hygiene, it is sometimes useful to generate a ;; unique symbol, which can be used as a variable name or in some ;; other way. Here is the gensym procedure: (define gensym (let ((n -1)) (lambda () (set! n (+ n 1)) (string->symbol (string-append "gensym-" (number->string n)))))) ;; Boxes provide a way to pass arguments to procedures by reference ;; instead of the usual passing by value; put the argument in a box, ;; then access and reset the argument in the procedure: (define (box v) (vector v)) (define (unbox box) (vector-ref box 0)) (define (box! box v) (vector-set! box 0 v)) ;; It is sometimes useful to generate a list of the permutations of a ;; list. The function below is from Shmuel Zaks, A new algorithm for ;; generation of permutations, Technical Report 220, Technion-Israel ;; Institute of Technology, 1981: (define (permutations xs) (define (rev xs n ys) (if (zero? n) ys (rev (cdr xs) (- n 1) (cons (car xs) ys)))) (let ((xs xs) (perms (list xs))) (define (perm n) (if (> n 1) (do ((j (- n 1) (- j 1))) ((zero? j) (perm (- n 1))) (perm (- n 1)) (set! xs (rev xs n (list-tail xs n))) (set! perms (cons xs perms))))) (perm (length xs)) perms)) ))
true
6c0611143e809672fe5c86cb635d9a7fe85ffc87
08b21a94e7d29f08ca6452b148fcc873d71e2bae
/src/scheme/load.sld
b60cfc71ab557188429d6bd5293229dc793df8c3
[ "MIT" ]
permissive
rickbutton/loki
cbdd7ad13b27e275bb6e160e7380847d7fcf3b3a
7addd2985de5cee206010043aaf112c77e21f475
refs/heads/master
2021-12-23T09:05:06.552835
2021-06-13T08:38:23
2021-06-13T08:38:23
200,152,485
21
1
NOASSERTION
2020-07-16T06:51:33
2019-08-02T02:42:39
Scheme
UTF-8
Scheme
false
false
82
sld
load.sld
(define-library (scheme load) (import (loki core primitives)) (export load))
false
b54f7b65e61cb805674a3d81b0687ed711e504b7
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/runtime/cdebug.scm
0f57317c998ba4a60baf3fdd201f43e6af491c83
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
6,157
scm
cdebug.scm
;;; ******** ;;; ;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt, ;;; Beranek and Newman Inc. ;;; ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice and this permission appear in all copies and in ;;; supporting documentation, and that the name Bolt, Beranek and Newman ;;; Inc. not be used in advertising or publicity pertaining to distribution ;;; of the software without specific, written prior permission. In ;;; addition, BBN makes no respresentation about the suitability of this ;;; software for any purposes. It is provided "AS IS" without express or ;;; implied warranties including (but not limited to) all implied warranties ;;; of merchantability and fitness. In no event shall BBN be liable for any ;;; special, indirect or consequential damages whatsoever resulting from ;;; loss of use, data or profits, whether in an action of contract, ;;; negligence or other tortuous action, arising out of or in connection ;;; with the use or performance of this software. ;;; ;;; ******** ;;; ;;;;;; -*-Scheme-*- (declare (usual-integrations)) (define compiled-stack-tag '(*compiled-stack*)) ((access add-unparser-special-object! unparser-package) compiled-stack-tag (lambda (vec) (write-char #\#) (write-char #\[) (write-string "COMPILED-CODE ") (write-string (number->string (primitive-datum vec) 16)) (write-char #\space) (write-string (number->string (vector-length vec))) (write-char #\]))) (in-package continuation-package (define-standard-parser 'REENTER-COMPILED-CODE (lambda (stack history cont) (cont (list->vector (cons compiled-stack-tag (stack-list (stack-tail stack 1) (stack-ref stack 0)))) undefined-environment (1+ (stack-ref stack 0)) ;offset ))) ) ; End CONTINUATION-PACKAGE (define compiled-debug-package (make-environment (define command-set (make-command-set 'compiled-debug-commands)) (define (define-debug-command letter function help-text) (define-letter-command command-set letter function help-text)) (define-debug-command #\? (standard-help-command command-set) "Help, list command letters") (define-debug-command #\Q standard-exit-command "Quit (exit DEBUG)") (define-debug-command #\B (named-lambda (backwards-frame) (if (> current-frame 0) (begin (set! current-frame (-1+ current-frame)) (print-current-frame)) *the-non-printing-object*)) "Go back one frame") (define-debug-command #\F (named-lambda (forwards-frame) (if (< current-frame (-1+ (vector-length frame-vector))) (begin (set! current-frame (1+ current-frame)) (print-current-frame)) *the-non-printing-object*)) "Go forward one frame") (define frame-vector) (define current-frame) (set! (access debug-compiled-continuation debug-package) (named-lambda (debug-compiled-continuation cont) (if (and (continuation? cont) (setup-compiled-debug cont)) (letter-commands command-set (lambda () ((standard-rep-message "Compiled Code Debugger"))) "CDB -->") (begin (newline) (display "Not a compiled stack frame") (newline))))) (define (setup-compiled-debug cont) (let ((stack (continuation-expression cont))) (if (and (vector? stack) (eq? (vector-ref stack 0) compiled-stack-tag)) (begin (set! frame-vector (list->vector (reverse (parse-compiled-stuff stack)))) (newline) (newline) (display (vector-length frame-vector)) (display " Frames") (newline) (set! current-frame (-1+ (vector-length frame-vector))) (print-current-frame) #t) #f))) (define (parse-compiled-stuff stuff) (let loop ((index (-1+ (vector-length stuff))) (last (-1+ (vector-length stuff))) (result '())) (cond ((= index 1) (if (= index last) result (cons (subvector->list stuff index last) result))) ((primitive-type? #x28 (vector-ref stuff index)) (loop (-1+ index) (-1+ index) (cons (subvector->list stuff index last) result))) (else (loop (-1+ index) last result))))) (define (print-current-frame) (newline) (if (and (>= current-frame 0) (< current-frame (vector-length frame-vector))) (let ((frame (vector-ref frame-vector current-frame))) (if (null? frame) (begin (display "*** THE RETURN FRAME ***") (newline)) (for-each (lambda (x) (display " ") (display-compiled x) (newline)) frame))) (begin (display "*** NO STACK FRAME ***") (newline)))) (define get-place-in-code (make-primitive-procedure 'get-place-in-code)) (define (display-compiled x) (cond ((primitive-type? #x28 x) (let ((place (get-place-in-code x))) (if (pair? place) (begin (display "In file ") (display (car place)) (display " at ") (display (number->string (cdr place) 16))) (begin (display "Not in compiled code at ") (display (number->string place 16)))))) (else (display x)))) (define (print-stack-summary) (newline) (let loop ((index (-1+ (vector-length frame-vector)))) (cond ((< index 0) *the-non-printing-object*) ((null? (vector-ref frame-vector index)) (display "*** THE RETURN FRAME ***") (newline)) ((primitive-type? #x28 (car (vector-ref frame-vector index))) (display-compiled (car (vector-ref frame-vector index))) (newline) (loop (-1+ index))) (else (display (cdr (with-output-to-truncated-string 75 (lambda () (display-compiled (vector-ref frame-vector index)))))) (newline) (loop (-1+ index)))))) (define-debug-command #\H print-stack-summary "Print the stack briefly") )) ; End COMPILED-DEBUG-PACKAGE
false
518a5e07121e0589d05c8522cdee64401f9ef886
75efeba493b8ddf9b3d084962d7d9edf492a26cd
/test/chan.scm
7de0d24617459c8c235a2fe96f5dcbeacbff1a88
[]
no_license
wehu/nao
63566553ce01fd7668b85cb04fbff2d01d894a99
ca6b0c76719e533e5a2a9561ee77e54fd7dc662a
refs/heads/master
2021-04-26T07:29:01.015941
2012-11-07T02:39:24
2012-11-07T02:39:24
6,457,247
0
1
null
null
null
null
UTF-8
Scheme
false
false
94
scm
chan.scm
(import nao) (define c (make-chan)) (always@ (c) (info (<- c))) (initial (-> c "aa"))
false
7990dffd9ef4b04ddc19bd784e33a5582ff0e6cf
f04768e1564b225dc8ffa58c37fe0213235efe5d
/Interpreter/continuation.ss
454177d373768cf9204c48f8b12b4a9175c6a090
[]
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
1,146
ss
continuation.ss
(define-datatype kontinuation kontinuation? [init-k] [rator-k (rands (list-of expression?)) (env environment?) (k kontinuation?)] [rands-k (proc-value scheme-value?) (k kontinuation?)] [prim-k (args (list-of expression?)) (env environment?) (k kontinuation?)] [callcc-k (next-cont kontinuation?)] [exit-k] ) (define (apply-k k val) (cases kontinuation k [init-k () val] [rator-k (rands env k) (eval-rands rands env (rands-k val k))] [rands-k (proc-value k) (if (box? proc-value) (apply-proc (unbox proc-value) val k) (apply-proc proc-value val k)) ] [prim-k (args env k) (eval-rands args env (rands-k val k))] [callcc-k (next-k) (cases proc-val val [closure (id body env) (eval-exp (car body) (extend-env (map (lambda (x) (cadr x)) id) (list (cont next-k)) env) next-k)] [prim-proc (op) (apply-prim-proc op proc-val next-k)] [cont (k) (apply-k k (car proc-val))] [else (eopl:error 'apply-k "call/cc did not receive a proper procedure ~s" val)])] [exit-k () (begin (pretty-print val))] ))
false
958b5dc156dd13993b4b39ce650d16dce98bb2e7
8841d71d56929d83aa93fb6769cdb175eb69e747
/packages.scm
8be094983df09da96f5a7c8ceaa2e48a71655471
[ "LicenseRef-scancode-public-domain" ]
permissive
jeffd/slime48
bb1d25c9eac08d78c249affebeb890accde459ea
67abfd0648d0f6dc99bedbdc2e3dc90b683eb2ca
refs/heads/master
2021-01-13T02:36:29.157263
2007-06-07T06:08:50
2007-06-07T06:08:50
210,074
1
0
null
null
null
null
UTF-8
Scheme
false
false
18,383
scm
packages.scm
;;; -*- mode: scheme; scheme48-package: (config) -*- ;;;;;; SLIME for Scheme48 ;;;;;; Package definitions ;;; This code is written by Taylor Campbell and placed in the Public ;;; Domain. All warranties are disclaimed. (define-structure swank-worlds swank-worlds-interface (open scheme define-record-type* simple-signals module-control (subset packages (make-modified-structure make-simple-package)) (subset packages-internal (set-package-integrate?!)) (subset environments (make-reflective-tower set-reflective-tower-maker! environment-define!)) weak-utilities cells proposals ) (optimize auto-integrate) (files world)) (define-structure swank-sessions swank-sessions-interface (open scheme define-record-type* destructure-case destructuring receiving value-pipes placeholders ; for input requests locks ; for input request table tables cells weak-utilities simple-signals simple-conditions handle restarting restarting-hooks formats string-i/o (subset i/o (force-output)) continuation-data-type fluids fluids-internal threads threads-internal scheduler queues (subset environments (with-interaction-environment set-interaction-environment!)) packages packages-internal (subset package-mutation (package-system-sentinel)) swank-logging swank-worlds ) (optimize auto-integrate) (files session)) (define-structure swank-i/o swank-i/o-interface (open scheme receiving define-record-type* simple-signals i/o i/o-internal ports byte-vectors (subset primitives (copy-bytes!)) proposals locks placeholders swank-sessions ) (optimize auto-integrate) (files io)) (define-structure swank-tcp-servers swank-tcp-servers-interface (open scheme define-record-type* receiving sockets threads (subset threads-internal (terminate-thread!)) placeholders handle simple-signals simple-conditions ascii bitwise (subset i/o (write-string read-block force-output)) (subset string-i/o (read-from-string write-to-string)) swank-worlds swank-sessions swank-sldb swank-i/o swank-logging ) (optimize auto-integrate) (files tcp-server)) (define-structure swank-logging swank-logging-interface (open scheme formats i/o) ;++ cheesy temporary implementation (begin (define (swank-log fmt . args) (format (current-noise-port) "~&[Swank: ~?]~%" fmt args)))) ;;; ---------------- ;;; Swank RPC implementations (define-structures ((swank-general-rpc swank-general-rpc-interface) (swank-quitting (export with-swank-quitter))) (open scheme fluids (subset posix-files (working-directory set-working-directory!)) (subset sockets (get-host-name)) swank-sessions swank-versions ) (optimize auto-integrate) (files general)) (define-structures ((swank-repl swank-repl-interface) (swank-repl-rpc swank-repl-rpc-interface)) (open scheme receiving string-i/o i/o (subset i/o-internal (call-with-current-output-port)) extended-writing pp simple-signals weak-utilities reduce package-loader packages (subset packages-internal (package-name)) (subset environments (set-interaction-environment!)) module-control swank-sessions swank-worlds ) (optimize auto-integrate) (files repl)) (define-structures ((swank-sldb swank-sldb-interface) (swank-sldb-rpc swank-sldb-rpc-interface)) (open scheme receiving srfi-2 ;and-let* fluids simple-signals handle simple-conditions (subset display-conditions (display-condition)) restarting threads threads-internal string-i/o extended-writing pp continuations debugger-utilities disassembler ;++ flush (see comment by SWANK-INSPECTOR) ;; The next two are for accessing PUSH-SWANK-LEVEL's template ;; to filter it out of backtraces. (subset closures (closure-template)) loopholes (subset names (generated? generated-name generated-uid name->symbol)) swank-repl ; for evaluating in frames swank-inspector ; for inspecting frames swank-worlds swank-sessions swank-logging ) (optimize auto-integrate) (files sldb)) (define-structures ((swank-inspector swank-inspector-interface) (swank-inspector-rpc swank-inspector-rpc-interface)) (open scheme define-record-type* receiving destructuring string-i/o extended-writing (subset i/o (write-string)) simple-signals xvectors methods module-control reduce ; looping macros swank-sessions swank-repl ;; for the various inspector methods more-types low-level ; cell-unassigned & vector-unassigned? locations (subset packages-internal (package-name-table)) weak cells templates ;++ This brings in a dependency on the disassembler ;++ Scheme48 command processor and ought ;++ to be replaced. byte-vectors closures debug-data disclosers records record-types handle tables ports architecture bitwise ) (optimize auto-integrate) (files inspector)) ;;; These next few stub RPC structures are necessary for any semblance ;;; of sanity in a usual SLIME interaction. They will be replaced at ;;; some later time with real implementations, but these suffice for ;;; now. (define-structure swank-arglist-rpc swank-arglist-rpc-interface (open scheme) (optimize auto-integrate) (begin (define (swank:arglist-for-echo-area names . options) 'nil) (define :print-right-margin ':print-right-margin) (define :print-lines ':print-lines) (define :arg-indices ':arg-indices) (define (swank:variable-desc-for-echo-area name) 'nil) (define (swank:arglist-for-insertion name) ':not-available) (define (swank:complete-form form-string) ':not-available) )) (define-structure swank-completion-rpc swank-completion-rpc-interface (open scheme receiving handle (subset util (fold)) (subset string-i/o (write-to-string read-from-string)) (subset packages-internal (for-each-definition for-each-export package-opens)) swank-sessions swank-worlds ) (optimize auto-integrate) (files completion)) (define-structure swank-apropos-rpc swank-apropos-rpc-interface (open scheme sort destructuring string-i/o simple-signals (subset packages (structure? structure-package package-uid)) (subset packages-internal (for-each-definition for-each-export package-opens structure-name)) meta-types bindings locations (subset transforms (transform?)) (subset nodes (operator?)) (subset primops (primop?)) (subset names (name->symbol)) posix-regexps (subset swank-sessions (current-swank-world abort-swank-rpc)) swank-worlds ) (optimize auto-integrate) (files apropos)) (define-structure swank-definition-finding-rpc swank-definition-finding-rpc-interface (open scheme module-control string-i/o debugger-utilities (subset display-conditions (display-condition)) closures destructuring (subset disclosers (template-debug-data)) (subset debug-data (debug-data-name))) (optimize auto-integrate) (begin (define (swank:find-definitions-for-emacs name) (maybe-environment-ref (interaction-environment) (read-from-string name) (lambda (value) (if (closure? value) (cond ((template-source-location (closure-template value) ;; PC is non-#F only for continuations. #f) => (lambda (location) ;; One location -> one-element list. `((,(hybrid-write-to-string (debug-data-name (template-debug-data (closure-template value)))) ,location)))) (else 'nil)) 'nil)) (lambda (condition) `((,name (:ERROR ,(call-with-string-output-port (lambda (port) (display-condition condition port))))))))) (define (swank:buffer-first-change filename) '()) )) (define-structure swank-compiler/loader-rpc swank-compiler/loader-rpc-interface (open scheme receiving string-i/o filenames module-control package-loader (subset packages (package->environment structure-package package-uid link!)) (subset compiler-envs (bind-source-file-name)) syntactic (subset compiler (compile-forms)) compile-packages ;++ replace for FASL library (subset closures (make-closure)) (subset vm-exposure (invoke-closure)) handle simple-conditions (subset display-conditions (display-condition)) restarting time (subset swank-repl-rpc (swank:set-package)) swank-sessions swank-worlds ) (optimize auto-integrate) (files loader)) ;;; This macro should go somewhere else. (define-syntax define-compound-structure (syntax-rules () ((DEFINE-COMPOUND-STRUCTURE name component ...) (DEFINE-STRUCTURE name (COMPOUND-INTERFACE (INTERFACE-OF component) ...) (OPEN component ...))))) (define-compound-structure swank-rpc swank-general-rpc swank-repl-rpc swank-sldb-rpc swank-inspector-rpc swank-arglist-rpc swank-completion-rpc swank-apropos-rpc swank-definition-finding-rpc swank-compiler/loader-rpc ) ;;; ---------------- ;;; Random internal utility stuff (define-structure module-control module-control-interface (open scheme srfi-2 ;and-let* simple-signals (subset simple-conditions (make-vm-exception)) enumerated (subset architecture (op exception)) (subset primitives (find-all-records)) (subset i/o (silently)) packages packages-internal (subset compiler-envs (environment-macro-eval)) (subset environments (set-reflective-tower-maker!)) bindings locations (subset meta-types (syntax-type)) (subset names (name?)) package-mutation package-loader ensures-loaded ;++ flush ) (optimize auto-integrate) (files module)) (define-structure package-loader package-loader-interface (open scheme packages interfaces ensures-loaded restarting formats) ;++ cheesy temporary implementation -- replace with FASL library (begin (define (load-package package) (with-exiting-restarter 'abort (format #f "Abort loading of ~S." package) (lambda () (call-with-current-continuation (lambda (win) (let lose () (with-exiting-restarter 'retry (format #f "Retry loading of ~S." package) (lambda () (ensure-loaded (make-structure package (make-simple-interface #f '()))) (win))) (lose))))))))) (define-structure debugger-utilities debugger-utilities-interface (open scheme receiving srfi-2 fluids simple-signals simple-conditions handle continuations (subset vm-exposure (primitive-catch)) (subset templates (template? template-package-id)) (subset disclosers (template-debug-data debug-data-names)) debug-data string-i/o extended-writing ;; The next two are for constructing expressions in arbitrary ;; environments, maintaining invariants of Scheme forms. (subset nodes (get-operator)) (subset meta-types (syntax-type)) module-control (subset packages-internal (package-file-name package-clauses)) filenames ) (optimize auto-integrate) (files debug-util)) ;;; ---------------- ;;; Utilities -- stuff that should be built-in (define-structures ((restarting restarting-interface) (restarting-hooks (export with-restarter-invoker-hook))) (open scheme fluids receiving define-record-type* simple-signals ;; These two are for the RESTARTERS-IN-THREAD crock. (subset fluids-internal (get-dynamic-env set-dynamic-env!)) (subset threads-internal (thread-dynamic-env)) ) (optimize auto-integrate) (files restart)) (define-structure weak-utilities weak-utilities-interface (open scheme define-record-type* receiving weak tables locks ) (optimize auto-integrate) (files weak)) (define-structure xvectors xvectors-interface (open scheme define-record-type*) (optimize auto-integrate) (files xvector)) (define-structure string-i/o string-i/o-interface (open scheme extended-ports (subset i/o-internal (call-with-current-output-port)) pp extended-writing ) (optimize auto-integrate) (begin (define (with-output-to-string thunk) (call-with-string-output-port (lambda (port) (call-with-current-output-port port thunk)))) (define (read-from-string string) (read (make-string-input-port string))) (define (to-string obj outputter) (call-with-string-output-port (lambda (port) (outputter obj port)))) (define (display-to-string obj) (to-string obj display)) (define (write-to-string obj) (to-string obj write)) (define (pp-to-string obj) (to-string obj p)) (define (extended-write-to-string obj) (to-string obj extended-write)) (define (limited-write-to-string obj) (to-string obj limited-write)) (define (shared-write-to-string obj) (to-string obj shared-write)) (define (hybrid-write-to-string obj) (to-string obj hybrid-write)) )) (define-structure extended-writing extended-writing-interface (open scheme fluids cells writing simple-signals (subset i/o (make-null-output-port write-string)) ) (optimize auto-integrate) (files write)) (define-structure destructure-case (export (destructure-case :syntax) (destructure-enum-case :syntax)) (open scheme destructuring enum-case) (begin ;++ check input syntax more carefully (define-syntax destructure-case (lambda (form r compare) `(,(r 'LET) ((,(r 'LIST) ,(cadr form))) (,(r 'CASE) (,(r 'CAR) ,(r 'LIST)) ,@(map (lambda (clause) (if (compare (car clause) (r 'ELSE)) `(,(r 'ELSE) ,@(cdr clause)) `(,(if (list? (caar clause)) (caar clause) (list (caar clause))) (,(r 'DESTRUCTURE) ((,(cdar clause) (,(r 'CDR) ,(r 'LIST)))) ,@(cdr clause))))) (cddr form))))) (CAR CDR LET CASE ELSE DESTRUCTURE)) (define-syntax destructure-enum-case (lambda (form r compare) `(,(r 'LET) ((,(r 'LIST) ,(caddr form))) (,(r 'ENUM-CASE) ,(cadr form) (,(r 'CAR) ,(r 'LIST)) ,@(map (lambda (clause) (if (compare (car clause) (r 'ELSE)) `(,(r 'ELSE) ,@(cdr clause)) `(,(if (list? (caar clause)) (caar clause) (list (caar clause))) (,(r 'DESTRUCTURE) ((,(cdar clause) (,(r 'CDR) ,(r 'LIST)))) ,@(cdr clause))))) (cdddr form))))) (CAR CDR LET ENUM-CASE ELSE DESTRUCTURE)) ; (put 'destructure-case 'scheme-indent-function 1) ; (put 'destructure-enum-case 'scheme-indent-function 2) )) (define-structure continuation-data-type continuation-data-type-interface (open scheme define-record-types) (optimize auto-integrate) (files continuation))
true
a144551ea890bae03a28dd4a8fd61803983c7152
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/chibi/string-test.sld
a00ac84a36f05eb9b2ff883862b10ebf4b1374d8
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
3,671
sld
string-test.sld
(define-library (chibi string-test) (export run-tests) (import (scheme base) (scheme char) (chibi test) (chibi string)) (cond-expand (chibi (import (only (chibi) string-cursor->index))) (else (begin (define (string-cursor->index str i) i)))) (begin (define (digit-value ch) (case ch ((#\0) 0) ((#\1) 1) ((#\2) 2) ((#\3) 3) ((#\4) 4) ((#\5) 5) ((#\6) 6) ((#\7) 7) ((#\8) 8) ((#\9) 9) (else #f))) (define (string-find/index str pred) (string-cursor->index str (string-find str pred))) (define (string-find-right/index str pred) (string-cursor->index str (string-find-right str pred))) (define (string-skip/index str pred) (string-cursor->index str (string-skip str pred))) (define (string-skip-right/index str pred) (string-cursor->index str (string-skip-right str pred))) (define (run-tests) (test-begin "strings") (test #t (string-null? "")) (test #f (string-null? " ")) (test #t (string-every char-alphabetic? "abc")) (test #f (string-every char-alphabetic? "abc0")) (test #f (string-every char-alphabetic? " abc")) (test #f (string-every char-alphabetic? "a.c")) (test 3 (string-any digit-value "a3c")) (test #f (string-any digit-value "abc")) (test 0 (string-find/index "abc" char-alphabetic?)) (test 3 (string-find/index "abc0" char-numeric?)) (test 3 (string-find/index "abc" char-numeric?)) (test 3 (string-find-right/index "abc" char-alphabetic?)) (test 4 (string-find-right/index "abc0" char-numeric?)) (test 0 (string-find-right/index "abc" char-numeric?)) (test 0 (string-skip/index "abc" char-numeric?)) (test 3 (string-skip/index "abc0" char-alphabetic?)) (test 3 (string-skip/index "abc" char-alphabetic?)) (test 3 (string-skip-right/index "abc" char-numeric?)) (test 4 (string-skip-right/index "abc0" char-alphabetic?)) (test 0 (string-skip-right/index "abc" char-alphabetic?)) (test "foobarbaz" (string-join '("foo" "bar" "baz"))) (test "foo bar baz" (string-join '("foo" "bar" "baz") " ")) (test '() (string-split "")) (test '("" "") (string-split " ")) (test '("foo" "bar" "baz") (string-split "foo bar baz")) (test '("foo" "bar" "baz" "") (string-split "foo bar baz ")) (test '("foo" "bar" "baz") (string-split "foo:bar:baz" #\:)) (test '("" "foo" "bar" "baz") (string-split ":foo:bar:baz" #\:)) (test '("foo" "bar" "baz" "") (string-split "foo:bar:baz:" #\:)) (test '("foo" "bar:baz") (string-split "foo:bar:baz" #\: 2)) (test "abc" (string-trim-left " abc")) (test "abc " (string-trim-left "abc ")) (test "abc " (string-trim-left " abc ")) (test " abc" (string-trim-right " abc")) (test "abc" (string-trim-right "abc ")) (test " abc" (string-trim-right " abc ")) (test "abc" (string-trim " abc")) (test "abc" (string-trim "abc ")) (test "abc" (string-trim " abc ")) (test "" (string-trim "")) (test "" (string-trim " ")) (test "" (string-trim " ")) (test #t (string-prefix? "abc" "abc")) (test #t (string-prefix? "abc" "abcde")) (test #f (string-prefix? "abcde" "abc")) (test #t (string-suffix? "abc" "abc")) (test #f (string-suffix? "abc" "abcde")) (test #f (string-suffix? "abcde" "abc")) (test #f (string-suffix? "abcde" "cde")) (test #t (string-suffix? "cde" "abcde")) (test 3 (string-count "!a0 bc /.," char-alphabetic?)) (test "ABC" (string-map char-upcase "abc")) (test-end))))
false
331443d5d21528a0c259fa19a93c6c22008111bb
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch4/ex-4.11.scm
4a16e4590af7e0377c1a16f514c656833b8bc114
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,952
scm
ex-4.11.scm
#lang sicp (#%require "evaluator.scm") ;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-26.html#%_thm_4.11 ;; Represent frame as list of (name value) pair bindings, instead of two lists ;; of (names...) (values...) (define (make-frame variables values) (map cons variables values)) (define (frame-variables frame) (map car frame)) (define (frame-values frame) (map cdr frame)) (define (add-binding-to-frame! var val frame) (define (add-binding! binding frame) (if (null? (cdr frame)) (set-cdr! frame binding) (add-binding! binding (cdr frame)))) (add-binding! (list (cons var val)) frame)) ;; These could be written in terms of the selectors above, however the prior ;; versions optimize by knowing about the structure of the frames, so we'll ;; rewrite them also. (define (lookup-variable-value var env) (define (env-loop env) (define (scan bindings) (cond ((null? bindings) (env-loop (enclosing-environment env))) ((eq? var (caar bindings)) (cdar bindings)) (else (scan (cdr bindings))))) (if (eq? env the-empty-environment) (error "Unbound variable" var) (scan (first-frame env)))) (env-loop env)) (define (set-variable-value! var val env) (define (env-loop env) (define (scan bindings) (cond ((null? bindings) (env-loop (enclosing-environment env))) ((eq? var (caar bindings)) (set-cdr! (car bindings) val)) (else (scan (cdr bindings))))) (if (eq? env the-empty-environment) (error "Unbound variable: SET!" var) (scan (first-frame env)))) (env-loop env)) (define (define-variable! var val env) (define (scan bindings) (cond ((null? bindings) (add-binding-to-frame! var val (first-frame env))) ((eq? var (caar bindings)) (set-cdr! (car bindings) val)) (else (scan (cdr bindings))))) (scan (first-frame env)))
false
4d5fa84714f61502a3b93ccfb263264024f83314
ee8d866a11b6f484bc470558d222ed6be9e31d21
/example/test/exp.scm
d49da39c3f2432184375d4aaea3d7845b6026aed
[ "MIT" ]
permissive
corona10/gvmt
e00c6f351ea61d7b1b85c13dd376d5845c84bbb1
566eac01724b687bc5e11317e44230faab15f895
refs/heads/master
2021-12-08T05:12:08.378130
2011-11-14T17:49:18
2011-11-14T17:49:18
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
313
scm
exp.scm
(define (exp2 n) (if (= n 0) 1 (let* ((m (/ n 2)) (x (exp2 m))) (if (= (- n m) m) (* x x) (* 2 (* x x)))))) (do ((i 0 (+ i 1))) ((> i 15)) (display i) (display " ") (display (exp2 i)) (newline))
false
a58a551c8b425da0f4216d5d41029d600f309826
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
/boot/lib/errors.scm
827728e9859c5da9f2575a7aa1b8b860d309150b
[ "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
11,178
scm
errors.scm
(library (core errors) (export describe-condition assertion-violation undefined-violation lexical-violation syntax-violation error implementation-restriction-violation undefined/syntax-violation assertion/syntax-violation raise-i/o-filename-error raise-i/o-error raise-misc-i/o-error-with-port raise-misc-i/o-error raise-i/o-read-error raise-i/o-write-error raise-i/o-file-protection-error raise-i/o-file-is-read-only-error raise-i/o-file-already-exists-error raise-i/o-file-does-not-exist-error raise-i/o-invalid-position-error raise-i/o-decoding-error raise-i/o-encoding-error) (import (core) (core base) (sagittarius)) (define describe-condition (lambda (c) (define list-parents (lambda (rtd) (let loop ((rtd rtd) (lst '())) (cond ((record-type-parent rtd) => (lambda (p) (loop p (cons (record-type-name p) lst)))) (else (reverse (cdr lst))))))) (cond ((condition? c) (receive (buf proc) (open-string-output-port) (format buf " #<condition~%") (let ((lst (simple-conditions c))) (for-each (lambda (rec) (let ((rtd (record-rtd rec))) (let ((name (record-type-name rtd)) (parents (list-parents rtd)) (count (vector-length (record-type-field-names rtd)))) (format buf "~% ~a" name) (and (pair? parents) (format buf " ~a" parents)) (cond ((= count 1) (let ((obj ((record-accessor rtd 0) rec))) (if (string? obj) (format buf ": ~a" ((record-accessor rtd 0) rec)) (format buf ": ~s" ((record-accessor rtd 0) rec))))) ((> count 1) (let ((lst (vector->list (record-type-field-names rtd)))) (let loop ((i 0) (lst lst)) (and (pair? lst) (let ((obj ((record-accessor rtd i) rec))) (if (string? obj) (format buf "~% ~a: ~a" (car lst) obj) (format buf "~% ~a: ~s" (car lst) obj)) (loop (+ i 1) (cdr lst))))))))))) lst)) (format buf "~% >") (format "~a~%" (proc)))) (else (format "~a~%" c))))) #| (define raise (lambda (c) (cond ((current-exception-handler) => (lambda (proc) (proc c) (cond ((parent-exception-handler) => (lambda (proc) (proc (condition (make-non-continuable-violation) (make-who-condition 'raise) (make-message-condition "returned from non-continuable exception") (make-irritants-condition (list c))))))) (scheme-error 'raise (format "returned from non-continuable exception~%~%irritants:~%~a" (describe-condition c)))))) (scheme-error 'raise (format "unhandled exception has occurred~%~%irritants:~%~a" (describe-condition c))))) (define raise-continuable (lambda (c) (cond ((current-exception-handler) => (lambda (proc) (proc c))) (else (scheme-error 'raise-continuable (format "unhandled exception has occurred~%~%irritants:~%~a" (describe-condition c))))))) (define with-exception-handler (lambda (handler thunk) (let ((parent (current-exception-handler))) (let ((parent-save (parent-exception-handler)) (current-save (current-exception-handler)) (new-current (lambda (condition) (let ((current-save2 (current-exception-handler))) (dynamic-wind (lambda () (current-exception-handler parent)) (lambda () (handler condition)) (lambda () (current-exception-handler current-save2))))))) (dynamic-wind (lambda () (parent-exception-handler parent) (current-exception-handler new-current)) thunk (lambda () (parent-exception-handler parent-save) (current-exception-handler current-save))))))) |# (define assertion-violation (lambda (who message . irritants) (raise (apply condition (filter values (list (make-assertion-violation) (and who (make-who-condition who)) (make-message-condition message) (make-irritants-condition irritants))))))) (define undefined-violation (lambda (who . message) (raise (apply condition (filter values (list (make-undefined-violation) (and who (make-who-condition who)) (and (pair? message) (make-message-condition (car message))))))))) (define lexical-violation (lambda (who . message) (raise (apply condition (filter values (list (make-lexical-violation) (and who (make-who-condition who)) (and (pair? message) (make-message-condition (car message))))))))) (define syntax-violation (lambda (who message form . subform) (raise (apply condition (filter values (list (make-syntax-violation form (and (pair? subform) (car subform))) (if who (make-who-condition who) (cond ((let ((obj form)) (cond ((identifier? obj) (id-name obj)) ((and (pair? obj) (identifier? (car obj))) (id-name (car obj))) (else #f))) => make-who-condition) (else #f))) (make-message-condition message))))))) (define error (lambda (who message . irritants) (raise (apply condition (filter values (list (make-error) (and who (make-who-condition who)) (make-message-condition message) (make-irritants-condition irritants))))))) (define implementation-restriction-violation (lambda (who message . irritants) (raise (apply condition (filter values (list (make-implementation-restriction-violation) (and who (make-who-condition who)) (make-message-condition message) (and (pair? irritants) (make-irritants-condition irritants)))))))) (define undefined/syntax-violation (lambda (who message form . subform) (raise (apply condition (filter values (list (make-syntax-violation form (and (pair? subform) (car subform))) (make-undefined-violation) (and who (make-who-condition who)) (make-message-condition message))))))) (define assertion/syntax-violation (lambda (who message form . subform) (raise (apply condition (filter values (list (make-syntax-violation form (and (pair? subform) (car subform))) (make-assertion-violation) (and who (make-who-condition who)) (make-message-condition message))))))) (define raise-i/o-filename-error (lambda (who message filename . irritants) (raise (apply condition (filter values (list (make-i/o-filename-error filename) (and who (make-who-condition who)) (make-message-condition message) (and (pair? irritants) (make-irritants-condition irritants)))))))) (define raise-i/o-error (lambda (who message . irritants) (raise (apply condition (filter values (list (make-i/o-error) (and who (make-who-condition who)) (make-message-condition message) (and (pair? irritants) (make-irritants-condition irritants)))))))) (define raise-misc-i/o-error-with-port (lambda (constructor who message port . options) (raise (apply condition (filter values (list (apply constructor options) (and who (make-who-condition who)) (make-message-condition message) (and port (make-i/o-port-error port)) (make-irritants-condition (cons* port options)))))))) (define raise-misc-i/o-error (lambda (constructor who message . options) (raise (apply condition (filter values (list (apply constructor options) (and who (make-who-condition who)) (make-message-condition message) (and (pair? options) (make-irritants-condition options)))))))) (define raise-i/o-read-error (lambda (who message port) (raise-misc-i/o-error-with-port make-i/o-read-error who message port))) (define raise-i/o-write-error (lambda (who message port) (raise-misc-i/o-error-with-port make-i/o-write-error who message port))) (define raise-i/o-file-protection-error (lambda (who message filename) (raise-misc-i/o-error make-i/o-file-protection-error who message filename))) (define raise-i/o-file-is-read-only-error (lambda (who message port) (raise-misc-i/o-error-with-port make-i/o-file-is-read-only-error who message port))) (define raise-i/o-file-already-exists-error (lambda (who message filename) (raise-misc-i/o-error make-i/o-file-already-exists-error who message filename))) (define raise-i/o-file-does-not-exist-error (lambda (who message filename) (raise-misc-i/o-error make-i/o-file-does-not-exist-error who message filename))) (define raise-i/o-invalid-position-error (lambda (who message port position) (raise-misc-i/o-error-with-port make-i/o-invalid-position-error who message port position))) (define raise-i/o-decoding-error (lambda (who message port) (raise-misc-i/o-error make-i/o-decoding-error who message port))) (define raise-i/o-encoding-error (lambda (who message port char) (raise-misc-i/o-error make-i/o-encoding-error who message port char))) )
false
8919131e56cb4891b0fafbed3f2847ef0a9363b4
6e359a216e1e435de5d39bc64e75998945940a8c
/ex5.11.scm
6681c81944b9628c661f129e79501c70e2baea25
[]
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
838
scm
ex5.11.scm
;1. ;replace (assign n (reg val)) and (restore val) with (restore n); then n contains fib (n - 1), val contains (n - 2),add them,get the next val. the procedure works still; ;2. (define (make-save inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (push stack (cons (stack-inst-reg-name inst) (get-contents reg))) (advance-pc pc))))` (define (make-resore inst machine stack pc) (let ((reg (get-register machine (stack-inst-reg-name inst)))) (lambda () (let ((reg-value (pop stack))) (if (not (equal? (car reg-value) (stack-inst-reg-name inst))) (error "Unmatched registernames" (stack-inst-reg-name inst)) (begin (set-contents! reg (cdr reg-value)) (advance-pc pc))))))) ;3.Delete the machine's stack,give every register a stack; ;see ex5.11-3.scm
false
c93359f2e694fa722ff3a0618cda64c047f69324
ebec97e229a18c79dda6c4df3b5f82f7b9392232
/src/uft-haskell/examples/kntest.scm
a77e553a73d55904b5adce4380351a5b0db7b190
[]
no_license
Skyb0rg007/COMP-150-VMs
7c6045f3e9c9afd7dc9267f572e789ed93c146ed
428cdc3e53751371bd3cd7442ea9352cce7516dc
refs/heads/master
2023-02-02T07:34:29.956372
2020-10-27T01:22:31
2020-10-27T01:22:31
294,217,736
0
0
null
null
null
null
UTF-8
Scheme
false
false
582
scm
kntest.scm
; ExpLit (let* ([r0 1] [r1 1]) (check r0 "1") (expect r1 "1")) ; ExpVar (let* ([r0 1] [r1 r0] [r2 1]) (check r1 "r0") (expect r2 "1")) ; ExpLet (let ([r0 2]) (let ([r2 2]) (check r0 "2") (expect r2 "2"))) ; ExpSet (let* ([r0 1] [r1 2]) (set r0 r1) (check r0 "r0") (expect r1 "2")) ; ExpSeq (let* ([r0 1] [r1 1] [r2 2]) (begin (set r1 r2) (set r0 r1)) (check r0 "r0") (expect r2 "2")) ; ExpCmd (let* ([r0 2] [r1 2] [r3 (+ r0 r1)] [r4 4]) (check r3 "(+ 2 2)") (expect r4 "4"))
false
e03d601795d35690ba31b4b6df00c53f63c03f9b
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 2/2.2/Ex2.52.scm
5c7f376df4a39369592817b545d5be5bbfb29dbb
[]
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
46
scm
Ex2.52.scm
#lang planet neil/sicp ;;Skipping Ex2.52.scm
false
ba106ed4b040db6694639ba214d5ce8d6c462e0c
2e4afc99b01124a1d69fa4f44126ef274f596777
/apng/resources/dracula/private/hash.ss
39ffb63da7efaa25876ccd46c99a87cb7174928f
[]
no_license
directrix1/se2
8fb8204707098404179c9e024384053e82674ab8
931e2e55dbcc55089d9728eb4194ebc29b44991f
refs/heads/master
2020-06-04T03:10:30.843691
2011-05-05T03:32:54
2011-05-05T03:32:54
1,293,430
0
0
null
null
null
null
UTF-8
Scheme
false
false
837
ss
hash.ss
#lang scheme (define (hash-contains? table key) (let/ec return (hash-ref table key (lambda () (return #f))) #t)) (define (hash-ref/check table key) (hash-ref table key)) (define (hash-ref/identity table key) (hash-ref table key (lambda () key))) (define (hash-ref/default table key default) (hash-ref table key (lambda () default))) (define (hash-domain table) (for/list ([i (in-hash-keys table)]) i)) (define (hash-range table) (for/list ([i (in-hash-values table)]) i)) (provide/contract [hash-contains? (-> hash? any/c boolean?)] [hash-ref/identity (-> hash? any/c any/c)] [hash-ref/default (-> hash? any/c any/c any/c)] [hash-ref/check (->d ([table hash?] [key any/c]) () #:pre-cond (hash-contains? table key) [_ any/c])] [hash-domain (-> hash? list?)] [hash-range (-> hash? list?)])
false
a18e5efe4c655aaf2aec1b9d05e19878bd711678
7666204be35fcbc664e29fd0742a18841a7b601d
/code/1-34.scm
5c3ca5972fe8b271483e0eeb2e5d79ba65388755
[]
no_license
cosail/sicp
b8a78932e40bd1a54415e50312e911d558f893eb
3ff79fd94eda81c315a1cee0165cec3c4dbcc43c
refs/heads/master
2021-01-18T04:47:30.692237
2014-01-06T13:32:54
2014-01-06T13:32:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
239
scm
1-34.scm
#lang racket (define (square x) (* x x)) (define (f g) (g 2)) (f square) ; (square 2) (f (lambda (z) (* z (+ z 1)))) ; ((lambda (z) (* z (+ z 1))) 2) ; (* 2 (+ 2 1)) ; 6 (f f) ; (f 2) ; (2 2) ; --> error[expected procedure, given: 2]
false
9e69a5ba9892e9d202abdc867a1be70b970bef8b
bdcc255b5af12d070214fb288112c48bf343c7f6
/srfi/i6.vicare.sls
641d96bcd2e9f8ab6fe425ca47fa8645875c2f98
[]
no_license
xaengceilbiths/chez-lib
089af4ab1d7580ed86fc224af137f24d91d81fa4
b7c825f18b9ada589ce52bf5b5c7c42ac7009872
refs/heads/master
2021-08-14T10:36:51.315630
2017-11-15T11:43:57
2017-11-15T11:43:57
109,713,952
5
1
null
null
null
null
UTF-8
Scheme
false
false
301
sls
i6.vicare.sls
#!chezscheme (library (srfi i6) (export open-output-string get-output-string open-input-string) (import (only (rnrs) define open-string-input-port) (r7b-util string-buffer)) (define open-input-string open-string-input-port) )
false
a889ae69eb69bf4a6dbd935f3618cf2f2ded0ea6
eaa28dbef6926d67307a4dc8bae385f78acf70f9
/lib/pikkukivi/command/verkko/pervo.sld
abd00ba2923cde65bddcf0a12f522475e6ce9cb5
[ "Unlicense" ]
permissive
mytoh/pikkukivi
d792a3c20db4738d99d5cee0530401a144027f1f
d3d77df71f4267b9629c3fc21a49be77940bf8ad
refs/heads/master
2016-09-01T18:42:53.979557
2015-09-04T08:32:08
2015-09-04T08:32:08
5,688,224
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,337
sld
pervo.sld
(define-library (pikkukivi command verkko pervo) (export pervo) (import (scheme base) (scheme file) (gauche base) (rfc http) (rfc uri) (rfc cookie) (rfc md5) (util digest) (util list) (text tree) (kirjasto verkko) (sxml ssax) (srfi 1) (srfi 13) (srfi 19) (srfi 27) (srfi 42) (math mt-random) (file util) (kirjasto merkkijono) (gauche sequence)) (begin (define (alist->ns-cookie-string alist) (tree->string (intersperse ";" (map (lambda (x) (intersperse "=" x)) alist)))) (define *interval* 2) (define member-id (let ((m (make <mersenne-twister> :seed (date-nanosecond (current-date))))) (rxmatch->string #/(\d){6}/ (number->string (+ (mt-random-real m) (mt-random-real m)))))) (define *eh-cookie* (alist->ns-cookie-string `(("ipb_pass_hash" ,(digest-hexify (md5-digest-string member-id))) ("ipb_member_id" ,member-id) ("path" "/") ("domain" ".exhentai.org") ("nw" 1) ("tips" 1)))) (define *download-directory* "download") (define parse-image-url (lambda (line) (sys-sleep *interval*) (rxmatch->string #/\"http\:\/\/(\d+(\.)?)+(:\d+)?\/[^\"]+(jpg|gif|png)\"/ line))) (define (parse-single-pages html) (map (lambda (s) (rxmatch->string #/http\:\/\/\w+\.org\/s\/(\w+)\/(\d+)-(\d+)/ s)) (filter (lambda (s) (string-scan s "gdtm")) (find-all-tags "div" html)))) (define (get-page url number) (surl (build-path url (string-append "?p=" (number->string number))))) (define (parse-last-page-number html) (/ (length (filter (lambda (s) (#/http\:\/\/\w+\.org\/\w\/(\d+)\/(\w+)\/\?p\=\d/ s)) (find-all-tags "a" html))) 2)) (define (surl uri) (let-values (((scheme user-info hostname port-number path query fragment) (uri-parse uri))) (values-ref (http-get hostname (or (uri-compose :path path :query query) "/") :cookie *eh-cookie*) 2))) (define (get-image index directory url) (sys-sleep *interval*) (let* ((ext (path-extension (string-trim-both url #\"))) (file (build-path (path-swap-extension (number->string index) ext))) (dir (build-path *download-directory* directory)) (download-path (build-path dir file))) (print download-path) (when (not (file-exists? dir)) (make-directory* dir)) (if (file-exists? download-path) (print download-path " exists!") (save-image (string-trim-both url #\") download-path)))) (define (save-image url download-path) (print url) (call-with-output-file download-path (lambda (in) (let-values (((scheme user-info hostname port-number path query fragment) (uri-parse (string-trim-both url #\")))) (values-ref (http-get (if port-number (string-append hostname ":" (number->string port-number)) hostname) path :cookie *eh-cookie* :sink in :flusher (lambda _ #true)) 2))))) (define (make-save-directory-name html) (regexp-replace-all #/\<\/?\w+(\s+id\=\"\w+\")?\>/ (car (find-all-tags "h1" html)) "")) (define (pervo args) (let* ((index-page (surl (car args))) (last-page-number (parse-last-page-number index-page)) (single-pages (append-ec (:range i last-page-number) (parse-single-pages (get-page (car args) i)))) (directory-name (make-save-directory-name index-page))) (for-each-with-index (lambda (page-number url) (guard (exc ((<system-error> exc) (get-image page-number directory-name (parse-image-url (surl url))))) (get-image page-number directory-name (parse-image-url (surl url))))) single-pages))) ))
false
49a4201d7404790014fbbe2746f9e49af6085b3d
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/reflection/assembly-title-attribute.sls
9ff3591bdf2b91ac276d390c0fafaffafe551bcd
[]
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
594
sls
assembly-title-attribute.sls
(library (system reflection assembly-title-attribute) (export new is? assembly-title-attribute? title) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Reflection.AssemblyTitleAttribute a ...))))) (define (is? a) (clr-is System.Reflection.AssemblyTitleAttribute a)) (define (assembly-title-attribute? a) (clr-is System.Reflection.AssemblyTitleAttribute a)) (define-field-port title #f #f (property:) System.Reflection.AssemblyTitleAttribute Title System.String))
true
31733033f3fe59665861411b780b7a9c7ae41166
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/zcomp/machines/butterfly/make.scm
4e78aee24b4f90bfa6e1266f5b96d887e9b66d4f
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
8,496
scm
make.scm
#| -*-Scheme-*- $Header: make.scm,v 1.5 89/02/08 15:08:11 las Exp $ $MIT-Header: make.scm,v 4.7 88/03/14 19:38:20 GMT jinx Exp $ Copyright (c) 1987 Massachusetts Institute of Technology This material was developed by the Scheme project at the Massachusetts Institute of Technology, Department of Electrical Engineering and Computer Science. Permission to copy this software, to redistribute it, and to use it for any purpose is granted, subject to the following restrictions and understandings. 1. Any copy made of this software must include this copyright notice in full. 2. Users of this software agree to make their best efforts (a) to return to the MIT Scheme project any improvements or extensions that they make, so that these may be included in future releases; and (b) to inform MIT of noteworthy uses of this software. 3. All materials developed as a consequence of the use of this software shall duly acknowledge such use, in accordance with the usual standards of acknowledging credit in academic research. 4. MIT has made no warrantee or representation that the operation of this software will be error-free, and MIT is under no obligation to provide any services, by way of maintenance, update, or otherwise. 5. In conjunction with products arising from the use of this material, there shall be no use of the name of the Massachusetts Institute of Technology nor of any adaptation thereof in any advertising, promotional, or sales literature without prior written consent from MIT in each case. |# ;;;; Compiler Make File for MC68020 (declare (usual-integrations)) (load "base/pkging.bin" system-global-environment) (in-package compiler-package (define compiler-system (make-environment (define :name "Liar (Butterfly 68020)") (define :version 4) (define :modification 7) (define :files) (define :rcs-header "$Header: make.scm,v 1.5 89/02/08 15:08:11 las Exp $") (define :files-lists (list (cons touchifier-package '("touchify.com" ;future (touch) support )) (cons system-global-environment '("base/pbs.bin" ;bit-string read/write syntax "etc/direct.bin" ;directory reader "etc/butils.bin" ;system building utilities )) (cons compiler-package '("base/switch.bin" ;compiler option switches "base/macros.bin" ;compiler syntax "base/hashtb.com" ;hash tables )) (cons decls-package '("base/decls.com" ;declarations )) (cons compiler-package '("base/object.com" ;tagged object support "base/enumer.com" ;enumerations "base/queue.com" ;queue abstraction "base/sets.com" ;set abstraction "base/mvalue.com" ;multiple-value support "base/scode.com" ;SCode abstraction "base/pmlook.com" ;pattern matcher: lookup "base/pmpars.com" ;pattern matcher: parser "machines/butterfly/machin.com" ;machine dependent stuff "base/toplev.com" ;top level "base/debug.com" ;debugging support "base/utils.com" ;odds and ends "base/cfg1.com" ;control flow graph "base/cfg2.com" "base/cfg3.com" "base/ctypes.com" ;CFG datatypes "base/rvalue.com" ;Right hand values "base/lvalue.com" ;Left hand values "base/blocks.com" ;rvalue: blocks "base/proced.com" ;rvalue: procedures "base/contin.com" ;rvalue: continuations "base/subprb.com" ;subproblem datatype "rtlbase/rgraph.com" ;program graph abstraction "rtlbase/rtlty1.com" ;RTL: type definitions "rtlbase/rtlty2.com" ;RTL: type definitions "rtlbase/rtlexp.com" ;RTL: expression operations "rtlbase/rtlcon.com" ;RTL: complex constructors "rtlbase/rtlreg.com" ;RTL: registers "rtlbase/rtlcfg.com" ;RTL: CFG types "rtlbase/rtlobj.com" ;RTL: CFG objects "rtlbase/regset.com" ;RTL: register sets "base/infutl.com" ;utilities for info generation, shared "back/insseq.com" ;LAP instruction sequences "machines/butterfly/dassm1.com" ;disassembler )) (cons disassembler-package '("machines/butterfly/dassm2.com" ;disassembler "machines/butterfly/dassm3.com" )) (cons fg-generator-package '("fggen/fggen.com" ;SCode->flow-graph converter "fggen/declar.com" ;Declaration handling )) (cons fg-optimizer-package '("fgopt/simapp.com" ;simulate applications "fgopt/outer.com" ;outer analysis "fgopt/folcon.com" ;fold constants "fgopt/operan.com" ;operator analysis "fgopt/closan.com" ;closure analysis "fgopt/blktyp.com" ;environment type assignment "fgopt/contan.com" ;continuation analysis "fgopt/simple.com" ;simplicity analysis "fgopt/order.com" ;subproblem ordering "fgopt/conect.com" ;connectivity analysis "fgopt/desenv.com" ;environment design "fgopt/offset.com" ;compute node offsets )) (cons rtl-generator-package '("rtlgen/rtlgen.com" ;RTL generator "rtlgen/rgproc.com" ;procedure headers "rtlgen/rgstmt.com" ;statements "rtlgen/rgrval.com" ;rvalues "rtlgen/rgcomb.com" ;combinations "rtlgen/rgretn.com" ;returns "rtlgen/fndblk.com" ;find blocks and variables "rtlgen/opncod.com" ;open-coded primitives "machines/butterfly/rgspcm.com" ;special close-coded primitives "rtlbase/rtline.com" ;linearizer )) (cons rtl-cse-package '("rtlopt/rcse1.com" ;RTL common subexpression eliminator "rtlopt/rcse2.com" "rtlopt/rcseep.com" ;CSE expression predicates "rtlopt/rcseht.com" ;CSE hash table "rtlopt/rcserq.com" ;CSE register/quantity abstractions "rtlopt/rcsesr.com" ;CSE stack references )) (cons rtl-optimizer-package '("rtlopt/rlife.com" ;RTL register lifetime analyzer "rtlopt/rdeath.com" ;RTL code compression "rtlopt/rdebug.com" ;RTL optimizer debugging output "rtlopt/ralloc.com" ;RTL register allocation )) (cons debugging-information-package '("base/infnew.com" ;debugging information generation )) (cons lap-syntax-package '("back/lapgn1.com" ;LAP generator. "back/lapgn2.com" "back/lapgn3.com" "back/regmap.com" ;Hardware register allocator. "back/linear.com" ;LAP linearizer. "machines/butterfly/lapgen.com" ;code generation rules. "machines/butterfly/rules1.com" "machines/butterfly/rules2.com" "machines/butterfly/rules3.com" "machines/butterfly/rules4.com" "back/syntax.com" ;Generic syntax phase "machines/butterfly/coerce.com" ;Coercions: integer -> bit string "back/asmmac.com" ;Macros for hairy syntax "machines/butterfly/insmac.com" ;Macros for hairy syntax "machines/butterfly/insutl.com" ;Utilities for instructions "machines/butterfly/instr1.com" ;68000 Effective addressing "machines/butterfly/instr2.com" ;68000 Instructions "machines/butterfly/instr3.com" ; " " "machines/butterfly/instr4.com" ; " " )) (cons bit-package '("machines/butterfly/assmd.com" ;Machine dependent "back/symtab.com" ;Symbol tables "back/bitutl.com" ;Assembly blocks "back/bittop.com" ;Assembler top level )) )) )) (load-system! compiler-system)) ;;; ;;; Special loading of bbn-inline-code. Each piece of the file ;;; must be evaluated in the appropriate environment. ;;; (let ((load-compiled? (begin (newline) (write-string "Load bbn inline code files compiled? ") (eq? (read) 'y)))) (let ((scode-list (fasload-multiple (if load-compiled? "bbn-inline-code.com" "bbn-inline-code.bin")))) (for-each (lambda (scode env) (scode-eval scode env)) scode-list (list compiler-package (access rtl-cse-package compiler-package) (access rtl-method-package compiler-package) (access open-coder-package (access rtl-generator-package compiler-package)) (access lap-syntax-package compiler-package))) (load (if load-compiled? "fltasm.com" "fltasm.bin") (access lap-syntax-package compiler-package)))) ;; This does not use system-global-environment so that multiple ;; versions of the compiler can coexist in different environments. ;; This file must therefore be loaded into system-global-environment ;; when the names below must be exported everywhere. (let ((top-level-env system-global-environment)) ;; was (the-environment) (for-each (lambda (name) (local-assignment top-level-env name (lexical-reference compiler-package name))) '(CF COMPILE-BIN-FILE COMPILE-PROCEDURE COMPILER:RESET! COMPILER:WRITE-LAP-FILE COMPILER:WRITE-RTL-FILE)))
false
9cbe3d1b3080ac691e9bcfbd2fd5b5ee3a69bb34
295dbd430419a7c36df8d2fd033f8e9afdc308c3
/Computing_with_Register_Machines/ex/29.scm
883fb0905b70565099b72b1db5032ca463a67603
[]
no_license
ojima-h/sicp
f76b38a46a4f413d6a33f1ba0df4f6af28208fa1
4bbcd6a011076aef6fe36071958b76e05f653c75
refs/heads/master
2016-09-05T17:36:32.319932
2014-06-09T00:30:37
2014-06-09T00:30:37
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
525
scm
29.scm
(load "compat") (load "load-eceval") (define the-global-environment (setup-environment)) (start eceval) (define (fib n) (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2))))) (fib 0) (fib 1) (fib 2) (fib 3) (fib 4) ;; maximum-depth = 5 * n - 2 ;; total-pushes = S(n) ;; S(n) = S(n - 1) + S(n - 2) + 40 ;; S(0) = S(1) = 16 ;; [S(n) + 40]/56 = [S(n - 1) + 40]/56 + [S(n - 2) + 40]/56 ;; [S(0) + 40] = [S(1) + 40] = 1 ;; [S(n) + 40]/56 = Fib(n + 1) ;; S(n) = 56 * Fib(n + 1) - 40 ;; ^^^^^^^^^^^^^^^^^^^^^^^^^^^
false
961d7acc7060cddb38368790b282e2818d36f402
ac6ca831a64544efd82dd1e6c8fc44c35a9538a2
/test/callcc.scm
ed54c35776e5d01f2654594c41bd09a19080858c
[ "MIT" ]
permissive
ypyf/fscm
4bce4622cccccbfce8a5a1b4f482880ed14fa7c7
8be570e1c85a7ad6e1b888a2e3069ddcf4319569
refs/heads/master
2023-09-04T04:47:07.247132
2023-08-29T13:38:22
2023-08-29T13:59:56
5,802,289
5
1
null
2015-05-17T01:10:29
2012-09-13T23:10:28
Scheme
UTF-8
Scheme
false
false
1,513
scm
callcc.scm
;(call/cc call/cc) ; 返回#<cont> 第一个callcc用它的继续当参数调用第二个callcc函数 ;((call/cc call/cc) (call/cc call/cc)) ;; 死循环.左边子表达式是当前继续,右边也是当前继续(但是是右边的) ;; ([] []) (define lwp-list '()) (define lwp (lambda (thunk) (set! lwp-list (append lwp-list (list thunk))))) (define start (lambda () (let ((p (car lwp-list))) (set! lwp-list (cdr lwp-list)) (p)))) (define pause (lambda () (call/cc (lambda (k) (lwp (lambda () (k #f))) (start))))) (define (f0) (pause) (display "h") (f0)) (define (f1) (pause) (display "e") (f1)) (define (f2) (pause) (display "y") (f2)) (define (f3) (pause) (display "!") (f3)) (define (f4) (pause) (newline) (flush-output) (f4)) (lwp f0) (lwp f1) (lwp f2) (lwp f3) (lwp f4) ;(lwp (lambda () (let f () (pause) (display "h") (f)))) ;(lwp (lambda () (let f () (pause) (display "e") (f)))) ;(lwp (lambda () (let f () (pause) (display "y") (f)))) ;(lwp (lambda () (let f () (pause) (display "!") (f)))) ;(lwp (lambda () (let f () (pause) (newline) (f)))) ;; memory leak? (define (leak-test1 identity-thunk) (let loop ((id (lambda (x) x))) (loop (id (identity-thunk))))) (let* ((yin ((lambda (foo) (newline) foo) (call/cc (lambda (bar) bar)))) (yang ((lambda (foo) (write-char #\*) foo) (call/cc (lambda (bar) bar))))) (yin yang))
false
3abb601b1307464fa134f31f622124640ac3842c
97c107938d7a7b80d319442337316604200fc0ae
/engine/ai.ss
692b67fa6907064106371faf9abaf9693f005aa7
[]
no_license
jeapostrophe/rl
ddb131563cb37da80905c5de2debd01ec6c371d6
865f2a68e075bb5cc91754839181a35b03e08cb9
refs/heads/master
2021-01-19T03:10:04.613667
2013-10-31T01:24:57
2013-10-31T01:24:57
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,093
ss
ai.ss
#lang scheme (require "../lib/random.ss" "../lib/posn.ss" "../lib/tree.ss" "../copy-obj/this-class.ss" "action.ss" "mob.ss") (define ai<%> (interface (mob<%>) receive-message)) (define pythonista% (class%* mob% (ai<%>) (define/override (short-desc) "Rabid Pythonista") (inherit-field posn) (inherit current-floor-map) (define/override (next-action) (define map (current-floor-map)) (cons this (make-move (random-element (for/fold ([options empty]) ([d directions] [np (posn-neighbors posn)]) (define-values (enter? msg) (send (send map tile np) enter?)) (if enter? (list* d options) options)))))) (define/public (receive-message m) this) (define/override (look map) (values tree-empty this)) (define/override (render) 'pythonista) (super-new))) (provide/contract [ai<%> interface?] [pythonista% (implementation?/c ai<%>)])
false
33f927ad9ca0d4ab11cc520230ab39cc5c6060de
c63772c43d0cda82479d8feec60123ee673cc070
/ch1/31.scm
b3819ffd373c24e1b11180894ec4adea46301730
[ "Apache-2.0" ]
permissive
liuyang1/sicp-ans
26150c9a9a9c2aaf23be00ced91add50b84c72ba
c3072fc65baa725d252201b603259efbccce990d
refs/heads/master
2021-01-21T05:02:54.508419
2017-09-04T02:48:46
2017-09-04T02:48:52
14,819,541
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,266
scm
31.scm
#lang racket ; on POSITIVE-INTEGER sequence (define (inc x) (+ 1 x)) ; abstract to group set ; group is on OP and UNIT ; 1. (X op Y) op Z = X op (Y op Z) ; 2. exist UNIT, X op UNIT = X ; for MUL(*), UNIT is 1; for ADD(+), UNIT is 0. ; 3. exist INV element. X op (INV X) = UNIT ; for MUL(*), INV is DIV; for ADD(+), INV is NEGATIVE. ; generate all elements in group by iter if it only have a generator action. ; refer to Caley Graph of group. (define (gen-group-iter op unit) (define (iter-func func a next b) (define (iter a acc) (if (> a b) acc (iter (next a) (op acc (func a))))) (iter a unit)) iter-func) (define product-iter (gen-group-iter * 1)) (define (product-rec func a next b) (if (> a b) 1 (* (func a) (product-rec func (next a) next b)))) (define (gen-group-rec op unit) (define (rec func a next b) (if (> a b) unit (op (func a) (rec func (next a) next b)))) rec) (define product-rec1 (gen-group-rec * 1)) (define (func-pi n) (if (even? n) (/ n (+ n 1.0)) (/ (+ n 1.0) n))) (define (call-pi-fn pi-fn end) (* 4 (pi-fn func-pi 2 inc end))) (call-pi-fn product-iter 100000) (call-pi-fn product-rec 100000) (call-pi-fn product-rec1 100000)
false
4896cf0e66c810be719d48412ddb8705f2744e9c
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec3/q3.38.scm
40b008f83402bc80a8a157b807de73c2a415359b
[]
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
741
scm
q3.38.scm
;; sec3.1.1.scm のwithdraw手続き ; default : 100 ; Peter: (set! balance (+ balance 10)) ; Paul: (set! balance (- balance 20)) ; Mary: (set! balance (- balance (/ balance 2))) ;; (a). 3つのプロセスをある順序で逐次的に走らせる場合 ;; ;; 1. Pe -> Pa -> M => (((100 + 10) - 20) / 2) => 45 ;; 2. Pe -> M -> Pa => (((100 + 10) / 2) - 20) => 45 ;; 3. Pa -> Pe -> M => (((100 - 20) + 10) / 2) => 45 ;; 4. Pa -> M -> Pe => (((100 - 20) / 2) + 10) => 50 ;; 5. M -> Pa -> Pe => (((100 / 2) - 20) + 10) => 40 ;; 6. M -> Pe -> Pa => (((100 / 2) + 10) - 20) => 40 ;; ;; ゆえに 40, 45, 50の3通り ;; (b). システムがプロセスに混ざり合って進むことを許した場合 ;; 網羅するいい方法
false