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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b89a401ac01229e39be61ff5c8dca1d7a14d9642
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System.Xml/mono/xml/schema/xsd-key-entry-field.sls
|
6b5df731c3360587e5e98f89eeca62af838c741a
|
[] |
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,822 |
sls
|
xsd-key-entry-field.sls
|
(library (mono xml schema xsd-key-entry-field)
(export new
is?
xsd-key-entry-field?
set-identity-field?
field-found?-get
field-found?-set!
field-found?-update!
field-line-number-get
field-line-number-set!
field-line-number-update!
field-line-position-get
field-line-position-set!
field-line-position-update!
field-has-line-info?-get
field-has-line-info?-set!
field-has-line-info?-update!
field-type-get
field-type-set!
field-type-update!
identity-get
identity-set!
identity-update!
is-xsi-nil?-get
is-xsi-nil?-set!
is-xsi-nil?-update!
field-found-depth-get
field-found-depth-set!
field-found-depth-update!
field-found-path-get
field-found-path-set!
field-found-path-update!
consuming?-get
consuming?-set!
consuming?-update!
consumed?-get
consumed?-set!
consumed?-update!
field)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new Mono.Xml.Schema.XsdKeyEntryField a ...)))))
(define (is? a) (clr-is Mono.Xml.Schema.XsdKeyEntryField a))
(define (xsd-key-entry-field? a)
(clr-is Mono.Xml.Schema.XsdKeyEntryField a))
(define-method-port
set-identity-field?
Mono.Xml.Schema.XsdKeyEntryField
SetIdentityField
(System.Boolean
System.Object
System.Boolean
Mono.Xml.Schema.XsdAnySimpleType
System.Int32
System.Xml.IXmlLineInfo))
(define-field-port
field-found?-get
field-found?-set!
field-found?-update!
()
Mono.Xml.Schema.XsdKeyEntryField
FieldFound
System.Boolean)
(define-field-port
field-line-number-get
field-line-number-set!
field-line-number-update!
()
Mono.Xml.Schema.XsdKeyEntryField
FieldLineNumber
System.Int32)
(define-field-port
field-line-position-get
field-line-position-set!
field-line-position-update!
()
Mono.Xml.Schema.XsdKeyEntryField
FieldLinePosition
System.Int32)
(define-field-port
field-has-line-info?-get
field-has-line-info?-set!
field-has-line-info?-update!
()
Mono.Xml.Schema.XsdKeyEntryField
FieldHasLineInfo
System.Boolean)
(define-field-port
field-type-get
field-type-set!
field-type-update!
()
Mono.Xml.Schema.XsdKeyEntryField
FieldType
Mono.Xml.Schema.XsdAnySimpleType)
(define-field-port
identity-get
identity-set!
identity-update!
()
Mono.Xml.Schema.XsdKeyEntryField
Identity
System.Object)
(define-field-port
is-xsi-nil?-get
is-xsi-nil?-set!
is-xsi-nil?-update!
()
Mono.Xml.Schema.XsdKeyEntryField
IsXsiNil
System.Boolean)
(define-field-port
field-found-depth-get
field-found-depth-set!
field-found-depth-update!
()
Mono.Xml.Schema.XsdKeyEntryField
FieldFoundDepth
System.Int32)
(define-field-port
field-found-path-get
field-found-path-set!
field-found-path-update!
()
Mono.Xml.Schema.XsdKeyEntryField
FieldFoundPath
Mono.Xml.Schema.XsdIdentityPath)
(define-field-port
consuming?-get
consuming?-set!
consuming?-update!
()
Mono.Xml.Schema.XsdKeyEntryField
Consuming
System.Boolean)
(define-field-port
consumed?-get
consumed?-set!
consumed?-update!
()
Mono.Xml.Schema.XsdKeyEntryField
Consumed
System.Boolean)
(define-field-port
field
#f
#f
(property:)
Mono.Xml.Schema.XsdKeyEntryField
Field
Mono.Xml.Schema.XsdIdentityField))
| true |
9ccc250332c62d600f5b567ceaa1517b4b828b85
|
a64e884113e5fdfa0c828154938c60347a51aaa3
|
/04-only-members.scm
|
c86be44d13ff639392112a75d689ae909e96ab25
|
[] |
no_license
|
frankitox/the-reasoned-schemer
|
af817457485d977457e464a570bbac130b4eeba2
|
58647eeb1f3063f8ab2361bfc7d7021ec9e0d1d6
|
refs/heads/master
| 2021-01-20T07:08:47.302962 | 2017-09-18T01:54:39 | 2017-09-18T01:54:39 | 89,967,291 | 4 | 3 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,667 |
scm
|
04-only-members.scm
|
(load "mk.scm")
(load "mkextraforms.scm")
(load "03-seeing-old-friends-in-new-ways.scm")
(define S succeed)
(define U fail)
(define memo
(lambda (x l out)
(conde
((nullo l) U)
((eq-caro l x) (== l out))
(else
(fresh (ll)
(cdro l ll)
(memo x ll out))))))
(run 1 (out)
(memo 'tofu '(a b tofu d tofu e) out))
;; '((tofu d tofu e))
(run 1 (out)
(fresh (x)
(memo 'tofu (list 'a 'b x 'd 'tofu 'e) out)))
;; '((tofu d tofu e))
(run* (r)
(memo r
'(a b tofu d tofu e)
'(tofu d tofu e))) ;; '(tofu)
(run* (q)
(memo 'tofu '(tofu e) '(tofu e))
(== #t q)) ;; (#t)
(run* (q)
(memo 'tofu '(tofu e) '(tofu))
(== #t q)) ;; ()
(run* (x)
(memo 'tofu '(tofu e) (list x 'e)))
;; '(tofu)
(run* (x)
(memo 'tofu '(tofu e) (list 'peas x)))
;; ()
(run* (out)
(fresh (x)
(memo 'tofu (list 'a 'b x 'd 'tofu 'e) out)))
;; '(('tofu 'd 'tofu 'e) ('tofu 'e))
(run 12 (z)
(fresh (u)
(memo
'tofu
(append '(a b tofu d tofu)
(cons 'e z))
u)))
;; _.0
;; _.0
;; '(tofu . _.0)
;; '(_.0 tofu . _.1)
;; '(_.0 _.1 tofu . _.2)
;; and so on...
(define rembero
(lambda (x l out)
(conde
((nullo l) (== () out))
((eq-caro l x) (cdro l out))
((fresh (res)
(fresh (d)
(cdro l d)
(rembero x d res))
(fresh (a)
(caro l a)
(conso a res out)))))))
; (define rembero
; (lambda (x l out)
; (conde
; ((nullo l) (== '() out))
; ((eq-caro l x) (cdro l out))
; (else
; (fresh (a d res)
; (conso a d l)
; (rembero x d res)
; (conso a res out))))))
(run 1 (out)
(fresh (y)
(rembero 'peas
(list 'a 'b y 'd 'peas 'e) out)))
;; '(a b d peas e)
(run* (out)
(fresh (y z)
(rembero y (list 'a 'b y 'd z 'e) out)))
;; ('b 'a 'd _.0 'e)
;; ('a 'b 'd _.0 'e)
;; ('a 'b 'd _.0 'e)
;; ('a 'b 'd _.0 'e)
;; ('a 'b _.0 'd 'e)
;; ('a 'b 'e 'd _.0)
;; ('a 'b _.0 'd _.1 'e)
(run* (r)
(fresh (y z)
(rembero y
(list y 'd z 'e)
(list y 'd 'e))
(== (list y z) r)))
;; ('d 'd)
;; ('d 'd)
;; (_.0 _.0)
;; ('e 'e)
(run 13 (w)
(fresh (y z out)
(rembero
y
(append (list 'a 'b y 'd)
(cons z w))
out)))
;; _.0
;; _.0
;; _.0
;; _.0
;; _.0
;; ()
;; (_.0 . _.1)
;; (_.0 . ())
;; (_.0 _.1 . _.2)
;; (_.0 _.1 . ())
;; (_.0 _.1 _.2 . _.3)
;; (_.0 _.1 _.2 . ())
;; and so on.
(define surpriseo
(lambda (s)
(rembero s '(a b c) '(a b c))))
(run* (r)
(== 'd r)
(surpriseo r))
;; '((a b c))
(run* (r)
(surpriseo r)) ;; (_.0)
(run* (r)
(surpriseo r)
(== r 'a))
| false |
022abdf58ec6249014de9d1d4791faa5d012bece
|
b83ef8d27287a1a6655a2e8e6f37ca2daf5820b7
|
/testsuite/struct_in_union-test.scm
|
9d4ad788b5a5aab9ce9add92016ce4c49c5a64a2
|
[
"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 | 737 |
scm
|
struct_in_union-test.scm
|
;;;
;;; Test struct_in_union
;;;
(use gauche.test)
(test-start "struct_in_union")
(use c-wrapper)
(test-module 'c-wrapper)
(c-include "./struct_in_union.h")
(test "reference"
0
(lambda ()
(ref (ref (ref (make <c-struct:struct_in_union>) 'u) 's1) 'v1)))
(test "set"
1
(lambda ()
(let ((struct (make <c-struct:struct_in_union>)))
(set! (ref (ref (ref struct 'u) 's1) 'v1) 1)
(ref (ref (ref struct 'u) 's1) 'v1))))
(test "a union in an array"
2
(lambda ()
(let ((array (make (<c-struct:struct_in_union> 3))))
(set! (ref (ref (ref (ref array 1) 'u) 's1) 'v1) 2)
(ref (ref (ref (ref array 1) 'u) 's1) 'v1))))
;; epilogue
(test-end)
| false |
85af1695c26e780167e34edfabe3f3ce573f80f3
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System.Xml.Linq/system/xml/linq/xutil.sls
|
2e6296fa019de2c5404389fb91eade39b59a7e2f
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,850 |
sls
|
xutil.sls
|
(library (system xml linq xutil)
(export is?
xutil?
expand-array
to-date-time
get-detached-object
convert-to-boolean?
clone
to-string
to-nullable-boolean
to-boolean?
to-node
xmlns-namespace)
(import (ironscheme-clr-port))
(define (is? a) (clr-is System.Xml.Linq.XUtil a))
(define (xutil? a) (clr-is System.Xml.Linq.XUtil a))
(define-method-port
expand-array
System.Xml.Linq.XUtil
ExpandArray
(static: System.Collections.IEnumerable System.Object))
(define-method-port
to-date-time
System.Xml.Linq.XUtil
ToDateTime
(static: System.DateTime System.String))
(define-method-port
get-detached-object
System.Xml.Linq.XUtil
GetDetachedObject
(static: System.Object System.Xml.Linq.XObject))
(define-method-port
convert-to-boolean?
System.Xml.Linq.XUtil
ConvertToBoolean
(static: System.Boolean System.String))
(define-method-port
clone
System.Xml.Linq.XUtil
Clone
(static: System.Object System.Object))
(define-method-port
to-string
System.Xml.Linq.XUtil
ToString
(static: System.String System.Object))
(define-method-port
to-nullable-boolean
System.Xml.Linq.XUtil
ToNullableBoolean
(static:
"System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
System.Object))
(define-method-port
to-boolean?
System.Xml.Linq.XUtil
ToBoolean
(static: System.Boolean System.Object))
(define-method-port
to-node
System.Xml.Linq.XUtil
ToNode
(static: System.Xml.Linq.XNode System.Object))
(define-field-port
xmlns-namespace
#f
#f
(static:)
System.Xml.Linq.XUtil
XmlnsNamespace
System.String))
| false |
9e1867bd350596e8f8f01642f383e8b945ad2539
|
4bd59493b25febc53ac9e62c259383fba410ec0e
|
/Scripts/Task/first-class-functions-use-numbers-analogously/scheme/first-class-functions-use-numbers-analogously.ss
|
fb73861fda482b9cf5b23599622dde8f5c17fe1f
|
[] |
no_license
|
stefanos1316/Rosetta-Code-Research
|
160a64ea4be0b5dcce79b961793acb60c3e9696b
|
de36e40041021ba47eabd84ecd1796cf01607514
|
refs/heads/master
| 2021-03-24T10:18:49.444120 | 2017-08-28T11:21:42 | 2017-08-28T11:21:42 | 88,520,573 | 5 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 401 |
ss
|
first-class-functions-use-numbers-analogously.ss
|
(define x 2.0)
(define xi 0.5)
(define y 4.0)
(define yi 0.25)
(define z (+ x y))
(define zi (/ (+ x y)))
(define number (list x y z))
(define inverse (list xi yi zi))
(define (multiplier n1 n2) (lambda (m) (* n1 n2 m)))
(define m 0.5)
(define (go n1 n2)
(for-each (lambda (n1 n2)
(display ((multiplier n1 n2) m))
(newline))
n1 n2))
(go number inverse)
| false |
497bb47425cd61cce224fd5b0a0cb31b031cd479
|
c157305e3b08b76c2f4b0ac4f9c04b435097d0dc
|
/AVL_tree/tree-records.scm
|
31b25b63d41661cf85632332e25f2b8a6386c322
|
[] |
no_license
|
rstewart2702/scheme_programs
|
a5e91bd0e1587eac3859058da18dd9271a497721
|
767d019d84896569f2fc02de95925b05a38cac4d
|
refs/heads/master
| 2021-05-02T02:01:01.964797 | 2014-03-31T19:02:36 | 2014-03-31T19:02:36 | 13,077,035 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 119 |
scm
|
tree-records.scm
|
(define tree-x
(new-tree
'(tree-rec "Stewart, Richard" (a b c))
(lambda (x y) (string<? (cadr x) (cadr y))) ) )
| false |
b5fe40ece370bd98ebfa9fc64511e43a6205ab6a
|
6bd63be924173b3cf53a903f182e50a1150b60a8
|
/chapter_1/1.45.scm
|
6c1e33db12dfef3905824086c3e2de7928aff8ac
|
[] |
no_license
|
lf2013/SICP-answer
|
d29ee3095f0d018de1d30507e66b12ff890907a5
|
2712b67edc6df8ccef3156f4ef08a2b58dcfdf81
|
refs/heads/master
| 2020-04-06T13:13:51.086818 | 2019-09-11T11:39:45 | 2019-09-11T11:39:45 | 8,695,137 | 0 | 1 | null | 2016-03-17T13:19:21 | 2013-03-11T02:24:41 |
Scheme
|
UTF-8
|
Scheme
| false | false | 786 |
scm
|
1.45.scm
|
; 1.45
(define (fixed-point f first-guess)
(display first-guess) ; update here
(newline) ; and there
(define (close-enough? a b)
(< (abs (- a b)) 0.0001))
(if (close-enough? (f first-guess) first-guess)
first-guess
(fixed-point f (f first-guess))))
(define (repeated f count)
(if (= count 1)
(lambda (x) (f x))
(lambda (x) (f ((repeated f (- count 1)) x)))))
(define (average-damp f)
(lambda (x) (/ (+ x (f x)) 2)))
(define (sqrt x)
(fixed-point ((repeated average-damp 1) (lambda (y) (/ x y))) 1.0))
; need to write a test function like this
(define (try n x)
(define (log2 a) (/ (log a) (log 2)))
(fixed-point ((repeated average-damp (log2 n)) (lambda (y) (/ x (expt y (- n 1))))) 1.0))
| false |
dc4f28e649713454445931ce84a761d04d411c1b
|
d0f8e92265486bf0a3ac513fa65ab9c92e7d6e10
|
/src/pattern.scm
|
262d8f3492473c13a8bbadf7657d3d7b4e11bc97
|
[
"BSD-3-Clause"
] |
permissive
|
catseye/Treacle
|
b72756e94a09508a811439916f475d5974e31426
|
a7ade79a1675aa38d4138d2708ee0fe38669bbf5
|
refs/heads/master
| 2021-01-23T05:36:07.120720 | 2014-08-19T11:40:26 | 2014-08-19T11:40:26 | 4,618,679 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,471 |
scm
|
pattern.scm
|
;
; Basic data structures for context-rewriting patterns (names, holes, wildcards)
; Chris Pressey, March 2008
;
; Copyright (c)2008 Cat's Eye Technologies. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
;
; 1. Redistributions of source code must retain the above copyright
; notices, this list of conditions and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright
; notices, this list of conditions, and the following disclaimer in
; the documentation and/or other materials provided with the
; distribution.
; 3. Neither the names of the copyright holders nor the names of their
; contributors may be used to endorse or promote products derived
; from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
; ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
; FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
; COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
; BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
; ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
; POSSIBILITY OF SUCH DAMAGE.
;
; Patterns are structured as follows.
;
; Atoms, numbers, and lists are literals, to be matched.
;
; A vector of length 1 where the first and only element is the
; atom 'wildcard' is a wildcard.
;
; A vector of length 3 where the first element is the atom 'named'
; is a named term. The second element is an atom giving the name
; of the term, and the third element gives the subpattern so named.
;
; A vector of length 3 where the first element is the atom 'hole'
; is a hole. The second element indicates the match search order
; to apply inside this hole, either 'innermost' or 'outermost'. The
; third element is the subpattern to be matched inside this hole.
;
(define mk-wildcard
(lambda ()
(vector 'wildcard)))
(define mk-named
(lambda (name subpat)
(vector 'named name subpat)))
(define mk-hole
(lambda (order subpat)
(vector 'hole order subpat)))
(define mk-newref
(lambda ()
(vector 'newref)))
;
; Helper predicate for following predicates.
;
(define is-type?
(lambda (label pattern)
(and (vector? pattern)
(eq? (vector-ref pattern 0) label))))
;
; Return #t if the given pattern is a named pattern, #f otherwise.
;
(define is-named?
(lambda (pattern)
(is-type? 'named pattern)))
;
; Return the name of the given pattern variable.
; Assumes that its input is in fact a pattern variable.
;
(define get-name
(lambda (named-pattern)
(vector-ref named-pattern 1))) ; just return the 2nd element of the vector
;
; Return the name of the given pattern variable.
; Assumes that its input is in fact a pattern variable.
;
(define get-named-subpat
(lambda (named-pattern)
(vector-ref named-pattern 2))) ; just return the 3nd element of the vector
;
; Return #t if the given pattern is a hole, #f otherwise.
;
(define is-hole?
(lambda (pattern)
(is-type? 'hole pattern)))
;
; Return the search order of the given hole.
; Assumes that its input is in fact a hole.
;
(define get-hole-order
(lambda (hole)
(vector-ref hole 1))) ; just return the 2nd element of the vector
;
; Return the subpattern to search for in the given hole.
; Assumes that its input is in fact a hole.
;
(define get-hole-subpat
(lambda (hole)
(vector-ref hole 2))) ; just return the 3rd element of the vector
;
; Return #t if the given pattern is a wildcard, #f otherwise.
;
(define is-wildcard?
(lambda (pattern)
(is-type? 'wildcard pattern)))
;
; Return #t if the given pattern is a newref, #f otherwise.
;
(define is-newref?
(lambda (pattern)
(is-type? 'newref pattern)))
;
; Ground terms are a subset of patterns which may not contain
; wildcards, holes, or named terms.
;
(define is-ground?
(lambda (term)
(cond
((is-wildcard? term)
#f)
((is-hole? term)
#f)
((is-named? term)
#f)
((is-newref? term)
#f)
((null? term)
#t)
((list? term)
(and (is-ground? (car term))
(is-ground? (cdr term))))
((number? term)
#t)
((symbol? term)
#t)
(else
#f))))
;
; Replacements are a subset of patterns which may contain named
; terms, but may not contain wildcards or holes.
;
; In addition, replacements may contain newrefs, which are replaced
; with unique symbols upon expansion.
;
(define is-replacement?
(lambda (term)
(cond
((is-wildcard? term)
#f)
((is-hole? term)
#f)
((is-named? term)
(is-replacement? (get-named-subpat term)))
((is-newref? term)
#t)
((null? term)
#t)
((list? term)
(and (is-replacement? (car term))
(is-replacement? (cdr term))))
((number? term)
#t)
((symbol? term)
#t)
(else
#f))))
| false |
ef219bd07102c030aad5c24d600f83e7e8dddf3e
|
958488bc7f3c2044206e0358e56d7690b6ae696c
|
/scheme/bitcoin/bench-abstract.scm
|
9182cc113b6740b8b20b6e19a134b31879e74ea3
|
[] |
no_license
|
possientis/Prog
|
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
|
d4b3debc37610a88e0dac3ac5914903604fd1d1f
|
refs/heads/master
| 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 |
Coq
|
UTF-8
|
Scheme
| false | false | 1,786 |
scm
|
bench-abstract.scm
|
(load "rand.scm")
(require 'printf)
(define bench-abstract
(let ()
; object created from data is message passing interface
(define (this data)
(lambda (m)
(cond ((eq? m 'run) (run data))
((eq? m 'self) (self data))
(else (error "bench-abstract: unknown instance member" m)))))
;
; static data
(define generator (rand 'new))
;
; static interface
(define (static m . args)
(cond ((eq? m 'new) (apply new args))
((eq? m 'generator) generator)
(else (error "bench-anstract: unknown static member" m))))
;
(define (self data) (cadr data)) ; concrete object
;
(define (run data)
(let ((self (self data)))
(if (equal? #f self)
(error "bench-abstract: run method is abstract")
(self 'run)))) ; running concrete method
;
(define (new self) (this (list 'data self)))
;
; returning static interface
static))
(define (get-random-bytes num-bytes)
((bench-abstract 'generator) 'get-random-bytes num-bytes))
(define (log-message message)
(let ((message (string-append message "\n")))
(let ((len (string-length message)))
(let ((bytes (string->bytes message)) (stderr (current-error-port)))
(write-bytes bytes len stderr)))))
(define (benchmark call-back name iterations)
(let ((start (get-internal-run-time)))
(let loop ((i 0))
(if (< i iterations)
(begin
(call-back)
(loop (+ i 1)))))
(let ((end (get-internal-run-time)))
(fprintf (current-error-port)
"Benchmark: %s, %d iterations ran in %.3f seconds\n"
name
iterations
(/ (- end start) internal-time-units-per-second)))))
| false |
2117ab5c5799fc1f63c7dc4cde5b5289398b5dd1
|
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
|
/scheme/swl1.3/src/swl/preferences.ss
|
acf312eb847319009ac32c4030bdab4adbfd730e
|
[
"SWL",
"TCL"
] |
permissive
|
ktosiu/snippets
|
79c58416117fa646ae06a8fd590193c9dd89f414
|
08e0655361695ed90e1b901d75f184c52bb72f35
|
refs/heads/master
| 2021-01-17T08:13:34.067768 | 2016-01-29T15:42:14 | 2016-01-29T15:42:14 | 53,054,819 | 1 | 0 | null | 2016-03-03T14:06:53 | 2016-03-03T14:06:53 | null |
UTF-8
|
Scheme
| false | false | 9,537 |
ss
|
preferences.ss
|
; Searches for prefs in cwd then in home directory.
; Saves new prefs in home directory.
; Saves updated prefs only to the file from which prefs were loaded on startup.
(define swl:load-preferences)
(define swl:save-preferences!)
(module ()
(import swl:oop)
(import swl:macros)
(import swl:option)
(import swl:threads)
(define *prefs* #f)
(define *prefs-path* #f)
(define prefs-filename ".swlprefs")
(define swlprefs-directory
; returns string or #f
(lambda ()
(or (getenv "SWL_PREFS_DIR")
(case (machine-type)
[(i3nt ppcnt)
(let ([key (format "HKEY_LOCAL_MACHINE\\Software\\Chez Scheme\\swl~a\\SwlPrefsDir" swl:version)])
(cond
[(swl:get-registry key #t)]
[(getenv "APPDATA") =>
(lambda (s) (format "~a\\Scheme Widget Library" s))]
[else
(warning-dialog 'noblock
(format
"Unable to locate SWL preferences file.\n\nSet registry key ~a to path."
key))
#f]))]
[else (or (getenv "HOME") "~")]))))
(define (search-paths) (list current-directory swlprefs-directory))
; cute future implementation would be to represent objects
; as records and use parameterized reader syntax and custom
; print methods to manage the "serialization"
(define unparse
; would be nice to have a serialize method
(lambda (x)
(cond
[(not (instance? x)) x]
[(isa? x <font>)
(with-values (send x get-actual-values)
(lambda (family size style)
`(font (family ,family) (size ,size) (style ,style))))]
[(isa? x <rgb>)
(with-values (send x rgb-values)
(lambda (r g b)
`(rgb ,r ,g, b)))]
[else (assertion-violationf 'swl:set-preference! "unexpected instance ~s" x)])))
(define parse
(lambda (x)
(syntax-case x (font family size style rgb)
[(font (family fam) (size sz) (style st))
(create <font> #'fam #'sz #'st)]
[(rgb r g b)
(make <rgb> #'r #'g #'b)]
[else x])))
(define map-prefs
(lambda (convert prefs)
(map (lambda (app-prefs)
(cons (car app-prefs)
(map (lambda (kv) (cons (car kv) (convert (cdr kv))))
(cdr app-prefs))))
prefs)))
(define read-preferences
(lambda (filename)
(on-error #f
(map-prefs parse
(with-input-from-file filename
(lambda ()
(let ([x (read)])
(if (eof-object? x) '() x))))))))
(define write-preferences
(lambda (filename)
; perhaps should lock file
(with-output-to-file filename
(lambda ()
(display "; SWL preferences (automatically generated file, manual edits may be lost)\n")
(pretty-print (map-prefs unparse *prefs*)))
'truncate)))
; seems this should just be (define m (make <sem> 1)) but see the mail
; I sent to Kent (titled "surprise") about strangeness of visit evaluating
; the rhs of non-compile-time things within a module.
;** Actually, we might need this anyway since we probably can't make a
;** sem until we've run install-thread-system.
(module (m)
(define m "tut, tut, you didn't call swl:init-preferences-hack")
(set! swl:init-preferences-hack
(lambda ()
(set! m (make <sem> 1))
(when (memq (machine-type) '(i3nt ppcnt))
(set! swl:get-registry
(let ()
(define expand-key
(lambda (s)
(let ([ip (open-input-string s)] [op (open-output-string)])
(let f ()
(let ([c (read-char ip)])
(if (eof-object? c)
(get-output-string op)
(begin
(case c
[(#\\) (write-char #\/ op)]
[(#\%)
(let ([c (read-char ip)])
(if (eof-object? c)
(write-char #\% op)
(case c
[(#\u)
(display
(or (getenv "USERNAME") "user")
op)]
[(#\t)
(display
(or (getenv "TEMP") "c:/temp")
op)]
[else
(write-char #\% op)
(write-char c op)])))]
[else (write-char c op)])
(f))))))))
(rec swl:get-registry
(case-lambda
[(s) (swl:get-registry s #f)]
[(s expand?)
(let ([s (get-registry s)])
(if (and (string? s) expand?)
(expand-key s)
s))])))))))
)
(define warn-prefs
(lambda (verb msg)
(warning-dialog 'noblock (format "Unable to ~s preferences.\n\n~a" verb msg))))
(define complain
; could arrange to put swl:version in at compile time...
(lambda (filenames . args)
(apply string-append
(append args
(map (lambda (name)
(format "File ~a exists, but is not recognizable as SWL ~a preferences file.\n" name swl:version))
filenames)))))
(define make-path
(lambda (dir)
(and dir (string-append dir "/" prefs-filename))))
(define (shallow-copy x)
(if (pair? x)
(cons (car x) (shallow-copy (cdr x)))
x))
(set! swl:load-preferences
(lambda (tag)
(define (default-prefs msg) (warn-prefs 'load msg) '())
(with-mutex m
(unless *prefs*
(set! *prefs*
(on-error (with-message msg (default-prefs msg))
(let loop ([ps (search-paths)] [files '()])
(if (null? ps)
(if (null? files)
'()
(default-prefs (complain (reverse files))))
(let ([filename (make-path ((car ps)))])
(if (and filename (file-exists? filename))
(let ([prefs (read-preferences filename)])
(if prefs
(begin
(set! *prefs-path* filename)
(unless (null? files)
(warning-dialog 'noblock
(complain (reverse files) "Using preferences from " filename ".\n\n")))
prefs)
(loop (cdr ps) (cons filename files))))
(loop (cdr ps) files))))))))
(cond
[(assq tag *prefs*) => (lambda (a) (map shallow-copy (cdr a)))]
[else '()]))))
(set! swl:save-preferences!
(lambda (tag als)
(define do-save
(lambda ()
(unless (string? *prefs-path*) (assertion-violationf #f "internal error in preference code (expected *prefs-path* to be set by now)"))
(let ([path *prefs-path*])
(if (file-exists? path)
(if (read-preferences path)
(write-preferences path)
(warn-prefs 'save
(complain (list path) "Unwilling to overwrite file " path ".\n\n")))
(write-preferences path)))))
(with-mutex m
(on-error (with-message msg (warn-prefs 'save msg))
(if *prefs*
(let ([a (assq tag *prefs*)] [new (map shallow-copy als)])
(if a
(set-cdr! a new)
(set! *prefs* (cons (cons tag new) *prefs*))))
(set! *prefs* (list (cons tag (map shallow-copy als)))))
(if *prefs-path*
(do-save)
(let* ([directory (swlprefs-directory)]
[filename (make-path directory)])
(if (not filename)
(warn-prefs 'save "unable to determine directory in which to save preferences.")
(if (file-exists? filename)
(warn-prefs #f
(format "Saving preferences would overwrite the file ~a that was not present or not recognized as a SWL ~a preferences file when preferences were loaded on startup.\n\nPlease rename that file and try again."
filename swl:version))
(begin
(unless (file-exists? directory)
(case (machine-type)
[(i3nt ppcnt)
(let ([dosdir (list->string
(substv #\\ #\/
(string->list directory)))])
(system (format "mkdir ~s" dosdir)))]
[else (system (format "mkdir -p ~s" directory))]))
(set! *prefs-path* filename)
(do-save))))))))))
)
#!eof
or just store the whole file as a single string in the registry?
(only affects read and write preferences then)
(swl:tcl-eval 'package 'require 'registry 1.0)
(format "HKEY_CURRENT_USER\\SWLRC\\~a\\~a" application key)
print result of (format "~s" data) as type sz
#!eof
(repl text-font (font (family helvetica) (points 10) (style bold)))
(repl text-foreground 'blue)
(repl text-background (rgb 100 0 102))
(repl text-hilight 'gray)
(repl use-the-box #f)
(repl wrap-lines #f)
| false |
9250e42147fb6c5302ec8703e6db7d6e550d64b4
|
435ca18a711b537aead4a73807b206ff99f57785
|
/tests/closure.scm
|
969b79f6ebcd26bcebefe791a92413924dd8caac
|
[] |
no_license
|
mushrom/schemecc
|
59c961dc8ae85a4ea8089e62d6a1e1272fe487a9
|
cb3c7a48a9feaf134b297dcb9ae181909f4e1451
|
refs/heads/master
| 2021-01-01T05:17:44.911566 | 2016-05-18T02:58:16 | 2016-05-18T02:58:16 | 57,012,633 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 416 |
scm
|
closure.scm
|
(import (scheme base))
(let ((x (+ 5 5))
(double
(lambda (y) (+ y y)))
(add
(lambda (x y)
(begin
(+ (+ x x) y)
(+ (+ x x) y)
(+ (+ x x) y))
(+ x y)))
(curry
(lambda (x)
(lambda (y)
(lambda ()
(+ x y))))))
(+ x 1)
(if (> x 5)
(double (((curry x) 10)))
(add 20 22)))
| false |
4f6faa718bfd749031d25f80f3f2c0e5f94b5889
|
d074b9a2169d667227f0642c76d332c6d517f1ba
|
/sicp/lib/amb-eval.scm
|
3545a867684e1eaa66b4922c92b43fb616e5c14d
|
[] |
no_license
|
zenspider/schemers
|
4d0390553dda5f46bd486d146ad5eac0ba74cbb4
|
2939ca553ac79013a4c3aaaec812c1bad3933b16
|
refs/heads/master
| 2020-12-02T18:27:37.261206 | 2019-07-14T15:27:42 | 2019-07-14T15:27:42 | 26,163,837 | 7 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 14,067 |
scm
|
amb-eval.scm
|
;; (put 'scheme-define 'scheme-indent-function 1)
(module amb-eval
(eval eval
setup-environment
compound-procedure?)
(import
(only scheme
* + - / < = > abs and append caadr caar cadddr caddr cadr car
cdadr cdddr cddr cdr cond cons define eq? if lambda length let
list map member not null? number? or pair? quote set! set-car!
set-cdr! string? symbol?)
(prefix (only scheme apply) scheme-) ; scheme-apply
(only chicken error use exit))
(use (only extras printf random))
(use (only data-structures shuffle))
(use (only srfi-1 zip))
(define (eval exp env succeed fail)
((analyze exp) env succeed fail))
(define (analyze exp)
(cond ((self-evaluating? exp) (analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((p-assignment? exp) (analyze-p-assignment exp))
((definition? exp) (analyze-definition exp))
((if? exp) (analyze-if exp))
((lambda? exp) (analyze-lambda exp))
((begin? exp) (analyze-sequence exp))
((cond? exp) (analyze (cond->if exp)))
((let? exp) (analyze (let->combination exp)))
((amb? exp) (analyze-amb exp))
((ramb? exp) (analyze-ramb exp))
((application? exp) (analyze-application exp))
((eq? #!eof exp) (printf "~Ndone~N") (exit))
(else
(error "Unknown expression type -- EVAL" exp))))
;; Simple Aliases:
(define application? pair?)
(define assignment-value caddr)
(define assignment-variable cadr)
(define cond-actions cdr)
(define cond-clauses cdr)
(define cond-predicate car)
(define false #f)
(define first-exp car)
(define first-frame car)
(define first-operand car)
(define if-consequent caddr)
(define if-predicate cadr)
(define lambda-body cddr)
(define lambda-params cadr)
(define let-body cddr)
(define let-params cadr)
(define no-operands? null?)
(define null '())
(define operands cdr)
(define operator car)
(define primitive-implementation cadr)
(define procedure-body caddr)
(define procedure-environment cadddr)
(define procedure-params cadr)
(define rest-exps cdr)
(define rest-frames cdr)
(define rest-operands cdr)
(define text-of-quotation cadr)
(define the-empty-environment null)
(define true #t)
;; Other Values:
(define primitive-procedures
(list (list '* *)
(list '+ +)
(list '- -)
(list '/ /)
(list '= =)
(list '> >)
(list 'abs abs)
(list 'car car)
(list 'cdr cdr)
(list 'cons cons)
(list 'eq? eq?)
(list 'list list)
(list 'member member)
(list 'printf printf)
(list 'not not)
(list 'null? null?)))
;; Support Functions (sorted):
(define (add-binding-to-frame! var val frame)
(set-cdr! frame (cons (car frame) (cdr frame)))
(set-car! frame (list var val)))
(define (amb-choices exp) (cdr exp))
(define (ramb-choices exp) (shuffle (cdr exp) random))
(define (amb? exp) (tagged-list? exp 'amb))
(define (ramb? exp) (tagged-list? exp 'ramb))
(define (analyze-amb exp)
(let ((cprocs (map analyze (amb-choices exp))))
(lambda (env succeed fail)
(define (try-next choices)
(if (null? choices) (fail)
((car choices) env
succeed
(lambda () (try-next (cdr choices))))))
(try-next cprocs))))
(define (analyze-ramb exp) ; REFACTOR: against analyze-amb
(let ((cprocs (map analyze (ramb-choices exp))))
(lambda (env succeed fail)
(define (try-next choices)
(if (null? choices) (fail)
((car choices) env
succeed
(lambda () (try-next (cdr choices))))))
(try-next cprocs))))
(define (analyze-application exp)
(let ((fproc (analyze (operator exp)))
(aprocs (map analyze (operands exp))))
(lambda (env succeed fail)
(fproc env
(lambda (proc fail2)
(get-args aprocs
env
(lambda (args fail3)
(execute-application proc args succeed fail3))
fail2))
fail))))
(define (analyze-assignment exp)
(let ((var (assignment-variable exp))
(vproc (analyze (assignment-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(let ((old-value (lookup-variable-value var env)))
(set-variable-value! var val env)
(succeed 'ok
(lambda ()
(set-variable-value! var old-value env)
(fail2)))))
fail))))
(define (analyze-p-assignment exp)
(let ((var (assignment-variable exp))
(vproc (analyze (assignment-value exp))))
(lambda (env succeed fail)
(set-variable-value! var (vproc env succeed fail) env)
(succeed 'ok fail))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(set-variable-value! var val env)
(succeed 'ok (lambda () (fail2))))
fail))))
(define (analyze-definition exp)
(let ((var (definition-variable exp))
(vproc (analyze (definition-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(define-variable! var val env)
(succeed 'ok fail2))
fail))))
(define (analyze-if exp)
(let ((pproc (analyze (if-predicate exp)))
(cproc (analyze (if-consequent exp)))
(aproc (analyze (if-alternative exp))))
(lambda (env succeed fail)
(pproc env
;; success continuation for evaluating the predicate to obtain pred--value
(lambda (pred-value fail2)
(if (true? pred-value)
(cproc env succeed fail2)
(aproc env succeed fail2)))
fail))))
(define (analyze-lambda exp)
(let ((vars (lambda-params exp))
(bproc (analyze-sequence (lambda-body exp))))
(lambda (env succeed fail)
(succeed (make-procedure vars bproc env) fail))))
(define (analyze-quoted exp)
(let ((val (text-of-quotation exp)))
(lambda (env succeed fail)
(succeed val fail))))
(define (analyze-self-evaluating exp)
(lambda (env succeed fail) (succeed exp fail)))
(define (analyze-sequence exps)
(define (sequentially p1 p2)
(lambda (env succeed fail)
(p1 env (lambda (a-value fail2) (p2 env succeed fail2)) fail)))
(define (loop p1 p*)
(if (null? p*) p1
(loop (sequentially p1 (car p*)) (cdr p*))))
(let ((procs (map analyze exps)))
(if (null? procs)
(error "Empty sequence -- ANALYZE"))
(loop (car procs) (cdr procs))))
(define (analyze-variable exp)
(lambda (env succeed fail)
(succeed (lookup-variable-value exp env) fail)))
(define (apply-primitive-procedure proc args)
(scheme-apply (primitive-implementation proc) args))
(define (assignment? exp)
(tagged-list? exp 'set))
(define (p-assignment? exp)
(tagged-list? exp 'permanent-set))
(define (begin? exp)
(tagged-list? exp 'begin))
(define (compound-procedure? exp)
(tagged-list? exp 'proc))
(define (cond->if exp)
(expand-clauses (cond-clauses exp)))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond? exp)
(tagged-list? exp 'cond))
(define (define-variable! var val env)
(let ((pair (find-pair-in-frame (first-frame env) var)))
(if (null? pair)
(add-binding-to-frame! var val (first-frame env))
(set-cdr! pair (list val)))))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(make-lambda (cdadr exp) ; params
(cddr exp)))) ; body
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
(define (definition? exp)
(tagged-list? exp 'define))
(define (eval-sequence exps env)
(cond ((last-exp? exps) (eval (first-exp exps) env))
(else (eval (first-exp exps) env)
(eval-sequence (rest-exps exps) env))))
(define (execute-application proc args succeed fail)
(cond ((primitive-procedure? proc)
(succeed (apply-primitive-procedure proc args) fail))
((compound-procedure? proc)
((procedure-body proc)
(extend-environment (procedure-params proc)
args
(procedure-environment proc))
succeed fail))
(else
(error "Unknown procedure type -- APPLY" proc))))
(define (expand-clauses clauses)
(if (null? clauses) 'false
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last --COND->IF" clauses))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (find-pair-in-env env var)
(if (eq? env the-empty-environment) null
(let ((pair (find-pair-in-frame (first-frame env) var)))
(if (null? pair) (find-pair-in-env (rest-frames env) var)
pair))))
(define (find-pair-in-frame frame var)
(cond ((null? frame) null)
((eq? var (caar frame)) (car frame))
(else (find-pair-in-frame (cdr frame) var))))
(define (get-args aprocs env succeed fail)
(if (null? aprocs) (succeed '() fail)
((car aprocs) env (lambda (arg fail2)
(get-args (cdr aprocs)
env
(lambda (args fail3)
(succeed (cons arg args) fail3))
fail2))
fail)))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))
(define (if? exp)
(tagged-list? exp 'if))
(define (lambda? exp)
(tagged-list? exp 'lambda))
(define (last-exp? seq)
(null? (cdr seq)))
(define (let->call args vals body)
(append (list (append (list 'lambda args) body)) vals))
(define (let->combination exp)
(let->call (let-args exp) (let-vals exp) (let-body exp)))
(define (let-args exp)
(map car (let-params exp)))
(define (let-vals exp)
(map cadr (let-params exp)))
(define (let? exp)
(tagged-list? exp 'let))
(define (list-of-values exps env)
(if (no-operands? exps) null
(cons (eval (first-operand exps) env)
(list-of-values (rest-operands exps) env))))
(define (lookup-variable-value var env)
(let ((pair (find-pair-in-env env var)))
(if (null? pair)
(error "Unbound variable" var)
(cadr pair))))
(define (make-begin seq)
(cons 'begin seq))
(define (make-frame vars vals)
(zip vars vals))
(define (make-if predicate consequent alternative)
(if alternative
(list 'if predicate consequent alternative)
(list 'if predicate consequent)))
(define (make-lambda params body)
(append (list 'lambda params) body))
(define (make-procedure params body env)
(list 'proc params body env))
(define (primitive-procedure-names) (map car primitive-procedures))
(define (primitive-procedure-objects)
(map (lambda (x) (list 'prim (cadr x))) primitive-procedures))
(define (primitive-procedure? exp)
(tagged-list? exp 'prim))
(define (quoted? exp)
(tagged-list? exp 'quote))
(define (self-evaluating? exp)
(or (number? exp) (string? exp)))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq)
(first-exp seq))
(else (make-begin seq))))
(define (set-variable-value! var val env)
(let ((pair (find-pair-in-env env var)))
(if (null? pair)
(error "Unbound variable -- SET!" var)
(set-cdr! pair (list val)))))
(define (setup-environment)
(let ((initial-env (extend-environment (primitive-procedure-names)
(primitive-procedure-objects)
the-empty-environment)))
(define-variable! 'true true initial-env)
(define-variable! 'false false initial-env)
initial-env))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (true? exp)
(not (eq? exp false)))
(define (variable? exp) (symbol? exp))
)
| false |
963caa7f37a260af5153ae9f7040d36743ba80bf
|
c085780da34766c02f47f181bd8a7bb515126caa
|
/lab7 string.scm
|
4d60fddf79516f98dec8c08ef8b0b83cedf28193
|
[] |
no_license
|
juleari/r5rs
|
37ede50989e59b0936f7aac2b204cb9affa22d21
|
880b0df41e94c103386c158cc172b658f485a465
|
refs/heads/master
| 2016-09-16T17:23:42.192923 | 2016-05-04T11:58:18 | 2016-05-04T11:58:18 | 42,339,524 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,128 |
scm
|
lab7 string.scm
|
(define (string-trim-left str)
(define (trim-left xs)
(let ((x (car xs)))
(if (or (eqv? x #\space)
(eqv? x #\newline)
(eqv? x #\tab))
(trim-left (cdr xs))
xs)))
(list->string (trim-left (string->list str))))
(define (string-trim-right str)
(list->string
(reverse (string->list (string-trim-left (list->string (reverse (string->list str))))))))
(define (string-trim str)
(string-trim-left (string-trim-right str)))
(define (string-prefix? a b)
(let ((as (string->list a))
(bs (string->list b)))
(or (null? as)
(and (not (null? bs))
(eqv? (car as) (car bs))
(string-prefix? (list->string (cdr as)) (list->string (cdr bs)))))))
(define (string-suffix? a b)
(string-prefix? (list->string (reverse (string->list a)))
(list->string (reverse (string->list b)))))
(define (string-infix? a b)
(let ((bs (string->list b)))
(and (not (null? bs))
(or (string-prefix? a b)
(string-infix? a (list->string (cdr bs)))))))
(define (string-split str sep)
(define (trim-sep str len)
(if (= 0 len)
str
(trim-sep (list->string (cdr (string->list str))) (- len 1))))
(define (helper ss str)
(cond ((null? (string->list str)) (list (list->string ss)))
((string-prefix? sep str) (cons (list->string ss)
(helper '() (trim-sep str (string-length sep)))))
(else (helper (append ss (list (car (string->list str))))
(list->string (cdr (string->list str)))))))
(helper '() str))
;; tests
(string-trim-left "\t\tabc def")
(string-trim-right "abc def\t")
(string-trim "\t abc def \n")
(string-prefix? "abc" "abcdef")
(string-prefix? "bcd" "abcdef")
(string-suffix? "def" "abcdef")
(string-suffix? "bcd" "abcdef")
(string-infix? "def" "abcdefgh")
(string-infix? "abc" "abcdefgh")
(string-infix? "fgh" "abcdefgh")
(string-infix? "ijk" "abcdefgh")
(string-split "x;y;z" ";")
(string-split "x-->y-->z" "-->")
| false |
7f332e6a1e152f7c413dde6431019f5a6e2b1671
|
a6d6b0f9c9a754d58ed7ec03a1a8770c7a5808e7
|
/4.2.scm
|
4d7077438f50b5a304c62dcc281601599b8cfd06
|
[] |
no_license
|
andreqwert/functional_programming
|
acea3a0f36dfbf0d0023410187b27ef6d92338b3
|
0ac415bde27f97bfe3c8d8a34cc6f8abff48af57
|
refs/heads/master
| 2020-03-28T02:29:01.391252 | 2018-12-07T22:45:11 | 2018-12-07T22:45:11 | 147,573,403 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 920 |
scm
|
4.2.scm
|
; Возвращает список, полученный путем вставки элемента e между элементами списка xs
(define (intersperse e xs)
(cond ((null? xs) '()) ; если список пустой - вывести пустой список
(else (cond ((null? (cdr xs)) xs) ; если хвост списка пустой, вывести текущий список
(else
; сконструировать список из первого элемента текущего списка и
; (сконструировать из элемента e и переданной на вход рекурсивно функции от оставшихся
; элементов списка)
(cons (car xs) (cons e (intersperse e (cdr xs)))))))))
(intersperse 'x '(1 2 3 4))
| false |
3501d6e8b0083e347062452818d9976bb3f92230
|
8ebb8dfb17ecafdb8becb6251c456eaf82a5f514
|
/lib/bytecode.scm
|
66d272ff432844d3268fdf955a8eb4ae4a2c889c
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
DemiMarie/rusty_scheme
|
cf5abd908000e21d191ba3be072157914415f900
|
b1291b921de317eb29effe3062ae94c003370e2c
|
refs/heads/master
| 2020-04-12T05:33:35.560463 | 2016-10-03T02:12:49 | 2016-10-03T02:12:49 | 62,069,176 | 27 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,833 |
scm
|
bytecode.scm
|
;;;; bytecode.scm – bytecode objects and bytecode generation
;;;
;;; This library defines the type of bytecode objects. It also defines
;;; operations for appending bytecodes.
(import
(rnrs)
(only (srfi :1) proper-list?)
(srfi :9)
(only (srfi :43) vector-copy)
(only (srfi :69) make-hash-table hash-table-ref hash-table-set!))
(define-record-type :bco
(make-bco len instrs consts consts-len stack-depth memo counter)
bco?
(len bco.len len-set!)
(instrs bco.instrs instrs-set!)
(consts bco.consts consts-set!)
(consts-len bco.consts-len consts-len-set!)
(stack-depth stack-depth stack-depth-set!)
(memo memo)
(counter counter counter-set!))
(define (create-bco)
(make-bco 0 '#() '#(#f) 0 0 (make-hash-table) 0))
;; Add `object` to the constant vector of `bco`.
;; Returns the index of `object` in the constant vector of `bco`.
;; `object` must not be modified afterwords.
(define (add-to-constant-vector bco object)
(assert (not (procedure? object)))
(let ((constants (bco.consts bco))
(bco-consts-len (bco.consts-len bco)))
(assert (fixnum? bco-consts-len))
(let ((capacity (vector-length constants)))
(vector-set!
(if (= bco-consts-len capacity)
(let ((new-vector
(vector-copy constants
0
(+ 3 (* 2 capacity)) #f)))
(consts-set! bco new-vector)
new-vector)
constants)
bco-consts-len object)
(consts-len-set! bco (+ 1 bco-consts-len))
bco-consts-len)))
(define (emit bco . opcode)
(assert (bco? bco))
(let ((bytecode (bco.instrs bco))
(bco-len (bco.len bco)))
(let ((capacity (vector-length bytecode)))
(vector-set!
(cond
((= bco-len capacity)
(let ((new-vector (vector-copy bytecode 0 (+ 3 (* 2 bco-len)) #f)))
(instrs-set! bco new-vector)
new-vector))
((< bco-len capacity)
bytecode)
(else
(assert #f)))
bco-len opcode)
(len-set! bco (+ 1 bco-len))
bco-len)))
(define (emit-stack-reset bco depth)
(emit bco 'stack-reset depth)
(stack-depth-set! bco depth))
(define (emit-load bco arg)
(if (pair? arg)
(case (cdr arg)
((argument) (emit bco 'load-argument (car arg)))
((global primitive) (emit bco 'load-global (car arg)))
((()) (emit bco 'load-environment (car arg)))
(else (error 'assert "bad cdr of arg to be loaded" arg)))
(emit bco 'load-environment arg)))
(define (emit-global bco symbol)
(emit bco 'global-load symbol)
(let ((new-depth (+ 1 (stack-depth bco))))
(stack-depth-set! bco new-depth)
new-depth))
;; Emit bindings.
;; Args: `bco` = bytecode object, `variables` = variables being bound
;; `env` = environment
(define (emit-bindings bco variables expressions env compile-form old-val)
(assert (proper-list? variables))
(assert (proper-list? expressions))
(assert (= (length variables) (length expressions)))
(let ((depth (stack-depth bco)))
(for-each
(lambda (var expr old-val)
(compile-form expr)
(if (> (stack-depth bco) depth)
(emit bco 'adjust-stack (- (stack-depth bco) depth)))
(set! depth (+ 1 depth))
(stack-depth-set! bco depth)
(hash-table-set! env var (cons depth old-val)))
variables expressions old-val)
depth))
(define (emit-variable-reference bco stack-position)
(assert (bco? bco))
(let ((new-stack-depth (+ 1 (stack-depth bco))))
(stack-depth-set! bco new-stack-depth)
(cond
((symbol? stack-position)
(emit bco 'global-load stack-position))
((fixnum? stack-position)
(emit bco 'load stack-position))
(else (assert #f)))))
(define (emit-constant bco object)
(case object
((#f) (emit bco 'load-f))
((#t) (emit bco 'load-t))
((0) (emit bco 'load-0))
((1) (emit bco 'load-1))
(else
(if (null? object)
(begin
(emit bco 'load-nil))
;; Memoize the objects using the bytecode object's memo table
(let ((index (hash-table-ref (memo bco) object (lambda () #f))))
(emit bco
'load-constant-index
(if index
index
(begin
(add-to-constant-vector bco object)
(let ((len (bco.consts-len bco)))
(hash-table-set! (memo bco) object len)
len)))))))))
(define (emit-set! bco stack-position)
(cond
((symbol? stack-position)
(emit bco 'global-load stack-position))
((fixnum? stack-position)
(emit bco 'store-environment stack-position))
((pair? stack-position)
(case (cdr stack-position)
((argument)
(emit bco 'store-argument (car stack-position)))
((global)
(emit bco 'store-global (car stack-position)))
(else (assert #f))))
(else
(error 'assert "invalid stack position" stack-position))))
(define (emit-lambda-definition bco variadic? fixed-args body)
(let ((stack-position (stack-depth bco))
(label-start (incr-counter bco))
(label-end (incr-counter bco)))
(emit bco 'closure fixed-args variadic? label-end)
(body)
(emit bco 'label label-end)))
(define (incr-counter bco)
(let ((old-val (counter bco)))
(counter-set! bco (+ 1 old-val))
old-val))
;; Emit a jump.
(define (emit-jump bco condition yes no)
(let ((stack-position (+ 1 (stack-depth bco)))
(label-true (incr-counter bco))
(label-false (incr-counter bco)))
(condition)
(emit bco 'branch label-true)
(no)
(emit bco 'jump label-false)
(emit bco 'label label-true)
(yes)
(emit bco 'label label-false)))
;;; Local Variables:
;;; mode: scheme
;;; End:
| false |
6b71d606b33c49ef65264210f7b89cb79d2a6f55
|
1207c1b1be1eda2063389ca07840846ef67ce768
|
/homework4.scm
|
58c857325ec5e6ca8f8ac5def27ba6773b473644
|
[] |
no_license
|
hetaalll/Rutgers-Prin-Prog-314
|
b68fb77ca40e38cfbf669af43976a65b9ca3808a
|
3ab470f8cf5be1794317413d2f0d6e78f7ac92af
|
refs/heads/master
| 2020-03-22T12:11:05.562500 | 2018-07-06T19:41:21 | 2018-07-06T19:41:21 | 140,022,830 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,989 |
scm
|
homework4.scm
|
;; 1. a b c --> a a b b c c
;; a (b c) --> a a (b c) (b c)
(define (echo lst)
(if (null? lst) '()
(cons (car lst) (cons (car lst) (echo (cdr lst)))) );;print first element twice, then call the function again on the rest of the list
) ;;end define
;; 2. a (b c) 3 --> (a a a (b c) (bc) (bc))
(define (echo-lots lst n)
(if (null? lst) '()
(let loop ((i (- n 1)) (lt (car lst))) ;; loop for n-1 times and print the first element
(if (zero? i)
(cons lt (echo-lots (cdr lst) n)) ;;if i==0; start again with the rest of the list
(cons lt (loop (- i 1) lt)))))) ;; else loop till i==0
;; 3. (a (b c)) --> (a a (b b c c) (b b c c))
(define (echo-all lst)
(if (null? lst) '()
(if (not (list? (car lst))) ;;end not
(cons (car lst) (cons (car lst) (echo-all (cdr lst) ) ) ) ;;if not a list, print first element twice, call the function on rest of the list
;;end first cons if not a list
(cons (echo (car lst)) (cons (echo (car lst)) (echo-all (cdr lst))) ) ) ) ;;if list, duplicate list, then duplicate inside
;;then call the function of the rest of the list
) ;;end define
;; 4. (nth 0 '(a b c)) --> a
(define (nth i lst)
(if (null? lst) '()
(if(= i 0) (car lst) ;;is it the first element?
(nth (- i 1) (cdr lst))));;no? go to the rest of the list
) ;;end define
;;5. (assoc-all '(a d c d) '((a apple)(b boy)(c (cat cow))(d dog)))
(define assoc-all (lambda (keys a-list)
(if(null? keys) '() ;;if keys is null
(map (lambda (keys)
(if(not(assoc keys a-list)) '() ;;if a certain key is not present
(cadr(assoc keys a-list)))) keys)))) ;;cadr to get apple from (a apple)
;;6. filter even numbers out '(3 4 5) --> (4)
(define (filter fn lst)
(if (null? lst) '()
(if(fn(car lst)) (cons (car lst) (filter fn (cdr lst))) ;;if #t for fn, then add to the output
(filter fn (cdr lst)));else go to the rest of the list
));end define
| false |
d450afb67c86d8c83771e82e32b19a1371700efa
|
d37f41737effcc07eb2bda1e3c4f54ac02aa7afa
|
/sanitize.ss
|
9dfd30cc0c1e46ea333a797df0c2e20b594f087a
|
[] |
no_license
|
plt/planet-server
|
ea3cae6f59679e98df0cff1639fb4a0b12e821cd
|
a8074909b4c570b750a47e19d8d27d6c7c27ed92
|
refs/heads/master
| 2020-12-24T15:49:51.488474 | 2016-03-10T03:00:07 | 2016-03-10T03:00:07 | 4,863,599 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,607 |
ss
|
sanitize.ss
|
#lang scheme/base
#|
This cuts out unrecognized html tags and attributes from xexprs to try to prevent XSS attacks.
|#
(require scheme/match xml)
(provide sanitize)
(define good-tags
'(a abbr acronym address area b big blockquote br button caption center cite code col colgroup dd del dfn dir div dl dt em fieldset font form h1 h2 h3 h4 h5 h6 hr i img input ins kbd label legend li map menu ol optgroup option p pre q s samp select small span strike strong sub sup table tbody td textarea tfoot th thead tr tt u ul var))
(define good-attributes
'(abbr accept accept-charset accesskey action align alt axis border cellpadding cellspacing char charoff charset checked cite class clear cols colspan color compact coords datetime dir disabled enctype for frame headers height href hreflang hspace id ismap label lang longdesc maxlength media method multiple name nohref noshade nowrap prompt readonly rel rev rows rowspan rules scope selected shape size span src start summary tabindex target title type usemap valign value vspace width))
(define tag-ht (make-hasheq))
(for-each (λ (x) (hash-set! tag-ht x #t)) good-tags)
(define (good-tag? x) (hash-ref tag-ht x #f))
(define attr-ht (make-hasheq))
(for-each (λ (x) (hash-set! attr-ht x #t)) good-attributes)
(define (good-attribute? x) (hash-ref attr-ht x #f))
(define (sanitize xexpr)
(match xexpr
[`(pre ,attrs ,stuff ...)
`(tt ,@(apply append (map split-newlines stuff)))]
[`(,tag ((,attrs ,bindings) ...) ,stuff ...)
(if (good-tag? tag)
`(,tag ,(filter-attrs attrs bindings) ,@(map sanitize stuff))
`(div ,@(map sanitize stuff)))]
[`(,tag ,stuff ...)
(if (good-tag? tag)
`(,tag ,@(map sanitize stuff))
`(div ,@(map sanitize stuff)))]
[else
(if (or (string? xexpr)
(symbol? xexpr)
(exact-nonnegative-integer? xexpr)
(cdata? xexpr)
(comment? xexpr)
(pcdata? xexpr))
xexpr
"")]))
(define (filter-attrs attrs bindings)
(filter (λ (x) (good-attribute? (car x)))
(map list attrs bindings)))
(define (split-newlines stuff)
(cond
[(string? stuff)
(let ([strs (regexp-split #rx"\n" stuff)])
(if (or (null? strs) (null? (cdr strs)))
strs
(let loop ([str (car strs)]
[strs (cdr strs)])
(cond [(null? strs) (list str)]
[else (list* str '(br) (loop (car strs) (cdr strs)))]))))]
[else (list stuff)]))
#|
(sanitize "x")
(sanitize `(abbr ((style "x") (href "y")) nbsp))
(sanitize `(abbr (script ((style "x") (href "y")) nbsp)))
|#
| false |
e4ef35281c876728d760d5363617e243c9e9c36e
|
0bc4163b3571382861380e47eef4aa1afc862024
|
/scheme/geometry/point.scm
|
c4722fb9fd3ec55fa3f801dd17993d95ef968d7b
|
[] |
no_license
|
mjgordon/fluxcadd
|
49f7c633d4430d98cfa0f24485bfc737fac1a321
|
afedf70e8a9b43563bb3fe5fdc2265260f4a981b
|
refs/heads/master
| 2023-07-21T10:19:36.544424 | 2023-07-08T00:19:06 | 2023-07-08T00:19:06 | 84,756,384 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 230 |
scm
|
point.scm
|
(import "utility.Util")
(define (add-point point)
(.add geometry point))
(define (point x y z)
(let ((p (Point. (Util.explicitFloat x)
(Util.explicitFloat y)
(Util.explicitFloat z))))
(.add geometry p)
p))
| false |
982c4ed3b8186b99749cfef957bbd7c9eb537005
|
b9eb119317d72a6742dce6db5be8c1f78c7275ad
|
/racket/web/xml-versus-ssax-comparison.ss
|
a369b9366d7f6224f99d8a2dedcab2f541aa39ed
|
[] |
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,164 |
ss
|
xml-versus-ssax-comparison.ss
|
#lang scheme
(require (only-in (planet lizorkin/ssax/ssax) ssax:xml->sxml)
xml)
(define (collapse-adjacent-strings seq)
(if (list? seq)
(reverse
(for/fold ([result '()])
([elt (in-list seq)])
(if (and (not (null? result))
(string? (car result))
(string? elt))
(cons (string-append (car result)
elt)
(cdr result))
(cons (collapse-adjacent-strings elt) result))))
seq))
(define *input* (string-append "<snord foo=\"bar\">Plop & Flop<child>flip & flop</child></snord> "))
(printf "From SSAX: ~s~%" (call-with-input-string
*input*
(lambda (ip)
(ssax:xml->sxml ip '()))))
(printf "From XML : ~s~%" (collapse-adjacent-strings
(call-with-input-string
*input*
(lambda (ip)
(xml->xexpr
(document-element
(read-xml ip)))))))
| false |
afd522f529766c786f572588a00bb288fa6cc576
|
d8d4bcb61e4af58a86fd1a02503e608b03d8c89f
|
/sitelib/errata/helper.scm
|
1f6b13f867912c17a44e78ef7aa29b3d36a8d2c9
|
[
"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 | 33,163 |
scm
|
helper.scm
|
(library (errata helper)
(export errata-description
errata-keywords
errata-logo
errata-rss-links
jquery-scripts
powered-by-lunula
powered-by-mathjax
creativecommons-attribution-logo
creativecommons-attribution
preload-script
menu
links
belt
public-revisions
bib-window
acknowledgement-view
agreement-view
report-history-window
report-window
review-div
revision-report-tr
diff-table
diff-tr
revision-window
shelf-window
exlibris-window
notification-window)
(import (except (rnrs) div)
(only (core) format)
(match)
(only (srfi :13) string-tokenize)
(only (srfi :19) date->string date-year)
(only (lcs) lcs-fold)
(prefix (only (uri) encode-string) uri:)
(only (lunula gettext) __ ___)
(only (lunula md) md5)
(only (lunula mysql) lookup lookup-all)
(prefix (lunula html) html:)
(only (lunula path) build-entry-path build-api-path)
(only (lunula persistent-record) id-of created-at-of)
(only (lunula session) account account-nick account-name account-mail-address)
(only (lunula string) blank? string-truncate)
(only (errata calendar) ad->japanese-era datetime->date datetime->y/m/d)
(only (errata configuration) url-base google-cx)
(only (errata font) face->style)
(only (errata isbn) pretty-isbn13 isbn10->amazon)
(errata model)
(only (errata notification) notification notification-subject notification-body notification->url)
(errata helper pagination)
(errata page)
(only (errata url) bib&revision->url record->fragment report->url))
(define errata-description
(html:meta ((name "description") (content "書籍などの正誤表を共有するためのサービス。"))))
(define errata-keywords
(html:meta ((name "keywords") (content "errata,typo,proofreading,正誤表,共有,誤植,タイポ,誤訳,校正"))))
(define (errata-logo uuid . _)
(html:h1 ((id "logo") (title "えらった べーた"))
(html:a ((href (build-entry-path 'index uuid)))
(cons "Errata" (html:span ((style "color:red;")) "β")))))
(define errata-rss-links
(map
(lambda (name)
(html:link ((href (format "/~a.rss" name)) (rel "alternate") (type "application/rss+xml") (title (___ name)))))
'(recent-revisions
recent-reports
recent-reviews
recent-acknowledgements
recent-agreements)))
(define jquery-scripts
(map
(lambda (src)
(html:script ((type "text/javascript") (src (format "/javascript/~a" src)))))
'(jquery-1.4.2.min.js
jquery.corner.js
MathJax/MathJax.js)))
(define powered-by-lunula
(html:div ((id "bottom")) "powered by "
(html:a ((href "http://fixedpoint.jp/lunula/") (target "_blank")) 'Lunula)))
(define powered-by-mathjax
(let ((title "Powered by MathJax")
(url "http://www.mathjax.org/"))
(html:a ((href url)
(target "_blank"))
(html:img ((src (string-append url "/badge.gif"))
(border 0)
(alt title)
(title title))))))
(define creativecommons-attribution
(html:a ((href "http://creativecommons.org/licenses/by/2.1/jp/")
(target "_blank"))
"\"CreativeCommons 表示(Attribution)\""))
(define creativecommons-attribution-logo
(html:a ((rel "license") (href "http://creativecommons.org/licenses/by/2.1/jp/") (target "_blank"))
(html:img ((alt "Creative Commons License") (style "border-width:0;") (src "http://i.creativecommons.org/l/by/2.1/jp/80x15.png")))))
(define preload-script
'("$(document).ready(function() {"
"$('.links').corner();"
"$('#private').corner();"
"$('#public').corner();"
"$('.corner').corner();"
"$('.dog').corner('dog tr 15px');"
"$('.permalink').focus(function() {$(this).select();});"
"});"))
(define (menu uuid . _)
(html:p
((id "menu"))
(cond ((string? uuid)
(html:span (html:a ((href (build-entry-path 'logout uuid))) "ログアウト")))
(else
(list
(html:span (html:a ((href (build-entry-path 'login))) "ログイン"))
" "
(html:span (html:a ((href (build-entry-path 'sign-up))) "サインアップ")))))))
(define *public-links* '((board . "書誌一覧")))
(define *private-links*
'((inbox . "Inbox")
(shelf . "書棚の閲覧")
(put-on . "蔵書の登録")
(edit-preference . "設定の編集")
(modify-account . "アカウントの編集")
(modify-password . "パスワードの編集")
(cancel . "アカウントの解除")
))
(define (recent-acknowledgement uuid tuple)
(match tuple
((ack a pref q rep r b)
(html:p
(html:a ((href (report->url rep uuid ack)))
(html:escape-string (acknowledgement->caption ack)))))
(_ "?")))
(define (recent-agreement uuid tuple)
(match tuple
((agr a pref c q rep r b)
(html:p
(html:a ((href (report->url rep uuid agr)))
(html:escape-string (agreement->caption agr)))))
(_ "?")))
(define (recent-revision uuid tuple)
(match tuple
((pub ex a pref r b)
(html:p (html:a ((href (bib&revision->url b r uuid))) (bib-title b))))
(_ "?")))
(define (recent-review uuid tuple)
(match tuple
((rvw ex a pref r b)
(html:p (html:a ((href (bib&revision->url b r uuid rvw)))
(html:escape-string (review->caption rvw)))))
(_ "?")))
(define (recent-report uuid tuple)
(match tuple
((rep a pref r b q o c)
(html:p (html:a ((href (bib&revision->url b r uuid rep)))
(html:escape-string (report->caption rep)))))
(_ "?")))
(define (google-search-form)
(format "<form action=\"http://www.google.co.jp/cse\" id=\"cse-search-box\" target=\"_blank\">
<div>
<input type=\"hidden\" name=\"cx\" value=\"~a\" />
<input type=\"hidden\" name=\"ie\" value=\"UTF-8\" />
<input type=\"text\" name=\"q\" size=\"20\" />
<input type=\"submit\" name=\"sa\" value=\"検索\" />
</div>
</form>
<script type=\"text/javascript\" src=\"http://www.google.co.jp/cse/brand?form=cse-search-box&lang=ja\"></script>"
google-cx))
(define (links uuid . _)
(define (p-link pair)
(html:p (html:a ((href (build-entry-path (car pair) uuid))) (cdr pair))))
(append
`(,(google-search-form))
(html:div
(html:form ((action (build-entry-path 'find-bib uuid)))
"ISBN:"
(html:input ((type "text") (name "isbn")))
(html:input ((type "submit") (value (__ find-bib))))))
(html:div
((class "links"))
(html:div (map p-link *public-links*)))
(with-uuid
uuid
(html:div
((class "links"))
(html:div (map p-link *private-links*))))
(html:div
((id "recent-revisions") (class "corner"))
(html:h3 (__ recent-revisions))
(map
(lambda (tuple) (recent-revision uuid tuple))
(recent-revisions 3)))
(html:div
((id "recent-reviews") (class "corner"))
(html:h3 (__ recent-reviews))
(map
(lambda (tuple) (recent-review uuid tuple))
(recent-reviews 3)))
(html:div
((id "recent-reports") (class "corner"))
(html:h3 (__ recent-reports))
(map
(lambda (tuple) (recent-report uuid tuple))
(recent-reports 3)))
(html:div
((id "recent-acknowledgements") (class "corner"))
(html:h3 (__ recent-acknowledgements))
(map
(lambda (tuple) (recent-acknowledgement uuid tuple))
(recent-acknowledgements 3)))
(html:div
((id "recent-agreements") (class "corner"))
(html:h3 (__ recent-agreements))
(map
(lambda (tuple) (recent-agreement uuid tuple))
(recent-agreements 3)))
))
(define (belt uuid . _)
(html:div
((id "belt"))
(map
(lambda (pair)
(list
(html:a ((href (build-entry-path (car pair) uuid))) (cdr pair))
" | "))
'((faq . "FAQ")
(terms-of-service . "利用規約")
(privacy-policy . "プライバシーポリシー")
(feedback . "フィードバック")))
" © 2009,2010 "
(html:a ((href "http://fixedpoint.jp/")) "fixedpoint.jp")))
(define (hidden-field name value)
(html:input ((type "hidden") (name name) (value value))))
(define (date->ymd date)
(let ((year (date-year date)))
(guard (e
(else (date->string date "~Y-~m-~d")))
(append (html:span ((title (ad->japanese-era year))) year)
(date->string date "-~m-~d")))))
(define (datetime->ymd str)
(cond ((datetime->date str) => date->ymd)
(else #f)))
(define *gravatar-size* 24)
(define (optional-gravatar a pref)
(if (and (number? (preference-gravatar pref))
(= 1 (preference-gravatar pref)))
(html:img ((src (format "http://www.gravatar.com/gravatar/~a.jpg?s=~d"
(md5 (string->utf8 (account-mail-address a)))
*gravatar-size*))
(alt (account-nick a))
(width *gravatar-size*)
(height *gravatar-size*)))
(account-nick a)))
(define (signature a pref)
(html:span ((title (html:escape-string (account-name a))))
(optional-gravatar a pref)))
(define-syntax with-uuid
(syntax-rules ()
((_ uuid thunk)
(if (string? uuid)
thunk
'()))))
(define (bib->image b)
(let* ((image (bib-image b))
(img (if (blank? image)
(html:img ((src "/image/no-image.png") (alt "No Image")))
(html:img ((src image) (alt (html:escape-string (bib-title b))) (style "border-width:0px;"))))))
(cond ((isbn10->amazon (bib-isbn10 b))
=> (lambda (url) (html:a ((href url) (target "_blank")) img)))
(else img))))
(define-syntax revision-skeleton
(syntax-rules ()
((_ b r x y z)
(append
(html:h3 (html:escape-string (bib-title b)))
(html:table
(html:tr
(html:th
((rowspan 4))
(bib->image b))
(html:th ((rowspan 2) (style "text-align:left;")) (__ ISBN))
(html:td ((style "color:#555555;")) (cond ((bib-isbn13 b) => pretty-isbn13) (else "-"))))
(html:tr
(html:td ((style "color:#555555;")) (or (bib-isbn10 b) "-")))
(html:tr
(html:th ((style "text-align:left;")) (__ Revision))
(html:td ((style "color:#555555;"))
(cons* (html:escape-string (revision-name r))
"(" (datetime->ymd (revision-revised-at r)) ")" x)))
(html:tr
(html:th y)
(html:td z)))))))
(define (go-to-board uuid)
(html:form ((action (build-entry-path 'board uuid)))
(html:input ((type "submit") (value (__ to-board))))))
(define (go-to-table uuid r)
(html:form ((action (build-entry-path 'table uuid)))
(hidden-field "id" (id-of r))
(html:input ((type "submit") (value (__ to-table))))))
(define (go-to-shelf uuid)
(html:form ((action (build-entry-path 'shelf uuid)))
(html:input ((type "submit") (value (__ to-shelf))))))
(define (go-to-detail uuid rep)
(html:form ((action (build-entry-path 'detail uuid)))
(hidden-field "id" (id-of rep))
(html:input ((type "submit") (value (__ to-detail))))))
(define (public-revisions uuid page)
(with-pagination
(board uuid page)
(publicity (exlibris publicity) (account exlibris) (revision exlibris) (bib revision))
()
((order-by (publicity (created-at desc))))
(lambda (tuple)
(match tuple
((pub ex a r b)
(append
(revision-skeleton b r
'()
(go-to-table uuid r)
'())
(revision-reviews r)
(html:hr ((style "color:#999999;")))))
(_ "?")))))
(define (bib-window uuid id)
(assert (integer? id))
(let ((tuples (lookup-all (revision
(bib revision))
((bib (id id))
(exists (publicity
(exlibris publicity)
(account exlibris))
((exlibris (revision)))))
((order-by (revision (revised-at desc)))))))
(cond ((null? tuples)
(__ bib-not-found))
(else
(let ((title (bib-title (cadr (car tuples)))))
(html:div
(html:h3 (html:escape-string title))
(html:p (__ following-revisions-found))
(html:table
(html:tbody
(map
(lambda (tuple)
(match tuple
((r b)
(html:tr
(html:td (html:escape-string (revision-name r))
"("
(datetime->ymd (revision-revised-at r))
")")
(html:td (html:a ((href (bib&revision->url b r uuid)))
(__ permanent-link)))))
(_ '())))
tuples)))))))))
(define (revision-window uuid id)
(assert (integer? id))
(match (lookup (revision (bib revision)) ((revision (id id))))
((r b) (revision-frame uuid b r))
(_ "?")))
(define (report-history-window uuid id)
(assert (integer? id))
(cond ((lookup (report (revision report) (bib revision)) ((report (id id))))
=> (lambda (tuple0)
(match tuple0
((rep r b)
(html:div
(go-to-detail uuid rep)
(revision-skeleton b r '() '() '())
(html:h4 (__ History) " " creativecommons-attribution-logo)
(diff-table
(map
(lambda (tuple1)
(match tuple1
((rh a pref q o c)
(report-history-tr uuid rh a pref q o c))
(_ "?")))
(lookup-all (report-history
(account report-history)
(preference (account left))
(quotation report-history)
(occurrence report-history)
(correction report-history))
((report-history (uuid (report-uuid rep))))
((order-by (report-history (created-at desc)))))))))
(_ '()))))
(else '())))
(define-syntax report-history-tr
(syntax-rules ()
((_ uuid rh a pref q o c)
(append
(html:tr
(html:td ((colspan 2) (style "font-size:small;"))
(html:span ((class "page")) "page " (occurrence-page o) "/" (occurrence-position o)) " "
(anchor (rh (class "subject")) (report-history-subject rh)) " "
"("
(html:span ((style "font-size:x-small;")) "reported by ")
(signature a pref)
")"))
(diff-tr uuid q c)
(ack/nak-tr uuid q c '())))))
(define (report-window uuid id)
(assert (integer? id))
(match (lookup (report
(account report)
(preference (account left))
(quotation report)
(occurrence report)
(correction report)
(revision report)
(bib revision))
((report (id id))))
((rep a pref q o c r b) (report-frame uuid rep a pref q o c r b))
(_ "?")))
(define (report-frame uuid rep a pref q o c r b)
(html:div
(go-to-table uuid r)
(revision-skeleton b r '() '() '())
(html:h4 (__ Detail) " " creativecommons-attribution-logo)
(diff-table
(revision-report-tr uuid rep a pref q o c
(html:form ((action (build-entry-path 'show-report-history uuid)))
(hidden-field "id" (id-of rep))
(html:input ((type "submit") (value (__ show-report-history)))))
(ack/nak-tr uuid q c
(with-uuid
uuid
(html:tr
(html:td
(html:form ((action (build-entry-path 'acknowledge uuid)))
(hidden-field "report" (id-of rep))
(hidden-field "quotation" (id-of q))
(html:input ((type "submit") (value (__ acknowledge))))))
(html:td
(html:form ((action (build-entry-path 'agree uuid)))
(hidden-field "report" (id-of rep))
(hidden-field "correction" (id-of c))
(html:input ((type "submit") (value (__ agree)))))))))))))
(define (diff-table x)
(html:table
((class "diff"))
(html:tr
(html:th ((class "title")) (__ Quotation))
(html:th ((class "title")) (__ Correction))
(html:td))
x))
(define-syntax anchor
(syntax-rules ()
((_ (record a0 ...) e0 ...)
(html:a ((name (record->fragment record))
a0 ...)
e0 ...))))
(define (revision-report-tr uuid rep a pref q o c x y)
(append
(html:tr
(html:td ((colspan 2) (style "font-size:small;"))
(html:span ((class "page")) "page " (occurrence-page o) "/" (occurrence-position o)) " "
(anchor (rep (class "subject")) (report-subject rep)) " "
"("
(html:span ((style "font-size:x-small;")) "reported by ")
(signature a pref)
(cond ((created-at-of rep)
=> (lambda (t) (cons " @ " (html:span ((style "text-align:right;")) (datetime->ymd t)))))
(else '()))
")"))
(diff-tr uuid q c x)
y))
(define (review-div tuple)
(match tuple
((rvw ex a pref)
(html:div ((class "dog") (style "background-color:#c7ff6f;"))
(anchor (rvw) (signature a pref) ":")
(html:pre (html:escape-string (review-body rvw)))
))
(_ "?")))
(define (revision-reviews r)
(html:div
(html:h4 (__ Review) " " creativecommons-attribution-logo)
(let ((ls (lookup-all (review
(exlibris review)
(account exlibris)
(preference (account left)))
((exlibris (revision-id (id-of r)))))))
(if (null? ls)
"(なし)"
(map review-div ls)))))
(define (lcs-decoration class c rest)
(case c
((#\linefeed)
(cons (html:br) rest))
((#\space)
(cons (html:span ((class class)) " ") rest))
(else
(cons (html:span ((class class)) (html:escape-char c)) rest))))
(define (lcs-filter-minus x pair)
(match pair
((xa . xb)
`(,(lcs-decoration "minus" x xa) . ,xb))))
(define (lcs-filter-plus x pair)
(match pair
((xa . xb)
`(,xa . ,(lcs-decoration "plus" x xb)))))
(define (lcs-filter-both x pair)
(match pair
((xa . xb)
(case x
((#\linefeed)
`(,(cons (html:br) xa) . ,(cons (html:br) xb)))
((#\space)
`(,(cons " " xa) . ,(cons " " xb)))
(else
`(,(cons (html:escape-char x) xa) . ,(cons (html:escape-char x) xb)))))))
(define (tex-display body)
(html:script ((type "math/tex; mode=display")) body))
(define (tex-text body)
(html:script ((type "math/tex")) body))
(define (diff-tr uuid q c . forms)
(let* ((q-body (quotation-body q))
(c-body (correction-body c))
(a (string->list q-body))
(b (string->list c-body)))
(define (side ff body zc)
(html:td ((class "width:49%;"))
(html:blockquote
(let ((bq (html:span ((style (face->style ff))) (reverse zc))))
(cond ((string=? "tex-display" ff)
(cons
(html:span ((class "MathJax_Preview")) bq)
(tex-display (html:escape-string body))))
((string=? "tex-text" ff)
(cons
(html:span ((class "MathJax_Preview")) bq)
(tex-text (html:escape-string body))))
(else bq))))))
(match (lcs-fold
lcs-filter-minus
lcs-filter-plus
lcs-filter-both
'(() . ())
a
b)
((xa . xb)
(html:tr
(side (quotation-font-face q) q-body xa)
(side (correction-font-face c) c-body xb)
(html:td forms))))))
(define (acknowledgement-view ack a pref)
(html:div
(anchor (ack (class "credit")) (signature a pref) ": ")
(html:span ((class (if (acknowledgement-positive? ack) "ack" "nak")))
(html:escape-string (acknowledgement-comment ack)))))
(define (agreement-view agr a pref)
(html:div
(anchor (agr (class "credit")) (signature a pref) ": ")
(html:span (html:escape-string (agreement-comment agr)))))
(define (ack/nak-tr uuid q c x)
(append
x
(html:tr
(html:td
(let ((tuples (lookup-all (acknowledgement
(account acknowledgement)
(preference (account left)))
((acknowledgement (quotation-id (id-of q))))
((order-by (acknowledgement (created-at desc)))))))
(if (null? tuples)
'()
(html:div
((class "acknowledgement"))
(map
(lambda (tuple)
(apply acknowledgement-view tuple))
tuples))))
(html:td
(let ((tuples (lookup-all (agreement
(account agreement)
(preference (account left)))
((agreement (correction-id (id-of c))))
((order-by (agreement (created-at desc)))))))
(if (null? tuples)
'()
(html:div
((class "agreement"))
(map
(lambda (tuple)
(apply agreement-view tuple))
tuples)))))))))
(define-syntax report-table
(syntax-rules ()
((_ uuid r proc tuples)
(diff-table
(map
(lambda (tuple)
(match tuple
((rep a pref q o c) (revision-report-tr uuid rep a pref q o c (proc rep) '()))))
(list-sort
(lambda (t0 t1)
(page<? (occurrence-page (cadddr (cdr t0)))
(occurrence-page (cadddr (cdr t1)))))
tuples))))))
(define (revision-reports uuid r proc)
(report-table uuid r proc
(lookup-all (report
(account report)
(preference (account left))
(quotation report)
(occurrence report)
(correction report))
((report (revision-id (id-of r)))
(exists (publicity (exlibris publicity))
((exlibris (account))
(exlibris (revision-id (id-of r)))))))))
(define (revision-frame uuid b r)
(html:div
(go-to-board uuid)
(revision-skeleton b r
'()
(__ permalink)
(html:input ((class "permalink")
(type "text")
(readonly #t)
(size 64)
(value
(string-append
url-base
(bib&revision->url b r))))))
(with-uuid uuid
(html:form ((action (build-entry-path 'import-bib uuid)))
(hidden-field "id" (id-of b))
(html:input ((type "submit") (value (__ import-bib))))))
(html:h4 (__ Table) " " creativecommons-attribution-logo)
(revision-reports uuid r (lambda (rep) (go-to-detail uuid rep)))))
(define (exlibris-panel uuid b r ex)
(html:div
(revision-skeleton b r
'()
(html:form ((action (build-entry-path 'desk uuid)))
(hidden-field "id" (id-of ex))
(html:input ((type "submit") (value (__ to-desk)))))
(html:form ((action (build-entry-path 'put-at-top uuid)))
(hidden-field "id" (id-of ex))
(html:input ((type "submit") (value (__ put-at-top))))))
(html:hr ((style "color:#999999;")))))
(define (exlibris-reports uuid ex r proc)
(report-table uuid r proc
(append
(if (lookup publicity ((exlibris-id (id-of ex))))
'() ; the public ones suffice
(lookup-all (report
(account report)
(preference (account left))
(quotation report)
(occurrence report)
(correction report))
((report (revision-id (id-of r)))
(account (id (exlibris-account-id ex))))))
(lookup-all (report
(account report)
(preference (account left))
(quotation report)
(occurrence report)
(correction report))
((report (revision-id (id-of r)))
(exists (publicity (exlibris publicity))
((exlibris (account))
(exlibris (revision-id (id-of r))))))))))
(define (exlibris-frame uuid b r ex)
(let ((id (id-of ex)))
(html:div
(go-to-shelf uuid)
(revision-skeleton b r
(html:form ((action (build-entry-path 'modify-revision uuid)))
(hidden-field "id" id)
(html:input ((type "submit") (value (__ modify-revision)))))
(cond ((lookup publicity ((exlibris-id id)))
=> (lambda (pub)
(html:form ((action (build-entry-path 'hide-exlibris uuid)))
(hidden-field "id" id)
(html:input ((type "submit") (value (__ hide-exlibris)))))))
(else
(html:form ((action (build-entry-path 'share-exlibris uuid)))
(hidden-field "id" id)
(html:input ((type "submit") (value (__ share-exlibris)))))))
(html:form ((action (build-entry-path 'put-off uuid)))
(hidden-field "id" id)
(html:input ((type "submit") (value (__ put-off))))))
(html:h4 (__ Review) " " creativecommons-attribution-logo)
(html:form ((action (build-entry-path 'edit-review uuid)))
(hidden-field "id" id)
(html:input ((type "submit") (value (__ edit-review)))))
(cond ((lookup (review (exlibris review) (account exlibris) (preference (account left))) ((exlibris (id id)))) => review-div)
(else "(なし)"))
(html:h4 (__ Table) " " creativecommons-attribution-logo)
(html:div
(html:form ((action (build-entry-path 'new-report uuid)))
(hidden-field "id" (id-of ex))
(html:input ((type "submit") (value (__ new-report))))))
(exlibris-reports uuid ex r (lambda (rep)
(append
(html:form ((action (build-entry-path 'add-occurrence uuid)))
(hidden-field "report" (id-of rep))
(hidden-field "exlibris" (id-of ex))
(html:input ((type "submit") (value (__ add-occurrence)))))
(if (= (exlibris-account-id ex) (report-account-id rep)) ; it is one's own report
(append
(html:form ((action (build-entry-path 'modify-report uuid)))
(hidden-field "report" (id-of rep))
(hidden-field "exlibris" (id-of ex))
(html:input ((type "submit") (value (__ modify-report)))))
(html:form ((action (build-entry-path 'drop-report uuid)))
(hidden-field "report" (id-of rep))
(hidden-field "exlibris" (id-of ex))
(html:input ((type "submit") (value (__ drop-report))))))
'())))))))
(define (shelf-window uuid body)
(match body
((id page)
(with-pagination
(shelf uuid page)
(exlibris (revision exlibris) (bib revision))
((exlibris (account-id id)))
((order-by (exlibris (position asc) (updated-at desc))))
(lambda (tuple)
(match tuple
((ex r b) (exlibris-panel uuid b r ex))
(_ "?")))))
(_ "??")))
(define (exlibris-window uuid id)
(match (lookup (exlibris (revision exlibris) (bib revision)) ((exlibris (id id))))
((ex r b) (exlibris-frame uuid b r ex))
(_ "?")))
(define (notification-window uuid id)
(let ((ls (lookup-all
(notification)
((notification (account-id id)))
((order-by (notification (created-at desc)))))))
(if (null? ls)
(html:p "(新しい通知はありません)")
(html:ul
(map
(lambda (tuple)
(match tuple
((nt)
(html:li
(html:escape-string (notification-subject nt))
(html:span ((style "font-size:x-small;"))
"(" (datetime->ymd (created-at-of nt)) ")")
(html:form ((action (build-entry-path 'drop-notification uuid)))
(hidden-field "id" (id-of nt))
(html:input ((type "submit") (value (__ drop-notification)))))
(html:br)
(html:a ((href (notification->url nt uuid)))
(html:q (html:escape-string (notification-body nt))))))
(_ '())))
ls)))))
)
| true |
511389b39f768d441a54f03dee2db46dad0e472d
|
e538a8c054bbf0f4bc9a5d1340130eb029322c56
|
/scm/bootstrap.scm
|
f7bff8b5bf8a67c4780bfc24fb7d97b53e06d6ee
|
[] |
no_license
|
jcubic/kiss
|
ee888ed32c34afd14c4a5a65f4dbed2375f895ea
|
f5656022b66085293b984d61245b489175e36bfe
|
refs/heads/master
| 2023-06-10T08:16:59.938466 | 2020-08-18T10:01:10 | 2020-08-18T10:01:10 | 286,073,691 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 19,489 |
scm
|
bootstrap.scm
|
;; -*- scheme -*-
;; This file contain essential functions and macros for LIPS
;;
;; This file is part of the LIPS - Scheme based Powerful LISP in JavaScript
;; Copyriht (C) 2019-2020 Jakub T. Jankiewicz <https://jcubic.pl>
;; Released under MIT license
;; -----------------------------------------------------------------------------
(define-macro (let-syntax vars . body)
"(let-syntax ((name fn)) body)
Macro works like combination of let and define-syntax. It creaates
local macros and evaluate body in context of those macros.
The macro to letrec-syntax is like letrec is to let."
`(let ,vars
,@(map (lambda (rule)
`(typecheck "let-syntax" ,(car rule) "syntax"))
vars)
,@body))
;; -----------------------------------------------------------------------------
(define-macro (letrec-syntax vars . body)
"(letrec-syntax ((name fn)) body)
Macro works like combination of letrec and define-syntax. It creaates
local macros and evaluate body in context of those macros."
`(letrec ,vars
,@(map (lambda (rule)
`(typecheck "letrec-syntax" ,(car rule) "syntax"))
vars)
,@body))
;; -----------------------------------------------------------------------------
(define-macro (define-syntax name expr . rest)
"(define-syntax name expression [__doc__])
Macro define new hygienic macro using syntax-rules with optional documentation"
(let ((expr-name (gensym)))
`(define ,name
(let ((,expr-name ,expr))
(typecheck "define-syntax" ,expr-name "syntax")
,expr-name)
,@rest)))
;; -----------------------------------------------------------------------------
(define (quoted-symbol? x)
"(quoted-symbol? code)
Helper function that test if value is quoted symbol. To be used in macros
that pass literal code that is transformed by parser.
usage:
(define-macro (test x)
(if (quoted-symbol? x)
`',(cadr x)))
(list 'hello (test 'world))"
(and (pair? x) (eq? (car x) 'quote) (symbol? (cadr x)) (null? (cddr x))))
;; -----------------------------------------------------------------------------
(define-macro (--> expr . code)
"Helper macro that simplify calling methods on objects. It work with chaining
usage: (--> ($ \"body\")
(css \"color\" \"red\")
(on \"click\" (lambda () (display \"click\"))))
(--> document (querySelectorAll \"div\"))
(--> (fetch \"https://jcubic.pl\") (text) (match /<title>([^<]+)<\\/title>/) 1)
(--> document (querySelectorAll \".cmd-prompt\") 0 \"innerText\")"
(let ((obj (gensym)))
`(let* ((,obj ,expr))
,@(map (lambda (code)
(let ((name (gensym))
(value (gensym)))
`(let* ((,name ,(cond ((quoted-symbol? code) (symbol->string (cadr code)))
((pair? code) (symbol->string (car code)))
(true code)))
(,value (. ,obj ,name)))
,(if (and (pair? code) (not (quoted-symbol? code)))
`(set! ,obj (,value ,@(cdr code)))
`(set! ,obj ,value)))))
code)
,obj)))
;; -----------------------------------------------------------------------------
(define-macro (define-global first . rest)
"(define-global var value)
(define-global (name . args) body)
Macro that define functions or variables in global context, so they can be used
inside let and get let variables in closure, Useful for universal macros."
(if (pair? first)
(let ((name (car first)))
`(--> (. lips 'env)
(set ,(symbol->string name) (lambda ,(cdr first) ,@rest))))
`(--> (. lips 'env) (set ,(symbol->string first) ,(car rest)))))
;; -----------------------------------------------------------------------------
(define-macro (globalize expr . rest)
"(globalize expr)
Macro will get the value of the expression and add each method as function to global
scope."
(let* ((env (current-environment))
(obj (eval expr env))
(name (gensym))
(env-name (gensym))
(make-name (if (pair? rest)
(let ((pre (symbol->string (car rest))))
(lambda (name) (string->symbol (concat pre name))))
string->symbol)))
`(let ((,name ,expr))
,@(filter pair?
(map (lambda (key)
(if (and (not (match /^_/ key)) (function? (. obj key)))
(let* ((args (gensym)))
`(define-global (,(make-name key) . ,args)
(apply (. ,name ,key) ,args)))))
(array->list (--> Object (keys obj))))))))
;; -----------------------------------------------------------------------------
(define (single list)
"(single list)
Function check if argument is list with single element"
(and (pair? list) (not (cdr list))))
;; -----------------------------------------------------------------------------
(define (iterator? x)
"(iterator? x)
Function check if value is JavaScript iterator object"
(and (object? x) (procedure? (. x Symbol.iterator))))
;; -----------------------------------------------------------------------------
(define-macro (.. expr)
"(.. foo.bar.baz)
Macro that gets value from nested object where argument is comma separated symbol"
(if (not (symbol? expr))
expr
(let ((parts (split "." (symbol->string expr))))
(if (single parts)
expr
`(. ,(string->symbol (car parts)) ,@(cdr parts))))))
;; ---------------------------------------------------------------------------------------
(define (plain-object? x)
"(plain-object? x)
Function check if value is plain JavaScript object. Created using make-object macro."
(and (eq? (type x) "object") (eq? (. x 'constructor) Object)))
;; -----------------------------------------------------------------------------
(define (symbol->string s)
"(symbol->string symbol)
Function convert LIPS symbol to string."
(if (symbol? s)
(let ((name (. s "name")))
(if (string? name)
name
(--> name (toString))))))
;; -----------------------------------------------------------------------------
(define (string->symbol string)
"(string->symbol string)
Function convert string to LIPS symbol."
(and (string? string) (%as.data (new (. lips "LSymbol") string))))
;; -----------------------------------------------------------------------------
(define (alist->object alist)
"(alist->object alist)
Function convert alist pairs to JavaScript object."
(if (pair? alist)
(alist.toObject)
(alist->object (new lips.Pair undefined nil))))
;; -----------------------------------------------------------------------------
(define (parent.frames)
"(parent.frames)
Funcion return list of environments from parent frames (lambda function calls)"
(let iter ((result '()) (frame (parent.frame 1)))
(if (eq? frame (interaction-environment))
(cons frame result)
(if (null? frame)
result
(let ((parent.frame (--> frame (get 'parent.frame (make-object :throwError false)))))
(if (function? parent.frame)
(iter (cons frame result) (parent.frame 0))
result))))))
;; -----------------------------------------------------------------------------
(define-macro (wait time . expr)
"(wait time . expr)
Function return promise that will resolve with evaluating the expression after delay."
`(promise (timer ,time (resolve (begin ,@expr)))))
;; -----------------------------------------------------------------------------
(define (pair-map fn seq-list)
"(pair-map fn list)
Function call fn argument for pairs in a list and return combined list with
values returned from function fn. It work like the map but take two items from list"
(let iter ((seq-list seq-list) (result '()))
(if (null? seq-list)
result
(if (and (pair? seq-list) (pair? (cdr seq-list)))
(let* ((first (car seq-list))
(second (cadr seq-list))
(value (fn first second)))
(if (null? value)
(iter (cddr seq-list) result)
(iter (cddr seq-list) (cons value result))))))))
;; -----------------------------------------------------------------------------
(define (object-expander expr)
"(object-expander '(:foo (:bar 10) (:baz (1 2 3))))
Recursive function helper for defining LIPS code for create objects using key like syntax."
(let ((name (gensym)))
(if (null? expr)
`(alist->object ())
`(let ((,name (alist->object '())))
,@(pair-map (lambda (key value)
(if (not (key? key))
(let ((msg (string-append (type key) " " (repr key) " is not a symbol!")))
(throw msg))
(let ((prop (key->string key)))
(if (and (pair? value) (key? (car value)))
`(set-obj! ,name ,prop ,(object-expander value))
`(set-obj! ,name ,prop ,value)))))
expr)
,name))))
;; -----------------------------------------------------------------------------
(define-macro (make-object . expr)
"(make-object :name value)
Macro that create JavaScript object using key like syntax."
(try
(object-expander expr)
(catch (e)
(error e.message))))
;; -----------------------------------------------------------------------------
(define (alist->assign desc . sources)
"(alist->assign alist . list-of-alists)
Function that work like Object.assign but for LIPS alist."
(for-each (lambda (source)
(for-each (lambda (pair)
(let* ((key (car pair))
(value (cdr pair))
(d-pair (assoc key desc)))
(if (pair? d-pair)
(set-cdr! d-pair value)
(append! desc (list pair)))))
source))
sources)
desc)
;; -----------------------------------------------------------------------------
(define (key? symbol)
"(key? symbol)
Function check if symbol is key symbol, have colon as first character."
;; we can't use string=? because it's in R5RS.scm we use same code that use cmp
(and (symbol? symbol) (== (--> (substring (symbol->string symbol) 0 1) (cmp ":")) 0)))
;; -----------------------------------------------------------------------------
(define (key->string symbol)
"(key->string symbol)
If symbol is key it convert that to string - remove colon."
(if (key? symbol)
(substring (symbol->string symbol) 1)))
;; -----------------------------------------------------------------------------
(define (%as.data obj)
"(%as.data obj)
Mark object as data to stop evaluation."
(if (object? obj)
(begin
(set-obj! obj 'data true)
obj)))
;; -----------------------------------------------------------------------------
(define (dir obj)
"(dir obj)
Function return all props on the object including those in prototype chain."
(if (null? obj) nil
(append (array->list (Object.getOwnPropertyNames obj))
(dir (Object.getPrototypeOf obj)))))
;; ---------------------------------------------------------------------------------------
(define (tree-map f tree)
"(tree-map fn tree)
Tree version of map. Function is invoked on every leaf."
(if (pair? tree)
(cons (tree-map f (car tree)) (tree-map f (cdr tree)))
(f tree)))
;; -----------------------------------------------------------------------------
(define (native.number x)
"(native.number obj)
If argument is number it will convert to native number."
(if (number? x)
(value x)
x))
;; -----------------------------------------------------------------------------
(define (value obj)
"(value obj)
Function unwrap LNumbers and convert nil value to undefined."
(if (eq? obj nil)
undefined
(if (number? obj)
((. obj "valueOf"))
obj)))
;; -----------------------------------------------------------------------------
(define-macro (define-formatter-rule . patterns)
"(rule-pattern pattern)
Anaphoric Macro for defining patterns for formatter. With Ahead, Pattern and * defined values."
(let ((rules (gensym)))
`(let ((,rules (.. lips.Formatter.rules))
(Ahead (lambda (pattern)
(let ((Ahead (.. lips.Formatter.Ahead)))
(new Ahead (if (string? pattern) (new RegExp pattern) pattern)))))
(* ((.. Symbol.for) "*"))
(Pattern (lambda (pattern flag)
(new (.. lips.Formatter.Pattern) (list->array pattern)
(if (null? flag) undefined flag)))))
,@(map (lambda (pattern)
`(--> ,rules (push (tree->array (tree-map native.number ,@pattern)))))
patterns))))
;; -----------------------------------------------------------------------------
(define-macro (cond . list)
"(cond (predicate? . body)
(predicate? . body))
Macro for condition check. For usage instead of nested ifs."
(if (pair? list)
(let* ((item (car list))
(first (car item))
(forms (cdr item))
(rest (cdr list)))
`(if ,first
(begin
,@forms)
,(if (and (pair? rest)
(or (eq? (caar rest) true)
(eq? (caar rest) 'else)))
`(begin
,@(cdar rest))
(if (not (null? rest))
`(cond ,@rest)))))
nil))
;; -----------------------------------------------------------------------------
;; formatter rules for cond to break after each S-Expression
;; regex literal /[^)]/ breaks scheme emacs mode so we use string and macro use RegExp constructor
(define-formatter-rule ((list (list "(" "cond" (Pattern (list "(" * ")") "+")) 1 (Ahead "[^)]"))))
;; -----------------------------------------------------------------------------
(define (interaction-environment)
"(interaction-environment)
Function return interaction environement equal to lips.env can be overwritten,
when creating new interpreter with lips.Interpreter."
**interaction-environment**)
;; -----------------------------------------------------------------------------
(define (current-output-port)
"(current-output-port)
Function return default stdout port."
(let-env (interaction-environment)
stdout))
;; -----------------------------------------------------------------------------
(define (current-input-port)
"current-input-port)
Function return default stdin port."
(let-env (interaction-environment)
stdin))
(define (regex? x)
"(regex? x)
Function return true of value is regular expression, it return false otherwise."
(== (--> (type x) (cmp "regex")) 0))
;; -----------------------------------------------------------------------------
;; add syntax &(:foo 10) that's transformed into (make-object :foo 10)
;; -----------------------------------------------------------------------------
(add-special! "&" 'make-object lips.specials.SPLICE)
;; -----------------------------------------------------------------------------
(define (add-repr! type fn)
"(add-repr! type fn)
Function add string represention to the type, which should be constructor function.
Function fn should have args (obj q) and it should return string, obj is vlaue that
need to be converted to string, if the object is nested and you need to use `repr`,
it should pass second parameter q to repr, so string will be quoted when it's true.
e.g.: (lambda (obj q) (string-append \"<\" (repr obj q) \">\"))"
(typecheck "add-repr!" type "function")
(typecheck "add-repr!" fn "function")
(ignore (--> lips.repr (set type fn))))
;; -----------------------------------------------------------------------------
(define (remove-repr! type)
"(remove-repr! type)
Function remove string represention to the type, which should be constructor function,
added by add-repr! function."
(typecheck "add-repr!" type "function")
(ignore (--> lips.repr (delete type))))
;; -----------------------------------------------------------------------------
;; Object representation
(add-repr! Object
(lambda (x q)
(concat "&("
(--> (Object.getOwnPropertyNames x)
(map (lambda (key)
(concat ":" key
" "
(repr (. x key) q))))
(join " "))
")")))
;; -----------------------------------------------------------------------------
(define (bound? x . rest)
"(bound? x [env])
Function check if variable is defined in given environement or interaction environment
if not specified."
(let ((env (if (null? rest) (interaction-environment) (car rest))))
(try (begin
(--> env (get x))
true)
(catch (e)
false))))
;; -----------------------------------------------------------------------------
;; source https://stackoverflow.com/a/4297432/387194
;; -----------------------------------------------------------------------------
(define (qsort e predicate)
"(qsort list predicate)
Sort the list using quick sort alorithm according to predicate."
(if (or (null? e) (<= (length e) 1))
e
(let loop ((left nil) (right nil)
(pivot (car e)) (rest (cdr e)))
(if (null? rest)
(append (append (qsort left predicate) (list pivot)) (qsort right predicate))
(if (predicate (car rest) pivot)
(loop (append left (list (car rest))) right pivot (cdr rest))
(loop left (append right (list (car rest))) pivot (cdr rest)))))))
;; -----------------------------------------------------------------------------
(define (sort list . rest)
"(sort list [predicate])
Sort the list using optional predicate function. if not function is specified
it will use <= and sort in increasing order."
(let ((predicate (if (null? rest) <= (car rest))))
(typecheck "sort" list "pair")
(typecheck "sort" predicate "function")
(qsort list predicate)))
;; -----------------------------------------------------------------------------
(define (every fn list)
"(every fn list)
Function call function fn on each item of the list, if every value is true
it will return true otherwise it return false."
(if (null? list)
true
(and (fn (car list)) (every fn (cdr list)))))
;; -----------------------------------------------------------------------------
(define (zip . args)
"(zip list1 list2 ...)
Create one list by taking each element if each list."
(if (null? args)
nil
(if (some null? args)
nil
(cons (map car args) (apply zip (map cdr args))))))
| true |
e071bb857602cc634c8d75bd6b291e7c98ec09bb
|
2d19dc910d6635700bac6a1e5326edaa28979810
|
/ext/crypto/math_stub.stub
|
aee317b9deacdb494e07e88ad354bddce8ee23f9
|
[
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"BSD-2-Clause",
"MIT"
] |
permissive
|
spurious/sagittarius-scheme-mirror
|
e88c68cd4a72c371f265f5174d4e5f7c9189fff5
|
53f104188934109227c01b1e9a9af5312f9ce997
|
refs/heads/master
| 2021-01-23T18:00:33.235458 | 2018-11-27T21:03:18 | 2018-11-27T21:03:18 | 2,843,561 | 5 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,460 |
stub
|
math_stub.stub
|
;; -*- mode: scheme; coding: utf-8; -*-
(decl-code
(.include <sagittarius.h>)
(.define "LIBSAGITTARIUS_EXT_BODY")
(.include <sagittarius/extend.h>
<sagittarius-math.h>))
(define-type <prng> "SgObject")
(define-type <hash-algorithm> "SgObject")
(define-c-proc prng? (o) ::<boolean> :constant SG_PRNGP)
(define-c-proc pseudo-random? (o) ::<boolean> :constant SG_PRNGP)
(define-c-proc secure-random? (o) ::<boolean> :constant
(result (and (SG_PRNGP o) (SG_SECURE_RANDOM_P o))))
;; pseudo random
(define-c-proc make-pseudo-random (name::<string> :optional (seed #f))
(unless (or (SG_FALSEP seed) (SG_BVECTORP seed))
(Sg_WrongTypeOfArgumentViolation 'make-pseudo-random
(SG_MAKE_STRING "bytevector or #f")
seed '()))
(result (Sg_MakePseudoRandom name seed)))
(define-c-proc make-secure-random (name::<string> bits::<fixnum>)
(when (< bits 0)
(Sg_WrongTypeOfArgumentViolation 'make-secure-random
(SG_MAKE_STRING "positive integer")
(SG_MAKE_INT bits) '()))
(result (Sg_MakeSecureRandom name bits)))
(define-c-proc %random-seed-set! (prng::<prng> seed::<bytevector>) Sg_VMSetSeed)
(define-c-proc read-sys-random (bits::<fixnum>) Sg_ReadSysRandom)
(define-c-proc read-random-bytes (prng::<prng> size::<fixnum>)
(when (<= size 0)
(Sg_WrongTypeOfArgumentViolation 'read-random-bytes
(SG_MAKE_STRING "positive integer")
(SG_MAKE_INT size) '()))
(result (Sg_VMReadRandomBytes prng size)))
(define-c-proc read-random-bytes!
(prng::<prng> bv::<bytevector> size::<fixnum>)
(when (<= size 0)
(Sg_WrongTypeOfArgumentViolation 'read-random-bytes
(SG_MAKE_STRING "positive integer")
(SG_MAKE_INT size) '()))
(result (Sg_VMReadRandomBytesX prng bv size)))
(define-c-proc register-prng (name clazz) ::<boolean> Sg_RegisterPrng)
(define-c-proc lookup-prng (name) :no-side-effect Sg_LookupPrng)
;; hash
(define-c-proc hash-algorithm? (o) ::<boolean> :constant SG_HASH_P)
(define-c-proc make-hash-algorithm (name::<string>) :no-side-effect
Sg_MakeHash)
(define-c-proc hash-init! (h::<hash-algorithm>) Sg_VMHashInit)
(define-c-proc hash-process! (h::<hash-algorithm> in::<bytevector>
:optional (start::<fixnum> 0) (end::<fixnum> -1))
Sg_VMHashProcess)
(define-c-proc hash-done! (h::<hash-algorithm> out::<bytevector>
:optional (start::<fixnum> 0) (end::<fixnum> -1))
Sg_VMHashDone)
(define-c-proc hash-size (h) :no-side-effect
(unless (or (SG_HASH_P h) (SG_STRINGP h))
(Sg_WrongTypeOfArgumentViolation 'hash-oid
(SG_MAKE_STRING "<string> or <hash-algorithm> required") h '()))
(when (SG_STRINGP h) (set! h (Sg_MakeHash (SG_STRING h))))
(result (Sg_HashSize h)))
(define-c-proc hash-block-size (h) :no-side-effect
(unless (or (SG_HASH_P h)
(SG_STRINGP h))
(Sg_WrongTypeOfArgumentViolation 'hash-oid
(SG_MAKE_STRING "<string> or <hash-algorithm> required") h '()))
(when (SG_STRINGP h) (set! h (Sg_MakeHash (SG_STRING h))))
(result (Sg_HashBlockSize h)))
(define-c-proc hash-oid (h) :no-side-effect
(unless (or (SG_HASH_P h)
(SG_STRINGP h))
(Sg_WrongTypeOfArgumentViolation 'hash-oid
(SG_MAKE_STRING "<string> or <hash-algorithm> required") h '()))
(when (SG_STRINGP h) (set! h (Sg_MakeHash (SG_STRING h))))
(result (Sg_HashOid h)))
(define-c-proc register-hash (name clazz) ::<boolean> Sg_RegisterHash)
(define-c-proc lookup-hash (name) :no-side-effect Sg_LookupHash)
| false |
ed174aba84efaa00894da47e802305fc1c804092
|
37c751fc27e790303b84730013217d1c8cbb60cc
|
/s48/cavespider/hash-util.scm
|
18f2077a92a7ff4d8a4f8c387d28dae076188832
|
[
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] |
permissive
|
gitGNU/gnu_sunterlib
|
e82df45894f0075e2ad2df88ce6edf0f1704c6a0
|
96d443b55c990506e81f2c893e02245b7e2b5f4c
|
refs/heads/master
| 2023-08-06T09:32:59.463520 | 2017-03-07T14:31:05 | 2017-03-07T14:31:05 | 90,394,267 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,918 |
scm
|
hash-util.scm
|
;;;
;;; Copyright (c) 2012 Johan Ceuppens
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; 3. The name of the authors may not be used to endorse or promote products
;;; derived from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;;; IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(define HASHTABLESIZE 1000000)
(define (make-hash-table n)
(let ((*symtab (make-vector 1000000)))
*symtab))
(define url-ascii-vector
(vector #\A #\B #\C #\D #\E #\F #\G #\H #\I #\J #\K #\L
#\M #\N #\O #\P #\R #\S #\T #\U #\V #\W #\X #\Y
#\Z
#\a #\b #\c #\d #\e #\f #\g #\h #\i #\j #\k #\l
#\m #\n #\o #\p #\r #\s #\t #\u #\v #\w #\x #\y
#\z
#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))
(define (hash-explode str)
(let ((ret (make-vector (string-length str))))
(do ((i 0 (+ i 1)))
((>= i (string-length str))
#t)
(vector-set! ret i (string-ref str i))
)
ret))
(define (hash-f key)
(let ((keyexplosionvec (hash-explode key))
(sum 0))
(do ((i 0 (+ i 1)))
((>= i (vector-length keyexplosionvec))
(display "Unknown/Known KEY char"))
(do ((j 0 (+ j 1)))
((cond ((>= j (vector-length url-ascii-vector))
#t)
((eq? (vector-ref keyexplosionvec i)
(vector-ref url-ascii-vector j))
(set! sum (+ sum j)));;FIXME *
))
))
sum))
(define (hash-ref table key)
(vector-ref table (hash-f key)))
(define (hash-set! table key value)
(vector-set! table (hash-f key) value))
;; test
;;(define ht (make-hash-table HASHTABLESIZE))
;;(hash-set! ht "abc" 22)
;;(display (hash-ref ht "abc"))
| false |
70a52fb512c145bce582ab1cf1f8b122ce79b9cb
|
c763eaf97ffd7226a70d2f9a77465cbeae8937a8
|
/scheme/sqlite3/foreign.scm
|
49f3eac54a2288e5f879d847889b85b133401b18
|
[] |
no_license
|
jhidding/crossword
|
66907f12e87593a0b72f234ebfabbd2fb56dae9c
|
b3084b6b1046eb0a996143db1a144fd32379916f
|
refs/heads/master
| 2020-12-02T19:33:08.677722 | 2017-08-21T21:07:43 | 2017-08-21T21:07:43 | 96,357,240 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,022 |
scm
|
foreign.scm
|
(library (sqlite3 foreign)
(export sqlite3-open sqlite3-close sqlite3-errmsg
sqlite3-prepare sqlite3-step sqlite3-reset sqlite3-finalize
sqlite3-column-count sqlite3-column-type sqlite3-column-name
sqlite3-column-text
sqlite3-column-double
sqlite3-column-int
sqlite3-bind-text
sqlite3-bind-double
sqlite3-bind-int
sqlite3-bind-parameter-index
sqlite3-bind-parameter-count)
(import (rnrs (6))
(only (guile) dynamic-link dynamic-func)
(system foreign))
;(only (system foreign) dynamic-link dynamic-func pointer->procedure int))
(define libsqlite3 (dynamic-link "libsqlite3"))
#| Open a database connection
| (sqlite3-open (string: filename)
| (**sqlite3: db))
| The first argument is the filename of the database, the second is a
| pointer to a db-pointer. This pointer will (almost always) be filled
| with a pointer to a database object, which needs to be deleted using
| `sqlite3-close`.
|#
(define sqlite3-open
(pointer->procedure int (dynamic-func "sqlite3_open" libsqlite3)
(list '* '*)))
(define sqlite3-close
(pointer->procedure int (dynamic-func "sqlite3_close" libsqlite3)
(list '*)))
(define sqlite3-errmsg
(pointer->procedure '* (dynamic-func "sqlite3_errmsg" libsqlite3)
(list '*)))
#| Prepare a SQL statement
| (sqlite3-prepare (*sqlite3: db)
| (string: source)
| (int: statement-length)
| (**statement: handle)
| (**char: source-ptr))
|#
(define sqlite3-prepare
(pointer->procedure int (dynamic-func "sqlite3_prepare_v2" libsqlite3)
(list '* '* int '* '*)))
(define sqlite3-reset
(pointer->procedure int (dynamic-func "sqlite3_reset" libsqlite3)
(list '*)))
#| Destroy a statement
| (sqlite3-finalize (*sqlite3-statement: statement))
|#
(define sqlite3-finalize
(pointer->procedure int (dynamic-func "sqlite3_finalize" libsqlite3)
(list '*)))
#| Step statement
| (sqlite3-step (*sqlite3-statement: statement))
|#
(define sqlite3-step
(pointer->procedure int (dynamic-func "sqlite3_step" libsqlite3)
(list '*)))
#| Binders
| (sqlite3-bind-<type>
| (*sqlite3-statement: statement)
| (int: parameter-idx)
| (*<type>: value)
| [(int: byte-size)
| (function(void (*)): deleter)])
|#
(define sqlite3-bind-text
(pointer->procedure int (dynamic-func "sqlite3_bind_text" libsqlite3)
(list '* int '* int '*)))
(define sqlite3-bind-int
(pointer->procedure int (dynamic-func "sqlite3_bind_int" libsqlite3)
(list '* int int)))
(define sqlite3-bind-double
(pointer->procedure int (dynamic-func "sqlite3_bind_double" libsqlite3)
(list '* int double)))
(define sqlite3-bind-parameter-count
(pointer->procedure int (dynamic-func "sqlite3_bind_parameter_count" libsqlite3)
(list '*)))
(define sqlite3-bind-parameter-index
(pointer->procedure int (dynamic-func "sqlite3_bind_parameter_index" libsqlite3)
(list '* '*)))
#|
int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
void(*)(void*));
int sqlite3_bind_double(sqlite3_stmt*, int, double);
int sqlite3_bind_int(sqlite3_stmt*, int, int);
int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
int sqlite3_bind_null(sqlite3_stmt*, int);
int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
void(*)(void*), unsigned char encoding);
int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
int sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
|#
(define sqlite3-column-type
(pointer->procedure int (dynamic-func "sqlite3_column_type" libsqlite3)
(list '* int)))
(define sqlite3-column-count
(pointer->procedure int (dynamic-func "sqlite3_column_count" libsqlite3)
(list '*)))
(define sqlite3-column-name
(pointer->procedure '* (dynamic-func "sqlite3_column_name" libsqlite3)
(list '* int)))
#| Read value from column
| (sqlite3-column-<type>
| (*sqlite3-statement: statement)
| (int: index))
| Returns value.
|#
(define sqlite3-column-text
(pointer->procedure '* (dynamic-func "sqlite3_column_text" libsqlite3)
(list '* int)))
(define sqlite3-column-int
(pointer->procedure int (dynamic-func "sqlite3_column_int" libsqlite3)
(list '* int)))
(define sqlite3-column-double
(pointer->procedure double (dynamic-func "sqlite3_column_double" libsqlite3)
(list '* int)))
#|
const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
double sqlite3_column_double(sqlite3_stmt*, int iCol);
int sqlite3_column_int(sqlite3_stmt*, int iCol);
sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
int sqlite3_column_type(sqlite3_stmt*, int iCol);
sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
|#
)
| false |
93e93ecc2e4343e1e51e1208d06996605630dc0d
|
f4b5638d7b74ef015fe00ad09da47552742201b3
|
/spc-semantic-pass.ss
|
bef1525366be773ceb1a5f2c988736f1035dd649
|
[] |
no_license
|
jartur/spc
|
03fb5f883d8a71dffaf9faa16747a4392f8a0920
|
4e567a188740777318b925d7d64d02901acb42be
|
refs/heads/master
| 2021-01-19T16:58:39.581980 | 2010-03-13T05:19:40 | 2010-03-13T05:19:40 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 5,906 |
ss
|
spc-semantic-pass.ss
|
(module spc-semantic-pass scheme
(require "spc-structures.ss"
srfi/1)
; (require "spc-parser.ss")
(provide semantic-pass)
(define (raise-error tk msg)
(raise-user-error (string-append (pos-token->position-string tk) ": " msg)))
(define *blocks* (list (make-block '()
'()
(list (make-type-def 'integer 'integer)
(make-type-def 'string 'string)
(make-type-def 'real 'real)
(make-type-def 'boolean 'boolean))
'()
'()
'())))
(define (get-constant name (blocks *blocks*))
(if (null? blocks)
#f
(let loop ([rest (block-constants (car blocks))])
(if (null? rest)
(get-constant name (cdr blocks))
(if (eq? name (constant-id (car rest)))
(car rest)
(loop (cdr rest)))))))
(define (get-type name type-pred (blocks *blocks*))
(if (null? blocks)
#f
(let loop ([rest (block-types (car blocks))])
(if (null? rest)
(get-type name type-pred (cdr blocks))
(if (eq? name (type-def-id (car rest)))
(if (type-pred (type-def-type (car rest)))
(car rest)
#f)
(loop (cdr rest)))))))
(define (semantic-pass ast)
(check-block ast))
(define (check-block block)
(set! *blocks* (cons block *blocks*))
(check-constants (block-constants block))
(check-types (block-types block)))
(define (check-types types)
(define (check-types-loop types checked)
(define (find-in-checked pred name)
(let ([r (find (λ (td)
(and (eq? name (type-def-id td))
(pred (type-def-type td))))
checked)])
(if r (type-def-type r) #f)))
(define ord-type? (λ (x) (or (enum-type? x) (range-type? x))))
(define (check-range-type type)
(if (range-type? type)
(let ([s (pos-token-val (range-type-start type))]
[e (pos-token-val (range-type-end type))])
(if (and (ordinal-type-value? s)
(ordinal-type-value? e))
(make-range-type s e)
#f))
#f))
(define (ordinal-type-value? v)
(or (string? v)
(number? v)
(enum-member? v)
(let ([c (get-constant v)])
(if (constant? c)
(or (string? (constant-value c))
(integer? (constant-value c)))
#f))))
(define (check-enum-type type)
(if (enum-type? type)
#t
#f))
(define (enum-member? v)
#f)
(define (check-type-def typedef)
(let ([id (pos-token-val (type-def-id typedef))]
[type (type-def-type typedef)])
(cond [(pos-token? type) #f]
[(enum-type? type) #f]
[(range-type? type) (make-type-def id (check-range-type type))]
[(array-type? type)
(make-type-def
id
(make-array-type
; Check all array range fields
(map (λ (t)
(or (check-range-type t)
(check-enum-type t)
(find-in-checked ord-type? (pos-token-val t))
(get-type ord-type? (pos-token-val t) (cdr *blocks*))
(raise-error t
"Array range specifier must be an ordinal type")))
(array-type-range type))
; Check array type
'type-here))]
[(record-type? type) (make-type-def id 'record)]
[(set-type? type) #f]
[(file-type? type) #f]
[(pointer-type? type) #f])))
(if (null? types)
checked
(check-types-loop (cdr types) (cons (check-type-def (car types)) checked))))
(check-types-loop types '()))
(define (check-constants constants)
(define (find-in-checked name list)
(if (null? list)
#f
(if (eq? name (constant-id (car list)))
(car list)
(find-in-checked name (cdr list)))))
(let loop ([rest constants]
[checked null])
(if (null? rest)
checked
(let* ([const (car rest)]
[id (pos-token-val (constant-id const))]
[value (constant-value const)]
[sign (if (list? value) (car value) '+)]
[valtk (if (list? value) (cadr value) value)]
[val (pos-token-val valtk)])
(if (or (number? val)
(string? val))
(loop (cdr rest) (cons (make-constant id val) checked))
; Look if right hand symbol is known
(let* ([rhs (find-in-checked val checked)]
[rhs (if rhs rhs (get-constant val (cdr *blocks*)))])
(if (not rhs)
(raise-error valtk
"Only literal or declared constant may be on the right side of constant declaration")
; Replace right hand symbol with its value
(loop (cdr rest) (cons (make-constant id ((if (eq? sign '-) - +) (constant-value rhs))) checked)))))))))
; (semantic-pass (run-parser (open-input-file "test.pas")))
)
| false |
cac5768abc856a13af5a1c58723a44a5100b4d82
|
e73f1de93c0af44a53d43079d88f8ba9effb647f
|
/text-tools.ss
|
8758c7aefa9cc97de9ee82241905fa3248e02dc0
|
[] |
no_license
|
dlm2/racket-text-tools
|
65e7f8024c41acc4fa7a840d58dfc67d75b465a3
|
1799ebe08ff7689bfaeb167699ce3400fc3579e2
|
refs/heads/master
| 2021-01-25T09:59:28.608077 | 2010-11-10T22:17:01 | 2010-11-10T22:17:01 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,579 |
ss
|
text-tools.ss
|
;; Hi-lock: ((";*;|.*" (0 (quote fg-gray35) t))) ;; Hi-lock: ((";*;-.*" (0 (quote fg-gray1) t))) ;; Hi-lock: ((";*;/.*" (0 (quote fg-gray1) t))) ;; Hi-lock: (("^/.*" (0 (quote fg-gray1) t))) ;; Hi-lock: (("let\\*-values\\|let-values\\|define-values\\|when\\|case-lambda\\|make-struct-type\\|define-struct\\|def-stx-rules\\|def-stx\\|with-handlers\\|begin0\\|ƛ" (0 (quote keyword) t))) ;; Hi-lock: (("define[/\-][a-zA-Z0-9\-\_]+" (0 (quote keyword) t))) ;; Hi-lock: ((";;/.*" (0 (quote fg-gray1) t))) ;; Hi-lock: ((";;$.*" (0 (quote fg-red4) t))) ;; Hi-lock: (("[a-zA-Z0-9\-\_]+%" (0 (quote class-var) t))) ;; Hi-lock: (("[( ']>[a-zA-Z0-9\-\_/]+" (0 (quote control-id) t)))
#|
/ TEXT-TOOLS.SS
/ Tools for text handling
|#
(module text-tools
scheme
(provide
expand-template
format-text-to-width
)
(require "std.ss")
(require "segm-tools.ss")
;;/------------------------------------------------------------------
(define (expand-template
template
key/val-alist
#:var-regexp [var-re #rx"<([a-zA-Z0-9_-]+)>"]
#:return-as [return-as 'string])
(def-stx-rules insure-key-is-symbol ()
[(_ $key/val) (if (number? (car $key/val))
(cons (num->sym (car $key/val)) (cdr $key/val))
$key/val)])
(define (keys-as-symbols key/val-alist)
;;| Converts any keys that are numbers to symbols
(let loop ([lst key/val-alist] [store '()])
(if (empty? lst)
(reverse store)
(let*([key/val (car lst)])
(loop (cdr lst)
(cons (insure-key-is-symbol key/val)
store))))))
(def-stx-rules as-list ()
[(_ $a)
(cond [(string? $a) (regexp-split #rx"\n" $a)]
[(list? $a) template]
[else (error 'EXPAND-TEMPLATE
"parameter 'template' must be string or list of strings")])])
(def-stx-rules pre-var ()
[(_ $line $i $r) (substr $line $i (car $r))])
(def-stx-rules post-var ()
[(_ $line $r) (substr $line (cdr $r))])
(def-stx-rules var->id ()
[(_ $var) (str->sym (nth 1 (regexp-match var-re $var))) ])
(let*([key/val-alist (keys-as-symbols key/val-alist)])
(define (expand line range-pairs)
(let loop ([lst range-pairs] [i 0] [store '()])
(if (empty? lst)
(apply str+ (reverse (cons (substr line i) store) ))
(let*([r (car lst)]
[var (substr line (car r) (cdr r))]
[key/val (assq (var->id var) key/val-alist)]
[sub (if key/val (cdr key/val) var)])
(loop (cdr lst)
(cdr r)
(cons (str+ (pre-var line i r) sub)
store))))))
(let loop ([lst (as-list template)] [store '()])
(if (empty? lst)
(cond
[(eq? 'string return-as)
(str-join (reverse store) "\n")]
[(eq? 'list return-as)
(reverse store)])
(let*([line (car lst)]
[m (regexp-match-positions* var-re line)])
(if (empty? m)
(loop (cdr lst) (cons line store))
(loop (cdr lst) (cons (expand line m) store)))))) ))
;;/------------------------------------------------------------------
(define (format-text-to-width text width)
(tagged-segms->width-formatted-lines
(text->tagged-segms text)
width))
);| module
| false |
646a5ff6af81056860919e11a8e38268f837efaa
|
4b480cab3426c89e3e49554d05d1b36aad8aeef4
|
/chapter-04/ex4.11-test-dgoon.scm
|
0ea31a9ccff7f0493ef3bf79e243f1dedd4ae880
|
[] |
no_license
|
tuestudy/study-sicp
|
a5dc423719ca30a30ae685e1686534a2c9183b31
|
a2d5d65e711ac5fee3914e45be7d5c2a62bfc20f
|
refs/heads/master
| 2021-01-12T13:37:56.874455 | 2016-10-04T12:26:45 | 2016-10-04T12:26:45 | 69,962,129 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,570 |
scm
|
ex4.11-test-dgoon.scm
|
(load "ex4.11-dgoon.scm")
(load "../misc/scheme-test-r5rs.scm")
(define test-environment (setup-environment))
(define test-frame (make-frame '(a b c) '(1 2 3)))
(define test-frame-2 (make-frame-2 '(a b c) '(1 2 3)))
(define test-proc
'(define (fact n)
(if (or (= 1 n)
(> 1 n))
1
(* n (fact (- n 1))))))
(run-named-test "TEST for ORIGINAL IMPLEMENTATION"
(make-testcase
'(assert-equal? '((a b c) 1 2 3)
test-frame)
'(assert-equal? '(a b c)
(frame-variables test-frame))
'(assert-equal? '(1 2 3)
(frame-values test-frame))
))
(myeval test-proc test-environment)
(run-named-test "TEST for Evaluating factorial"
(make-testcase
'(assert-equal? 1
(myeval '(fact 1)
test-environment))
'(assert-equal? 120
(myeval '(fact 5)
test-environment))
))
(run-named-test "TEST for REWRITTEN IMPLEMENTATION"
(make-testcase
'(assert-equal? '((a . 1) (b . 2) (c . 3))
test-frame-2)
'(assert-equal? '(a b c)
(frame-variables-2 test-frame-2))
'(assert-equal? '(1 2 3)
(frame-values-2 test-frame-2))
))
(define make-frame make-frame-2)
(define frame-variables frame-variables-2)
(define frame-values frame-values-2)
(define add-binding-to-frame! add-binding-to-frame-2!)
(define new-test-environment (setup-environment))
(myeval test-proc new-test-environment)
(run-named-test "TEST for Evaluating factorial"
(make-testcase
'(assert-equal? 1
(myeval '(fact 1)
new-test-environment))
'(assert-equal? 120
(myeval '(fact 5)
new-test-environment))
))
| false |
d0619a772b9819bfc4a89b50b84516d36d5fb3c0
|
f5083e14d7e451225c8590cc6aabe68fac63ffbd
|
/cs/01-Programming/cs61a/course/library/scheme2.scm
|
53c453a3f2ba101e68fa7bc4ee26ae3a6587c3ab
|
[] |
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 | 7,114 |
scm
|
scheme2.scm
|
;; Simple evaluator for Scheme, introducing environment model.
;; Version 2: Adds DEFINE to Scheme-1.
;; In order to remember definitions, we need something new: *environments*.
;; An environment is a collection of names and associated values. We'll
;; represent an environment as a table. (You'll see in the homework that
;; this isn't quite good enough, but it works in almost all situations.)
(DEFINE THE-GLOBAL-ENVIRONMENT (LIST '*TABLE*))
;; EVAL-2 now requires two arguments: the expression to evaluate, and an
;; environment in which to find variables. This changes the REPL. Also,
;; instead of just PRINT we use a magic incantation of FORMAT that lets
;; PRINT print circular structures without getting in an infinite
;; loop, because someone might try to print a procedure.
(define (scheme-2)
(display "Scheme-2: ")
(flush)
(print (format #f "~w" (eval-2 (read) THE-GLOBAL-ENVIRONMENT)))
(scheme-2))
;; Comments on EVAL-2 vs. EVAL-1:
;; EVAL-2 takes the current environment as an argument.
;; Here are the four expression types:
;; 1. self-evaluating (a/k/a constant) expressions: numbers, #t, etc.
;; 2. symbols (variables)
;; 3. special forms (in this evaluator, just QUOTE, IF, LAMBDA, and DEFINE)
;; 4. procedure calls (can call a primitive or a LAMBDA-generated procedure)
;; 1. No change to handling of self-evaluating expressions. They don't
;; have to refer to the environment because their values are constant.
;; Since we aren't using substitution, we can remove the kludge in scheme-1
;; wherein an STk procedure is considered a self-evaluating expression.
;; 2. Now we have local variables, so we look up variables in the
;; current environment, which is a table. If we don't find the name in
;; the environment, we continue to cheat by asking STk for a global
;; value, so that we inherit all the Scheme primitives.
;; 3. The handling of QUOTE is unchanged.
;; IF is almost unchanged, but the recursive calls to EVAL-2 require
;; the environment as a second argument.
;; LAMBDA is handled differently, because a procedure is now something
;; more than just its defining text. It must also remember the
;; environment in which it was created (the right bubble in SICP
;; environment diagrams).
;; To handle internal definitions, we have to allow more than one
;; expression in a procedure body. (This affects APPLY-2.)
;; Don't try to print SCHEME-2 procedures in STk! The data structure
;; that represents the procedure is circular. (It includes the environment,
;; which generally includes a binding whose value is the procedure.) But
;; you can use the magic incantation
;; (print (format #f "~w" foo))
;; to print circular structures without looping.
;; DEFINE is a new special form. It extends the current environment with
;; a new name-value pair, using the PUT procedure for table updating.
;; Note that this DEFINE does not handle the shortcut notation for
;; defining procedures! You have to say
;; (define foo (lambda (x) ...))
;; and not
;; (define (foo x) ...)
;; 4. Procedure calling is unchanged except that the recursive calls to
;; EVAL-2 require the environment as an argument. (But when we get to APPLY-2
;; we'll have to remember that a procedure isn't just a lambda expression.)
(define (eval-2 exp ENV) ; second arg is env
(cond ((constant? exp) exp)
((symbol? exp) (LOOKUP EXP ENV)) ; look in environment
((quote-exp? exp) (cadr exp))
((if-exp? exp)
(if (eval-2 (cadr exp) ENV)
(eval-2 (caddr exp) ENV)
(eval-2 (cadddr exp) ENV)))
((lambda-exp? exp) (MAKE-PROC EXP ENV)) ; procs include env
((DEFINE-EXP? EXP) (PUT (CADR EXP) ; the DEFINE form
(EVAL-2 (CADDR EXP) ENV)
ENV)
'OKAY)
((pair? exp) (apply-2 (eval-2 (car exp) ENV)
(map (LAMBDA (E) (EVAL-2 E ENV)) (cdr exp))))
(else (error "bad expr: " exp))))
;; Comments on APPLY-2 vs. APPLY-1:
;; Primitive procedure calling is unchanged.
;; But user-defined procedures are no longer invoked by substitution!
;; Instead, we just EVAL-2 the body *in a new environment* that we
;; create by adding bindings for the procedure's parameters to the
;; environment in which the procedure was created.
;; Note that EXTEND-ENVIRONMENT makes a new table, with a new header
;; pair, even though the new table starts with the same association
;; list as the environment we're extending. This is important because
;; the new bindings we add should affect only this procedure call, not
;; the enclosing environment.
;; A procedure body is now a list of expressions, not just one
;; expression, so we invent EVAL-SEQUENCE to evaluate them.
(define (apply-2 proc args)
(cond ((procedure? proc) ; use underlying Scheme's APPLY
(apply proc args))
((LAMBDA-PROC? proc)
(EVAL-SEQUENCE (PROC-BODY PROC)
(EXTEND-ENVIRONMENT (PROC-PARAMS PROC)
ARGS
(PROC-ENV PROC))))
(else (error "bad proc: " proc))))
(DEFINE (EVAL-SEQUENCE EXPS ENV)
(IF (NULL? (CDR EXPS)) ; unusual base case so that we
(EVAL-2 (CAR EXPS) ENV) ; return the value of the last expr
(BEGIN (EVAL-2 (CAR EXPS) ENV)
(EVAL-SEQUENCE (CDR EXPS) ENV))))
(DEFINE (EXTEND-ENVIRONMENT PARAMS ARGS ENV)
(LET ((NEW-ENV (CONS '*TABLE* (CDR ENV))))
(DEFINE (EE-LOOP PARAMS ARGS)
(IF (NULL? PARAMS)
NEW-ENV
(BEGIN (PUT (CAR PARAMS) (CAR ARGS) NEW-ENV)
(EE-LOOP (CDR PARAMS) (CDR ARGS)))))
(EE-LOOP PARAMS ARGS)))
;; Some trivial helper procedures:
(define (constant? exp)
(or (number? exp) (boolean? exp) (string? exp)))
(define (exp-checker type)
(lambda (exp) (and (pair? exp) (eq? (car exp) type))))
(define quote-exp? (exp-checker 'quote))
(define if-exp? (exp-checker 'if))
(define lambda-exp? (exp-checker 'lambda))
(DEFINE DEFINE-EXP? (EXP-CHECKER 'DEFINE))
;; Data abstraction for procedures:
(DEFINE (MAKE-PROC EXP ENV)
(LIST 'PROCEDURE EXP ENV))
(DEFINE LAMBDA-PROC? (EXP-CHECKER 'PROCEDURE))
(DEFINE PROC-LAMBDA CADR)
(DEFINE PROC-ENV CADDR)
(DEFINE (PROC-PARAMS PROC)
(CADR (PROC-LAMBDA PROC)))
(DEFINE (PROC-BODY PROC) ; note CDDR not CADDR because
(CDDR (PROC-LAMBDA PROC))) ; a body can be more than one expr
;; Environment (table) maintenance
;; PUT is different from the one in the book because if we add a new
;; entry with the same key as an old entry (a new variable with the
;; same name as an old one), we don't want to modify the old pair,
;; which might still be valid in an outer environment. This will be
;; the case in a situation like
;; (define (foo x)
;; (define (baz x)
;; ...)
;; ...)
(DEFINE (LOOKUP VAR ENV)
(LET ((RESULT (ASSOC VAR (CDR ENV))))
(IF RESULT
(CDR RESULT)
(EVAL VAR)))) ; Not in env, ask STk
(DEFINE (PUT VAR VAL ENV)
(SET-CDR! ENV (CONS (CONS VAR VAL) (CDR ENV))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sample evaluation, using a primitive as argument to MAP:
; Scheme-2: (define map
; (lambda (f seq)
; (if (null? seq)
; '()
; (cons (f (car seq)) (map f (cdr seq))))))
; okay
; Scheme-2: (map first '(the rain in spain))
; (t r i s)
| false |
d0c865fc604cd31e9e079ba27f189359223d033f
|
77f0eef0782195c4d90f97675b605da300fe270a
|
/src/tests/test-assignments.scm
|
0126c4f53486addf7b8904371f76c89df5a8ef33
|
[] |
no_license
|
boraseoksoon/scheme_x86
|
a36a273d99195e6203b45641b6cafb4a92c37818
|
2a02cde1e482bc4be73ad460c97d643a4ea0e2e0
|
refs/heads/master
| 2022-03-16T12:08:59.743217 | 2019-11-23T16:44:19 | 2019-11-23T16:44:19 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 350 |
scm
|
test-assignments.scm
|
(add-tests-with-string-output "assignments"
[(let ([f (lambda (c)
(prim-apply cons (lambda (v) (set! c v)) (lambda () c)))])
(let ([p (f 0)]) ((prim-apply car p) 12) ((prim-apply cdr p))))
=> "12\n"]
[(let ([f 1]) (set! f 2) f) => "2\n"]
;; macro expansion in `(set! ...)`
[(let ([f 1]) (set! f (+ 2 3)) f) => "5\n"])
| false |
22c05b6109a4e3f96ff7b1563bec727e8ecb5e62
|
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
|
/packages/srfi/%3a41/streams/derived.sls
|
ecf7aba185d585dd0c1ded856c07c0b6f7b15587
|
[
"X11-distribute-modifications-variant",
"MIT"
] |
permissive
|
evilbinary/scheme-lib
|
a6d42c7c4f37e684c123bff574816544132cb957
|
690352c118748413f9730838b001a03be9a6f18e
|
refs/heads/master
| 2022-06-22T06:16:56.203827 | 2022-06-16T05:54:54 | 2022-06-16T05:54:54 | 76,329,726 | 609 | 71 |
MIT
| 2022-06-16T05:54:55 | 2016-12-13T06:27:36 |
Scheme
|
UTF-8
|
Scheme
| false | false | 17,102 |
sls
|
derived.sls
|
#!r6rs
;;; Copyright (C) Philip L. Bewig (2007). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation files
;;; (the "Software"), to deal in the Software without restriction,
;;; including without limitation the rights to use, copy, modify, merge,
;;; publish, distribute, sublicense, and/or sell copies of the Software,
;;; and to permit persons to whom the Software is furnished to do so,
;;; subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. 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.
(library (srfi :41 streams derived)
(export stream-null stream-cons stream? stream-null? stream-pair? stream-car
stream-cdr stream-lambda define-stream list->stream port->stream stream
stream->list stream-append stream-concat stream-constant stream-drop
stream-drop-while stream-filter stream-fold stream-for-each stream-from
stream-iterate stream-length stream-let stream-map stream-match
stream-of stream-range stream-ref stream-reverse stream-scan stream-take
stream-take-while stream-unfold stream-unfolds stream-zip)
(import (rnrs) (srfi :41 streams primitive))
(define-syntax define-stream
(syntax-rules ()
((define-stream (name . formal) body0 body1 ...)
(define name (stream-lambda formal body0 body1 ...)))))
(define (list->stream objs)
(define list->stream
(stream-lambda (objs)
(if (null? objs)
stream-null
(stream-cons (car objs) (list->stream (cdr objs))))))
(if (not (list? objs))
(error 'list->stream "non-list argument")
(list->stream objs)))
(define (port->stream . port)
(define port->stream
(stream-lambda (p)
(let ((c (read-char p)))
(if (eof-object? c)
stream-null
(stream-cons c (port->stream p))))))
(let ((p (if (null? port) (current-input-port) (car port))))
(if (not (input-port? p))
(error 'port->stream "non-input-port argument")
(port->stream p))))
(define-syntax stream
(syntax-rules ()
((stream) stream-null)
((stream x y ...) (stream-cons x (stream y ...)))))
(define (stream->list . args)
(let ((n (if (= 1 (length args)) #f (car args)))
(strm (if (= 1 (length args)) (car args) (cadr args))))
(cond ((not (stream? strm)) (error 'stream->list "non-stream argument"))
((and n (not (integer? n))) (error 'stream->list "non-integer count"))
((and n (negative? n)) (error 'stream->list "negative count"))
(else (let loop ((n (if n n -1)) (strm strm))
(if (or (zero? n) (stream-null? strm))
'()
(cons (stream-car strm) (loop (- n 1) (stream-cdr strm)))))))))
(define (stream-append . strms)
(define stream-append
(stream-lambda (strms)
(cond ((null? (cdr strms)) (car strms))
((stream-null? (car strms)) (stream-append (cdr strms)))
(else (stream-cons (stream-car (car strms))
(stream-append (cons (stream-cdr (car strms)) (cdr strms))))))))
(cond ((null? strms) stream-null)
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-append "non-stream argument"))
(else (stream-append strms))))
(define (stream-concat strms)
(define stream-concat
(stream-lambda (strms)
(cond ((stream-null? strms) stream-null)
((not (stream? (stream-car strms)))
(error 'stream-concat "non-stream object in input stream"))
((stream-null? (stream-car strms))
(stream-concat (stream-cdr strms)))
(else (stream-cons
(stream-car (stream-car strms))
(stream-concat
(stream-cons (stream-cdr (stream-car strms)) (stream-cdr strms))))))))
(if (not (stream? strms))
(error 'stream-concat "non-stream argument")
(stream-concat strms)))
(define stream-constant
(stream-lambda objs
(cond ((null? objs) stream-null)
((null? (cdr objs)) (stream-cons (car objs) (stream-constant (car objs))))
(else (stream-cons (car objs)
(apply stream-constant (append (cdr objs) (list (car objs)))))))))
(define (stream-drop n strm)
(define stream-drop
(stream-lambda (n strm)
(if (or (zero? n) (stream-null? strm))
strm
(stream-drop (- n 1) (stream-cdr strm)))))
(cond ((not (integer? n)) (error 'stream-drop "non-integer argument"))
((negative? n) (error 'stream-drop "negative argument"))
((not (stream? strm)) (error 'stream-drop "non-stream argument"))
(else (stream-drop n strm))))
(define (stream-drop-while pred? strm)
(define stream-drop-while
(stream-lambda (strm)
(if (and (stream-pair? strm) (pred? (stream-car strm)))
(stream-drop-while (stream-cdr strm))
strm)))
(cond ((not (procedure? pred?)) (error 'stream-drop-while "non-procedural argument"))
((not (stream? strm)) (error 'stream-drop-while "non-stream argument"))
(else (stream-drop-while strm))))
(define (stream-filter pred? strm)
(define stream-filter
(stream-lambda (strm)
(cond ((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm) (stream-filter (stream-cdr strm))))
(else (stream-filter (stream-cdr strm))))))
(cond ((not (procedure? pred?)) (error 'stream-filter "non-procedural argument"))
((not (stream? strm)) (error 'stream-filter "non-stream argument"))
(else (stream-filter strm))))
(define (stream-fold proc base strm)
(cond ((not (procedure? proc)) (error 'stream-fold "non-procedural argument"))
((not (stream? strm)) (error 'stream-fold "non-stream argument"))
(else (let loop ((base base) (strm strm))
(if (stream-null? strm)
base
(loop (proc base (stream-car strm)) (stream-cdr strm)))))))
(define (stream-for-each proc . strms)
(define (stream-for-each strms)
(if (not (exists stream-null? strms))
(begin (apply proc (map stream-car strms))
(stream-for-each (map stream-cdr strms)))))
(cond ((not (procedure? proc)) (error 'stream-for-each "non-procedural argument"))
((null? strms) (error 'stream-for-each "no stream arguments"))
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-for-each "non-stream argument"))
(else (stream-for-each strms))))
(define (stream-from first . step)
(define stream-from
(stream-lambda (first delta)
(stream-cons first (stream-from (+ first delta) delta))))
(let ((delta (if (null? step) 1 (car step))))
(cond ((not (number? first)) (error 'stream-from "non-numeric starting number"))
((not (number? delta)) (error 'stream-from "non-numeric step size"))
(else (stream-from first delta)))))
(define (stream-iterate proc base)
(define stream-iterate
(stream-lambda (base)
(stream-cons base (stream-iterate (proc base)))))
(if (not (procedure? proc))
(error 'stream-iterate "non-procedural argument")
(stream-iterate base)))
(define (stream-length strm)
(if (not (stream? strm))
(error 'stream-length "non-stream argument")
(let loop ((len 0) (strm strm))
(if (stream-null? strm)
len
(loop (+ len 1) (stream-cdr strm))))))
(define-syntax stream-let
(syntax-rules ()
((stream-let tag ((name val) ...) body1 body2 ...)
((letrec ((tag (stream-lambda (name ...) body1 body2 ...))) tag) val ...))))
(define (stream-map proc . strms)
(define stream-map
(stream-lambda (strms)
(if (exists stream-null? strms)
stream-null
(stream-cons (apply proc (map stream-car strms))
(stream-map (map stream-cdr strms))))))
(cond ((not (procedure? proc)) (error 'stream-map "non-procedural argument"))
((null? strms) (error 'stream-map "no stream arguments"))
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-map "non-stream argument"))
(else (stream-map strms))))
(define-syntax stream-match
(syntax-rules ()
((stream-match strm-expr clause ...)
(let ((strm strm-expr))
(cond
((not (stream? strm)) (error 'stream-match "non-stream argument"))
((stream-match-test strm clause) => car) ...
(else (error 'stream-match "pattern failure")))))))
(define-syntax stream-match-test
(syntax-rules ()
((stream-match-test strm (pattern fender expr))
(stream-match-pattern strm pattern () (and fender (list expr))))
((stream-match-test strm (pattern expr))
(stream-match-pattern strm pattern () (list expr)))))
(define-syntax stream-match-pattern
(lambda (x)
(define (wildcard? x)
(and (identifier? x)
(free-identifier=? x (syntax _))))
(syntax-case x ()
((stream-match-pattern strm () (binding ...) body)
(syntax (and (stream-null? strm) (let (binding ...) body))))
((stream-match-pattern strm (w? . rest) (binding ...) body)
(wildcard? #'w?)
(syntax (and (stream-pair? strm)
(let ((strm (stream-cdr strm)))
(stream-match-pattern strm rest (binding ...) body)))))
((stream-match-pattern strm (var . rest) (binding ...) body)
(syntax (and (stream-pair? strm)
(let ((temp (stream-car strm)) (strm (stream-cdr strm)))
(stream-match-pattern strm rest ((var temp) binding ...) body)))))
((stream-match-pattern strm w? (binding ...) body)
(wildcard? #'w?)
(syntax (let (binding ...) body)))
((stream-match-pattern strm var (binding ...) body)
(syntax (let ((var strm) binding ...) body))))))
(define-syntax stream-of
(syntax-rules ()
((_ expr rest ...)
(stream-of-aux expr stream-null rest ...))))
(define-syntax stream-of-aux
(syntax-rules (in is)
((stream-of-aux expr base)
(stream-cons expr base))
((stream-of-aux expr base (var in stream) rest ...)
(stream-let loop ((strm stream))
(if (stream-null? strm)
base
(let ((var (stream-car strm)))
(stream-of-aux expr (loop (stream-cdr strm)) rest ...)))))
((stream-of-aux expr base (var is exp) rest ...)
(let ((var exp)) (stream-of-aux expr base rest ...)))
((stream-of-aux expr base pred? rest ...)
(if pred? (stream-of-aux expr base rest ...) base))))
(define (stream-range first past . step)
(define stream-range
(stream-lambda (first past delta lt?)
(if (lt? first past)
(stream-cons first (stream-range (+ first delta) past delta lt?))
stream-null)))
(cond ((not (number? first)) (error 'stream-range "non-numeric starting number"))
((not (number? past)) (error 'stream-range "non-numeric ending number"))
(else (let ((delta (cond ((pair? step) (car step)) ((< first past) 1) (else -1))))
(if (not (number? delta))
(error 'stream-range "non-numeric step size")
(let ((lt? (if (< 0 delta) < >)))
(stream-range first past delta lt?)))))))
(define (stream-ref strm n)
(cond ((not (stream? strm)) (error 'stream-ref "non-stream argument"))
((not (integer? n)) (error 'stream-ref "non-integer argument"))
((negative? n) (error 'stream-ref "negative argument"))
(else (let loop ((strm strm) (n n))
(cond ((stream-null? strm) (error 'stream-ref "beyond end of stream"))
((zero? n) (stream-car strm))
(else (loop (stream-cdr strm) (- n 1))))))))
(define (stream-reverse strm)
(define stream-reverse
(stream-lambda (strm rev)
(if (stream-null? strm)
rev
(stream-reverse (stream-cdr strm) (stream-cons (stream-car strm) rev)))))
(if (not (stream? strm))
(error 'stream-reverse "non-stream argument")
(stream-reverse strm stream-null)))
(define (stream-scan proc base strm)
(define stream-scan
(stream-lambda (base strm)
(if (stream-null? strm)
(stream base)
(stream-cons base (stream-scan (proc base (stream-car strm)) (stream-cdr strm))))))
(cond ((not (procedure? proc)) (error 'stream-scan "non-procedural argument"))
((not (stream? strm)) (error 'stream-scan "non-stream argument"))
(else (stream-scan base strm))))
(define (stream-take n strm)
(define stream-take
(stream-lambda (n strm)
(if (or (stream-null? strm) (zero? n))
stream-null
(stream-cons (stream-car strm) (stream-take (- n 1) (stream-cdr strm))))))
(cond ((not (stream? strm)) (error 'stream-take "non-stream argument"))
((not (integer? n)) (error 'stream-take "non-integer argument"))
((negative? n) (error 'stream-take "negative argument"))
(else (stream-take n strm))))
(define (stream-take-while pred? strm)
(define stream-take-while
(stream-lambda (strm)
(cond ((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm) (stream-take-while (stream-cdr strm))))
(else stream-null))))
(cond ((not (stream? strm)) (error 'stream-take-while "non-stream argument"))
((not (procedure? pred?)) (error 'stream-take-while "non-procedural argument"))
(else (stream-take-while strm))))
(define (stream-unfold mapper pred? generator base)
(define stream-unfold
(stream-lambda (base)
(if (pred? base)
(stream-cons (mapper base) (stream-unfold (generator base)))
stream-null)))
(cond ((not (procedure? mapper)) (error 'stream-unfold "non-procedural mapper"))
((not (procedure? pred?)) (error 'stream-unfold "non-procedural pred?"))
((not (procedure? generator)) (error 'stream-unfold "non-procedural generator"))
(else (stream-unfold base))))
(define (stream-unfolds gen seed)
(define (len-values gen seed)
(call-with-values
(lambda () (gen seed))
(lambda vs (- (length vs) 1))))
(define unfold-result-stream
(stream-lambda (gen seed)
(call-with-values
(lambda () (gen seed))
(lambda (next . results)
(stream-cons results (unfold-result-stream gen next))))))
(define result-stream->output-stream
(stream-lambda (result-stream i)
(let ((result (list-ref (stream-car result-stream) (- i 1))))
(cond ((pair? result)
(stream-cons
(car result)
(result-stream->output-stream (stream-cdr result-stream) i)))
((not result)
(result-stream->output-stream (stream-cdr result-stream) i))
((null? result) stream-null)
(else (error 'stream-unfolds "can't happen"))))))
(define (result-stream->output-streams result-stream)
(let loop ((i (len-values gen seed)) (outputs '()))
(if (zero? i)
(apply values outputs)
(loop (- i 1) (cons (result-stream->output-stream result-stream i) outputs)))))
(if (not (procedure? gen))
(error 'stream-unfolds "non-procedural argument")
(result-stream->output-streams (unfold-result-stream gen seed))))
(define (stream-zip . strms)
(define stream-zip
(stream-lambda (strms)
(if (exists stream-null? strms)
stream-null
(stream-cons (map stream-car strms) (stream-zip (map stream-cdr strms))))))
(cond ((null? strms) (error 'stream-zip "no stream arguments"))
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-zip "non-stream argument"))
(else (stream-zip strms)))))
| true |
2bcad44b2c1cbae21324868b953a3d3319d58004
|
6e359a216e1e435de5d39bc64e75998945940a8c
|
/shiyan.scm
|
a2b41f1cfa4f92e7c98ae5cfd662473c10758360
|
[] |
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 | 775 |
scm
|
shiyan.scm
|
(define-syntax while
(syntax-rules ()
((while condition body)
(begin (define while-iter (lambda () (if condition
(begin body (while-iter))
'done)))
(while-iter)))))
;;;(define (while condition body)
;;;(define (while-iter)
;;;(if condition
;;;(begin body (while-iter))
;;;'done))
;;;(while-iter))
(define (test-while x)
(while (< x 10) (begin (set! x (+ x 2)) (display x))))
(define ar (list 'ordi 'lazy 'lazy 'ordi))
(define exps (list 1 2 3 4))
(define (f (a lazy) b (c lazy-memo) d)
(+ a b)
(* c d)
d)
(define (try-for-each li)
(let ((counter 0))
(define (judge x)
(if (= x 1)
(set! counter (+ counter 1))))
(for-each judge li)
counter))
(define (fuck x)
(let ((y 1))
(set! y 2)
(cons y (+ x 1))))
| true |
0d8776e6ca52dc7be3cccec685c0e7679b0fad1d
|
bd71f5bba1e6482f76962c2bdc01e10d18fac0aa
|
/effects.scm
|
1b7458ca6c707461e5f441a096fa0fec2d248a59
|
[] |
no_license
|
Hamayama/Gauche-effects
|
089fe0388bff1756c7b9845c4ce8d4723381f315
|
637ca0e86288a7a048577b4f1b0f949333c2eefa
|
refs/heads/master
| 2020-07-06T00:54:37.674086 | 2019-12-19T02:36:21 | 2019-12-19T02:41:28 | 202,837,835 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,620 |
scm
|
effects.scm
|
;;
;; effects.scm
;; 2019-12-17 v1.18
;;
;; modified for Gauche ( https://github.com/Hamayama/Gauche-effects )
;; ( the original is https://github.com/ayatoy/racket-effects )
;;
(define-module effects
(use gauche.partcont)
(use gauche.parameter)
(use gauche.record)
(use gauche.test)
(use emu-dynamic)
(export
make-handler define-handler
perform with-handler handle-with handle-with* handle
test-handler))
(select-module effects)
;; prepare Gauche's reset/shift
(define *use-native-reset* #f)
(define dynamic-wind (with-module scheme dynamic-wind))
(define call/cc (with-module scheme call/cc))
(define call/pc (with-module gauche.partcont call/pc))
(define reset (with-module gauche.partcont reset))
(define shift (with-module gauche.partcont shift))
(define parameterize (with-module gauche.parameter parameterize))
(define test-handler (with-module gauche.test test*))
(unless *use-native-reset*
;; use emulator of reset/shift
(set! dynamic-wind emu-dynamic-wind)
(set! call/cc emu-call/cc)
(set! call/pc emu-call/pc)
(set! reset emu-reset)
(set! shift emu-shift)
(set! parameterize emu-parameterize)
(set! test-handler (with-module emu-dynamic testA)))
;; Racket's definition
(define null '())
(define findf find)
(define *current-handler* (make-parameter #f))
;(define *tag* (make-continuation-prompt-tag))
(define-record-type <handler> handler handler?
(value handler-value)
(effect handler-effect)
(finally handler-finally))
(define-record-type <%effect> %effect %effect?
(value %effect-value)
(continue %effect-continue))
(define-syntax handler-clause
(syntax-rules (value effect finally else)
[(_ (value value-id body ...))
(cons 'value
(lambda (value-id) body ...))]
[(_ (effect value-id cont-id (test expr ...) ...))
(cons 'effect
(lambda (value-id cont-id)
(call/cc
(lambda (break)
(cond [test (break (begin expr ...))] ...)
(perform/pc value-id cont-id)))))]
[(_ (finally value-id body ...))
(cons 'finally
(lambda (value-id) body ...))]))
(define-syntax handler-clauses
(syntax-rules (value effect finally else)
[(_) null]
[(_ clause rest ...)
(cons (handler-clause clause)
(handler-clauses rest ...))]))
(define-syntax make-handler
(syntax-rules (value effect finally else)
[(_ clause ...)
(let ([handlers (handler-clauses clause ...)]
[find-handler
(lambda (type handlers)
(let ([handler (findf (lambda (h) (eq? type (car h)))
handlers)])
(and handler (cdr handler))))])
(handler
(or (find-handler 'value handlers) identity)
(or (find-handler 'effect handlers) (lambda (x k) (perform/pc x k)))
(or (find-handler 'finally handlers) identity)))]))
(define-syntax define-handler
(syntax-rules (value effect finally else)
[(_ name clause ...)
(define name (make-handler clause ...))]))
(define (perform/pc value k1)
(let ([handler (*current-handler*)])
(if (not handler)
(error "uncaught effect" value)
;(control-at *tag* k2
(shift k2
(%effect value
(lambda (x)
(%with-handler
handler
(lambda ()
(if (not k1)
(k2 x)
(k2 (k1 x)))))))))))
(define (perform value)
(perform/pc value #f))
(define (%with-handler handler thunk)
;(let ([result (prompt-at *tag*
(let ([result (reset
(parameterize ([*current-handler* handler])
(thunk)))])
(cond [(%effect? result)
((handler-effect handler)
(%effect-value result)
(%effect-continue result))]
[else ((handler-value handler) result)])))
(define (with-handler handler thunk)
((handler-finally handler) (%with-handler handler thunk)))
(define-syntax handle-with
(syntax-rules ()
[(_ handler body ...)
(with-handler handler (lambda () body ...))]))
(define-syntax handle-with*
(syntax-rules ()
[(_ (handler) body ...)
(handle-with handler body ...)]
[(_ (handler rest ...) body ...)
(handle-with handler
(handle-with* (rest ...) body ...))]))
(define-syntax handle
(syntax-rules (value effect finally else)
[(_ (clause ...) body ...)
(handle-with (make-handler clause ...) body ...)]))
| true |
229ef27de9190082b884be6318258745d0b0c905
|
784dc416df1855cfc41e9efb69637c19a08dca68
|
/src/bootstrap/gerbil/gambit/threads__0.scm
|
996a15a8eed9605f257e6387f053c890ef497c62
|
[
"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 | 9,921 |
scm
|
threads__0.scm
|
(declare (block) (standard-bindings) (extended-bindings))
(begin
(define gerbil/gambit/threads#spawn
(lambda (_f791_ . _args792_)
(gerbil/gambit/threads#spawn-actor _f791_ _args792_ '#!void '#f)))
(define gerbil/gambit/threads#spawn/name
(lambda (_name787_ _f788_ . _args789_)
(gerbil/gambit/threads#spawn-actor _f788_ _args789_ _name787_ '#f)))
(define gerbil/gambit/threads#spawn/group
(lambda (_name781_ _f782_ . _args783_)
(let ((_tgroup785_ (make-thread-group _name781_)))
(gerbil/gambit/threads#spawn-actor
_f782_
_args783_
_name781_
_tgroup785_))))
(define gerbil/gambit/threads#spawn-actor
(lambda (_f759_ _args760_ _name761_ _tgroup762_)
(letrec ((_thread-main764_
(lambda (_thunk773_)
(lambda ()
(with-exception-handler
(lambda (_exn776_)
(##continuation-capture
(lambda (_cont778_)
(begin
(if gerbil/gambit/threads#unhandled-actor-exception-hook
(with-catch
void
(lambda ()
(gerbil/gambit/threads#unhandled-actor-exception-hook
_cont778_
_exn776_)))
'#!void)
(##continuation-graft
(##continuation-last _cont778_)
##primordial-exception-handler
_exn776_)))))
_thunk773_)))))
(if (procedure? _f759_)
(let ((_thunk770_
(if (null? _args760_)
_f759_
(lambda () (apply _f759_ _args760_))))
(_tgroup771_
(let ((_$e767_ _tgroup762_))
(if _$e767_
_$e767_
(gerbil/gambit/threads#current-thread-group)))))
(thread-start!
(thread-init!
(gerbil/gambit/threads#construct-actor-thread '#f)
(_thread-main764_ _thunk770_)
_name761_
_tgroup771_)))
(error '"Bad argument; expected procedure" _f759_)))))
(begin
(namespace
("gerbil/gambit/threads#"
construct-actor-thread
actor-thread?
actor-thread-locals
actor-thread-locals-set!))
(define-type-of-thread
actor-thread
constructor:
construct-actor-thread
id:
gerbil#actor-thread::t
locals))
(define gerbil/gambit/threads#spawn-thread
(let ((_opt-lambda735741_
(lambda (_thunk737_ _name738_ _tgroup739_)
(thread-start! (make-thread _thunk737_ _name738_ _tgroup739_)))))
(lambda _g794_
(let ((_g793_ (length _g794_)))
(cond ((##fx= _g793_ 1)
(apply (lambda (_thunk744_)
(let* ((_name746_ absent-obj)
(_tgroup748_ absent-obj))
(_opt-lambda735741_
_thunk744_
_name746_
_tgroup748_)))
_g794_))
((##fx= _g793_ 2)
(apply (lambda (_thunk750_ _name751_)
(let ((_tgroup753_ absent-obj))
(_opt-lambda735741_
_thunk750_
_name751_
_tgroup753_)))
_g794_))
((##fx= _g793_ 3) (apply _opt-lambda735741_ _g794_))
(else
(##raise-wrong-number-of-arguments-exception
gerbil/gambit/threads#spawn-thread
_g794_)))))))
(define gerbil/gambit/threads#thread-local-ref
(let ((_opt-lambda719726_
(lambda (_key721_ _default722_)
(let ((_tab724_ (gerbil/gambit/threads#thread-local-table)))
(hash-ref _tab724_ _key721_ _default722_)))))
(lambda _g796_
(let ((_g795_ (length _g796_)))
(cond ((##fx= _g795_ 1)
(apply (lambda (_key729_)
(let ((_default731_ absent-obj))
(_opt-lambda719726_ _key729_ _default731_)))
_g796_))
((##fx= _g795_ 2) (apply _opt-lambda719726_ _g796_))
(else
(##raise-wrong-number-of-arguments-exception
gerbil/gambit/threads#thread-local-ref
_g796_)))))))
(define gerbil/gambit/threads#thread-local-get
(lambda (_key718_) (gerbil/gambit/threads#thread-local-ref _key718_ '#f)))
(define gerbil/gambit/threads#thread-local-set!
(lambda (_key713_ _value714_)
(let ((_tab716_ (gerbil/gambit/threads#thread-local-table)))
(hash-put! _tab716_ _key713_ _value714_))))
(define gerbil/gambit/threads#thread-local-clear!
(lambda (_key709_)
(let ((_tab711_ (gerbil/gambit/threads#thread-local-table)))
(hash-remove! _tab711_ _key709_))))
(define gerbil/gambit/threads#thread-local-table
(lambda ()
(let ((_thr695_ (current-thread)))
(if (gerbil/gambit/threads#actor-thread? _thr695_)
(let ((_$e697_ (gerbil/gambit/threads#actor-thread-locals
_thr695_)))
(if _$e697_
(values _$e697_)
(let ((_tab700_ (make-hash-table-eq)))
(begin
(gerbil/gambit/threads#actor-thread-locals-set!
_thr695_
_tab700_)
_tab700_))))
(if (eq? _thr695_ ##primordial-thread)
gerbil/gambit/threads#*primordial-thread-locals*
(begin
(mutex-lock! gerbil/gambit/threads#*thread-locals-mutex*)
(let ((_$e702_ (hash-get
gerbil/gambit/threads#*thread-locals*
_thr695_)))
(if _$e702_
((lambda (_tab705_)
(begin
(mutex-unlock!
gerbil/gambit/threads#*thread-locals-mutex*)
_tab705_))
_$e702_)
(let ((_tab707_ (make-hash-table-eq)))
(begin
(hash-put!
gerbil/gambit/threads#*thread-locals*
_thr695_
_tab707_)
(mutex-unlock!
gerbil/gambit/threads#*thread-locals-mutex*)
_tab707_))))))))))
(define gerbil/gambit/threads#*primordial-thread-locals*
(make-hash-table-eq))
(define gerbil/gambit/threads#*thread-locals*
(make-hash-table-eq 'weak-keys: '#t))
(define gerbil/gambit/threads#*thread-locals-mutex*
(make-mutex 'thread-locals))
(define gerbil/gambit/threads#unhandled-actor-exception-hook '#f)
(define gerbil/gambit/threads#unhandled-actor-exception-hook-set!
(lambda (_proc689_)
(if (let ((_$e691_ (not _proc689_)))
(if _$e691_ _$e691_ (procedure? _proc689_)))
(set! gerbil/gambit/threads#unhandled-actor-exception-hook _proc689_)
(error '"Bad argument; expected procedure or #f" _proc689_))))
(define gerbil/gambit/threads#with-exception-stack-trace
(let ((_opt-lambda668679_
(lambda (_thunk670_ _error-port671_)
(with-exception-handler
(let ((_E673_ (current-exception-handler)))
(lambda (_exn675_)
(##continuation-capture
(lambda (_cont677_)
(begin
(gerbil/gambit/threads#dump-stack-trace!
_cont677_
_exn675_
_error-port671_)
(_E673_ _exn675_))))))
_thunk670_))))
(lambda _g798_
(let ((_g797_ (length _g798_)))
(cond ((##fx= _g797_ 1)
(apply (lambda (_thunk682_)
(let ((_error-port684_ (current-error-port)))
(_opt-lambda668679_ _thunk682_ _error-port684_)))
_g798_))
((##fx= _g797_ 2) (apply _opt-lambda668679_ _g798_))
(else
(##raise-wrong-number-of-arguments-exception
gerbil/gambit/threads#with-exception-stack-trace
_g798_)))))))
(begin
(namespace ("gerbil/gambit/threads#" dump-stack-trace!))
(define (dump-stack-trace!
cont
exn
#!optional
(error-port (current-error-port)))
(let ((out (open-output-string)))
(display "*** Unhandled exception in " out)
(display (current-thread) out)
(newline out)
(display-exception exn out)
(display "Continuation backtrace: " out)
(newline out)
(##display-continuation-backtrace
cont
out
#f
#f
##backtrace-default-max-head
##backtrace-default-max-tail
0)
(##write-string (get-output-string out) error-port))))
(define gerbil/gambit/threads#current-thread-group
(lambda () (thread-thread-group (current-thread))))
(define gerbil/gambit/threads#with-lock
(lambda (_mx663_ _proc664_)
(dynamic-wind
(lambda () (mutex-lock! _mx663_))
_proc664_
(lambda () (mutex-unlock! _mx663_))))))
| false |
536c90dbe591b8b13a6160d4afbcc3528e5c79a5
|
b61214213da59c049ec1a018e815f4feb95bccca
|
/lexers/Scheme/init.scm
|
68be5c9848ea250adef19766700efa4a2055dc69
|
[] |
no_license
|
Alexey-T/lexer_tests
|
25ab893f928fe2ac073c153e349c140fd3bd8678
|
3d26a98a4f9a2ae12c4074ea90b9416d75736b83
|
refs/heads/master
| 2023-08-17T13:07:10.432096 | 2023-08-13T06:51:15 | 2023-08-13T06:51:15 | 74,854,492 | 3 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 497 |
scm
|
init.scm
|
(load "elf/eopl2/jscheme/genwrite.scm")
(load "elf/eopl2/jscheme/psyntax-init.scm")
;; At this point eval and load have been redefined to use
;; define-syntax. Code that needs define-syntax should be loaded by
;; this file.
(define (remv x ls)
(cond ((null? ls) ls)
((eqv? (car ls) x) (remv x (cdr ls)))
(else (cons (car ls) (remv x (cdr ls))))))
(define (printf x)
(display x)
(newline))
(define (print-gensym x) x) ; No op.
(define expand sc-expand)
(load "using/friedman6.scm")
| true |
089d5aad043d1d9f74bf0caf14e96508aabf61c3
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec4/q4.53.scm
|
7b6b39f94446e1bfc89f36f01ca00812712ffebe
|
[] |
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 | 4,152 |
scm
|
q4.53.scm
|
(load "./sec4.3-nondeterministic")
;; 問題4.51 (q4.51.scm) に述べたようなpermanent-set!と, 問題4.52 (q4.52.scm) のようなif-failを使うと
(let ((pairs '()))
(if-fail (let ((p (prime-sum-pair '(1 3 5 8) '(20 35 110))))
(permanent-set! pairs (cons p pairs))
;;(print "permanent-set!:" pairs) ; debug
(amb))
pairs))
;; の評価の結果はどうなるか.
(define (analyze exp)
(cond ((self-evaluating? exp)
(analyze-self-evaluating exp))
((quoted? exp) (analyze-quoted exp))
((variable? exp) (analyze-variable exp))
((assignment? exp) (analyze-assignment exp))
((permanent-set? exp) (analyze-permanent-set! exp)) ;; 追加
((definition? exp) (analyze-definition exp))
((let? exp) (analyze (let->combination exp)))
((if? exp) (analyze-if exp))
((if-fail? exp) (analyze-if-fail exp)) ;; 追加
((lambda? exp) (analyze-lambda exp))
((begin? exp) (analyze-sequence (begin-actions exp)))
((cond? exp) (analyze (cond->if exp)))
((amb? exp) (analyze-amb exp))
((application? exp) (analyze-application exp))
(else
(error "Unknown expression type -- ANALYZE" exp))))
(define (permanent-set? exp)
(tagged-list? exp 'permanent-set!))
(define (analyze-permanent-set! exp)
(let ((var (assignment-variable exp))
(vproc (analyze (assignment-value exp))))
(lambda (env succeed fail)
(vproc env
(lambda (val fail2)
(set-variable-value! var val env)
(succeed 'ok
(lambda () ;; 失敗継続でold-valueへ戻さない.
(fail2))))
fail))))
(define (if-fail? exp)
(tagged-list? exp 'if-fail))
(define (if-fail-success exp) (cadr exp))
(define (if-fail-failure exp) (caddr exp))
(define (analyze-if-fail exp)
(let ((sproc (analyze (if-fail-success exp)))
(fproc (analyze (if-fail-failure exp))))
(lambda (env succeed fail)
(sproc env
succeed
(lambda ()
(fproc env succeed fail))))))
;;; require定義(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))))
;;; }}} 前提定義
;; prime系補足定義(sec4.3本文, sec1/sec1.2.6.scm より) {{{
(define (prime-sum-pair list1 list2)
(let ((a (an-element-of list1))
(b (an-element-of list2)))
;;(print "check...(" a "+" b ")") ; debug
(require (prime? (+ a b)))
(list a b)))
(define (smallest-divisor n)
(find-divisor n 2))
(define (square x) (* x x))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor) ;#?= for test-divisor
(else (find-divisor n (+ test-divisor 1)))))
(define (divides? a b)
(= (remainder b a) 0))
(define (prime? n)
(= n (smallest-divisor n)))
;; }}}
;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 結果 ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;
; ;;; Amb-Eval input:
; (let ((pairs '()))
; (if-fail (let ((p (prime-sum-pair '(1 3 5 8) '(20 35 110))))
; (permanent-set! pairs (cons p pairs))
; (amb))
; pairs))
;
; ;;; Starting a new problem
;
; ;;; Amb-Eval value
; ((8 35) (3 110) (3 20))
;
; ;;; Amb-Eval input:
; try-again
;
; ;;; There are no more values of
; (let ((pairs '())) (if-fail (let ((p (prime-sum-pair '(1 3 5 8) '(20 35 110)))) (permanent-set! pairs (cons p pairs)) (amb)) pairs))
;;; debug行追加 ;;;
;; http://www.serendip.ws/archives/2578
;; > わかりやすくするために prime-sum-pair と if-fail 第1引数の (amb) の直前に print 文を追加して動作を確認する。
; ;;; Starting a new problem
; check...(1+20)
; check...(1+35)
; check...(1+110)
; check...(3+20)
; permanent-set!:((3 20))
; check...(3+35)
; check...(3+110)
; permanent-set!:((3 110) (3 20))
; check...(5+20)
; check...(5+35)
; check...(5+110)
; check...(8+20)
; check...(8+35)
; permanent-set!:((8 35) (3 110) (3 20))
; check...(8+110)
| false |
5e3cebc7894729e4e54718eda195a95a0b3b3532
|
1db1ff7b9a9ac4ef2c04e64beec85952e7e12c6b
|
/LexGen/lexgen.java.sch
|
241298da1ae7fe0ba2c009e147073b4980c22af4
|
[] |
no_license
|
pnkfelix/pgybs
|
c2a19db40287a2d0387d4fa00251be36ee4ff5ca
|
a34f70a65d26d2c5ad798a4bbf15eaf3acd1cced
|
refs/heads/master
| 2021-01-19T19:37:45.419606 | 2013-09-30T00:02:09 | 2013-09-30T00:02:09 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,988 |
sch
|
lexgen.java.sch
|
; Given a dfa in the representation generated by regexp.sch,
; construct a lexical analyzer written in Java.
; The states are integers beginning with 0.
; For the moment, comments and whitespace must be handled
; by editing the generated Java code.
; Also character classes such as letters and digits are best
; handled by editing the generated Java code.
;
; In short, this is quick-and-dirty code to save me the trouble
; of writing lexical analyzers in Java for my compiler classes.
; I may clean it up later, and make it more general.
;
; Uses output routines from ParseGen:parsegen.java.sch.
; Inelegant hacks.
; Whitespace is handled specially.
; The following symbols are recognized and treated specially:
; letter
; digit
(define character-classes
`((letter ,(string->symbol "Character.isLetter"))
(digit ,(string->symbol "Character.isDigit"))
(space ,(string->symbol "Character.isWhitespace"))
(lowercase ,(string->symbol "Character.isLowerCase"))
(uppercase ,(string->symbol "Character.isUpperCase"))))
(define (generate-java-for-lexer dfa)
(let ((dfa (mysort (lambda (entry1 entry2)
(let ((blocked1? (null? (nfa-entry-transitions entry1)))
(blocked2? (null? (nfa-entry-transitions entry2))))
(or (eq? entry1 (car dfa))
(and (not blocked1?) blocked2?)
(and (not blocked1?)
(not blocked2?)
(<= (nfa-entry-state entry1)
(nfa-entry-state entry2)))
(and blocked1?
blocked2?
(<= (nfa-entry-state entry1)
(nfa-entry-state entry2))))))
dfa)))
(gen-java 4 "private int scanner0() {" #\newline)
(gen-java 4 " int state = 0\;" #\newline)
(gen-java 4 " char c = scanChar()\;" #\newline)
(gen-java 4 #\newline)
(gen-java 4 " /* Edit here to consume whitespace. */" #\newline)
(gen-java 4 " while (isSkippableWhitespaceChar(c)) {" #\newline)
(gen-java 4 " consumeChar()\;" #\newline)
(gen-java 4 " resetAccumulator()\;" #\newline)
(gen-java 4 " c = scanChar()\;" #\newline)
(gen-java 4 " }" #\newline)
(gen-java 4 #\newline)
(gen-java 4 " if (c == EOF)" #\newline)
(gen-java 4 " return accept(Parser.zeof)\;" #\newline)
(gen-java 4 " else do switch (state) {" #\newline)
(for-each (lambda (entry)
(generate-java-for-lexer-state entry dfa))
dfa)
(gen-java 4 " default:" #\newline)
(gen-java 4 " return scannerError(errIllegalChar)\;" #\newline)
(gen-java 4 " } while (state >= 0)\;" #\newline)
(gen-java 4 " return scannerError(errLexGenBug)\;" #\newline)
(gen-java 4 "}" #\newline)
(gen-java 4 #\newline)))
(define (generate-java-for-lexer-state entry dfa)
(let ((transitions (nfa-entry-transitions entry))
(gen-char-transitions
(lambda (transitions)
; Given a list of transitions sorted by target,
; groups them by target and returns a list of
; the groups; each group is itself a list
(define (group-by-target transitions)
(define (loop target group groups transitions)
(cond ((null? transitions)
(cons group groups))
((= target (transition-target (car transitions)))
(loop target
(cons (car transitions) group)
groups
(cdr transitions)))
(else
(loop (transition-target (car transitions))
'()
(cons group groups)
transitions))))
(if (null? transitions)
transitions
(loop (transition-target (car transitions))
'() '() transitions)))
(let* ((transitions
(mysort (lambda (t1 t2)
(<= (transition-target t1)
(transition-target t2)))
transitions))
(grouped-transitions
(group-by-target transitions)))
(generate-java-for-char-transitions grouped-transitions dfa))))
(gen-symbol-transition (lambda (t)
(generate-java-for-symbol-transition t dfa)))
(char-transition? (lambda (t)
(char? (transition-token t))))
(symbol-transition? (lambda (t)
(not (char? (transition-token t))))))
(if (not (null? transitions))
(begin
(gen-java 12 "case " (nfa-entry-state entry) ":" #\newline)
(gen-java 12 " switch (c) {" #\newline)
(gen-char-transitions
(filter char-transition? transitions))
(gen-java 12 " default:" #\newline)
(for-each gen-symbol-transition
(filter symbol-transition? transitions))
(generate-java-for-blocked-state 24 entry)
(gen-java 12 " }" #\newline)
(gen-java 12 " break\;" #\newline)))))
(define (generate-java-for-blocked-state n entry)
(let ((accepts (nfa-entry-accepts entry)))
(cond ((or (not accepts)
(null? accepts))
(gen-java n "if (true) return scannerError(errIncompleteToken)\;"
#\newline)
#t)
((eq? accepts 'whitespace)
(gen-java n "resetAccumulator()\;" #\newline)
(gen-java n "c = scanChar()\;" #\newline)
(gen-java n "state = 0\;" #\newline)
(gen-java n "break\;" #\newline)
#f)
((symbol? accepts)
(gen-java n "if (true) return accept(Parser."
(string-append "z" (symbol->string accepts))
")\;"
#\newline)
#t)
((and (pair? accepts) (symbol? (car accepts)))
(generate-java-for-blocked-state
n
(make-nfa-entry (nfa-entry-state entry)
(car accepts)
'())))
(else
(gen-java n "/* WHAT GOES HERE? */" #\newline)
(gen-java n "state = -1\;" #\newline)
(gen-java n "break\;" #\newline)
#f))))
; Given a list of grouped char transitions,
; outputs a sequence of switch clauses.
(define (generate-java-for-char-transitions transitions dfa)
(for-each (lambda (group) (generate-java-for-lexer-transition group dfa))
transitions))
(define (generate-java-for-lexer-transition group dfa)
(let* ((transition (car group))
(tokens (map transition-token group))
(target (transition-target transition))
(entry (select (lambda (entry)
(eqv? target (nfa-entry-state entry)))
dfa)))
(for-each (lambda (c)
(if (char=? c #\')
(gen-java 20 "case '\\" c "':" #\newline)
(gen-java 20 "case '" c "':" #\newline)))
tokens)
(gen-java 20 " consumeChar()\;" #\newline)
(if (null? (nfa-entry-transitions entry))
(generate-java-for-blocked-state 24 entry)
(begin
(gen-java 20 " c = scanChar()\;" #\newline)
(gen-java 20 " state = " target "\;" #\newline)
(gen-java 20 " break\;" #\newline)))))
(define (generate-java-for-symbol-transition transition dfa)
(let* ((token (transition-token transition))
(target (transition-target transition))
(entry (select (lambda (entry)
(eqv? target (nfa-entry-state entry)))
dfa)))
(let ((handler (assq token character-classes)))
(if handler
(gen-java 20 " if (" (cadr handler) "(c)) {" #\newline)
(gen-java 20 " { /* " token " */" #\newline))
(gen-java 20 " consumeChar()\;" #\newline)
(if (null? (nfa-entry-transitions entry))
(generate-java-for-blocked-state 24 entry)
(begin
(gen-java 20 " c = scanChar()\;" #\newline)
(gen-java 20 " state = " target "\;" #\newline)
(gen-java 20 " break\;" #\newline)))
(if handler
(gen-java 20 " } else" #\newline)
(gen-java 20 " }" #\newline)))))
; To do:
;
; Transitions to states that always block can be replaced by in-line code.
; Then the cases for such states are never used.
; (This assumes the start state is not such a state, but big deal.)
;
; Handling of output-port1.
;
; Messages for scannerError.
| false |
a9cc56dc66f1eec832a24130bc54cba7547849f6
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/net/mail/mail-address.sls
|
7fae29d97737a6ebf7c70d301d40f5e3bb6d31b7
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,340 |
sls
|
mail-address.sls
|
(library (system net mail mail-address)
(export new
is?
mail-address?
get-hash-code
to-string
equals?
address
display-name
host
user)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.Net.Mail.MailAddress a ...)))))
(define (is? a) (clr-is System.Net.Mail.MailAddress a))
(define (mail-address? a) (clr-is System.Net.Mail.MailAddress a))
(define-method-port
get-hash-code
System.Net.Mail.MailAddress
GetHashCode
(System.Int32))
(define-method-port
to-string
System.Net.Mail.MailAddress
ToString
(System.String))
(define-method-port
equals?
System.Net.Mail.MailAddress
Equals
(System.Boolean System.Object))
(define-field-port
address
#f
#f
(property:)
System.Net.Mail.MailAddress
Address
System.String)
(define-field-port
display-name
#f
#f
(property:)
System.Net.Mail.MailAddress
DisplayName
System.String)
(define-field-port
host
#f
#f
(property:)
System.Net.Mail.MailAddress
Host
System.String)
(define-field-port
user
#f
#f
(property:)
System.Net.Mail.MailAddress
User
System.String))
| true |
7f67d38e901af03ab4855287cce19e8cc8a3817b
|
9cb1626e30c6ea40b11cd3715c03d0d5b88722de
|
/src/riaxpander/gambit.scm
|
986bdad3a8d8e7304ddead83d57b1dc3a9d2b13b
|
[
"Zlib"
] |
permissive
|
alvatar/sphere-core
|
fbc2a76ed6743cbe7be99ff0abf50a79e331bb55
|
09e07d8b881f6b0292a4292b8b9a30a4ab5798f7
|
refs/heads/master
| 2020-05-18T13:32:08.074184 | 2015-03-21T12:17:50 | 2015-03-21T12:17:50 | 976,512 | 9 | 0 | null | 2014-04-26T12:30:09 | 2010-10-10T15:43:10 |
Scheme
|
UTF-8
|
Scheme
| false | false | 23,346 |
scm
|
gambit.scm
|
;;;; Sourcification and Desourcification
(define riaxpander:source-mapping (make-parameter #f))
(define (riaxpander:desourcify form)
(cond ((riaxpander:source-mapping)
=> (lambda (mapping)
(let recur ((form form))
(cond ((##source? form)
(let ((code (##source-code form)))
(cond ((pair? code)
(table-set! mapping code (##source-locat form))
(cons (recur (car code))
(recur (cdr code))))
((symbol? code)
code) ;++ fix
(else code))))
((pair? form)
(cons (recur (car form))
(recur (cdr form))))
(else form)))))
(else (##desourcify form))))
;; (define (riaxpander:resourcify form history)
;; (cond ((not (pair? form)) form)
;; ((riaxpander:source-mapping)
;; => (lambda (mapping)
;; (if history
;; (cond ((table-ref mapping
;; (reduction/form
;; (history/original-reduction history)))
;; => (lambda (location)
;; (##make-source form location)))
;; (else form))
;; form)))
;; (else form)))
(define (riaxpander:expand form environment)
((lambda (results)
((if (compiling-expander)
##sourcify-deep
##sourcify)
(let ((r (if (and (pair? results)
(null? (cdr results))
(not (compiling-expander)))
(car results)
`(##begin ,@results))))
r)
(##make-source #f #f)))
(parameterize ((current-location-uid 0))
(map (lambda (item)
(cond ((binding? item) (gambit/compile-binding item))
((declaration? item) (gambit/compile-declaration item))
((expression? item) (gambit/compile-expression item))
(else (error "Invalid top-level item:" item))))
(let ((forms (list (##desourcify form))))
(scan-top-level identity-selector
forms
environment
(make-top-level-history forms environment)))))))
(define compiling-expander (make-parameter #f))
;;! By default do not compile macros
(define compile-loadable-macros? (make-parameter #f))
(define (riaxpander:expand-toplevel form)
(set! new-syntax-definitions '())
(let ((form* (riaxpander:expand form
(or riaxpander:top-level-environment
(make-gambit-environment)))))
(cond
((and (pair? new-syntax-definitions)
(compiling-expander))
;; include code to install the compiled macros at load time
(let ((macro*+form* (##sourcify-deep
`(##begin ,@(filter-map expand-toplevel-syntax-definition
new-syntax-definitions)
,(##desourcify form*)) (##make-source #f #f))))
macro*+form*))
(else
form*))))
(define (expand-toplevel-syntax-definition name)
(let ((transformer (syntactic-lookup riaxpander:top-level-environment name)))
(if (transformer? transformer)
(let ((source (transformer/source transformer)))
(if source
(let ((form (strip-syntactic-closures source riaxpander:top-level-environment)))
(cond
((pair? form)
(case (car form)
((rsc-macro-transformer)
(expand-rsc-macro-transformer name form))
((sc-macro-transformer)
(expand-sc-macro-transformer name form))
((er-macro-transformer)
(expand-er-macro-transformer name form))
(else
(warning "non-standard syntax transformer" name form)
`(syntactic-bind! riaxpander:top-level-environment ',name ,form))))
(else
(warning "non-standard syntax transformer" name form)
`(syntactic-bind! riaxpander:top-level-environment ',name ,form)))))))))
(define (expand-rsc-macro-transformer name form)
(let ((expr (gensym 'expr))
(use-env (gensym 'use-env))
(close-env (gensym 'close-env)))
`(syntactic-bind!
riaxpander:top-level-environment
',name
(make-transformer riaxpander:top-level-environment
,(and (pair? (cddr form)) (list 'quote (caddr form)))
(lambda (,expr ,use-env ,close-env)
(,(cadr form) ,expr ,close-env))
#f))))
(define (expand-sc-macro-transformer name form)
(let ((expr (gensym 'expr))
(use-env (gensym 'use-env))
(close-env (gensym 'close-env)))
`(syntactic-bind!
riaxpander:top-level-environment
',name
(make-transformer riaxpander:top-level-environment
,(and (pair? (cddr form)) (list 'quote (caddr form)))
(lambda (,expr ,use-env ,close-env)
(close-syntax (,(cadr form) ,expr ,use-env)
,close-env))
#f))))
(define (expand-er-macro-transformer name form)
(let ((expr (gensym 'expr))
(use-env (gensym 'use-env))
(close-env (gensym 'close-env)))
`(syntactic-bind!
riaxpander:top-level-environment
',name
(make-transformer riaxpander:top-level-environment
,(and (pair? (cddr form)) (list 'quote (caddr form)))
(lambda (,expr ,use-env ,close-env)
(,(cadr form)
,expr
(make-alias-generator ,close-env)
(make-name-comparator ,use-env)))
#f))))
;; XXXX use qualified names - since we currently have no modules and
;; all top-level macros just reference the same top-level namespace,
;; this isn't essential yet
(define (strip-syntactic-closures expr env)
(let strip ((x expr))
(cond
((pair? x)
;; XXXX hygienically strip syntax-quote
(if (or (eq? 'syntax-quote (car x))
(and (syntactic-closure? (car x))
(eq? 'syntax-quote (syntactic-closure/form (car x)))))
(list 'quote (strip (cadr x)))
(cons (strip (car x)) (strip (cdr x)))))
((syntactic-closure? x)
(strip (syntactic-closure/form x)))
(else
x))))
(define (riaxpander:c-expand-toplevel form)
(parameterize ((compiling-expander #t))
(riaxpander:expand-toplevel form)))
;; (trace riaxpander:c-expand-toplevel)
;; (trace riaxpander:expand-toplevel)
(define riaxpander:top-level-environment #f)
(define new-syntax-definitions '())
;;; This must be defined in case the compiler isn't loaded, so that
;;; the following assignment is not an error.
(define c#expand-source (lambda (src) src))
(define (riaxpander:install!)
(set! riaxpander:top-level-environment (make-gambit-environment))
(set! c#expand-source riaxpander:c-expand-toplevel)
(set! ##expand-source riaxpander:expand-toplevel))
(define (gambit/meta-evaluate expression environment)
(eval expression (interaction-environment)))
(define (gambit/compile-reference variable reference environment)
(if (not variable)
(name->symbol reference)
(let ((name (variable/name variable))
(location (variable/location variable)))
(cond ((number? location)
(string->symbol
(string-append (number->string location)
"#"
(symbol->string (name->symbol name)))))
((name? location)
;** Note that this strips the information necessary to
;** resolve hygienic module references later.
(name->symbol location))
(else
(error "Variable has bogus location:"
variable reference environment))))))
(define current-location-uid (make-parameter 0))
(define (gambit/allocate-location environment name)
(if (not (syntactic-environment/parent environment))
name
(let ((uid (current-location-uid)))
(current-location-uid (+ uid 1))
uid)))
;;;; S-Expression Syntactic Environment
(define (make-gambit-environment)
(let ((environment
(make-syntactic-environment gambit/syntactic-operations
gambit/syntactic-parameters
#f
'())))
(apply-macrology (gambit-macrology) environment)
environment))
(define (gambit-macrology)
(compose-macrologies
(macrology/standard-assignment)
(macrology/standard-conditional gambit/compile-conditional)
(macrology/standard-definition)
(macrology/standard-derived-syntax)
(macrology/standard-keyword-definition)
(macrology/standard-lambda gambit/compile-lambda gambit/map-lambda-bvl)
(macrology/standard-quotation gambit/compile-quotation)
(macrology/standard-sequence)
(macrology/standard-syntactic-binding)
(macrology/syntax-rules)
(gambit-extensions-macrology)))
(define gambit/syntactic-operations
(let ()
(define (global-bindings environment)
(syntactic-environment/data environment))
(define (set-global-bindings! environment bindings)
(set-syntactic-environment/data! environment bindings))
(make-syntactic-operations
(lambda (environment name) ;lookup
(cond ((assq name (global-bindings environment))
=> cdr)
((syntactic-closure? name)
(syntactic-lookup (syntactic-closure/environment name)
(syntactic-closure/form name)))
(else #f)))
(lambda (environment name denotation) ;bind!
(if (compile-loadable-macros?)
(set! new-syntax-definitions
(cons name new-syntax-definitions)))
(set-global-bindings! environment
(cons (cons name denotation)
(global-bindings environment))))
(lambda (environment) ;seal!
environment ;ignore
(if #f #f))
(lambda (environment name) ;alias
environment ;ignore
name)
(lambda (environment) ;disclose
environment ;ignore
'(sexp))
(lambda (environment procedure) ;for-each-binding
(for-each (lambda (binding)
(procedure (car binding) (cdr binding)))
(global-bindings environment))))))
(define gambit/syntactic-parameters
(lambda (key)
(cond ((eq? key variable-classifier) gambit/classify-variable)
((eq? key free-variable-classifier) gambit/classify-free-variable)
((eq? key datum-classifier) gambit/classify-datum)
((eq? key self-evaluating?) gambit/self-evaluating?)
((eq? key combination-classifier) gambit/classify-combination)
((eq? key location-allocator) gambit/allocate-location)
((eq? key meta-evaluator) gambit/meta-evaluate)
(else #f))))
;;;; Gambit Specifics
(define-record-type <declaration>
(make-declaration forms environment history)
declaration?
(forms declaration/forms)
(environment declaration/environment)
(history declaration/history))
(define (make-declaration-definition selector forms environment history)
selector ;ignore
(make-definition
(lambda (definition-environment)
definition-environment ;ignore
(list (make-declaration forms environment history)))))
(define (gambit/compile-declaration declaration)
;++ Can any Gambit declarations affect local variables? If so, this
;++ needs to go through the list of forms to rename any references to
;++ them. (This is why we include the environment.)
`(declare ,@(declaration/forms declaration)))
(define (macrology/gambit-sequence)
(make-extended-classifier-macrology
(lambda (define-classifier)
(define-classifier '(##begin * form)
(lambda (form environment history)
(classify-sequence cdr-selector (cdr form) environment history))))))
(define (macrology/gambit-define)
(make-extended-classifier-macrology
(lambda (define-classifier)
(define-classifier '(declare + (name * datum))
(lambda (form environment history)
(values (make-declaration-definition cdr-selector
(cdr form)
environment
history)
history))))))
(define (macrology/gambit-cond-expand)
(make-extended-classifier-macrology
(lambda (define-classifier)
(define-classifier '(cond-expand + (expression + expression))
(lambda (form environment history)
(let ((clauses (cdr form))
(clauses-selector cdr-selector))
(define (err x)
(syntax-error "syntax error in COND-EXPAND form"
x (cons 'cond-expand clauses)))
(define (test feature-requirement)
(cond ((symbol? feature-requirement)
(not (not (memq feature-requirement (##cond-expand-features)))))
((not (pair? feature-requirement))
(err feature-requirement))
(else
(let ((head (car feature-requirement))
(rest (cdr feature-requirement)))
(case head
((and) (or (eq? rest '())
(if (pair? rest)
(and (test (car rest))
(test `(and ,@(cdr rest))))
(err feature-requirement))))
((or) (and (not (eq? rest '()))
(if (pair? rest)
(or (test (car rest))
(test `(or ,@(cdr rest))))
(err feature-requirement))))
((not) (not (test (cadr feature-requirement))))
(else (err feature-requirement)))))))
(let expand ((clauses clauses)
(clauses-selector clauses-selector))
(cond ((eq? clauses '())
(apply syntax-error `("no matching clause in `cond-expand' form"
,(map (lambda (x) (car x)) clauses))))
((not (pair? clauses)) (err clauses))
(else
(let ((clause (car clauses))
(clause-selector (select-car clauses-selector))
(rclauses (cdr clauses))
(rclauses-selector (select-cdr clauses-selector)))
(if (not (pair? clause))
(err clause)
(let ((feature-requirement (car clause))
(expressions (cdr clause))
(expressions-selector (select-cdr clause-selector)))
(cond ((eq? feature-requirement 'else)
(if (eq? expressions '())
(err "invalid ELSE <expression>")
(classify-sequence expressions-selector expressions environment history)))
((test feature-requirement)
(classify-sequence expressions-selector expressions environment history))
(else (expand rclauses rclauses-selector)))))))))))))))
(define (gambit-extensions-macrology)
(compose-macrologies
(macrology/non-standard-macro-transformers)
(macrology/syntax-quote 'syntax-quote gambit/compile-quotation)
(macrology/gambit-sequence)
(macrology/gambit-cond-expand)
(macrology/gambit-define)))
;;;;; S-Expression Syntactic Parameters
(define (gambit/classify-datum datum environment history)
(if (gambit/self-evaluating? datum)
(values (make-expression (lambda () datum)) history)
(classify-error "Inevaluable datum:" history datum)))
(define (gambit/self-evaluating? datum)
(or (boolean? datum)
(char? datum)
(number? datum)
(string? datum)
(keyword? datum)
(memq datum
'(
#!eof ;ARGH! What *stupid* lossage.
#!key
#!rest
#!optional
#!unbound
#!unbound2
#!void
))))
(define (gambit/classify-variable variable reference environment history)
(values
(make-location
(lambda () (gambit/compile-reference variable reference environment))
(lambda (expression assignment-history)
assignment-history ;ignore
`(set! ,(gambit/compile-reference variable reference environment)
,(gambit/compile-expression expression))))
history))
(define (gambit/classify-free-variable reference environment history)
(gambit/classify-variable #f reference environment history))
(define (gambit/classify-combination operator operator-history
selector forms environment history)
(cond ((not (expression? operator))
(classify-error "Non-expression in operator position of combination:"
operator-history
operator))
((not (list? forms))
(classify-error "Invalid operands in combination -- improper list:"
history
forms))
(else
(values
(make-expression
(lambda ()
(gambit/compile-combination
operator
(classify-subexpressions selector forms environment history)
history)))
history))))
;;;;; S-Expression Compilers
(define (gambit/compile-quotation datum history)
history ;ignore
(if (gambit/self-evaluating? datum)
datum
`',datum))
(define (gambit/compile-conditional condition consequent alternative history)
history ;ignore
`(if ,(gambit/compile-expression condition)
,(gambit/compile-expression consequent)
,@(if alternative
`(,(gambit/compile-expression alternative))
'())))
(define (gambit/compile-lambda bvl body environment history)
history ;ignore
`(lambda ,(gambit/%map-lambda-bvl bvl
(lambda (variable)
(gambit/compile-reference variable #f environment)))
,@(gambit/compile-lambda-body body)))
(define (gambit/compile-lambda-body body)
(receive (definitions expressions) (classify/sequence scan-r6rs-body body)
`(,@(map (lambda (item)
(cond ((binding? item) (gambit/compile-binding item))
((declaration? item) (gambit/compile-declaration item))
(else (error "Invalid item in body:" item))))
definitions)
,@(map gambit/compile-expression expressions))))
;++ Handle extended BVLs.
(define (gambit/map-lambda-bvl bvl history procedure)
(if (not (gambit/valid-bvl? bvl))
(syntax-error "Invalid lambda BVL:" history bvl)
(gambit/%map-lambda-bvl bvl procedure)))
(define (gambit/valid-bvl? bvl)
(let loop ((bvl bvl) (seen '()))
(if (pair? bvl)
(and (name? (car bvl))
(not (memq (car bvl) seen))
(loop (cdr bvl) (cons (car bvl) seen)))
(or (null? bvl)
(and (name? bvl)
(not (memq bvl seen)))))))
(define (gambit/%map-lambda-bvl bvl procedure)
(let recur ((bvl bvl))
(cond ((pair? bvl)
(cons (procedure (car bvl))
(recur (cdr bvl))))
((null? bvl)
'())
(else
(procedure bvl)))))
;;;;; S-Expression Compilation Utilities
(define (gambit/compile-expression expression)
(cond ((location? expression)
((location/expression-compiler expression)))
((sequence? expression)
(gambit/compile-sequence
(classify/sequence scan-expressions expression)
(sequence/history expression)))
(else
((expression/compiler expression)))))
(define (gambit/compile-expressions expressions)
(map gambit/compile-expression expressions))
(define (gambit/compile-combination operator operands history)
history ;ignore
`(,(gambit/compile-expression operator)
,@(gambit/compile-expressions operands)))
(define (gambit/compile-binding binding)
`(define ,(gambit/compile-reference (binding/variable binding)
#f
(binding/environment binding))
,(receive (expression history) ((binding/classifier binding))
history ;ignore
(gambit/compile-expression expression))))
(define (gambit/compile-sequence expressions history)
history ;ignore
`(##begin ,@(map gambit/compile-expression expressions)))
(define (riaxpander:include file)
(with-input-from-file
file
(lambda () (let recur ((form (read)))
(if (not (eof-object? form))
(begin (eval form)
(recur (read))))))))
;; (define (riaxpander:include file)
;; (for-each eval (with-input-from-file file read-all)))
;; Redefine include
(eval '(define-macro (include #!rest f) `(expander:include ,@f)))
;; (define-syntax define-macro
;; (syntax-rules ()
;; ((_ (id . llist) . body)
;; (define-syntax id
;; (rsc-macro-transformer
;; (lambda (exp env)
;; (apply (lambda llist . body) (cdr exp))))))
;; ((_ id expander)
;; (define-syntax id
;; (rsc-macro-transformer
;; (lambda (exp env)
;; (apply expander (cdr exp))))))))
;; (define-syntax include
;; (rsc-macro-transformer
;; (lambda (exp env)
;; (syntax-check '(keyword expression) exp)
;; (let ((filename (cadr exp)))
;; (let ((path (##sys#resolve-include-filename filename #t)))
;; (if (load-verbose) (print "; including " path " ..."))
;; `(,(make-syntactic-closure env '() 'begin)
;; ,@(with-input-from-file path
;; (lambda ()
;; (do ((x (read) (read))
;; (xs '() (cons x xs)))
;; ((eof-object? x)
;; (reverse xs)))))))))))
| true |
a628b17b68c2e3e0d7b4fa818447de5215818bc5
|
eb2cb6452e5690a3e7475e342c6698c855b10d70
|
/repl.scm
|
fcd895ba35ddbae4dff0df5f349e4b84fcb83494
|
[
"Boehm-GC",
"X11-distribute-modifications-variant",
"BSD-2-Clause"
] |
permissive
|
david135/mosh-scheme
|
67375fcef15209e0af1dae6df937f2c268bf52b0
|
8247d45bc34c8b503047600b9f2eacb5443aaa83
|
refs/heads/master
| 2021-01-15T17:07:12.792938 | 2009-11-23T08:42:02 | 2009-11-23T08:42:02 | 32,497,499 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,084 |
scm
|
repl.scm
|
;; (import (rnrs)
;; (mosh string))
(define (for-each-with-index proc lst)
(do ((i 1 (+ i 1)) ; start with 1
(lst lst (cdr lst)))
((null? lst))
(proc i (car lst))))
(define (repl . x)
(define (rec)
(display "mosh>")
(guard (e
(e
(for-each-with-index
(lambda (i x)
(cond
[(who-condition? x)
(format #t " ~d. &who: ~a\n" i (condition-who x))]
[(message-condition? x)
(format #t " ~d. &message: ~s\n" i (condition-message x))]
[(violation? x)
(format #t " ~d. ~a\n" i (record-type-name (record-rtd x)))]
[(irritants-condition? x)
(format #t " ~d. &irritants: ~s\n" i (condition-irritants x))]
[else
(format #t " ~d. ~a\n" i (record-type-name (record-rtd x)))]))
(simple-conditions e))))
(let ([obj (read (current-input-port))])
(if (eof-object? obj)
(exit)
(display (remp obj)))))
(rec))
(rec))
(repl)
| false |
58ab54e5c5c84bcfd601c9d2640f78e7b14c82ac
|
d696b5c5cc0ee7032ab13b6ed486d6158646f828
|
/Exercise3-68.scm
|
e0b3e4c460173d7566337f5ab8330f72baa86d8b
|
[] |
no_license
|
senwong/SICPExercises
|
4f96b1480fa30031b1fe8f44757702c0d7102d2b
|
1206705162f0d18892fc70ccb7376a425b6f6534
|
refs/heads/master
| 2021-09-03T01:31:38.882431 | 2018-01-04T15:45:37 | 2018-01-04T15:45:37 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 179 |
scm
|
Exercise3-68.scm
|
(define (pairs s t)
(interleave
(stream-map (lambda (x) (list (stream-car s) x)) t)
(pairs (stream-cdr s) (stream-cdr t))))
(define integer-pairs (pairs integers integers))
| false |
9073a2de5467171d3a32ee459c6ac07d4de55825
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/loader-optimization-attribute.sls
|
b74f5170530873c5dc9a601014fc3ce4017bbc87
|
[] |
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 | 586 |
sls
|
loader-optimization-attribute.sls
|
(library (system loader-optimization-attribute)
(export new is? loader-optimization-attribute? value)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.LoaderOptimizationAttribute a ...)))))
(define (is? a) (clr-is System.LoaderOptimizationAttribute a))
(define (loader-optimization-attribute? a)
(clr-is System.LoaderOptimizationAttribute a))
(define-field-port
value
#f
#f
(property:)
System.LoaderOptimizationAttribute
Value
System.LoaderOptimization))
| true |
55e4c07551c4161b98878496410b86bc747c8318
|
174072a16ff2cb2cd60a91153376eec6fe98e9d2
|
/Chap-Three/3-24.scm
|
86a911192783001f025a3fab8a9e77f8811f70e5
|
[] |
no_license
|
Wang-Yann/sicp
|
0026d506ec192ac240c94a871e28ace7570b5196
|
245e48fc3ac7bfc00e586f4e928dd0d0c6c982ed
|
refs/heads/master
| 2021-01-01T03:50:36.708313 | 2016-10-11T10:46:37 | 2016-10-11T10:46:37 | 57,060,897 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 733 |
scm
|
3-24.scm
|
(define (make-table same-key?)
(let((local-table (list '*table*)))
(define (lookup key)
(let ((record (assoc key (cdr local-table))))
(if record (cdr record) #f)))
; (define (same-key? k1 k2) (< (- k1 k2) 0.01))
(define (assoc key records)
(cond ((null? records) #f)
((same-key? key (caar records)) (car records))
(else (assoc key (cdr records)))))
(define (insert! key value )
(let((record (assoc key (cdr local-table))))
(if record (set-cdr! record value)
(set-cdr! local-table
(cons (cons key value) (cdr local-table))))))
(define (dispatch m)
(cond ((eq? m 'lookup) lookup)
((eq? m 'insert) insert!)
(else (error "unknown command" m))))
dispatch))
(define N (make-table = ))
| false |
f0e49d3b84b091fcd7f91f853e9378f2ec990158
|
58381f6c0b3def1720ca7a14a7c6f0f350f89537
|
/Chapter 2/2.5/Ex2.87.scm
|
dc3b9b3b4134e598a6d719ff96d2f7dbf4e915b9
|
[] |
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 | 399 |
scm
|
Ex2.87.scm
|
#lang planet neil/sicp
;; INSTALLATION
(define (=zero-poly? poly)
(define (=zero-all-coeffs coeff-list)
(cond ((empty-termlist? coeff-list) true)
((not (=zero? (coeff (first-term coeff-list)))) false)
(else (=zero-all-coeffs (rest-terms coeff-list)))))
(=zero-all-coeffs (term-list poly)))
;; External interface for Integer package
(put '=zero? 'polynomial =zero-poly?)
| false |
fdbe0b71951bed7632a9cb85907e66c9b76c7c83
|
b67a7a30a1ab1a0734dedc6723c1a474104bd9c2
|
/tests/example.scm
|
cfb2b3016b6aa046a3a439a7bfed96e6dd43be4a
|
[] |
no_license
|
certainty/chicken_dict
|
124dcb4e9e349fe8d84d7a5220070fe66b4b09f8
|
7f1906aa07ee351354f364f41b07d85db18a0a6c
|
refs/heads/master
| 2021-01-22T11:46:51.282348 | 2012-05-12T11:02:10 | 2012-05-12T11:02:10 | 39,292,298 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,560 |
scm
|
example.scm
|
;;; example.scm ---
;;
;; Filename: example.scm
;; Description:
;; Author: David Krentzlin <[email protected]>
;; Maintainer:
;; Created: Di Apr 21 21:50:41 2009 (CEST)
;; Version: $Id$
;; Version:
;; Last-Updated: Mi Apr 22 22:48:40 2009 (CEST)
;; By: David Krentzlin <[email protected]>
;; Update #: 7
;; URL:
;; Keywords:
;; Compatibility:
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Commentary:
;;
;;
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Change log:
;;
;;
;; RCS $Log$
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Copyright (c) 2009 David Krentzlin <[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.
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;;; Code:
(use dict)
(*current-log-port* (current-output-port))
(define con (connect "dict.org"))
(receive (success matches) (!match con "scheme" db: 'all)
(if success
(printf "Found matches: ~A~%" matches)))
(receive (success def) (!define con "Scheme-to-C" db: "foldoc")
(if (and success (not (null? def)))
(printf "Defintion for Scheme-to-C: ~A~%" (definition-text (car def)))))
(receive (success strats) (!strategies con)
(if success
(printf "Strategies: ~A~%" strats)))
(disconnect con)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; example.scm ends here
| false |
4a69e94a681ddc1602a5c7d4b54066695174c76d
|
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
|
/sitelib/text/unicode/grapheme.scm
|
71f5ab76a4166e115490f78859d3d36801f09cac
|
[
"BSD-3-Clause",
"LicenseRef-scancode-other-permissive",
"MIT",
"BSD-2-Clause"
] |
permissive
|
ktakashi/sagittarius-scheme
|
0a6d23a9004e8775792ebe27a395366457daba81
|
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
|
refs/heads/master
| 2023-09-01T23:45:52.702741 | 2023-08-31T10:36:08 | 2023-08-31T10:36:08 | 41,153,733 | 48 | 7 |
NOASSERTION
| 2022-07-13T18:04:42 | 2015-08-21T12:07:54 |
Scheme
|
UTF-8
|
Scheme
| false | false | 5,481 |
scm
|
grapheme.scm
|
;;; -*- mode:scheme; coding:utf-8; -*-
;;;
;;; text/unicode/grapheme.scm - Unicode grapheme generator
;;;
;;; Copyright (c) 2023 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
#!nounbound
(library (text unicode grapheme)
(export grapheme-strategy)
(import (rnrs)
(peg)
(peg chars)
(sagittarius generators)
(sagittarius char-sets grapheme)
(sagittarius char-sets emojis)
(srfi :1 lists)
(srfi :13 strings)
(srfi :14 char-sets)
(srfi :127 lseqs))
(define $cr ($eqv? #\return))
(define $lf ($eqv? #\newline))
(define $control ($char-set-contains? char-set:control))
(define $hangul-l ($char-set-contains? char-set:hangul-l))
(define $hangul-v ($char-set-contains? char-set:hangul-v))
(define $hangul-t ($char-set-contains? char-set:hangul-t))
(define $hangul-lv ($char-set-contains? char-set:hangul-lv))
(define $hangul-lvt ($char-set-contains? char-set:hangul-lvt))
(define $extend ($char-set-contains? char-set:extend))
(define $zwj ($char-set-contains? char-set:zwj))
(define $ri ($char-set-contains? char-set:regional-indicator))
(define $spacing-mark ($char-set-contains? char-set:spacing-mark))
(define $prepend ($char-set-contains? char-set:prepend))
(define $ext-pict ($char-set-contains? char-set:extended-pictographic))
;; From Table 1b
;; extended grapheme cluster := crlf
;; | Control
;; | precore* core postcore*
(define $crlf ($seq $cr $lf ($return "\r\n")))
;; CR and LF is not Control, so need to explicitly added
(define $control ($do (c ($or $control $cr $lf)) ($return (string c))))
(define $precore $prepend)
;; postcore := [Extend ZWJ SpacingMark]
(define $postcore
($do (c ($or $extend $zwj $spacing-mark)) ($return (string c))))
;; hangul-syllable := L* (V+ | LV V* | LVT) T*
;; | L+
;; | T+
(define $hangul-syllable
($or ($let ((c0* ($many $hangul-l))
(c1* ($or ($many $hangul-v 1)
($do (lv $hangul-lv) (v* ($many $hangul-v))
($return (cons lv v*)))
($do (lvt $hangul-lvt) ($return (list lvt)))))
(c2* ($many $hangul-t)))
($return (string-append (list->string c0*)
(list->string c1*)
(list->string c2*))))
($do (c* ($many $hangul-l 1)) ($return (list->string c*)))
($do (c* ($many $hangul-t 1)) ($return (list->string c*)))))
;; RI-Sequence := RI RI
(define $ri-sequence ($do (ri0 $ri) (ri1 $ri) ($return (string ri0 ri1))))
;; The below is incorrect, so GB12 and GB13 is a bit misleading to me.
#;(define $ri-sequence
($do (2ri* ($many $riri 1)) ($return (string-concatenate 2ri*))))
;; xpicto-sequence := \p{Extended_Pictographic} (Extend* ZWJ \p{Extended_Pictographic})*
(define $xpicto-sequence
($let ((e1 $ext-pict)
(e* ($many ($do (e* ($many $extend)) (zwj $zwj) (ext $ext-pict)
($return (list->string `(,@e* ,zwj ,ext)))))))
($return (apply string-append (string e1) e*))))
;; core := hangul-syllable
;; | ri-sequence
;; | xpicto-sequence
;; | [^Control CR LF]
(define $core
($or $hangul-syllable
$ri-sequence
$xpicto-sequence
($do (($not ($or $control $cr $lf))) (c $any) ($return (string c)))))
(define $grapheme
($or $crlf
$control
($let ((pre* ($many $precore))
(core $core)
(post* ($many $postcore)))
($return (string-append (list->string pre*)
core
(string-concatenate post*))))
;; GB9a (this can't be handled by the regexp definition of Unicode)
($do (p* ($many $precore)) ($return (list->string p*)))
;; GB999 (default break)
($do (c $any) ($return (string c)))))
;; [Generator] -> [Generator]
;; extended grapheme strategy :)
(define (grapheme-strategy generator)
(let ((lseq (generator->lseq generator)))
(lambda ()
(if (null? lseq)
(eof-object)
(let-values (((s v nl) ($grapheme lseq)))
(cond ((parse-success? s)
(set! lseq nl)
v)
(else
(lseq-realize lseq)
(error 'grapheme-strategy
"Invalid character" (list->string lseq)))))))))
)
| false |
be53f030eb04ebeee2ce10a9e3f99c3fbc4b8314
|
51d30de9d65cc3d5079f050de33d574584183039
|
/utility/assert.scm
|
f2003922562d8f7e2dc27c0867aa40228bcc3258
|
[
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
langmartin/ykk
|
30feb00265d603ef765b5c664d2f759be34b7b89
|
dd6e441dddd5b6363ee9adbbdd0f346c1522ffcf
|
refs/heads/master
| 2016-09-05T20:01:19.353224 | 2009-12-10T16:25:55 | 2009-12-10T16:25:55 | 408,478 | 0 | 1 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 876 |
scm
|
assert.scm
|
(define-syntax assert
(syntax-rules (=>)
((_ expr => expected)
(let ((result expr))
(or (equal? result expected)
(error (concat (concat-write 'expr) " => " expected)
result))))
((_ e1 => r1 e2 ...)
(begin (assert e1 => r1)
(assert e2 ...)))
((_ expr)
(let ((result expr))
(or result (error (concat-write 'expr) #f))))
((_ e1 e2 ...)
(begin (assert e1)
(assert e2 ...)))))
(define (concat-for-each writer things)
(call-with-string-output-port
(lambda (port)
(call-with-current-output-port
port
(lambda ()
(for-each writer things))))))
(define (concat . things)
(concat-for-each display things))
(define (concat-write . things)
(concat-for-each write things))
(define (concat->symbol . args)
(string->symbol
(apply concat args)))
| true |
02740a1ffb19e3ca49b9afb9052b15d72a8f42dd
|
0bb7631745a274104b084f6684671c3ee9a7b804
|
/lib/_num#.scm
|
205af3a39ea29f5e25ba30845184b854bf5e7b65
|
[
"Apache-2.0",
"LGPL-2.1-only",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-or-later",
"LicenseRef-scancode-autoconf-simple-exception"
] |
permissive
|
feeley/gambit
|
f87fd33034403713ad8f6a16d3ef0290c57a77d5
|
7438e002c7a41a5b1de7f51e3254168b7d13e8ba
|
refs/heads/master
| 2023-03-17T06:19:15.652170 | 2022-09-05T14:31:53 | 2022-09-05T14:31:53 | 220,799,690 | 0 | 1 |
Apache-2.0
| 2019-11-10T15:09:28 | 2019-11-10T14:14:16 | null |
UTF-8
|
Scheme
| false | false | 25,524 |
scm
|
_num#.scm
|
;;;============================================================================
;;; File: "_num#.scm"
;;; Copyright (c) 1994-2021 by Marc Feeley, All Rights Reserved.
;;;============================================================================
;;; Representation of exceptions.
(define-library-type-of-exception range-exception
id: 10aa6857-6f27-45ab-ac38-2318ef2f277c
constructor: #f
opaque:
(procedure unprintable: read-only: no-functional-setter:)
(arguments unprintable: read-only: no-functional-setter:)
(arg-id unprintable: read-only: no-functional-setter:)
)
(define-library-type-of-exception divide-by-zero-exception
id: c4319ec5-29d5-43f3-bd16-fad15b238e82
constructor: #f
opaque:
(procedure unprintable: read-only: no-functional-setter:)
(arguments unprintable: read-only: no-functional-setter:)
)
(define-library-type-of-exception fixnum-overflow-exception
id: dd080472-485f-4f09-8e9e-924194042ff3
constructor: #f
opaque:
(procedure unprintable: read-only: no-functional-setter:)
(arguments unprintable: read-only: no-functional-setter:)
)
;;;----------------------------------------------------------------------------
;;; Define type checking macros.
(##define-macro (macro-index? var)
`(##not (##fxnegative? ,var)))
(##define-macro (macro-index-range? var lo hi)
`(macro-fixnum-range? ,var ,lo ,hi))
(##define-macro (macro-index-range-incl? var lo hi)
`(macro-fixnum-range-incl? ,var ,lo ,hi))
(##define-macro (macro-fixnum-range? var lo hi)
`(and (##not (##fx< ,var ,lo))
(##fx< ,var ,hi)))
(##define-macro (macro-fixnum-range-incl? var lo hi)
`(##fx<= ,lo ,var ,hi))
(##define-macro (macro-fixnum-and-fixnum-range-incl? var lo hi)
`(and (##fixnum? ,var)
(macro-fixnum-range-incl? ,var ,lo ,hi)))
(##define-macro (macro-range-incl? var lo hi)
`(and (macro-exact-int? ,var)
(##not (##< ,var ,lo))
(##not (##< ,hi ,var))))
(define-check-index-range-macro
index
macro-index?)
(define-check-index-range-macro
index-range
macro-index-range?
lo
hi)
(define-check-index-range-macro
index-range-incl
macro-index-range-incl?
lo
hi)
(define-check-index-range-macro
fixnum-range
macro-fixnum-range?
lo
hi)
(define-check-index-range-macro
fixnum-range-incl
macro-fixnum-range-incl?
lo
hi)
(define-check-type exact-unsigned-int8 'exact-unsigned-int8
macro-fixnum-and-fixnum-range-incl?
0
255)
(define-check-type (list exact-unsigned-int8-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-unsigned-int8-list exact-unsigned-int8-list-exact-unsigned-int8) 'exact-unsigned-int8-list
macro-fixnum-and-fixnum-range-incl?
0
255)
(macro-if-s8vector
(begin
(define-check-type exact-signed-int8 'exact-signed-int8
macro-fixnum-and-fixnum-range-incl?
-128
127)
(define-check-type (list exact-signed-int8-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-signed-int8-list exact-signed-int8-list-exact-signed-int8) 'exact-signed-int8-list
macro-fixnum-and-fixnum-range-incl?
-128
127)))
(macro-if-u16vector
(begin
(define-check-type exact-unsigned-int16 'exact-unsigned-int16
macro-fixnum-and-fixnum-range-incl?
0
65535)
(define-check-type (list exact-unsigned-int16-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-unsigned-int16-list exact-unsigned-int16-list-exact-unsigned-int16) 'exact-unsigned-int16-list
macro-fixnum-and-fixnum-range-incl?
0
65535)))
(macro-if-s16vector
(begin
(define-check-type exact-signed-int16 'exact-signed-int16
macro-fixnum-and-fixnum-range-incl?
-32768
32767)
(define-check-type (list exact-signed-int16-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-signed-int16-list exact-signed-int16-list-exact-signed-int16) 'exact-signed-int16-list
macro-fixnum-and-fixnum-range-incl?
-32768
32767)))
(macro-if-u32vector
(begin
(define-check-type exact-unsigned-int32 'exact-unsigned-int32
macro-range-incl?
0
4294967295)
(define-check-type (list exact-unsigned-int32-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-unsigned-int32-list exact-unsigned-int32-list-exact-unsigned-int32) 'exact-unsigned-int32-list
macro-range-incl?
0
4294967295)))
(macro-if-s32vector
(begin
(define-check-type exact-signed-int32 'exact-signed-int32
macro-range-incl?
-2147483648
2147483647)
(define-check-type (list exact-signed-int32-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-signed-int32-list exact-signed-int32-list-exact-signed-int32) 'exact-signed-int32-list
macro-range-incl?
-2147483648
2147483647)))
(macro-if-u64vector
(begin
(define-check-type exact-unsigned-int64 'exact-unsigned-int64
macro-range-incl?
0
18446744073709551615)
(define-check-type (list exact-unsigned-int64-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-unsigned-int64-list exact-unsigned-int64-list-exact-unsigned-int64) 'exact-unsigned-int64-list
macro-range-incl?
0
18446744073709551615)))
(macro-if-s64vector
(begin
(define-check-type exact-signed-int64 'exact-signed-int64
macro-range-incl?
-9223372036854775808
9223372036854775807)
(define-check-type (list exact-signed-int64-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (exact-signed-int64-list exact-signed-int64-list-exact-signed-int64) 'exact-signed-int64-list
macro-range-incl?
-9223372036854775808
9223372036854775807)))
(define-check-type exact-integer 'exact-integer
macro-exact-int?)
(define-check-type nonnegative-exact-integer 'nonnegative-exact-integer
macro-nonnegative-exact-int?)
(define-check-type inexact-real 'inexact-real
##flonum?)
(define-check-type (list inexact-real-list) #f
(lambda (obj) #t)) ;; defer detailed checks to logic traversing the list
(define-check-type (inexact-real-list inexact-real-list-inexact-real) 'inexact-real-list
##flonum?)
(define-check-type number 'number
##number?)
(define-check-type real 'real
##real?)
(define-check-type fixnum 'fixnum
##fixnum?)
(define-check-type flonum 'flonum
##flonum?)
;;;============================================================================
;;; Number representation.
;; There are 5 internal representations for numbers:
;;
;; fixnum, bignum, ratnum, flonum, cpxnum
;;
;; Fixnums and bignums form the class of exact-int.
;; Fixnums, bignums and ratnums form the class of exact-real.
;; Fixnums, bignums, ratnums and flonums form the class of noncpxnum.
;; The representation has some invariants:
;;
;; The numerator of a ratnum is a non-zero exact-int.
;; The denominator of a ratnum is an exact-int greater than 1.
;; The numerator and denominator have no common divisors greater than 1.
;;
;; The real part of a cpxnum is a noncpxnum.
;; The imaginary part of a cpxnum is a noncpxnum != fixnum 0
;; The following table gives the mapping of the Scheme exact numbers to their
;; internal representation:
;;
;; type representation
;; exact integer = exact-int (fixnum, bignum)
;; exact rational = exact-real (fixnum, bignum, ratnum)
;; exact real = exact-real (fixnum, bignum, ratnum)
;; exact complex = exact-real or cpxnum with exact-real real and imag parts
;; For inexact numbers, the representation is not quite as straightforward.
;;
;; There are 3 special classes of inexact representation:
;; flonum-int : flonum with integer value
;; cpxnum-real: cpxnum with imag part = flonum 0.0 or -0.0
;; cpxnum-int : cpxnum-real with exact-int or flonum-int real part
;;
;; Note: cpxnum-real and cpxnum-int only exist if
;; (macro-cpxnum-are-possibly-real?) returns #t.
;;
;; This gives the following table for Scheme's inexact numbers:
;;
;; type representation
;; inexact integer = flonum-int or cpxnum-int if it exists
;; inexact rational = flonum or cpxnum-real if it exists
;; inexact real = flonum or cpxnum-real if it exists
;; inexact complex = flonum or cpxnum with flonum real or imag part
(##define-macro (macro-special-case-exact-zero?) #t); (+ -0. 0)=-0. (* 4. 0)=0
(##define-macro (macro-cpxnum-are-possibly-real?) #f)
(##define-macro (macro-exact-int? obj) ;; obj can be any object
`(macro-exact-int-dispatch ,obj #f #t #t))
(##define-macro (macro-nonnegative-exact-int? obj)
`(let ((obj ,obj))
(macro-exact-int-dispatch
obj #f
(##not (##fxnegative? obj))
(##not (##negative? obj)))))
(##define-macro (macro-exact-real? obj) ;; obj can be any object
`(macro-exact-real-dispatch ,obj #f #t #t #t))
(##define-macro (macro-flonum-int? obj) ;; obj must be a flonum
`(##flinteger? ,obj))
(##define-macro (macro-flonum-rational? obj) ;; obj must be a flonum
`(##flfinite? ,obj))
(##define-macro (macro-noncpxnum-int? obj) ;; obj must be in fixnum/bignum/ratnum/flonum
`(if (##flonum? ,obj)
(macro-flonum-int? ,obj)
(##not (##ratnum? ,obj))))
(##define-macro (macro-noncpxnum-rational? obj) ;; obj must be in fixnum/bignum/ratnum/flonum
`(or (##not (##flonum? ,obj))
(macro-flonum-rational? ,obj)))
(##define-macro (macro-cpxnum-int? obj) ;; obj must be a cpxnum
`(and (macro-cpxnum-are-possibly-real?)
(macro-cpxnum-real? ,obj)
(let ((real (macro-cpxnum-real ,obj)))
(macro-noncpxnum-int? real))))
(##define-macro (macro-cpxnum-rational? obj) ;; obj must be a cpxnum
`(and (macro-cpxnum-are-possibly-real?)
(let ((imag (macro-cpxnum-imag ,obj)))
(and (##flonum? imag)
(##flzero? imag)
(let ((real (macro-cpxnum-real ,obj)))
(macro-noncpxnum-rational? real))))))
(##define-macro (macro-cpxnum-real? obj) ;; obj must be a cpxnum
`(and (macro-cpxnum-are-possibly-real?)
(let ((imag (macro-cpxnum-imag ,obj)))
(and (##flonum? imag)
(##flzero? imag)))))
(macro-define-syntax macro-if-bignum
(lambda (stx)
(syntax-case stx ()
((_ yes)
#'(macro-if-bignum yes (##begin)))
((_ yes no)
#'(cond-expand
((or enable-bignum (not disable-bignum))
yes)
(else
no))))))
(macro-define-syntax macro-if-ratnum
(lambda (stx)
(syntax-case stx ()
((_ yes)
#'(macro-if-ratnum yes (##begin)))
((_ yes no)
#'(cond-expand
((or enable-ratnum (not disable-ratnum))
yes)
(else
no))))))
(macro-define-syntax macro-if-cpxnum
(lambda (stx)
(syntax-case stx ()
((_ yes)
#'(macro-if-cpxnum yes (##begin)))
((_ yes no)
#'(cond-expand
((or enable-cpxnum (not disable-cpxnum))
yes)
(else
no))))))
;; Dispatch for number representation
(macro-define-syntax macro-number-dispatch
(lambda (stx)
(syntax-case stx ()
((_ num err fix big rat flo cpx)
#'(macro-if-bignum
(macro-if-ratnum
(macro-if-cpxnum
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
((##bignum? num) big)
((##ratnum? num) rat)
((##cpxnum? num) cpx)
(else err))
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
((##bignum? num) big)
((##ratnum? num) rat)
;;((##cpxnum? num) cpx)
(else err)))
(macro-if-cpxnum
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
((##bignum? num) big)
;;((##ratnum? num) rat)
((##cpxnum? num) cpx)
(else err))
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
((##bignum? num) big)
;;((##ratnum? num) rat)
;;((##cpxnum? num) cpx)
(else err))))
(macro-if-ratnum
(macro-if-cpxnum
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
;;((##bignum? num) big)
((##ratnum? num) rat)
((##cpxnum? num) cpx)
(else err))
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
;;((##bignum? num) big)
((##ratnum? num) rat)
;;((##cpxnum? num) cpx)
(else err)))
(macro-if-cpxnum
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
;;((##bignum? num) big)
;;((##ratnum? num) rat)
((##cpxnum? num) cpx)
(else err))
(cond ((##fixnum? num) fix)
((##flonum? num) flo)
;;((##bignum? num) big)
;;((##ratnum? num) rat)
;;((##cpxnum? num) cpx)
(else err)))))))))
(macro-define-syntax macro-exact-real-dispatch
(lambda (stx)
(syntax-case stx ()
((_ num err fix big rat)
#'(macro-if-bignum
(macro-if-ratnum
(cond ((##fixnum? num) fix)
((##bignum? num) big)
((##ratnum? num) rat)
(else err))
(cond ((##fixnum? num) fix)
((##bignum? num) big)
;;((##ratnum? num) rat)
(else err)))
(macro-if-ratnum
(cond ((##fixnum? num) fix)
;;((##bignum? num) big)
((##ratnum? num) rat)
(else err))
(cond ((##fixnum? num) fix)
;;((##bignum? num) big)
;;((##ratnum? num) rat)
(else err))))))))
(macro-define-syntax macro-exact-int-dispatch
(lambda (stx)
(syntax-case stx ()
((_ num err fix big)
#'(macro-if-bignum
(cond ((##fixnum? num) fix)
((##bignum? num) big)
(else err))
(cond ((##fixnum? num) fix)
;;((##bignum? num) big)
(else err)))))))
(macro-define-syntax macro-exact-int-dispatch-no-error
(lambda (stx)
(syntax-case stx ()
((_ num fix big)
#'(macro-if-bignum
(if (##fixnum? num)
fix
big)
fix)))))
(macro-define-syntax macro-if-enable-assert-normalized-exact-int
(lambda (stx)
(syntax-case stx ()
((_ yes)
#'(macro-if-enable-assert-normalized-exact-int yes (##begin)))
((_ yes no)
#'no))))
(macro-define-syntax macro-assert-normalized-exact-int
(lambda (stx)
(syntax-case stx ()
((_ expr)
#'(macro-if-enable-assert-normalized-exact-int
(##let (($val expr))
(##if (##not (##or (##fixnum? $val)
(##bignum.normalized? $val)))
(##error "normalized exact integer expected:" $val))
$val)
(##begin))))))
(macro-define-syntax define-prim-normalized-exact-int
(lambda (stx)
(syntax-case stx ()
((_ pattern . body)
#'(define-prim pattern
(macro-if-enable-assert-normalized-exact-int
(##let (($result (##let () . body)))
(macro-assert-normalized-exact-int $result)
$result)
(##let () . body)))))))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;; Miscellaneous constants.
(##define-macro (macro-inexact-+4) 4.0)
(##define-macro (macro-inexact-+2) 2.0)
(##define-macro (macro-inexact--2) -2.0)
(##define-macro (macro-inexact-+1) 1.0)
(##define-macro (macro-inexact--1) -1.0)
(##define-macro (macro-inexact-+1/2) 0.5)
(##define-macro (macro-inexact-+0) 0.0)
(##define-macro (macro-inexact--0) -0.0)
(##define-macro (macro-inexact-+pi) 3.141592653589793)
(##define-macro (macro-inexact--pi) -3.141592653589793)
(##define-macro (macro-inexact-+pi/2) 1.5707963267948966)
(##define-macro (macro-inexact--pi/2) -1.5707963267948966)
(##define-macro (macro-inexact-+pi/4) .7853981633974483)
(##define-macro (macro-inexact-+3pi/4) 2.356194490192345)
(##define-macro (macro-inexact-+inf) (/ +1. 0.))
(##define-macro (macro-inexact--inf) (/ -1. 0.))
(##define-macro (macro-inexact-+nan) (##flcopysign (/ 0. 0.) +1.))
(##define-macro (macro-cpxnum-+2i) +2i)
(##define-macro (macro-cpxnum--i) -i)
(##define-macro (macro-cpxnum-+i) +i)
(##define-macro (macro-cpxnum-+1/2+sqrt3/2i)
(make-rectangular 1/2 (/ (sqrt 3) 2)))
(##define-macro (macro-cpxnum-+1/2-sqrt3/2i)
(make-rectangular 1/2 (- (/ (sqrt 3) 2))))
(##define-macro (macro-cpxnum--1/2+sqrt3/2i)
(make-rectangular -1/2 (/ (sqrt 3) 2)))
(##define-macro (macro-cpxnum--1/2-sqrt3/2i)
(make-rectangular -1/2 (- (/ (sqrt 3) 2))))
(##define-macro (macro-cpxnum-+sqrt3/2+1/2i)
(make-rectangular (/ (sqrt 3) 2) 1/2))
(##define-macro (macro-cpxnum-+sqrt3/2-1/2i)
(make-rectangular (/ (sqrt 3) 2) -1/2))
(##define-macro (macro-cpxnum--sqrt3/2+1/2i)
(make-rectangular (- (/ (sqrt 3) 2)) 1/2))
(##define-macro (macro-cpxnum--sqrt3/2-1/2i)
(make-rectangular (- (/ (sqrt 3) 2)) -1/2))
(##define-macro (macro-inexact-exp-+1/2) (exp +1/2))
(##define-macro (macro-inexact-exp--1/2) (exp -1/2))
(##define-macro (macro-inexact-log-2) (log 2))
;;; The next constants are for 64-bit, IEEE 754 binary arithmetic
(##define-macro (macro-inexact-epsilon) 1.1102230246251565e-16) ; (- 1 epsilon) <> 1, epsilon smallest
(##define-macro (macro-inexact-lambda) 2.2250738585072014e-308) ; smallest positive flonum
(##define-macro (macro-inexact-omega) 1.7976931348623157e308) ; largest finite flonum
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;; Bignum related constants.
(##define-macro (macro-max-lines) 65536)
(##define-macro (macro-max-fixnum32-div-max-lines) 8191)
(##define-macro (macro-max-fixnum32) 536870911)
(##define-macro (macro-max-fixnum32-div-10) 53687091)
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;; Flonum related constants.
(##define-macro (macro-flonum-m-bits)
52)
(##define-macro (macro-flonum-m-bits-plus-1)
53)
(##define-macro (macro-flonum-m-bits-plus-1*2)
106)
(##define-macro (macro-flonum-e-bits)
11)
(##define-macro (macro-flonum-sign-bit) ;; (expt 2 (+ (macro-flonum-e-bits) (macro-flonum-m-bits)))
#x8000000000000000)
(##define-macro (macro-flonum-m-min) ;; (expt 2.0 (macro-flonum-m-bits))
4503599627370496.0)
(##define-macro (macro-flonum-+m-min) ;; (expt 2 (macro-flonum-m-bits))
4503599627370496)
(##define-macro (macro-flonum-+m-max-plus-1) ;; (expt 2 (macro-flonum-m-bits-plus-1))
9007199254740992)
(##define-macro (macro-flonum-+m-max) ;; (- (macro-flonum-+m-max-plus-1) 1)
9007199254740991)
(##define-macro (macro-flonum-+m-max-plus-1-inexact);; (exact->inexact (macro-flonum-+m-max-plus-1))
9007199254740992.0)
(##define-macro (macro-flonum-inverse-+m-max-plus-1-inexact);; (/ (macro-flonum-+m-max-plus-1-inexact))
(/ 9007199254740992.0))
(##define-macro (macro-flonum--m-min) ;; (- (macro-flonum-+m-min))
-4503599627370496)
(##define-macro (macro-flonum--m-max) ;; (- (macro-flonum-+m-max))
-9007199254740991)
(##define-macro (macro-flonum-e-bias) ;; (- (expt 2 (- (macro-flonum-e-bits) 1)) 1)
1023)
(##define-macro (macro-flonum-e-bias-plus-1) ;; (+ (macro-flonum-e-bias) 1)
1024)
(##define-macro (macro-flonum-e-bias-minus-1) ;; (- (macro-flonum-e-bias) 1)
1022)
(##define-macro (macro-flonum-e-min) ;; (- (+ (macro-flonum-e-bias) (macro-flonum-m-bits) -1))
-1074)
(##define-macro (macro-flonum-min-normal) ;; (expt 2.0 (+ (macro-flonum-m-bits) (macro-flonum-e-min)))
(expt 2.0 (+ 52 -1074)))
(##define-macro (macro-scale-down) ;; (expt 2 (- (+ (quotient (macro-flonum-e-bias-plus-1) 2) 1)))
(expt 2 -513))
(##define-macro (macro-inexact-scale-down) ;; (expt 2.0 (- (+ (quotient (macro-flonum-e-bias-plus-1) 2) 1)))
(expt 2.0 -513))
(##define-macro (macro-scale-up) ;; (expt 2 (+ (quotient (macro-flonum-e-bias-plus-1) 2) (macro-flonum-m-bits-plus-1)))
(expt 2 565))
(##define-macro (macro-inexact-scale-up) ;; (expt 2.0 (+ (quotient (macro-flonum-e-bias-plus-1) 2) (macro-flonum-m-bits-plus-1)))
(expt 2.0 565))
(##define-macro (macro-inexact-radix) ;; (exact->inexact (macro-radix))
16384.0)
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;; Ratnum objects.
;; A ratnum is represented by an object vector of length 2
;; slot 0 = numerator
;; slot 1 = denominator
(##define-macro (macro-ratnum-make num den) `(##ratnum-make ,num ,den))
(##define-macro (macro-ratnum-numerator r) `(##ratnum-numerator ,r))
(##define-macro (macro-ratnum-denominator r) `(##ratnum-denominator ,r))
(define-macro (macro-exact-int->ratnum x)
`(macro-ratnum-make ,x 1))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;;; Cpxnum objects.
;; A cpxnum is represented by an object vector of length 2
;; slot 0 = real
;; slot 1 = imag
(##define-macro (macro-cpxnum-make r i) `(##cpxnum-make ,r ,i))
(##define-macro (macro-cpxnum-real c) `(##cpxnum-real ,c))
(##define-macro (macro-cpxnum-imag c) `(##cpxnum-imag ,c))
(define-macro (macro-noncpxnum->cpxnum x)
`(macro-cpxnum-make ,x 0))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(##define-macro (macro-bignum-odd? x);;;;;;;;;;;;;;;;;;;;
`(##fxodd? (##bignum.mdigit-ref ,x 0)))
(##define-macro (macro-real->inexact x)
`(let ((x ,x))
(if (##flonum? x)
x
(##exact->inexact
(if (macro-cpxnum-are-possibly-real?)
(##real-part x)
x)))))
;;; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
;; Fast path for conversion of small integers and floating point numbers
;; possibly prefixed with a sign.
(##define-macro (macro-string->number-decimal-fast-path str)
`(let ((str ,str))
(declare (standard-bindings) (extended-bindings) (not safe) (not interrupts-enabled))
(let ((len (string-length str)))
(and (fx< 0 len) ;; at least one character
(let ((start
(let ((first (string-ref str 0)))
(if (or (char=? first #\+)
(char=? first #\-))
1
0))))
(and (fx< (fx- len start) 9) ;; won't overflow 32 bit fixnums?
(fx< start len) ;; at least one remaining character
(let loop1 ((i start)
(n 0))
(if (fx< i (string-length str))
(let ((d (fx- (char->integer (string-ref str i)) 48)))
(if (and (fx>= d 0) (fx<= d 9))
(loop1 (fx+ i 1)
(fx+ (fx* n 10) d))
(if (fx= d -2) ;; character is "."?
(let loop2 ((i (fx+ i 1)) (n n) (p10 1))
(if (fx< i (string-length str))
(let ((d (fx- (char->integer (string-ref str i)) 48)))
(if (and (fx>= d 0) (fx<= d 9))
(loop2 (fx+ i 1)
(fx+ (fx* n 10) d)
(fx* p10 10))
#f))
(let ((first (string-ref str 0)))
(and (or (fx< 1 p10) ;; end != "."
(not (fx= i
(if (or (char=? first #\+)
(char=? first #\-))
2
1))))
(##flcopysign
(fl/ (fixnum->flonum n)
(fixnum->flonum p10))
(if (char=? first #\-)
(macro-inexact--1)
(macro-inexact-+1)))))))
#f)))
(if (char=? (string-ref str 0) #\-)
(fx- n)
n)))))))))
;;;============================================================================
| true |
18e40413451f559779e859efd23c1d61af1c2a48
|
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
|
/scheme/swl1.3/src/oop/dispatch.ss
|
7c8bf1edfa2c48e6c26fb1bfe7bfcac8d2071f08
|
[
"SWL",
"TCL"
] |
permissive
|
ktosiu/snippets
|
79c58416117fa646ae06a8fd590193c9dd89f414
|
08e0655361695ed90e1b901d75f184c52bb72f35
|
refs/heads/master
| 2021-01-17T08:13:34.067768 | 2016-01-29T15:42:14 | 2016-01-29T15:42:14 | 53,054,819 | 1 | 0 | null | 2016-03-03T14:06:53 | 2016-03-03T14:06:53 | null |
UTF-8
|
Scheme
| false | false | 12,350 |
ss
|
dispatch.ss
|
;; Copyright (c) 1996 R. Kent Dybvig, Carl Bruggeman, and Oscar Waddell
;;
;; See the file "Notice" for information on usage and redistribution
;; of this file, and for a DISCLAIMER OF ALL WARRANTIES.
;;; swl:dispatch-table implementation based on object-lambda
;; for internal use only
;;; quick-hack mode on for now
;;; (swl:dispatch-table delegate [msg args body] ...)
;;; delegate is a binding for another swl:dispatch-table (gives inheritance)
;;; a variant of object-lambda
;;; (object-lambda self [msg args body] ...)
;;; self is optional, and if present must be an identifier.
;;; If supplied, it is a name by which the object may
;;; refer to itself.
;;; msg is any Scheme object and serves as a message
;;; specifier distinguished using eqv?.
;;; args is a lambda list specifying the message arguments.
;;; body is a lambda body (zero or more definitions followed
;;; by at least one expression.
;;; An object-lambda expression evaluates to a procedure. When a
;;; procedure created by object-lambda is invoked, at most one clause
;;; is selected. A clause is selected by comparing the incoming message
;;; (first argument) and arity (count of arguments excluding the message)
;;; against the messages and accepted arities of each clause, in
;;; left-to-right order. The first matching clause is selected. If no
;;; clause is selected, an error is signaled. If a clause is selected,
;;; its formal parameters (args) are bound to the actual paramters
;;; (exclusive of the message argument) within body.
;;; The same message specifier may appear in more than one object-lambda
;;; clauses, provided that the clauses have different arities. If two
;;; clauses have the same message specifier and arity, the first always
;;; takes precedence, and the second is therefore unreachable. Similarly,
;;; if two clauses have the same message specifier, and the first has
;;; a more general interface (necessarily a "dot" interface), the first
;;; again always takes precedence and the second is unreachable.
;;; An object-lambda expression expands into a case-lambda expression,
;;; each clause of which contains a case expression. Each clause of
;;; the object-lambda expression is represented by one case within
;;; each of one or more case-lambda clauses. Minimal reordering of
;;; clauses is done to preserve the user-specified ordering to allow
;;; programmers to base ordering on predicted message frequency for
;;; efficiency. Reordering is done only to allow correct left-to-right
;;; ordering of messages.
;;; The translation algorithm works as follows:
;;; * The set of required case-lambda clauses is determined from
;;; the set of object-lambda clauses. A clause accepting zero or
;;; more arguments is always created to serve as an "else"
;;; to catch invalid invocations. The clauses are reordered only
;;; as necessary to place more specific interfaces in front of
;;; less specific (but comparable) interfaces.
;;; * Cases are inserted into case-lambda clauses by a left-to-right
;;; traversal of the object-lambda clauses. An object-lambda
;;; clause with a "dot" interface may be represented by a case
;;; in more than one case-lambda clause. Warnings are issued
;;; for unreachable object-lambda clauses, which are otherwise
;;; discarded.
;;; * The output case-lambda expression is constructed, wrapped in a
;;; let expression containing temporary bindings for duplicated
;;; object-lambda clauses. Each clause of the case-lambda
;;; expression consists of a case expression. An else clause
;;; is included for each case expression to catch and signal
;;; invocation errors.
;; not intended to be exposed to user like object-lambda
(define-syntax swl:dispatch-table
(let ()
(import scheme)
(define arity
;; (arity '(x1 ... xn)), n>=0 => n
;; (arity 'r) => -1
;; (arity '(x1 ... xn . r)), n>=1 => -(n+1)
(lambda (args)
(let f ([args args] [n 0])
(if (pair? args)
(f (cdr args) (+ n 1))
(if (null? args)
n
(- -1 n))))))
(define flatten-args
;; (flatten-args '(x1 ... xn)), n>=0 => (x1 ... xn)
;; (flatten-args 'r) => (r)
;; (flatten-args '(x1 ... xn . r)), n>=1 => (x1 ... xn r)
(lambda (args)
(let f ([x args])
(syntax-case x ()
[(x . y) (with-syntax ([rest (f (syntax y))])
(syntax (x . rest)))]
[() (syntax ())]
[x (syntax (x))]))))
(define build-args
;; (build-args n), n>=0 => (g1 ... gn)
;; (build-args -(n+1)), n>=1 => (g1 ... gn . g)
;; (build-args -1) => g
(lambda (a)
(if (< a 0)
(let f ((a a))
(if (= a -1)
(gentmp)
(cons (gentmp) (f (+ a 1)))))
(generate-temporaries (make-list a #f)))))
(define gentmp
(lambda ()
(car (generate-temporaries '(#f)))))
(define-structure (objcase msg arity proc source)
([clauses '()]
[temp #f]))
(define-structure (clause arity args)
([cases '()]))
(define build-clauses
;; create list of clauses needed by the cases
;; reorder only if necessary to place a more specific case in
;; front of a less specific case (assumes sort performs a
;; stable sort)
(lambda (ocases)
(sort (lambda (x y)
; returns #t only if x must be placed before y
(let ([ax (clause-arity x)] [ay (clause-arity y)])
(and (< ay 0)
(or (>= ax 0)
(< ax ay)))))
(let f ([ocases ocases] [arities '()])
(if (null? ocases)
(if (memv -1 arities)
'()
(cons (make-clause -1 (gentmp)) '()))
(let ([a (objcase-arity (car ocases))])
(if (memv a arities)
(f (cdr ocases) arities)
(cons (make-clause a (build-args a))
(f (cdr ocases) (cons a arities))))))))))
(define mem
(lambda (pred? ls)
(unless (procedure? pred?)
(assertion-violationf 'mem "~s is not a procedure" pred?))
(let f ([l ls])
(cond
[(pair? l) (if (pred? (car l)) l (f (cdr l)))]
[(null? l) #f]
[else (assertion-violationf 'mem "~s is not a proper list" ls)]))))
(define memid
;; like memq, but for identifiers
(lambda (id ls)
(mem (lambda (x) (free-identifier=? x id))
ls)))
(define insert-case
;; insert ocase into clause if ocase arity matches clause arity
;; and ocase message not already represented
(lambda (ocase clause)
(let ([a (objcase-arity ocase)] [b (clause-arity clause)])
(when (and (if (>= a 0) (= a b) (if (>= b 0) (<= (- -1 a) b) (>= a b)))
(not (memid (objcase-msg ocase)
(map objcase-msg (clause-cases clause)))))
(set-objcase-clauses! ocase (cons clause (objcase-clauses ocase)))
; need to reverse cases later to preserve programmer order
(set-clause-cases! clause (cons ocase (clause-cases clause)))))))
(define build-output-bindings
;; create bindings from temp to lambda expression for all cases
;; that need them (those with nonfalse temp)
(lambda (ocases)
(if (null? ocases)
'()
(let ([temp (objcase-temp (car ocases))])
(if temp
(cons `(,temp ,(objcase-proc (car ocases)))
(build-output-bindings (cdr ocases)))
(build-output-bindings (cdr ocases)))))))
(define build-output-args
;; create the arguments for a call of arity a from arguments args.
(lambda (a args)
(if (>= a 0)
args
(let f ([a a] [args args])
(if (= a -1)
(if (list? args) ; proper list?
(with-syntax ([(arg ...) args])
(syntax ((list arg ...))))
(with-syntax ([(arg ...) (flatten-args args)])
(syntax ((list* arg ...)))))
(cons (car args) (f (+ a 1) (cdr args))))))))
(define build-ocase-clause
(lambda (ocase clause)
(with-syntax ([obj-msg (objcase-msg ocase)]
[obj-tmp (or (objcase-temp ocase) (objcase-proc ocase))]
[(out-arg ...) (build-output-args (objcase-arity ocase)
(clause-args clause))])
(syntax
[(obj-msg)
(obj-tmp self out-arg ...)]))))
(define build-output-clause
;; generate one case-lambda clause
(lambda (delegate-id clause)
(with-syntax ([delegate delegate-id]
[args (clause-args clause)]
[(cl ...) (map (lambda (ocase)
(build-ocase-clause ocase clause))
(reverse (clause-cases clause)))])
(if (negative? (clause-arity clause))
(with-syntax ((delegate-args (flatten-args (clause-args clause))))
(syntax
((msg inst . args)
(fluid-let-syntax ((self (identifier-syntax inst)))
(case msg
cl ...
(else (apply delegate msg inst . delegate-args)))))))
(syntax
((msg inst . args)
(fluid-let-syntax ((self (identifier-syntax inst)))
(case msg
cl ...
(else (delegate msg inst . args))))))))))
(define mk-ocase
(lambda (self-id) ; make sure we fluid-let-syntax the right self
(lambda (s) ; in case interaction-environment has changed
(syntax-case s ()
[(msg args e ...)
(with-syntax ([(flat-arg ...) (flatten-args #'args)])
(make-objcase
#'msg
(arity (syntax-object->datum #'args))
(with-syntax ([self self-id])
#'(lambda (init flat-arg ...)
(fluid-let-syntax ([self
(identifier-syntax init)])
e
...)))
#'(msg args e ...)))]))))
(define build-dispatch-table
(lambda (self-id delegate-id srcs)
(let ([ocases (map (mk-ocase self-id) srcs)])
(let ([clauses (build-clauses ocases)])
(for-each (lambda (ocase)
(for-each (lambda (clause) (insert-case ocase clause))
clauses))
ocases)
(for-each (lambda (ocase)
(if (null? (objcase-clauses ocase))
(warningf 'swl:dispatch-table
"unreachable case~n~s"
(syntax-object->datum (objcase-source ocase)))
(unless (null? (cdr (objcase-clauses ocase)))
(set-objcase-temp! ocase (gentmp)))))
ocases)
(with-syntax ([(binding ...) (build-output-bindings ocases)]
[(clause ...) (map (lambda (clause)
(build-output-clause
delegate-id clause))
clauses)])
(syntax (let (binding ...)
(case-lambda clause ...))))))))
(lambda (form)
(syntax-case form ()
[(_ self delegate (msg args e1 e2 ...) ...)
(with-syntax ([exp (build-dispatch-table (syntax self)
(syntax delegate)
(syntax ((msg args e1 e2 ...) ...)))])
(syntax exp))]))))
| true |
be88ca748673158dc4b2664d5533c0a9cad0d525
|
76d5c1dc03e5d3f239e9c0c66bfd4cfe884e27e6
|
/morescheme.scm
|
ddfc656af395c37f75e473c28666bbfb5d02eaec
|
[] |
no_license
|
vinport16/EECS-345-PLC
|
648d912eb15a1cfaf0f606eaff8d7677a5b0a007
|
9a68342fdc53fa8ad13df62731b0acad2627b693
|
refs/heads/master
| 2021-01-24T00:54:54.478472 | 2018-05-03T19:13:01 | 2018-05-03T19:13:01 | 122,787,356 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,988 |
scm
|
morescheme.scm
|
; (cadr x) = (car (cdr x))
; (caddr x) = (car (cdr (cdr x)))
; (caadr x) = (car (car (cdr x)))
; (cddr x) = (cdr (cdr x))
; m_value function: interprets prefix expressions
; '(* 3 5) => 15
; '(+ (- 2 1) 5) => 6
(define m_value
(lambda (exp)
(cond
((number? exp) exp)
((eq? (car exp) '+) (+ (m_value (cadr exp)) (m_value (caddr exp))))
((eq? (car exp) '-) (- (m_value (cadr exp)) (m_value (caddr exp))))
((eq? (car exp) '*) (* (m_value (cadr exp)) (m_value (caddr exp))))
((eq? (car exp) '/) (floor->exact (/ (m_value (cadr exp)) (m_value (caddr exp)))))
((eq? (car exp) '%) (- (m_value (cadr exp)) (* (floor->exact (/ (m_value (cadr exp)) (m_value (caddr exp)))) (caddr exp)) ))
(else '(error undefined "bad op"))
)))
;postfix kind
(define m_value
(lambda (exp)
(cond
((number? exp) exp)
((eq? (caddr exp) '+) (+ (m_value (car exp)) (m_value (cadr exp))))
((eq? (caddr exp) '-) (- (m_value (car exp)) (m_value (cadr exp))))
((eq? (caddr exp) '*) (* (m_value (car exp)) (m_value (cadr exp))))
((eq? (caddr exp) '/) (floor->exact (/ (m_value (car exp)) (m_value (cadr exp)))))
((eq? (caddr exp) '%) (- (m_value (car exp)) (* (floor->exact (/ (m_value (car exp)) (m_value (cadr exp)))) (cadr exp)) ))
(else '(error undefined "bad op"))
)))
;new thing: abstraction to put it in infix real quick
(define m_value
(lambda (exp)
(cond
((number? exp) exp)
((eq? (operator exp) '+) (+ (m_value (op1 exp)) (m_value (op2 exp))))
((eq? (operator exp) '-) (- (m_value (op1 exp)) (m_value (op2 exp))))
((eq? (operator exp) '*) (* (m_value (op1 exp)) (m_value (op2 exp))))
((eq? (operator exp) '/) (floor->exact (/ (m_value (op1 exp)) (m_value (op2 exp)))))
((eq? (operator exp) '%) (- (m_value (op1 exp)) (* (floor->exact (/ (m_value (op1 exp)) (m_value (op2 exp)))) (op2 exp)) ))
(else '(error undefined "bad op"))
)))
(define op1 car)
(define op2 caddr)
(define operator
(lambda (e)
(cadr e)))
| false |
71538c144e1f76003a6abd73bb2782af38743b40
|
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
|
/depends/xml-parser.ss
|
2794fddd23cb5bcaa6defe5e425c886e9ebf9db7
|
[
"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 | 90,325 |
ss
|
xml-parser.ss
|
; My Standard Scheme "Prelude"
; Version for Petite Chez Scheme 6.0a
; $Id: myenv-chez.scm,v 1.2 2004/07/08 21:53:32 oleg Exp $
(define-syntax include
(syntax-rules ()
((include "myenv.scm") (begin #f))
((include file) (load file))))
(define pp pretty-print)
;(define gensym gentemp)
(define-syntax declare ; Gambit-specific compiler-decl
(syntax-rules () ((declare . x) (begin #f))))
; A few convenient functions that are not Chez
(define (call-with-input-string str proc)
(proc (open-input-string str)))
(define (call-with-output-string proc)
(let ((port (open-output-string)))
(proc port)
(get-output-string port)))
(define (with-input-from-string str thunk)
(parameterize ((current-input-port (open-input-string str))) (thunk)))
(define (with-output-to-string thunk)
(let ((port (open-output-string)))
(parameterize ((current-output-port port)) (thunk))
(get-output-string port)))
; Frequently-occurring syntax-rule macros
; A symbol? predicate at the macro-expand time
; symbol?? FORM KT KF
; FORM is an arbitrary form or datum
; expands in KT if FORM is a symbol (identifier), Otherwise, expands in KF
(define-syntax symbol??
(syntax-rules ()
((symbol?? (x . y) kt kf) kf) ; It's a pair, not a symbol
((symbol?? #(x ...) kt kf) kf) ; It's a vector, not a symbol
((symbol?? maybe-symbol kt kf)
(let-syntax
((test
(syntax-rules ()
((test maybe-symbol t f) t)
((test x t f) f))))
(test abracadabra kt kf)))))
; A macro-expand-time memv function for identifiers
; id-memv?? FORM (ID ...) KT KF
; FORM is an arbitrary form or datum, ID is an identifier.
; The macro expands into KT if FORM is an identifier, which occurs
; in the list of identifiers supplied by the second argument.
; All the identifiers in that list must be unique.
; Otherwise, id-memv?? expands to KF.
; Two identifiers match if both refer to the same binding occurrence, or
; (both are undefined and have the same spelling).
; (id-memv?? ; old code.
; (syntax-rules ()
; ((_ x () kt kf) kf)
; ((_ x (y . rest) kt kf)
; (let-syntax
; ((test
; (syntax-rules (y)
; ((test y _x _rest _kt _kf) _kt)
; ((test any _x _rest _kt _kf)
; (id-memv?? _x _rest _kt _kf)))))
; (test x x rest kt kf)))))
(define-syntax id-memv??
(syntax-rules ()
((id-memv?? form (id ...) kt kf)
(let-syntax
((test
(syntax-rules (id ...)
((test id _kt _kf) _kt) ...
((test otherwise _kt _kf) _kf))))
(test form kt kf)))))
; Test cases
; (id-memv?? x (a b c) #t #f)
; (id-memv?? a (a b c) 'OK #f)
; (id-memv?? () (a b c) #t #f)
; (id-memv?? (x ...) (a b c) #t #f)
; (id-memv?? "abc" (a b c) #t #f)
; (id-memv?? x () #t #f)
; (let ((x 1))
; (id-memv?? x (a b x) 'OK #f))
; (let ((x 1))
; (id-memv?? x (a x b) 'OK #f))
; (let ((x 1))
; (id-memv?? x (x a b) 'OK #f))
; Commonly-used CPS macros
; The following macros follow the convention that a continuation argument
; has the form (k-head ! args ...)
; where ! is a dedicated symbol (placeholder).
; When a CPS macro invokes its continuation, it expands into
; (k-head value args ...)
; To distinguish such calling conventions, we prefix the names of
; such macros with k!
(define-syntax k!id ; Just the identity. Useful in CPS
(syntax-rules ()
((k!id x) x)))
; k!reverse ACC (FORM ...) K
; reverses the second argument, appends it to the first and passes
; the result to K
(define-syntax k!reverse
(syntax-rules (!)
((k!reverse acc () (k-head ! . k-args))
(k-head acc . k-args))
((k!reverse acc (x . rest) k)
(k!reverse (x . acc) rest k))))
; (k!reverse () (1 2 () (4 5)) '!) ;==> '((4 5) () 2 1)
; (k!reverse (x) (1 2 () (4 5)) '!) ;==> '((4 5) () 2 1 x)
; (k!reverse (x) () '!) ;==> '(x)
; assert the truth of an expression (or of a sequence of expressions)
;
; syntax: assert ?expr ?expr ... [report: ?r-exp ?r-exp ...]
;
; If (and ?expr ?expr ...) evaluates to anything but #f, the result
; is the value of that expression.
; If (and ?expr ?expr ...) evaluates to #f, an error is reported.
; The error message will show the failed expressions, as well
; as the values of selected variables (or expressions, in general).
; The user may explicitly specify the expressions whose
; values are to be printed upon assertion failure -- as ?r-exp that
; follow the identifier 'report:'
; Typically, ?r-exp is either a variable or a string constant.
; If the user specified no ?r-exp, the values of variables that are
; referenced in ?expr will be printed upon the assertion failure.
(define-syntax assert
(syntax-rules ()
((assert _expr . _others)
(letrec-syntax
((write-report
(syntax-rules ()
; given the list of expressions or vars,
; create a cerr form
((_ exprs prologue)
(k!reverse () (cerr . prologue)
(write-report* ! exprs #\newline)))))
(write-report*
(syntax-rules ()
((_ rev-prologue () prefix)
(k!reverse () (nl . rev-prologue) (k!id !)))
((_ rev-prologue (x . rest) prefix)
(symbol?? x
(write-report* (x ": " 'x #\newline . rev-prologue)
rest #\newline)
(write-report* (x prefix . rev-prologue) rest "")))))
; return the list of all unique "interesting"
; variables in the expr. Variables that are certain
; to be bound to procedures are not interesting.
(vars-of
(syntax-rules (!)
((_ vars (op . args) (k-head ! . k-args))
(id-memv?? op
(quote let let* letrec let*-values lambda cond quasiquote
case define do assert)
(k-head vars . k-args) ; won't go inside
; ignore the head of the application
(vars-of* vars args (k-head ! . k-args))))
; not an application -- ignore
((_ vars non-app (k-head ! . k-args)) (k-head vars . k-args))
))
(vars-of*
(syntax-rules (!)
((_ vars () (k-head ! . k-args)) (k-head vars . k-args))
((_ vars (x . rest) k)
(symbol?? x
(id-memv?? x vars
(vars-of* vars rest k)
(vars-of* (x . vars) rest k))
(vars-of vars x (vars-of* ! rest k))))))
(do-assert
(syntax-rules (report:)
((_ () expr) ; the most common case
(do-assert-c expr))
((_ () expr report: . others) ; another common case
(do-assert-c expr others))
((_ () expr . others) (do-assert (expr and) . others))
((_ exprs)
(k!reverse () exprs (do-assert-c !)))
((_ exprs report: . others)
(k!reverse () exprs (do-assert-c ! others)))
((_ exprs x . others) (do-assert (x . exprs) . others))))
(do-assert-c
(syntax-rules ()
((_ exprs)
(or exprs
(begin (vars-of () exprs
(write-report !
("failed assertion: " 'exprs nl "bindings")))
(error "assertion failure"))))
((_ exprs others)
(or exprs
(begin (write-report others
("failed assertion: " 'exprs))
(error "assertion failure"))))))
)
(do-assert () _expr . _others)
))))
(define-syntax assure
(syntax-rules ()
((assure exp error-msg) (assert exp report: error-msg))))
(define (identify-error msg args . disposition-msgs)
(let ((port (console-output-port)))
(newline port)
(display "ERROR" port)
(display msg port)
(for-each (lambda (msg) (display msg port))
(append args disposition-msgs))
(newline port)))
; (define-syntax assert
; (syntax-rules ()
; ((_ expr ...)
; (or (and expr ...)
; (begin (error "failed assertion: " '(expr ...)))))))
(define chez-error error)
(define error
(lambda (msg . args)
(chez-error 'runtime-error "~a~%" (cons msg args))))
; like cout << arguments << args
; where argument can be any Scheme object. If it's a procedure
; (without args) it's executed rather than printed (like newline)
(define (cout . args)
(for-each (lambda (x)
(if (procedure? x) (x) (display x)))
args))
;(define cerr cout)
(define (cerr . args)
(for-each (lambda (x)
(if (procedure? x) (x (console-output-port))
(display x (console-output-port))))
args))
(define nl (string #\newline))
; Some useful increment/decrement operators
(define-syntax inc! ; Mutable increment
(syntax-rules ()
((inc! x) (set! x (+ 1 x)))))
(define-syntax inc ; Read-only increment
(syntax-rules ()
((inc x) (+ 1 x))))
(define-syntax dec! ; Mutable decrement
(syntax-rules ()
((dec! x) (set! x (- x 1)))))
(define-syntax dec ; Read-only decrement
(syntax-rules ()
((dec x) (- x 1))))
; Some useful control operators
; if condition is true, execute stmts in turn
; and return the result of the last statement
; otherwise, return unspecified.
; Native in Petite
; (define-syntax when
; (syntax-rules ()
; ((when condition . stmts)
; (and condition (begin . stmts)))))
; if condition is false execute stmts in turn
; and return the result of the last statement
; otherwise, return unspecified.
; This primitive is often called 'unless'
(define-syntax whennot
(syntax-rules ()
((whennot condition . stmts)
(or condition (begin . stmts)))))
; Execute a sequence of forms and return the
; result of the _first_ one. Like PROG1 in Lisp.
; Typically used to evaluate one or more forms with
; side effects and return a value that must be
; computed before some or all of the side effects happen.
(define-syntax begin0
(syntax-rules ()
((begin0 form form1 ... )
(let ((val form)) form1 ... val))))
; Prepend an ITEM to a LIST, like a Lisp macro PUSH
; an ITEM can be an expression, but ls must be a VAR
(define-syntax push!
(syntax-rules ()
((push! item ls)
(set! ls (cons item ls)))))
; Is str the empty string?
; string-null? str -> bool
; See Olin Shiver's Underground String functions
(define-syntax string-null?
(syntax-rules ()
((string-null? str) (zero? (string-length str)))))
; A rather useful utility from SRFI-1
; cons* elt1 elt2 ... -> object
; Like LIST, but the last argument provides the tail of the constructed
; list -- i.e., (cons* a1 a2 ... an) = (cons a1 (cons a2 (cons ... an))).
;
; (cons* 1 2 3 4) => (1 2 3 . 4)
; (cons* 1) => 1
(define (cons* first . rest)
(let recur ((x first) (rest rest))
(if (pair? rest)
(cons x (recur (car rest) (cdr rest)))
x)))
; Support for let*-values form: SRFI-11
(define-syntax let*-values
(syntax-rules ()
((let*-values () . bodies) (begin . bodies))
((let*-values (((var) initializer) . rest) . bodies)
(let ((var initializer)) ; a single var optimization
(let*-values rest . bodies)))
((let*-values ((vars initializer) . rest) . bodies)
(call-with-values (lambda () initializer) ; the most generic case
(lambda vars (let*-values rest . bodies))))))
; assoc-primitives with a default clause
; If the search in the assoc list fails, the
; default action argument is returned. If this
; default action turns out to be a thunk,
; the result of its evaluation is returned.
; If the default action is not given, an error
; is signaled
(define-syntax assq-def
(syntax-rules ()
((assq-def key alist)
(or (assq key alist)
(error "failed to assq key '" key "' in a list " alist)))
((assq-def key alist #f)
(assq key alist))
((assq-def key alist default)
(or (assq key alist) (if (procedure? default) (default) default)))))
(define-syntax assv-def
(syntax-rules ()
((assv-def key alist)
(or (assv key alist)
(error "failed to assv key '" key "' in a list " alist)))
((assv-def key alist #f)
(assv key alist))
((assv-def key alist default)
(or (assv key alist) (if (procedure? default) (default) default)))))
(define-syntax assoc-def
(syntax-rules ()
((assoc-def key alist)
(or (assoc key alist)
(error "failed to assoc key '" key "' in a list " alist)))
((assoc-def key alist #f)
(assoc key alist))
((assoc-def key alist default)
(or (assoc key alist) (if (procedure? default) (default) default)))))
; Convenience macros to avoid quoting of symbols
; being deposited/looked up in the environment
(define-syntax env.find
(syntax-rules () ((env.find key) (%%env.find 'key))))
(define-syntax env.demand
(syntax-rules () ((env.demand key) (%%env.demand 'key))))
(define-syntax env.bind
(syntax-rules () ((env.bind key value) (%%env.bind 'key value))))
; Implementation of SRFI-0
; Only feature-identifiers srfi-0, chez, and
; petite-chez are assumed predefined.
; See below why this
; syntax-rule may NOT use an let-syntax.
(define-syntax cond-expand
(syntax-rules (else chez petite-chez srfi-0 and or not)
((cond-expand)
(error "Unfulfilled cond-expand"))
((cond-expand (else . cmd-or-defs*))
(begin . cmd-or-defs*))
((cond-expand "feature-id" chez kt kf) kt)
((cond-expand "feature-id" petite-chez kt kf) kt)
((cond-expand "feature-id" srfi-0 kt kf) kt)
((cond-expand "feature-id" x kt kf) kf)
((cond-expand "satisfies?" (and) kt kf) kt)
((cond-expand "satisfies?" (and clause) kt kf)
(cond-expand "satisfies?" clause kt kf))
((cond-expand "satisfies?" (and clause . rest) kt kf)
(cond-expand "satisfies?" clause
(cond-expand "satisfies?" (and . rest) kt kf) kf))
((cond-expand "satisfies?" (or) kt kf) kf)
((cond-expand "satisfies?" (or clause) kt kf)
(cond-expand "satisfies?" clause kt kf))
((cond-expand "satisfies?" (or clause . rest) kt kf)
(cond-expand "satisfies?" clause kt
(cond-expand "satisfies?" (or . rest) kt kf)))
((cond-expand "satisfies?" (not clause) kt kf)
(cond-expand "satisfies?" clause kf kt))
((cond-expand "satisfies?" x kt kf)
(cond-expand "feature-id" x kt kf))
((cond-expand (feature-req . cmd-or-defs*) . rest-clauses)
(cond-expand "satisfies?" feature-req
(begin . cmd-or-defs*)
(cond-expand . rest-clauses)))))
; define-opt: A concise definition allowing optional arguments.
; Example:
;
; (define-opt (foo arg1 arg2 (optional arg3 (arg4 init4))) body)
;
; The form define-opt is designed to be as compatible with DSSSL's
; extended define as possible -- while avoiding the non-standard
; lexical token #!optional. On systems that do support DSSSL (e.g.,
; Gambit, Bigloo, Kawa) our define-opt expands into DSSSL's extended
; define, which is implemented efficiently on these systems.
;
; Here's the relevant part of the DSSSL specification, lifted
; from Gambit's online documentation:
; define-formals = formal-argument-list | r4rs-define-formals
; formal-argument-list = reqs opts rest keys
; reqs = required-formal-argument*
; required-formal-argument = variable
; opts = #!optional optional-formal-argument* | empty
; optional-formal-argument = variable | ( variable initializer )
; rest = #!rest rest-formal-argument | empty
; rest-formal-argument = variable
; keys = #!key keyword-formal-argument* | empty
; keyword-formal-argument = variable | ( variable initializer )
; initializer = expression
; r4rs-lambda-formals = ( variable* ) | ( variable+ . variable ) | variable
; r4rs-define-formals = variable* | variable* . variable
;
; 1. Variables in required-formal-arguments are bound to successive actual
; arguments starting with the first actual argument. It shall be an error
; if there are fewer actual arguments than required-formal-arguments.
; 2. Next variables in optional-formal-arguments are bound to remaining
; actual arguments. If there are fewer remaining actual arguments than
; optional-formal-arguments, then the variables are bound to the result
; of evaluating initializer, if one was specified, and otherwise to #f.
; The initializer is evaluated in an environment in which all previous
; formal arguments have been bound.
; It shall be an error for a variable to appear more than once in a
; formal-argument-list.
; It is unspecified whether variables receive their value by binding or by
; assignment.
;
; Our define-opt does not currently support rest and keys arguments.
; Also, instead of #optional optional-formal-argument ...
; we write (optional optional-formal-argument ...)
;
; Our define-opt is similar to PLT Scheme's opt-lambda. However,
; the syntax of define-opt guarantees that optional arguments are
; really at the very end of the arg list.
; Chez does not support DSSSL extended defines and lambdas.
; Caveat: (define-opt name-bindings body) cannot expand into
; (let-syntax ((helper-macro ...)) (helper-macro name-bindings body))
; where helper-macro will generate the valid define.
; The mere appearance of (let-syntax ...) tells the Scheme system
; that whatever define will be generated, it is meant for the _internal_
; context. For example, the following code
;
; (define-syntax tdefine
; (syntax-rules ()
; ((tdefine _args . _bodies)
; (letrec-syntax
; ((helper
; (syntax-rules ()
; ((helper args bodies) (define args . bodies)))))
; (helper _args _bodies)))))
; (tdefine (foo x) (display "OK") (display x) (newline))
; (foo 42)
;
; runs OK on Petite Chez but gives an error "definition in expression context"
; on Scheme48 and SCM (and, consequently, the binding to foo does not occur).
(define-syntax define-opt
(syntax-rules (optional)
((define-opt (name . bindings) . bodies)
(define-opt "seek-optional" bindings () ((name . bindings) . bodies)))
((define-opt "seek-optional" ((optional . _opt-bindings))
(reqd ...) ((name . _bindings) . _bodies))
(define (name reqd ... . _rest)
(letrec-syntax
((handle-opts
(syntax-rules ()
((_ rest bodies (var init))
(let ((var (if (null? rest) init
(if (null? (cdr rest)) (car rest)
(error "extra rest" rest)))))
. bodies))
((_ rest bodies var) (handle-opts rest bodies (var #f)))
((_ rest bodies (var init) . other-vars)
(let ((var (if (null? rest) init (car rest)))
(new-rest (if (null? rest) '() (cdr rest))))
(handle-opts new-rest bodies . other-vars)))
((_ rest bodies var . other-vars)
(handle-opts rest bodies (var #f) . other-vars))
((_ rest bodies) ; no optional args, unlikely
(let ((_ (or (null? rest) (error "extra rest" rest))))
. bodies)))))
(handle-opts _rest _bodies . _opt-bindings))))
((define-opt "seek-optional" (x . rest) (reqd ...) form)
(define-opt "seek-optional" rest (reqd ... x) form))
((define-opt "seek-optional" not-a-pair reqd form)
(define . form)) ; No optional found, regular define
((define-opt name body) ; Just the definition for 'name',
(define name body)) ; for compatibilibility with define
))
; AND-LET* -- an AND with local bindings, a guarded LET* special form
;
; AND-LET* (formerly know as LAND*) is a generalized AND: it evaluates
; a sequence of forms one after another till the first one that yields
; #f; the non-#f result of a form can be bound to a fresh variable and
; used in the subsequent forms.
; It is defined in SRFI-2 <http://srfi.schemers.org/srfi-2/>
; This macro re-writes the and-let* form into a combination of
; 'and' and 'let'.
; See vland.scm for the denotational semantics and
; extensive validation tests.
(define-syntax and-let*
(syntax-rules ()
((_ ()) #t)
((_ claws) ; no body
; re-write (and-let* ((claw ... last-claw)) ) into
; (and-let* ((claw ...)) body) with 'body' derived from the last-claw
(and-let* "search-last-claw" () claws))
((_ "search-last-claw" first-claws ((exp)))
(and-let* first-claws exp)) ; (and-let* (... (exp)) )
((_ "search-last-claw" first-claws ((var exp)))
(and-let* first-claws exp)) ; (and-let* (... (var exp)) )
((_ "search-last-claw" first-claws (var))
(and-let* first-claws var)) ; (and-let* (... var) )
((_ "search-last-claw" (first-claw ...) (claw . rest))
(and-let* "search-last-claw" (first-claw ... claw) rest))
; now 'body' is present
((_ () . body) (begin . body)) ; (and-let* () form ...)
((_ ((exp) . claws) . body) ; (and-let* ( (exp) claw... ) body ...)
(and exp (and-let* claws . body)))
((_ ((var exp) . claws) . body) ; (and-let* ((var exp) claw...)body...)
(let ((var exp)) (and var (and-let* claws . body))))
((_ (var . claws) . body) ; (and-let* ( var claw... ) body ...)
(and var (and-let* claws . body)))
))
; A subset of SRFI-13 functions
;
; This file collects various SRFI-13 functions that are used in the
; input parsing library, the XML parser, and other code.
;
; It is always better to import the functions below from SRFI-13, if a
; Scheme implementation supports that SRFI natively. The present file
; can be used on a Scheme system that does not currently support SRFI-13.
;
; In implementing the string utility functions, we try to use whatever
; native facilities are available. That fact explains a fair number of
; cond-expand.
;
; $Id: srfi-13-local.scm,v 1.2 2004/07/08 21:53:32 oleg Exp $
; Implementations of string-xcopy! of SRFI-13, using
; whatever native facilities are available
(cond-expand
(bigloo
(define (string-xcopy! target tstart s sfrom sto)
(blit-string! s sfrom target tstart (- sto sfrom))))
(else
(define (string-xcopy! target tstart s sfrom sto)
(do ((i sfrom (inc i)) (j tstart (inc j)))
((>= i sto))
(string-set! target j (string-ref s i)))))
)
; procedure string-concatenate-reverse STRINGS FINAL END
(define (string-concatenate-reverse strs final end)
(if (null? strs) (substring final 0 end)
(let*
((total-len
(let loop ((len end) (lst strs))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((len end) (j total-len) (str final) (lst strs))
(string-xcopy! result (- j len) str 0 len)
(if (null? lst) result
(loop (string-length (car lst)) (- j len)
(car lst) (cdr lst)))))))
; string-concatenate/shared STRING-LIST -> STRING
(define (string-concatenate/shared strs)
(cond
((null? strs) "") ; Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(let*
((total-len
(let loop ((len (string-length (car strs))) (lst (cdr strs)))
(if (null? lst) len
(loop (+ len (string-length (car lst))) (cdr lst)))))
(result (make-string total-len)))
(let loop ((j 0) (str (car strs)) (lst (cdr strs)))
(string-xcopy! result j str 0 (string-length str))
(if (null? lst) result
(loop (+ j (string-length str))
(car lst) (cdr lst))))))))
; string-concatenate-reverse/shared STRING-LIST [FINAL-STRING END] -> STRING
; We do not use the optional arguments of this procedure. Therefore,
; we do not implement them. See SRFI-13 for the complete
; implementation.
(define (string-concatenate-reverse/shared strs)
(cond
((null? strs) "") ; Test for the fast path first
((null? (cdr strs)) (car strs))
(else
(string-concatenate-reverse (cdr strs)
(car strs) (string-length (car strs))))))
; Return the index of the first occurence of a-char in str, or #f
; This is a subset of the corresponding SRFI-13 function.
; The latter is more generic.
(define (string-index str a-char)
(let loop ((pos 0))
(cond
((>= pos (string-length str)) #f) ; whole string has been searched, in vain
((char=? a-char (string-ref str pos)) pos)
(else (loop (inc pos))))))
; Return the index of the last occurence of a-char in str, or #f
; This is a subset of the corresponding SRFI-13 function.
; The latter is more generic.
(define (string-index-right str a-char)
(let loop ((pos (dec (string-length str))))
(cond
((negative? pos) #f) ; whole string has been searched, in vain
((char=? a-char (string-ref str pos)) pos)
(else (loop (dec pos))))))
; string-contains s1 s2 [start1 end1 start2 end2] -> integer or false
; string-contains-ci s1 s2 [start1 end1 start2 end2] -> integer or false
; Does string s1 contain string s2?
; Return the index in s1 where s2 occurs as a substring, or false. The
; optional start/end indices restrict the operation to the indicated
; substrings.
; We do not support the optional arguments
(define (string-contains str pattern)
(let* ((pat-len (string-length pattern))
(search-span (- (string-length str) pat-len))
(c1 (if (zero? pat-len) #f (string-ref pattern 0)))
(c2 (if (<= pat-len 1) #f (string-ref pattern 1))))
(cond
((not c1) 0) ; empty pattern, matches upfront
((not c2) (string-index str c1)) ; one-char pattern
(else ; matching a pattern of at least two chars
(let outer ((pos 0))
(cond
((> pos search-span) #f) ; nothing was found thru the whole str
((not (char=? c1 (string-ref str pos)))
(outer (+ 1 pos))) ; keep looking for the right beginning
((not (char=? c2 (string-ref str (+ 1 pos))))
(outer (+ 1 pos))) ; could've done pos+2 if c1 == c2....
(else ; two char matched: high probability
; the rest will match too
(let inner ((i-pat 2) (i-str (+ 2 pos)))
(if (>= i-pat pat-len) pos ; whole pattern matched
(if (char=? (string-ref pattern i-pat)
(string-ref str i-str))
(inner (+ 1 i-pat) (+ 1 i-str))
(outer (+ 1 pos)))))))))))) ; mismatch after partial match
; Here are some specialized substring? functions
;
; -- procedure+: string-prefix? PATTERN STRING
; -- procedure+: string-prefix-ci? PATTERN STRING
; checks to make sure that PATTERN is a prefix of STRING
;
; (string-prefix? "pir" "pirate") => #t
; (string-prefix? "rat" "outrage") => #f
; (string-prefix? "" any-string) => #t
; (string-prefix? any-string any-string) => #t
(define (string-prefix? pattern str)
(let loop ((i 0))
(cond
((>= i (string-length pattern)) #t)
((>= i (string-length str)) #f)
((char=? (string-ref pattern i) (string-ref str i))
(loop (inc i)))
(else #f))))
(define (string-prefix-ci? pattern str)
(let loop ((i 0))
(cond
((>= i (string-length pattern)) #t)
((>= i (string-length str)) #f)
((char-ci=? (string-ref pattern i) (string-ref str i))
(loop (inc i)))
(else #f))))
; -- procedure+: string-suffix? PATTERN STRING
; -- procedure+: string-suffix-ci? PATTERN STRING
; checks to make sure that PATTERN is a suffix of STRING
;
; (string-suffix? "ate" "pirate") => #t
; (string-suffix? "rag" "outrage") => #f
; (string-suffix? "" any-string) => #t
; (string-suffix? any-string any-string) => #t
(define (string-suffix? pattern str)
(let loop ((i (dec (string-length pattern))) (j (dec (string-length str))))
(cond
((negative? i) #t)
((negative? j) #f)
((char=? (string-ref pattern i) (string-ref str j))
(loop (dec i) (dec j)))
(else #f))))
(define (string-suffix-ci? pattern str)
(let loop ((i (dec (string-length pattern))) (j (dec (string-length str))))
(cond
((negative? i) #t)
((negative? j) #f)
((char-ci=? (string-ref pattern i) (string-ref str j))
(loop (dec i) (dec j)))
(else #f))))
; Raise or lower the case of the alphabetic characters in the string.
(cond-expand
(bigloo #f) ; Bigloo implements them directly
(else
; Return a new string made of characters of the
; original string in the lower case
(define (string-downcase str)
(do ((target-str (make-string (string-length str))) (i 0 (inc i)))
((>= i (string-length str)) target-str)
(string-set! target-str i (char-downcase (string-ref str i)))))
; Return a new string made of characters of the
; original string in the upper case
(define (string-upcase str)
(do ((target-str (make-string (string-length str))) (i 0 (inc i)))
((>= i (string-length str)) target-str)
(string-set! target-str i (char-upcase (string-ref str i)))))
; Lower the case of string's characters inplace
(define (string-downcase! str)
(do ((i 0 (inc i))) ((>= i (string-length str)))
(string-set! str i (char-downcase (string-ref str i)))))
; Raise the case of string's characters inplace
(define (string-upcase! str)
(do ((i 0 (inc i))) ((>= i (string-length str)))
(string-set! str i (char-upcase (string-ref str i)))))
))
;****************************************************************************
; My Scheme misc utility functions
; (mainly dealing with string and list manipulations)
;
; myenv.scm, myenv-bigloo.scm or similar prelude is assumed.
; From SRFI-13, import many functions
; If a particular implementation lacks SRFI-13 support, please
; include the file srfi-13-local.scm
;
; $Id: util.scm,v 1.5 2004/07/07 16:02:31 sperber Exp $
;------------------------------------------------------------------------
; Iterator ANY?
;
; -- procedure+: any? PRED COLLECTION
; Searches for the first element in the collection satisfying a
; given predicate
; That is, the procedure applies PRED to every element of the
; COLLECTION in turn.
; The first element for which PRED returns non-#f stops the iteration;
; the value of the predicate is returned.
; If none of the elements of the COLLECTION satisfy the predicate,
; the return value from the procedure is #f
; COLLECTION can be a list, a vector, a string, or an input port.
; See vmyenv.scm for validation tests.
(define (any? <pred?> coll)
(cond
((list? coll)
(let loop ((curr-l coll))
(if (null? curr-l) #f
(or (<pred?> (car curr-l)) (loop (cdr curr-l))))))
((vector? coll)
(let ((len (vector-length coll)))
(let loop ((i 0))
(if (>= i len) #f
(or (<pred?> (vector-ref coll i)) (loop (inc i)))))))
((string? coll)
(let ((len (string-length coll)))
(let loop ((i 0))
(if (>= i len) #f
(or (<pred?> (string-ref coll i)) (loop (inc i)))))))
((input-port? coll)
(let loop ((c (read-char coll)))
(if (eof-object? c) #f
(or (<pred?> c) (loop (read-char coll))))))
(else (error "any? on an invalid collection"))))
;------------------------------------------------------------------------
; Some list manipulation functions
; -- procedure+: list-intersperse SRC-L ELEM
; inserts ELEM between elements of the SRC-L, returning a freshly allocated
; list (cells, that is)
(define (list-intersperse src-l elem)
(if (null? src-l) src-l
(let loop ((l (cdr src-l)) (dest (cons (car src-l) '())))
(if (null? l) (reverse dest)
(loop (cdr l) (cons (car l) (cons elem dest)))))))
; -- procedure+: list-intersperse! SRC-L ELEM
; inserts ELEM between elements of the SRC-L inplace
(define (list-intersperse! src-l elem)
(if (null? src-l) src-l
(let loop ((l src-l))
(let ((next-l (cdr l)))
(if (null? next-l) src-l
(begin
(set-cdr! l (cons elem next-l))
(loop next-l)))))))
; List-tail-difference: given two lists, list1 and list2 where
; list2 is presumably a tail of list1, return
; a (freshly allocated) list which is a difference between list1
; and list2. If list2 is *not* a tail of list1, the entire list1
; is returned.
(define (list-tail-diff list1 list2)
(let loop ((l1-curr list1) (difference '()))
(cond
((eq? l1-curr list2) (reverse difference))
((null? l1-curr) (reverse difference))
(else (loop (cdr l1-curr) (cons (car l1-curr) difference))))))
;------------------------------------------------------------------------
; String utilities
; See SRFI-13 or srfi-13-local.scm
; Return the index of the last occurence of a-char in str, or #f
; See SRFI-13
(define string-rindex string-index-right)
; -- procedure+: substring? PATTERN STRING
; Searches STRING to see if it contains the substring PATTERN.
; Returns the index of the first substring of STRING that is equal
; to PATTERN; or `#f' if STRING does not contain PATTERN.
;
; (substring? "rat" "pirate") => 2
; (substring? "rat" "outrage") => #f
; (substring? "" any-string) => 0
(define (substring? pattern str) (string-contains str pattern))
; -- procedure+: string->integer STR START END
;
; Makes sure a substring of the STR from START (inclusive) till END
; (exclusive) is a representation of a non-negative integer in decimal
; notation. If so, this integer is returned. Otherwise -- when the
; substring contains non-decimal characters, or when the range from
; START till END is not within STR, the result is #f.
;
; This procedure is a simplification of the standard string->number.
; The latter is far more generic: for example, it will try to read
; strings like "1/2" "1S2" "1.34" and even "1/0" (the latter causing
; a zero-divide error). Note that to string->number, "1S2" is a valid
; representation of an _inexact_ integer (100 to be precise).
; Oftentimes we want to be more restrictive about what we consider a
; number; we want merely to read an integral label.
(define (string->integer str start end)
(and (< -1 start end (inc (string-length str)))
(let loop ((pos start) (accum 0))
(cond
((>= pos end) accum)
((char-numeric? (string-ref str pos))
(loop (inc pos) (+ (char->integer (string-ref str pos))
(- (char->integer #\0)) (* 10 accum))))
(else #f)))))
;
; -- procedure+: string-split STRING
; -- procedure+: string-split STRING '()
; -- procedure+: string-split STRING '() MAXSPLIT
;
; Returns a list of whitespace delimited words in STRING.
; If STRING is empty or contains only whitespace, then the empty list
; is returned. Leading and trailing whitespaces are trimmed.
; If MAXSPLIT is specified and positive, the resulting list will
; contain at most MAXSPLIT elements, the last of which is the string
; remaining after (MAXSPLIT - 1) splits. If MAXSPLIT is specified and
; non-positive, the empty list is returned. "In time critical
; applications it behooves you not to split into more fields than you
; really need."
;
; -- procedure+: string-split STRING CHARSET
; -- procedure+: string-split STRING CHARSET MAXSPLIT
;
; Returns a list of words delimited by the characters in CHARSET in
; STRING. CHARSET is a list of characters that are treated as delimiters.
; Leading or trailing delimeters are NOT trimmed. That is, the resulting
; list will have as many initial empty string elements as there are
; leading delimiters in STRING.
;
; If MAXSPLIT is specified and positive, the resulting list will
; contain at most MAXSPLIT elements, the last of which is the string
; remaining after (MAXSPLIT - 1) splits. If MAXSPLIT is specified and
; non-positive, the empty list is returned. "In time critical
; applications it behooves you not to split into more fields than you
; really need."
;
; This is based on the split function in Python/Perl
;
; (string-split " abc d e f ") ==> ("abc" "d" "e" "f")
; (string-split " abc d e f " '() 1) ==> ("abc d e f ")
; (string-split " abc d e f " '() 0) ==> ()
; (string-split ":abc:d:e::f:" '(#\:)) ==> ("" "abc" "d" "e" "" "f" "")
; (string-split ":" '(#\:)) ==> ("" "")
; (string-split "root:x:0:0:Lord" '(#\:) 2) ==> ("root" "x:0:0:Lord")
; (string-split "/usr/local/bin:/usr/bin:/usr/ucb/bin" '(#\:))
; ==> ("/usr/local/bin" "/usr/bin" "/usr/ucb/bin")
; (string-split "/usr/local/bin" '(#\/)) ==> ("" "usr" "local" "bin")
(define (string-split str . rest)
; maxsplit is a positive number
(define (split-by-whitespace str maxsplit)
(define (skip-ws i yet-to-split-count)
(cond
((>= i (string-length str)) '())
((char-whitespace? (string-ref str i))
(skip-ws (inc i) yet-to-split-count))
(else (scan-beg-word (inc i) i yet-to-split-count))))
(define (scan-beg-word i from yet-to-split-count)
(cond
((zero? yet-to-split-count)
(cons (substring str from (string-length str)) '()))
(else (scan-word i from yet-to-split-count))))
(define (scan-word i from yet-to-split-count)
(cond
((>= i (string-length str))
(cons (substring str from i) '()))
((char-whitespace? (string-ref str i))
(cons (substring str from i)
(skip-ws (inc i) (- yet-to-split-count 1))))
(else (scan-word (inc i) from yet-to-split-count))))
(skip-ws 0 (- maxsplit 1)))
; maxsplit is a positive number
; str is not empty
(define (split-by-charset str delimeters maxsplit)
(define (scan-beg-word from yet-to-split-count)
(cond
((>= from (string-length str)) '(""))
((zero? yet-to-split-count)
(cons (substring str from (string-length str)) '()))
(else (scan-word from from yet-to-split-count))))
(define (scan-word i from yet-to-split-count)
(cond
((>= i (string-length str))
(cons (substring str from i) '()))
((memq (string-ref str i) delimeters)
(cons (substring str from i)
(scan-beg-word (inc i) (- yet-to-split-count 1))))
(else (scan-word (inc i) from yet-to-split-count))))
(scan-beg-word 0 (- maxsplit 1)))
; resolver of overloading...
; if omitted, maxsplit defaults to
; (inc (string-length str))
(if (string-null? str) '()
(if (null? rest)
(split-by-whitespace str (inc (string-length str)))
(let ((charset (car rest))
(maxsplit
(if (pair? (cdr rest)) (cadr rest) (inc (string-length str)))))
(cond
((not (positive? maxsplit)) '())
((null? charset) (split-by-whitespace str maxsplit))
(else (split-by-charset str charset maxsplit))))))
)
; make-char-quotator QUOT-RULES
;
; Given QUOT-RULES, an assoc list of (char . string) pairs, return
; a quotation procedure. The returned quotation procedure takes a string
; and returns either a string or a list of strings. The quotation procedure
; check to see if its argument string contains any instance of a character
; that needs to be encoded (quoted). If the argument string is "clean",
; it is returned unchanged. Otherwise, the quotation procedure will
; return a list of string fragments. The input straing will be broken
; at the places where the special characters occur. The special character
; will be replaced by the corresponding encoding strings.
;
; For example, to make a procedure that quotes special HTML characters,
; do
; (make-char-quotator
; '((#\< . "<") (#\> . ">") (#\& . "&") (#\" . """)))
(define (make-char-quotator char-encoding)
(let ((bad-chars (map car char-encoding)))
; Check to see if str contains one of the characters in charset,
; from the position i onward. If so, return that character's index.
; otherwise, return #f
(define (index-cset str i charset)
(let loop ((i i))
(and (< i (string-length str))
(if (memv (string-ref str i) charset) i
(loop (inc i))))))
; The body of the function
(lambda (str)
(let ((bad-pos (index-cset str 0 bad-chars)))
(if (not bad-pos) str ; str had all good chars
(let loop ((from 0) (to bad-pos))
(cond
((>= from (string-length str)) '())
((not to)
(cons (substring str from (string-length str)) '()))
(else
(let ((quoted-char
(cdr (assv (string-ref str to) char-encoding)))
(new-to
(index-cset str (inc to) bad-chars)))
(if (< from to)
(cons
(substring str from to)
(cons quoted-char (loop (inc to) new-to)))
(cons quoted-char (loop (inc to) new-to))))))))))
))
; Character-encoding module
;
; This module deals with particular character-encoding issues such as
; conversions between characters and their ASCII or UCS2 codes, Scheme
; representations of "Carriage Return" (CR), "tabulation" (TAB) and
; other control characters.
;
; This module by necessity is platform-specific as character encoding
; issues are hardly addressed in R5RS. For example, the result of
; char->integer is generally not an ASCII code of an integer (although
; it is, on many Scheme systems, with the important exception of
; Scheme48 and SCSH). The level of support for character sets other
; than ASCII varies widely among Scheme systems.
;
; This file collects various character-encoding functions that are
; necessary for the SSAX XML parser. The functions are of general use
; and scope.
;
; $Id: char-encoding.scm,v 1.1 2003/04/09 20:34:28 oleg Exp $
; ascii->char INT -> CHAR
; return a character whose ASCII code is INT
; Note, because ascii->char is injective (there are more characters than
; ASCII characters), the inverse transformation is not defined.
(cond-expand
(scheme48 #f) ; ascii->char is built into Scheme48
(scsh #f) ; ascii->char is built into Scheme48
(else
(define ascii->char integer->char)
)
)
; ucscode->char INT -> CHAR
; Return a character whose UCS (ISO/IEC 10646) code is INT
; Note
; This function is required for processing of XML character entities:
; According to Section "4.1 Character and Entity References"
; of the XML Recommendation:
; "[Definition: A character reference refers to a specific character
; in the ISO/IEC 10646 character set, for example one not directly
; accessible from available input devices.]"
(define (ucscode->char code)
(cond-expand
(bigloo
(ucs2->char (integer->ucs2 code)))
((or scheme48 scsh) ; Scheme48 has no support for UCS
(ascii->char code))
(else
(integer->char code))))
; Commonly used control characters
(define char-return (ascii->char 13))
(define char-tab (ascii->char 9))
(define char-newline (ascii->char 10)) ; a.k.a. #\newline, per R5RS
;****************************************************************************
; Simple Parsing of input
;
; The following simple functions surprisingly often suffice to parse
; an input stream. They either skip, or build and return tokens,
; according to inclusion or delimiting semantics. The list of
; characters to expect, include, or to break at may vary from one
; invocation of a function to another. This allows the functions to
; easily parse even context-sensitive languages.
;
; EOF is generally frowned on, and thrown up upon if encountered.
; Exceptions are mentioned specifically. The list of expected characters
; (characters to skip until, or break-characters) may include an EOF
; "character", which is to be coded as symbol *eof*
;
; The input stream to parse is specified as a PORT, which is usually
; the last (and optional) argument. It defaults to the current input
; port if omitted.
;
; IMPORT
; This package relies on a function parser-error, which must be defined
; by a user of the package. The function has the following signature:
; parser-error PORT MESSAGE SPECIALISING-MSG*
; Many procedures of this package call parser-error to report a parsing
; error. The first argument is a port, which typically points to the
; offending character or its neighborhood. Most of the Scheme systems
; let the user query a PORT for the current position. MESSAGE is the
; description of the error. Other arguments supply more details about
; the problem.
; myenv.scm, myenv-bigloo.scm or a similar prelude is assumed.
; From SRFI-13, string-concatenate-reverse
; If a particular implementation lacks SRFI-13 support, please
; include the file srfi-13-local.scm
;
; $Id: input-parse.scm,v 1.7 2004/07/07 16:02:31 sperber Exp $
;------------------------------------------------------------------------
; -- procedure+: peek-next-char [PORT]
; advances to the next character in the PORT and peeks at it.
; This function is useful when parsing LR(1)-type languages
; (one-char-read-ahead).
; The optional argument PORT defaults to the current input port.
(define-opt (peek-next-char (optional (port (current-input-port))))
(read-char port)
(peek-char port))
;------------------------------------------------------------------------
; -- procedure+: assert-curr-char CHAR-LIST STRING [PORT]
; Reads a character from the PORT and looks it up
; in the CHAR-LIST of expected characters
; If the read character was found among expected, it is returned
; Otherwise, the procedure writes a nasty message using STRING
; as a comment, and quits.
; The optional argument PORT defaults to the current input port.
;
(define-opt (assert-curr-char expected-chars comment
(optional (port (current-input-port))))
(let ((c (read-char port)))
(if (memv c expected-chars) c
(parser-error port "Wrong character " c
" (0x" (if (eof-object? c) "*eof*"
(number->string (char->integer c) 16)) ") "
comment ". " expected-chars " expected"))))
; -- procedure+: skip-until CHAR-LIST [PORT]
; Reads and skips characters from the PORT until one of the break
; characters is encountered. This break character is returned.
; The break characters are specified as the CHAR-LIST. This list
; may include EOF, which is to be coded as a symbol *eof*
;
; -- procedure+: skip-until NUMBER [PORT]
; Skips the specified NUMBER of characters from the PORT and returns #f
;
; The optional argument PORT defaults to the current input port.
(define-opt (skip-until arg (optional (port (current-input-port))) )
(cond
((number? arg) ; skip 'arg' characters
(do ((i arg (dec i)))
((not (positive? i)) #f)
(if (eof-object? (read-char port))
(parser-error port "Unexpected EOF while skipping "
arg " characters"))))
(else ; skip until break-chars (=arg)
(let loop ((c (read-char port)))
(cond
((memv c arg) c)
((eof-object? c)
(if (memq '*eof* arg) c
(parser-error port "Unexpected EOF while skipping until " arg)))
(else (loop (read-char port))))))))
; -- procedure+: skip-while CHAR-LIST [PORT]
; Reads characters from the PORT and disregards them,
; as long as they are mentioned in the CHAR-LIST.
; The first character (which may be EOF) peeked from the stream
; that is NOT a member of the CHAR-LIST is returned. This character
; is left on the stream.
; The optional argument PORT defaults to the current input port.
(define-opt (skip-while skip-chars (optional (port (current-input-port))) )
(do ((c (peek-char port) (peek-char port)))
((not (memv c skip-chars)) c)
(read-char port)))
; whitespace const
;------------------------------------------------------------------------
; Stream tokenizers
; -- procedure+:
; next-token PREFIX-CHAR-LIST BREAK-CHAR-LIST [COMMENT-STRING] [PORT]
; skips any number of the prefix characters (members of the
; PREFIX-CHAR-LIST), if any, and reads the sequence of characters
; up to (but not including) a break character, one of the
; BREAK-CHAR-LIST.
; The string of characters thus read is returned.
; The break character is left on the input stream
; The list of break characters may include EOF, which is to be coded as
; a symbol *eof*. Otherwise, EOF is fatal, generating an error message
; including a specified COMMENT-STRING (if any)
;
; The optional argument PORT defaults to the current input port.
;
; Note: since we can't tell offhand how large the token being read is
; going to be, we make a guess, pre-allocate a string, and grow it by
; quanta if necessary. The quantum is always the length of the string
; before it was extended the last time. Thus the algorithm does
; a Fibonacci-type extension, which has been proven optimal.
; Note, explicit port specification in read-char, peek-char helps.
; Procedure: input-parse:init-buffer
; returns an initial buffer for next-token* procedures.
; The input-parse:init-buffer may allocate a new buffer per each invocation:
; (define (input-parse:init-buffer) (make-string 32))
; Size 32 turns out to be fairly good, on average.
; That policy is good only when a Scheme system is multi-threaded with
; preemptive scheduling, or when a Scheme system supports shared substrings.
; In all the other cases, it's better for input-parse:init-buffer to
; return the same static buffer. next-token* functions return a copy
; (a substring) of accumulated data, so the same buffer can be reused.
; We shouldn't worry about an incoming token being too large:
; next-token will use another chunk automatically. Still,
; the best size for the static buffer is to allow most of the tokens to fit in.
; Using a static buffer _dramatically_ reduces the amount of produced garbage
; (e.g., during XML parsing).
(define input-parse:init-buffer
(let ((buffer (make-string 512)))
(lambda () buffer)))
; See a better version below
(define-opt (next-token-old prefix-skipped-chars break-chars
(optional (comment "") (port (current-input-port))) )
(let* ((buffer (input-parse:init-buffer))
(curr-buf-len (string-length buffer))
(quantum curr-buf-len))
(let loop ((i 0) (c (skip-while prefix-skipped-chars port)))
(cond
((memv c break-chars) (substring buffer 0 i))
((eof-object? c)
(if (memq '*eof* break-chars)
(substring buffer 0 i) ; was EOF expected?
(parser-error port "EOF while reading a token " comment)))
(else
(if (>= i curr-buf-len) ; make space for i-th char in buffer
(begin ; -> grow the buffer by the quantum
(set! buffer (string-append buffer (make-string quantum)))
(set! quantum curr-buf-len)
(set! curr-buf-len (string-length buffer))))
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i) (peek-char port))
)))))
; A better version of next-token, which accumulates the characters
; in chunks, and later on reverse-concatenates them, using
; SRFI-13 if available.
; The overhead of copying characters is only 100% (or even smaller: bulk
; string copying might be well-optimised), compared to the (hypothetical)
; circumstance if we had known the size of the token beforehand.
; For small tokens, the code performs just as above. For large
; tokens, we expect an improvement. Note, the code also has no
; assignments.
; See next-token-comp.scm
(define-opt (next-token prefix-skipped-chars break-chars
(optional (comment "") (port (current-input-port))) )
(let outer ((buffer (input-parse:init-buffer)) (filled-buffer-l '())
(c (skip-while prefix-skipped-chars port)))
(let ((curr-buf-len (string-length buffer)))
(let loop ((i 0) (c c))
(cond
((memv c break-chars)
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i)))
((eof-object? c)
(if (memq '*eof* break-chars) ; was EOF expected?
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i))
(parser-error port "EOF while reading a token " comment)))
((>= i curr-buf-len)
(outer (make-string curr-buf-len)
(cons buffer filled-buffer-l) c))
(else
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i) (peek-char port))))))))
; -- procedure+: next-token-of INC-CHARSET [PORT]
; Reads characters from the PORT that belong to the list of characters
; INC-CHARSET. The reading stops at the first character which is not
; a member of the set. This character is left on the stream.
; All the read characters are returned in a string.
;
; -- procedure+: next-token-of PRED [PORT]
; Reads characters from the PORT for which PRED (a procedure of one
; argument) returns non-#f. The reading stops at the first character
; for which PRED returns #f. That character is left on the stream.
; All the results of evaluating of PRED up to #f are returned in a
; string.
;
; PRED is a procedure that takes one argument (a character
; or the EOF object) and returns a character or #f. The returned
; character does not have to be the same as the input argument
; to the PRED. For example,
; (next-token-of (lambda (c)
; (cond ((eof-object? c) #f)
; ((char-alphabetic? c) (char-downcase c))
; (else #f))))
; will try to read an alphabetic token from the current
; input port, and return it in lower case.
;
; The optional argument PORT defaults to the current input port.
;
; This procedure is similar to next-token but only it implements
; an inclusion rather than delimiting semantics.
(define-opt (next-token-of incl-list/pred
(optional (port (current-input-port))) )
(let* ((buffer (input-parse:init-buffer))
(curr-buf-len (string-length buffer)))
(if (procedure? incl-list/pred)
(let outer ((buffer buffer) (filled-buffer-l '()))
(let loop ((i 0))
(if (>= i curr-buf-len) ; make sure we have space
(outer (make-string curr-buf-len) (cons buffer filled-buffer-l))
(let ((c (incl-list/pred (peek-char port))))
(if c
(begin
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i)))
; incl-list/pred decided it had had enough
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i)))))))
; incl-list/pred is a list of allowed characters
(let outer ((buffer buffer) (filled-buffer-l '()))
(let loop ((i 0))
(if (>= i curr-buf-len) ; make sure we have space
(outer (make-string curr-buf-len) (cons buffer filled-buffer-l))
(let ((c (peek-char port)))
(cond
((not (memv c incl-list/pred))
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i)))
(else
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i))))))))
)))
; -- procedure+: read-text-line [PORT]
; Reads one line of text from the PORT, and returns it as a string.
; A line is a (possibly empty) sequence of characters terminated
; by CR, CRLF or LF (or even the end of file).
; The terminating character (or CRLF combination) is removed from
; the input stream. The terminating character(s) is not a part
; of the return string either.
; If EOF is encountered before any character is read, the return
; value is EOF.
;
; The optional argument PORT defaults to the current input port.
(define *read-line-breaks* (list char-newline char-return '*eof*))
(define-opt (read-text-line (optional (port (current-input-port))) )
(if (eof-object? (peek-char port)) (peek-char port)
(let* ((line
(next-token '() *read-line-breaks*
"reading a line" port))
(c (read-char port))) ; must be either \n or \r or EOF
(and (eqv? c char-return) (eqv? (peek-char port) #\newline)
(read-char port)) ; skip \n that follows \r
line)))
; -- procedure+: read-string N [PORT]
; Reads N characters from the PORT, and returns them in a string.
; If EOF is encountered before N characters are read, a shorter string
; will be returned.
; If N is not positive, an empty string will be returned.
; The optional argument PORT defaults to the current input port.
(define-opt (read-string n (optional (port (current-input-port))) )
(if (not (positive? n)) ""
(let ((buffer (make-string n)))
(let loop ((i 0) (c (read-char port)))
(if (eof-object? c) (substring buffer 0 i)
(let ((i1 (inc i)))
(string-set! buffer i c)
(if (= i1 n) buffer
(loop i1 (read-char port)))))))))
; Catcher of errors
; catches an error when it occurs, preventing an abort that would otherwise
; follow.
; It is very useful in the validation code to make sure a test case that
; was supposed to fail fails indeed. An expected error would not
; cause the inferior REPL be entered, nor will it abort the execution,
; letting the validation process continue.
;
; $Id: catch-error.scm,v 1.2 2003/10/30 21:33:10 oleg Exp $
; Try to execute the thunk, and return #f if execution succeeded
; If an error occurred during the execution, it is caught, and
; the thunk-failed? procedure returns #t
(define (thunk-failed? thunk)
(let
((orig-error error) ; save the original 'error' primitive
(caught #f))
(call-with-current-continuation
(lambda (cont)
(set! error ; redefine the error primitive
(lambda (msg . args)
(identify-error msg args "The error above has been caught")
;(cerr "caught error: " msg)
;(for-each (lambda (arg) (cerr arg)) args)
;(cerr nl)
(set! caught #t)
(cont #t)))
(thunk)
#f))
(set! error orig-error)
caught))
(cond-expand
((or bigloo gambit)
(define-macro (failed? . stmts)
`(thunk-failed? (lambda () ,@stmts))))
(else
(define-syntax failed?
(syntax-rules ()
((failed? . stmts)
(thunk-failed? (lambda () . stmts)))))))
; like cout << arguments << args
; where argument can be any Scheme object. If it's a procedure
; (without args) it's executed rather than printed (like newline)
(define (cout . args)
(for-each (lambda (x)
(if (procedure? x) (x) (display x)))
args))
(define (cerr . args)
(for-each (lambda (x)
(if (procedure? x)
(x (current-error-port))
(display x (current-error-port))))
args))
;(##define-macro (nl) '(newline))
(define nl (string #\newline))
; Implementation of the structure parser-errors-vanilla
; for systems other than Scheme48 and PLT Scheme
; $Id: parser-errors-vanilla.scm,v 1.1 2004/08/06 23:01:09 oleg Exp $
(define (parser-error port message . rest)
(apply error message rest))
; -- Function: find-string-from-port? STR IN-PORT MAX-NO-CHARS
; Looks for a string STR within the first MAX-NO-CHARS chars of the
; input port IN-PORT
; MAX-NO-CHARS may be omitted: in that case, the search span would be
; limited only by the end of the input stream.
; When the STR is found, the function returns the number of
; characters it has read from the port, and the port is set
; to read the first char after that (that is, after the STR)
; The function returns #f when the string wasn't found
; Note the function reads the port *STRICTLY* sequentially, and does not
; perform any buffering. So the function can be used even if the port is open
; on a pipe or other communication channel.
;
; Probably can be classified as misc-io.
;
; Notes on the algorithm.
; A special care should be taken in a situation when one had achieved a partial
; match with (a head of) STR, and then some unexpected character appeared in
; the stream. It'll be rash to discard all already read characters. Consider
; an example of string "acab" and the stream "bacacab...", specifically when
; a c a _b_
; b a c a c a b ...
; that is, when 'aca' had matched, but then 'c' showed up in the stream
; while we were looking for 'b'. In that case, discarding all already read
; characters and starting the matching process from scratch, that is,
; from 'c a b ...', would miss a certain match.
; Note, we don't actually need to keep already read characters, or at least
; strlen(str) characters in some kind of buffer. If there has been no match,
; we can safely discard read characters. If there was some partial match,
; we already know the characters before, they are in the STR itself, so
; we don't need a special buffer for that.
;;; "MISCIO" Search for string from port.
; Written 1995 by Oleg Kiselyov ([email protected])
; Modified 1996 by A. Jaffer ([email protected])
;
; This code is in the public domain.
(define (MISCIO:find-string-from-port? str <input-port> . max-no-char)
(set! max-no-char (if (null? max-no-char) #f (car max-no-char)))
(letrec
((no-chars-read 0)
(my-peek-char ; Return a peeked char or #f
(lambda () (and (or (not max-no-char) (< no-chars-read max-no-char))
(let ((c (peek-char <input-port>)))
(if (eof-object? c) #f c)))))
(next-char (lambda () (read-char <input-port>)
(set! no-chars-read (inc no-chars-read))))
(match-1st-char ; of the string str
(lambda ()
(let ((c (my-peek-char)))
(if (not c) #f
(begin (next-char)
(if (char=? c (string-ref str 0))
(match-other-chars 1)
(match-1st-char)))))))
;; There has been a partial match, up to the point pos-to-match
;; (for example, str[0] has been found in the stream)
;; Now look to see if str[pos-to-match] for would be found, too
(match-other-chars
(lambda (pos-to-match)
(if (>= pos-to-match (string-length str))
no-chars-read ; the entire string has matched
(let ((c (my-peek-char)))
(and c
(if (not (char=? c (string-ref str pos-to-match)))
(backtrack 1 pos-to-match)
(begin (next-char)
(match-other-chars (inc pos-to-match)))))))))
;; There had been a partial match, but then a wrong char showed up.
;; Before discarding previously read (and matched) characters, we check
;; to see if there was some smaller partial match. Note, characters read
;; so far (which matter) are those of str[0..matched-substr-len - 1]
;; In other words, we will check to see if there is such i>0 that
;; substr(str,0,j) = substr(str,i,matched-substr-len)
;; where j=matched-substr-len - i
(backtrack
(lambda (i matched-substr-len)
(let ((j (- matched-substr-len i)))
(if (<= j 0)
(match-1st-char) ; backed off completely to the begining of str
(let loop ((k 0))
(if (>= k j)
(match-other-chars j) ; there was indeed a shorter match
(if (char=? (string-ref str k)
(string-ref str (+ i k)))
(loop (inc k))
(backtrack (inc i) matched-substr-len))))))))
)
(match-1st-char)))
(define find-string-from-port? MISCIO:find-string-from-port?)
;-----------------------------------------------------------------------------
; This is a test driver for miscio:find-string-from-port?, to make sure it
; really works as intended
; moved to vinput-parse.scm
(define-syntax run-test (syntax-rules (define) ((run-test "scan-exp" (define vars body)) (define vars (run-test "scan-exp" body))) ((run-test "scan-exp" ?body) (letrec-syntax ((scan-exp (syntax-rules (quote . `!) ((scan-exp '() (k-head ! . args)) (k-head '() . args)) ((scan-exp '(hd . tl) k) (scan-lit-lst (hd . tl) (do-wrap ! . `k))) ((scan-exp `(hd . tl) k) (scan-lit-lst (hd . tl) (do-wrap ! . `k))) ((scan-exp 'x (k-head ! . args)) (k-head (if (string? 'x) (string->symbol 'x) 'x) . args)) ((scan-exp (hd . tl) k) (scan-exp hd (do-tl ! scan-exp tl k))) ((scan-exp x (k-head ! . args)) (k-head x . args)))) (do-tl (syntax-rules (!) ((do-tl processed-hd fn () (k-head ! . args)) (k-head (processed-hd) . args)) ((do-tl processed-hd fn old-tl k) (fn old-tl (do-cons ! processed-hd k))))) (do-cons (syntax-rules (!) ((do-cons processed-tl processed-hd (k-head ! . args)) (k-head (processed-hd . processed-tl) . args)))) (do-wrap (syntax-rules (!) ((do-wrap val fn (k-head ! . args)) (k-head (fn val) . args)))) (do-finish (syntax-rules () ((do-finish new-body) new-body))) (scan-lit-lst (syntax-rules (quote unquote . ,@!) ((scan-lit-lst '() (k-head ! . args)) (k-head '() . args)) ((scan-lit-lst '(hd . tl) k) (do-tl quote scan-lit-lst ((hd . tl)) k)) ((scan-lit-lst ,x k) (scan-exp x (do-wrap ! . ,k))) ((scan-lit-lst ,@x k) (scan-exp x (do-wrap ! . ,@k))) ((scan-lit-lst 'x (k-head ! . args)) (k-head ,(if (string? 'x) (string->symbol 'x) 'x) . args)) ((scan-lit-lst (hd . tl) k) (scan-lit-lst hd (do-tl ! scan-lit-lst tl k))) ((scan-lit-lst x (k-head ! . args)) (k-head x . args))))) (scan-exp ?body (do-finish !)))) ((run-test body ...) (begin (run-test "scan-exp" body) ...))))
(define (make-xml-token kind head) (cons kind head))
(define xml-token? pair?)
(define-syntax xml-token-kind (syntax-rules () ((xml-token-kind token) (car token))))
(define-syntax xml-token-head (syntax-rules () ((xml-token-head token) (cdr token))))
(define (string-whitespace? str) (let ((len (string-length str))) (cond ((zero? len) #t) ((= 1 len) (char-whitespace? (string-ref str 0))) ((= 2 len) (and (char-whitespace? (string-ref str 0)) (char-whitespace? (string-ref str 1)))) (else (let loop ((i 0)) (or (>= i len) (and (char-whitespace? (string-ref str i)) (loop (inc i)))))))))
(define (assq-values val alist) (let loop ((alist alist) (scanned '())) (cond ((null? alist) (values #f scanned)) ((equal? val (caar alist)) (values (car alist) (append scanned (cdr alist)))) (else (loop (cdr alist) (cons (car alist) scanned))))))
(define (fold-right kons knil lis1) (let recur ((lis lis1)) (if (null? lis) knil (let ((head (car lis))) (kons head (recur (cdr lis)))))))
(define (fold kons knil lis1) (let lp ((lis lis1) (ans knil)) (if (null? lis) ans (lp (cdr lis) (kons (car lis) ans)))))
(define ssax:S-chars (map ascii->char '(32 10 9 13)))
(define (ssax:skip-S port) (skip-while ssax:S-chars port))
(define (ssax:ncname-starting-char? a-char) (and (char? a-char) (or (char-alphabetic? a-char) (char=? #\_ a-char))))
(define (ssax:read-NCName port) (let ((first-char (peek-char port))) (or (ssax:ncname-starting-char? first-char) (parser-error port "XMLNS [4] for '" first-char "'"))) (string->symbol (next-token-of (lambda (c) (cond ((eof-object? c) #f) ((char-alphabetic? c) c) ((string-index "0123456789.-_" c) c) (else #f))) port)))
(define (ssax:read-QName port) (let ((prefix-or-localpart (ssax:read-NCName port))) (case (peek-char port) ((#\:) (read-char port) (cons prefix-or-localpart (ssax:read-NCName port))) (else prefix-or-localpart))))
(define ssax:Prefix-XML (string->symbol "xml"))
(define name-compare (letrec ((symbol-compare (lambda (symb1 symb2) (cond ((eq? symb1 symb2) '=) ((string<? (symbol->string symb1) (symbol->string symb2)) '<) (else '>))))) (lambda (name1 name2) (cond ((symbol? name1) (if (symbol? name2) (symbol-compare name1 name2) '<)) ((symbol? name2) '>) ((eq? name2 ssax:largest-unres-name) '<) ((eq? name1 ssax:largest-unres-name) '>) ((eq? (car name1) (car name2)) (symbol-compare (cdr name1) (cdr name2))) (else (symbol-compare (car name1) (car name2)))))))
(define ssax:largest-unres-name (cons (string->symbol "#LARGEST-SYMBOL") (string->symbol "#LARGEST-SYMBOL")))
(define ssax:read-markup-token (let () (define (skip-comment port) (assert-curr-char '(#\-) "XML [15], second dash" port) (if (not (find-string-from-port? "-->" port)) (parser-error port "XML [15], no -->")) (make-xml-token 'COMMENT #f)) (define (read-cdata port) (assert (string=? "CDATA[" (read-string 6 port))) (make-xml-token 'CDSECT #f)) (lambda (port) (assert-curr-char '(#\<) "start of the token" port) (case (peek-char port) ((#\/) (read-char port) (begin0 (make-xml-token 'END (ssax:read-QName port)) (ssax:skip-S port) (assert-curr-char '(#\>) "XML [42]" port))) ((#\?) (read-char port) (make-xml-token 'PI (ssax:read-NCName port))) ((#\!) (case (peek-next-char port) ((#\-) (read-char port) (skip-comment port)) ((#\[) (read-char port) (read-cdata port)) (else (make-xml-token 'DECL (ssax:read-NCName port))))) (else (make-xml-token 'START (ssax:read-QName port)))))))
(define (ssax:skip-pi port) (if (not (find-string-from-port? "?>" port)) (parser-error port "Failed to find ?> terminating the PI")))
(define (ssax:read-pi-body-as-string port) (ssax:skip-S port) (string-concatenate/shared (let loop () (let ((pi-fragment (next-token '() '(#\?) "reading PI content" port))) (if (eqv? #\> (peek-next-char port)) (begin (read-char port) (cons pi-fragment '())) (cons* pi-fragment "?" (loop)))))))
(define (ssax:skip-internal-dtd port) (if (not (find-string-from-port? "]>" port)) (parser-error port "Failed to find ]> terminating the internal DTD subset")))
(define ssax:read-cdata-body (let ((cdata-delimiters (list char-return #\newline #\] #\&))) (lambda (port str-handler seed) (let loop ((seed seed)) (let ((fragment (next-token '() cdata-delimiters "reading CDATA" port))) (case (read-char port) ((#\newline) (loop (str-handler fragment nl seed))) ((#\]) (if (not (eqv? (peek-char port) #\])) (loop (str-handler fragment "]" seed)) (let check-after-second-braket ((seed (if (string-null? fragment) seed (str-handler fragment "" seed)))) (case (peek-next-char port) ((#\>) (read-char port) seed) ((#\]) (check-after-second-braket (str-handler "]" "" seed))) (else (loop (str-handler "]]" "" seed))))))) ((#\&) (let ((ent-ref (next-token-of (lambda (c) (and (not (eof-object? c)) (char-alphabetic? c) c)) port))) (cond ((and (string=? "gt" ent-ref) (eqv? (peek-char port) #\;)) (read-char port) (loop (str-handler fragment ">" seed))) (else (loop (str-handler ent-ref "" (str-handler fragment "&" seed))))))) (else (if (eqv? (peek-char port) #\newline) (read-char port)) (loop (str-handler fragment nl seed)))))))))
(define (ssax:read-char-ref port) (let* ((base (cond ((eqv? (peek-char port) #\x) (read-char port) 16) (else 10))) (name (next-token '() '(#\;) "XML [66]" port)) (char-code (string->number name base))) (read-char port) (if (integer? char-code) (ucscode->char char-code) (parser-error port "[wf-Legalchar] broken for '" name "'"))))
(define ssax:predefined-parsed-entities `((,(string->symbol "amp") . "&") (,(string->symbol "lt") . "<") (,(string->symbol "gt") . ">") (,(string->symbol "apos") . "'") (,(string->symbol "quot") . "\"")))
(define (ssax:handle-parsed-entity port name entities content-handler str-handler seed) (cond ((assq name entities) => (lambda (decl-entity) (let ((ent-body (cdr decl-entity)) (new-entities (cons (cons name #f) entities))) (cond ((string? ent-body) (call-with-input-string ent-body (lambda (port) (content-handler port new-entities seed)))) ((procedure? ent-body) (let ((port (ent-body))) (begin0 (content-handler port new-entities seed) (close-input-port port)))) (else (parser-error port "[norecursion] broken for " name)))))) ((assq name ssax:predefined-parsed-entities) => (lambda (decl-entity) (str-handler (cdr decl-entity) "" seed))) (else (parser-error port "[wf-entdeclared] broken for " name))))
(define (make-empty-attlist) '())
(define (attlist-add attlist name-value) (if (null? attlist) (cons name-value attlist) (case (name-compare (car name-value) (caar attlist)) ((=) #f) ((<) (cons name-value attlist)) (else (cons (car attlist) (attlist-add (cdr attlist) name-value))))))
(define attlist-null? null?)
(define (attlist-remove-top attlist) (values (car attlist) (cdr attlist)))
(define (attlist->alist attlist) attlist)
(define attlist-fold fold)
(define ssax:read-attributes (let ((value-delimeters (append ssax:S-chars '(#\< #\&)))) (define (read-attrib-value delimiter port entities prev-fragments) (let* ((new-fragments (cons (next-token '() (cons delimiter value-delimeters) "XML [10]" port) prev-fragments)) (cterm (read-char port))) (cond ((or (eof-object? cterm) (eqv? cterm delimiter)) new-fragments) ((eqv? cterm char-return) (if (eqv? (peek-char port) #\newline) (read-char port)) (read-attrib-value delimiter port entities (cons " " new-fragments))) ((memv cterm ssax:S-chars) (read-attrib-value delimiter port entities (cons " " new-fragments))) ((eqv? cterm #\&) (cond ((eqv? (peek-char port) #\#) (read-char port) (read-attrib-value delimiter port entities (cons (string (ssax:read-char-ref port)) new-fragments))) (else (read-attrib-value delimiter port entities (read-named-entity port entities new-fragments))))) (else (parser-error port "[CleanAttrVals] broken"))))) (define (read-named-entity port entities fragments) (let ((name (ssax:read-NCName port))) (assert-curr-char '(#\;) "XML [68]" port) (ssax:handle-parsed-entity port name entities (lambda (port entities fragments) (read-attrib-value '*eof* port entities fragments)) (lambda (str1 str2 fragments) (if (equal? "" str2) (cons str1 fragments) (cons* str2 str1 fragments))) fragments))) (lambda (port entities) (let loop ((attr-list (make-empty-attlist))) (if (not (ssax:ncname-starting-char? (ssax:skip-S port))) attr-list (let ((name (ssax:read-QName port))) (ssax:skip-S port) (assert-curr-char '(#\=) "XML [25]" port) (ssax:skip-S port) (let ((delimiter (assert-curr-char '(#\' #\") "XML [10]" port))) (loop (or (attlist-add attr-list (cons name (string-concatenate-reverse/shared (read-attrib-value delimiter port entities '())))) (parser-error port "[uniqattspec] broken for " name))))))))))
(define (ssax:resolve-name port unres-name namespaces apply-default-ns?) (cond ((pair? unres-name) (cons (cond ((assq (car unres-name) namespaces) => cadr) ((eq? (car unres-name) ssax:Prefix-XML) ssax:Prefix-XML) (else (parser-error port "[nsc-NSDeclared] broken; prefix " (car unres-name)))) (cdr unres-name))) (apply-default-ns? (let ((default-ns (assq '*DEFAULT* namespaces))) (if (and default-ns (cadr default-ns)) (cons (cadr default-ns) unres-name) unres-name))) (else unres-name)))
(define (ssax:uri-string->symbol uri-str) (string->symbol uri-str))
(define ssax:complete-start-tag (let ((xmlns (string->symbol "xmlns")) (largest-dummy-decl-attr (list ssax:largest-unres-name #f #f #f))) (define (validate-attrs port attlist decl-attrs) (define (add-default-decl decl-attr result) (let*-values (((attr-name content-type use-type default-value) (apply values decl-attr))) (and (eq? use-type 'REQUIRED) (parser-error port "[RequiredAttr] broken for" attr-name)) (if default-value (cons (cons attr-name default-value) result) result))) (let loop ((attlist attlist) (decl-attrs decl-attrs) (result '())) (if (attlist-null? attlist) (attlist-fold add-default-decl result decl-attrs) (let*-values (((attr attr-others) (attlist-remove-top attlist)) ((decl-attr other-decls) (if (attlist-null? decl-attrs) (values largest-dummy-decl-attr decl-attrs) (attlist-remove-top decl-attrs)))) (case (name-compare (car attr) (car decl-attr)) ((<) (if (or (eq? xmlns (car attr)) (and (pair? (car attr)) (eq? xmlns (caar attr)))) (loop attr-others decl-attrs (cons attr result)) (parser-error port "[ValueType] broken for " attr))) ((>) (loop attlist other-decls (add-default-decl decl-attr result))) (else (let*-values (((attr-name content-type use-type default-value) (apply values decl-attr))) (cond ((eq? use-type 'FIXED) (or (equal? (cdr attr) default-value) (parser-error port "[FixedAttr] broken for " attr-name))) ((eq? content-type 'CDATA) #t) ((pair? content-type) (or (member (cdr attr) content-type) (parser-error port "[enum] broken for " attr-name "=" (cdr attr)))) (else (ssax:warn port "declared content type " content-type " not verified yet"))) (loop attr-others other-decls (cons attr result))))))))) (define (add-ns port prefix uri-str namespaces) (and (equal? "" uri-str) (parser-error port "[dt-NSName] broken for " prefix)) (let ((uri-symbol (ssax:uri-string->symbol uri-str))) (let loop ((nss namespaces)) (cond ((null? nss) (cons (cons* prefix uri-symbol uri-symbol) namespaces)) ((eq? uri-symbol (cddar nss)) (cons (cons* prefix (cadar nss) uri-symbol) namespaces)) (else (loop (cdr nss))))))) (define (adjust-namespace-decl port attrs namespaces) (let loop ((attrs attrs) (proper-attrs '()) (namespaces namespaces)) (cond ((null? attrs) (values proper-attrs namespaces)) ((eq? xmlns (caar attrs)) (loop (cdr attrs) proper-attrs (if (equal? "" (cdar attrs)) (cons (cons* '*DEFAULT* #f #f) namespaces) (add-ns port '*DEFAULT* (cdar attrs) namespaces)))) ((and (pair? (caar attrs)) (eq? xmlns (caaar attrs))) (loop (cdr attrs) proper-attrs (add-ns port (cdaar attrs) (cdar attrs) namespaces))) (else (loop (cdr attrs) (cons (car attrs) proper-attrs) namespaces))))) (lambda (tag-head port elems entities namespaces) (let*-values (((attlist) (ssax:read-attributes port entities)) ((empty-el-tag?) (begin (ssax:skip-S port) (and (eqv? #\/ (assert-curr-char '(#\> #\/) "XML [40], XML [44], no '>'" port)) (assert-curr-char '(#\>) "XML [44], no '>'" port)))) ((elem-content decl-attrs) (if elems (cond ((assoc tag-head elems) => (lambda (decl-elem) (values (if empty-el-tag? 'EMPTY-TAG (cadr decl-elem)) (caddr decl-elem)))) (else (parser-error port "[elementvalid] broken, no decl for " tag-head))) (values (if empty-el-tag? 'EMPTY-TAG 'ANY) #f))) ((merged-attrs) (if decl-attrs (validate-attrs port attlist decl-attrs) (attlist->alist attlist))) ((proper-attrs namespaces) (adjust-namespace-decl port merged-attrs namespaces))) (values (ssax:resolve-name port tag-head namespaces #t) (fold-right (lambda (name-value attlist) (or (attlist-add attlist (cons (ssax:resolve-name port (car name-value) namespaces #f) (cdr name-value))) (parser-error port "[uniqattspec] after NS expansion broken for " name-value))) (make-empty-attlist) proper-attrs) namespaces elem-content)))))
(define (ssax:read-external-id port) (let ((discriminator (ssax:read-NCName port))) (assert-curr-char ssax:S-chars "space after SYSTEM or PUBLIC" port) (ssax:skip-S port) (let ((delimiter (assert-curr-char '(#\' #\") "XML [11], XML [12]" port))) (cond ((eq? discriminator (string->symbol "SYSTEM")) (begin0 (next-token '() (list delimiter) "XML [11]" port) (read-char port))) ((eq? discriminator (string->symbol "PUBLIC")) (skip-until (list delimiter) port) (assert-curr-char ssax:S-chars "space after PubidLiteral" port) (ssax:skip-S port) (let* ((delimiter (assert-curr-char '(#\' #\") "XML [11]" port)) (systemid (next-token '() (list delimiter) "XML [11]" port))) (read-char port) systemid)) (else (parser-error port "XML [75], " discriminator " rather than SYSTEM or PUBLIC"))))))
(define (ssax:scan-Misc port) (let loop ((c (ssax:skip-S port))) (cond ((eof-object? c) c) ((not (char=? c #\<)) (parser-error port "XML [22], char '" c "' unexpected")) (else (let ((token (ssax:read-markup-token port))) (case (xml-token-kind token) ((COMMENT) (loop (ssax:skip-S port))) ((PI DECL START) token) (else (parser-error port "XML [22], unexpected token of kind " (xml-token-kind token)))))))))
(define ssax:read-char-data (let ((terminators-usual (list #\< #\& char-return)) (terminators-usual-eof (list #\< '*eof* #\& char-return)) (handle-fragment (lambda (fragment str-handler seed) (if (string-null? fragment) seed (str-handler fragment "" seed))))) (lambda (port expect-eof? str-handler seed) (if (eqv? #\< (peek-char port)) (let ((token (ssax:read-markup-token port))) (case (xml-token-kind token) ((START END) (values seed token)) ((CDSECT) (let ((seed (ssax:read-cdata-body port str-handler seed))) (ssax:read-char-data port expect-eof? str-handler seed))) ((COMMENT) (ssax:read-char-data port expect-eof? str-handler seed)) (else (values seed token)))) (let ((char-data-terminators (if expect-eof? terminators-usual-eof terminators-usual))) (let loop ((seed seed)) (let* ((fragment (next-token '() char-data-terminators "reading char data" port)) (term-char (peek-char port))) (if (eof-object? term-char) (values (handle-fragment fragment str-handler seed) term-char) (case term-char ((#\<) (let ((token (ssax:read-markup-token port))) (case (xml-token-kind token) ((CDSECT) (loop (ssax:read-cdata-body port str-handler (handle-fragment fragment str-handler seed)))) ((COMMENT) (loop (handle-fragment fragment str-handler seed))) (else (values (handle-fragment fragment str-handler seed) token))))) ((#\&) (case (peek-next-char port) ((#\#) (read-char port) (loop (str-handler fragment (string (ssax:read-char-ref port)) seed))) (else (let ((name (ssax:read-NCName port))) (assert-curr-char '(#\;) "XML [68]" port) (values (handle-fragment fragment str-handler seed) (make-xml-token 'ENTITY-REF name)))))) (else (if (eqv? (peek-next-char port) #\newline) (read-char port)) (loop (str-handler fragment (string #\newline) seed))))))))))))
(define (ssax:assert-token token kind gi error-cont) (or (and (xml-token? token) (eq? kind (xml-token-kind token)) (equal? gi (xml-token-head token))) (error-cont token kind gi)))
(define-syntax ssax:make-pi-parser (syntax-rules () ((ssax:make-pi-parser orig-handlers) (letrec-syntax ((loop (syntax-rules (*DEFAULT*) ((loop () #f accum port target seed) (make-case ((else (ssax:warn port "Skipping PI: " target nl) (ssax:skip-pi port) seed) . accum) () target)) ((loop () default accum port target seed) (make-case ((else (default port target seed)) . accum) () target)) ((loop ((*DEFAULT* . default) . handlers) old-def accum port target seed) (loop handlers default accum port target seed)) ((loop ((tag . handler) . handlers) default accum port target seed) (loop handlers default (((tag) (handler port target seed)) . accum) port target seed)))) (make-case (syntax-rules () ((make-case () clauses target) (case target . clauses)) ((make-case (clause . clauses) accum target) (make-case clauses (clause . accum) target))))) (lambda (port target seed) (loop orig-handlers #f () port target seed))))))
(define-syntax ssax:make-elem-parser (syntax-rules () ((ssax:make-elem-parser my-new-level-seed my-finish-element my-char-data-handler my-pi-handlers) (lambda (start-tag-head port elems entities namespaces preserve-ws? seed) (define xml-space-gi (cons ssax:Prefix-XML (string->symbol "space"))) (let handle-start-tag ((start-tag-head start-tag-head) (port port) (entities entities) (namespaces namespaces) (preserve-ws? preserve-ws?) (parent-seed seed)) (let*-values (((elem-gi attributes namespaces expected-content) (ssax:complete-start-tag start-tag-head port elems entities namespaces)) ((seed) (my-new-level-seed elem-gi attributes namespaces expected-content parent-seed))) (case expected-content ((EMPTY-TAG) (my-finish-element elem-gi attributes namespaces parent-seed seed)) ((EMPTY) (ssax:assert-token (and (eqv? #\< (ssax:skip-S port)) (ssax:read-markup-token port)) 'END start-tag-head (lambda (token exp-kind exp-head) (parser-error port "[elementvalid] broken for " token " while expecting " exp-kind exp-head))) (my-finish-element elem-gi attributes namespaces parent-seed seed)) (else (let ((preserve-ws? (cond ((assoc xml-space-gi attributes) => (lambda (name-value) (equal? "preserve" (cdr name-value)))) (else preserve-ws?)))) (let loop ((port port) (entities entities) (expect-eof? #f) (seed seed)) (let*-values (((seed term-token) (ssax:read-char-data port expect-eof? my-char-data-handler seed))) (if (eof-object? term-token) seed (case (xml-token-kind term-token) ((END) (ssax:assert-token term-token 'END start-tag-head (lambda (token exp-kind exp-head) (parser-error port "[GIMatch] broken for " term-token " while expecting " exp-kind exp-head))) (my-finish-element elem-gi attributes namespaces parent-seed seed)) ((PI) (let ((seed ((ssax:make-pi-parser my-pi-handlers) port (xml-token-head term-token) seed))) (loop port entities expect-eof? seed))) ((ENTITY-REF) (let ((seed (ssax:handle-parsed-entity port (xml-token-head term-token) entities (lambda (port entities seed) (loop port entities #t seed)) my-char-data-handler seed))) (loop port entities expect-eof? seed))) ((START) (if (eq? expected-content 'PCDATA) (parser-error port "[elementvalid] broken for " elem-gi " with char content only; unexpected token " term-token)) (let ((seed (handle-start-tag (xml-token-head term-token) port entities namespaces preserve-ws? seed))) (loop port entities expect-eof? seed))) (else (parser-error port "XML [43] broken for " term-token)))))))))))))))
(define-syntax ssax:make-parser/positional-args (syntax-rules () ((ssax:make-parser/positional-args *handler-DOCTYPE *handler-UNDECL-ROOT *handler-DECL-ROOT *handler-NEW-LEVEL-SEED *handler-FINISH-ELEMENT *handler-CHAR-DATA-HANDLER *handler-PI) (lambda (port seed) (define (handle-decl port token-head seed) (or (eq? (string->symbol "DOCTYPE") token-head) (parser-error port "XML [22], expected DOCTYPE declaration, found " token-head)) (assert-curr-char ssax:S-chars "XML [28], space after DOCTYPE" port) (ssax:skip-S port) (let*-values (((docname) (ssax:read-QName port)) ((systemid) (and (ssax:ncname-starting-char? (ssax:skip-S port)) (ssax:read-external-id port))) ((internal-subset?) (begin (ssax:skip-S port) (eqv? #\[ (assert-curr-char '(#\> #\[) "XML [28], end-of-DOCTYPE" port)))) ((elems entities namespaces seed) (*handler-DOCTYPE port docname systemid internal-subset? seed))) (scan-for-significant-prolog-token-2 port elems entities namespaces seed))) (define (scan-for-significant-prolog-token-1 port seed) (let ((token (ssax:scan-Misc port))) (if (eof-object? token) (parser-error port "XML [22], unexpected EOF") (case (xml-token-kind token) ((PI) (let ((seed ((ssax:make-pi-parser *handler-PI) port (xml-token-head token) seed))) (scan-for-significant-prolog-token-1 port seed))) ((DECL) (handle-decl port (xml-token-head token) seed)) ((START) (let*-values (((elems entities namespaces seed) (*handler-UNDECL-ROOT (xml-token-head token) seed))) (element-parser (xml-token-head token) port elems entities namespaces #f seed))) (else (parser-error port "XML [22], unexpected markup " token)))))) (define (scan-for-significant-prolog-token-2 port elems entities namespaces seed) (let ((token (ssax:scan-Misc port))) (if (eof-object? token) (parser-error port "XML [22], unexpected EOF") (case (xml-token-kind token) ((PI) (let ((seed ((ssax:make-pi-parser *handler-PI) port (xml-token-head token) seed))) (scan-for-significant-prolog-token-2 port elems entities namespaces seed))) ((START) (element-parser (xml-token-head token) port elems entities namespaces #f (*handler-DECL-ROOT (xml-token-head token) seed))) (else (parser-error port "XML [22], unexpected markup " token)))))) (define element-parser (ssax:make-elem-parser *handler-NEW-LEVEL-SEED *handler-FINISH-ELEMENT *handler-CHAR-DATA-HANDLER *handler-PI)) (scan-for-significant-prolog-token-1 port seed)))))
(define-syntax ssax:define-labeled-arg-macro (syntax-rules () ((ssax:define-labeled-arg-macro labeled-arg-macro-name (positional-macro-name (arg-name . arg-def) ...)) (define-syntax labeled-arg-macro-name (syntax-rules () ((labeled-arg-macro-name . kw-val-pairs) (letrec-syntax ((find (syntax-rules (arg-name ...) ((find k-args (arg-name . default) arg-name val . others) (next val . k-args)) ... ((find k-args key arg-no-match-name val . others) (find k-args key . others)) ((find k-args (arg-name default)) (next default . k-args)) ...)) (next (syntax-rules () ((next val vals key . keys) (find ((val . vals) . keys) key . kw-val-pairs)) ((next val vals) (rev-apply (val) vals)))) (rev-apply (syntax-rules () ((rev-apply form (x . xs)) (rev-apply (x . form) xs)) ((rev-apply form ()) form)))) (next positional-macro-name () (arg-name . arg-def) ...))))))))
(ssax:define-labeled-arg-macro ssax:make-parser (ssax:make-parser/positional-args (DOCTYPE (lambda (port docname systemid internal-subset? seed) (when internal-subset? (ssax:warn port "Internal DTD subset is not currently handled ") (ssax:skip-internal-dtd port)) (ssax:warn port "DOCTYPE DECL " docname " " systemid " found and skipped") (values #f '() '() seed))) (UNDECL-ROOT (lambda (elem-gi seed) (values #f '() '() seed))) (DECL-ROOT (lambda (elem-gi seed) seed)) (NEW-LEVEL-SEED) (FINISH-ELEMENT) (CHAR-DATA-HANDLER) (PI ())))
(define (ssax:reverse-collect-str fragments) (cond ((null? fragments) '()) ((null? (cdr fragments)) fragments) (else (let loop ((fragments fragments) (result '()) (strs '())) (cond ((null? fragments) (if (null? strs) result (cons (string-concatenate/shared strs) result))) ((string? (car fragments)) (loop (cdr fragments) result (cons (car fragments) strs))) (else (loop (cdr fragments) (cons (car fragments) (if (null? strs) result (cons (string-concatenate/shared strs) result))) '())))))))
(define (ssax:reverse-collect-str-drop-ws fragments) (cond ((null? fragments) '()) ((null? (cdr fragments)) (if (and (string? (car fragments)) (string-whitespace? (car fragments))) '() fragments)) (else (let loop ((fragments fragments) (result '()) (strs '()) (all-whitespace? #t)) (cond ((null? fragments) (if all-whitespace? result (cons (string-concatenate/shared strs) result))) ((string? (car fragments)) (loop (cdr fragments) result (cons (car fragments) strs) (and all-whitespace? (string-whitespace? (car fragments))))) (else (loop (cdr fragments) (cons (car fragments) (if all-whitespace? result (cons (string-concatenate/shared strs) result))) '() #t)))))))
(define (ssax:xml->sxml port namespace-prefix-assig) (letrec ((namespaces (map (lambda (el) (cons* #f (car el) (ssax:uri-string->symbol (cdr el)))) namespace-prefix-assig)) (RES-NAME->SXML (lambda (res-name) (string->symbol (string-append (symbol->string (car res-name)) ":" (symbol->string (cdr res-name))))))) (let ((result (reverse ((ssax:make-parser NEW-LEVEL-SEED (lambda (elem-gi attributes namespaces expected-content seed) '()) FINISH-ELEMENT (lambda (elem-gi attributes namespaces parent-seed seed) (let ((seed (ssax:reverse-collect-str-drop-ws seed)) (attrs (attlist-fold (lambda (attr accum) (cons (list (if (symbol? (car attr)) (car attr) (RES-NAME->SXML (car attr))) (cdr attr)) accum)) '() attributes))) (cons (cons (if (symbol? elem-gi) elem-gi (RES-NAME->SXML elem-gi)) (if (null? attrs) seed (cons (cons '@ attrs) seed))) parent-seed))) CHAR-DATA-HANDLER (lambda (string1 string2 seed) (if (string-null? string2) (cons string1 seed) (cons* string2 string1 seed))) DOCTYPE (lambda (port docname systemid internal-subset? seed) (when internal-subset? (ssax:warn port "Internal DTD subset is not currently handled ") (ssax:skip-internal-dtd port)) (ssax:warn port "DOCTYPE DECL " docname " " systemid " found and skipped") (values #f '() namespaces seed)) UNDECL-ROOT (lambda (elem-gi seed) (values #f '() namespaces seed)) PI ((*DEFAULT* lambda (port pi-tag seed) (cons (list '*PI* pi-tag (ssax:read-pi-body-as-string port)) seed)))) port '())))) (cons '*TOP* (if (null? namespace-prefix-assig) result (cons (list '@ (cons '*NAMESPACES* (map (lambda (ns) (list (car ns) (cdr ns))) namespace-prefix-assig))) result))))))
(define SSAX:XML->SXML ssax:xml->sxml)
(define current-error-port console-output-port)
(define (ssax:warn port msg . other-msg)
(apply cerr (cons* nl "Warning: " msg other-msg)))
| true |
2d664620172661112ffd25400e564681eab2d2d8
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/mscorlib/system/security/principal/identity-not-mapped-exception.sls
|
0a77ff9002d0de0f8191bd7c138754b5c9451b3e
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,086 |
sls
|
identity-not-mapped-exception.sls
|
(library (system security principal identity-not-mapped-exception)
(export new
is?
identity-not-mapped-exception?
get-object-data
unmapped-identities)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.Security.Principal.IdentityNotMappedException
a
...)))))
(define (is? a)
(clr-is System.Security.Principal.IdentityNotMappedException a))
(define (identity-not-mapped-exception? a)
(clr-is System.Security.Principal.IdentityNotMappedException a))
(define-method-port
get-object-data
System.Security.Principal.IdentityNotMappedException
GetObjectData
(System.Void
System.Runtime.Serialization.SerializationInfo
System.Runtime.Serialization.StreamingContext))
(define-field-port
unmapped-identities
#f
#f
(property:)
System.Security.Principal.IdentityNotMappedException
UnmappedIdentities
System.Security.Principal.IdentityReferenceCollection))
| true |
c28a834e6629299ada59c5278d74530b3c3c8587
|
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
|
/scheme/swl1.3/tests/error-help/test36.ss
|
77249c49f66875be1f24cbdc583290160afae453
|
[
"SWL",
"TCL"
] |
permissive
|
ktosiu/snippets
|
79c58416117fa646ae06a8fd590193c9dd89f414
|
08e0655361695ed90e1b901d75f184c52bb72f35
|
refs/heads/master
| 2021-01-17T08:13:34.067768 | 2016-01-29T15:42:14 | 2016-01-29T15:42:14 | 53,054,819 | 1 | 0 | null | 2016-03-03T14:06:53 | 2016-03-03T14:06:53 | null |
UTF-8
|
Scheme
| false | false | 89 |
ss
|
test36.ss
|
; Test error "too many fields supplied for record ~s"
(define x '#[zinjanthropus 3 4 5])
| false |
87ad4648084e746ed00ba12b0ddc5983fd866b18
|
398496271fc1e4bc679f8520e2aa12d958c71059
|
/MihirGupta_101172281_comp3007final/partb1_generator.scm
|
8190243d6dc44176ecf094ad0282cb2c763169e2
|
[] |
no_license
|
guptamihir418/COMP-3007
|
f1d113d7f5fdc717eed424b486af6327e4b79efe
|
0d34a67658d9f7fab821cbaa922fa7b11889420a
|
refs/heads/main
| 2023-04-22T14:38:19.381362 | 2021-05-05T15:26:44 | 2021-05-05T15:26:44 | 364,622,119 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 270 |
scm
|
partb1_generator.scm
|
(define (utilForLG A B C D E)
(if (and (< C D) (negative? E)) (list ) (if (and (> C D) (> E 0)) (list ) (if (A C) (append (list (B C)) (utilForLG A B (+ E C) D E)) (utilForLG A B (+ E C) D E)))))
(define (list-generator A B) (lambda (C D E) (utilForLG A B C D E)))
| false |
e1da6d70ad7aec171f30edd13b6f14b2b8a5f5b1
|
6f86602ac19983fcdfcb2710de6e95b60bfb0e02
|
/exercises/practice/knapsack/test.scm
|
0411da44c441f1f7aef925ac39458a7c7c8f6608
|
[
"MIT",
"CC-BY-SA-3.0"
] |
permissive
|
exercism/scheme
|
a28bf9451b8c070d309be9be76f832110f2969a7
|
d22a0f187cd3719d071240b1d5a5471e739fed81
|
refs/heads/main
| 2023-07-20T13:35:56.639056 | 2023-07-18T08:38:59 | 2023-07-18T08:38:59 | 30,056,632 | 34 | 37 |
MIT
| 2023-09-04T21:08:27 | 2015-01-30T04:46:03 |
Scheme
|
UTF-8
|
Scheme
| false | false | 2,114 |
scm
|
test.scm
|
(load "test-util.ss")
(define test-cases
`((test-success "no items" = knapsack '(100 () ()) 0)
(test-success "one item, too heavy" = knapsack
'(10 (100) (1)) 0)
(test-success "five items (cannot be greedy by weight)" =
knapsack '(10 (2 2 2 2 10) (5 5 5 5 21)) 21)
(test-success "five items (cannot be greedy by value)" =
knapsack '(10 (2 2 2 2 10) (20 20 20 20 50)) 80)
(test-success "example knapsack" = knapsack
'(10 (5 4 6 4) (10 40 30 50)) 90)
(test-success "8 items" = knapsack
'(104 (25 35 45 5 25 3 2 2) (350 400 450 20 70 8 5 5)) 900)
(test-success "15 items" = knapsack
'(750 (70 73 77 80 82 87 90 94 98 106 110 113 115 118 120)
(135 139 149 150 156 163 173 184 192 201 210 214 221 229
240))
1458)
(test-success "example with 30 items" = knapsack
'(100000
(90001 89751 10002 89501 10254 89251 10506 89001 10758 88751
11010 88501 11262 88251 11514 88001 11766 87751 12018 87501
12270 87251 12522 87001 12774 86751 13026 86501 13278 86251)
(90000 89750 10001 89500 10252 89250 10503 89000 10754 88750
11005 88500 11256 88250 11507 88000 11758 87750 12009 87500
12260 87250 12511 87000 12762 86750 13013 86500 13264
86250))
99798)
(test-success "example with 50 items" = knapsack
'(341045
(4912 99732 56554 1818 108372 6750 1484 3072 13532 12050
18440 10972 1940 122094 5558 10630 2112 6942 39888 71276
8466 5662 231302 4690 18324 3384 7278 5566 706 10992 27552
7548 934 32038 1062 184848 2604 37644 1832 10306 1126 34886
3526 1196 1338 992 1390 56804 56804 634)
(1906 41516 23527 559 45136 2625 492 1086 5516 4875 7570 4436
620 50897 2129 4265 706 2721 16494 29688 3383 2181 96601
1795 7512 1242 2889 2133 103 4446 11326 3024 217 13269 281
77174 952 15572 566 4103 313 14393 1313 348 419 246 445
23552 23552 67))
142156)))
(run-with-cli "knapsack.scm" (list test-cases))
| false |
50d097520e8aa65f1e02235c329f671825271a98
|
cca999903bc2305da28e598c46298e7d31dbdef5
|
/src/web/collections/test/display-read.ss
|
73ba7ccba22ec4047e5d58513aa893f9b6fbd205
|
[
"Apache-2.0"
] |
permissive
|
ds26gte/kode.pyret.org
|
211183f7045f69cf998a8ebd8a9373cd719d29a1
|
534f2d4b61a6d6c650a364186a4477a52d1cd986
|
refs/heads/master
| 2021-01-11T14:56:43.120765 | 2018-05-02T22:27:55 | 2018-05-02T22:27:55 | 80,234,747 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 25,837 |
ss
|
display-read.ss
|
;; Display-read-utility v.0.8
;; =================
;; - display-read displays one image/string/number and shows a text editor, returns the string entered in the text buffer
;; - display-select displays one image/string/number and selection for the user, the selection can be a list of images, strings or numbers
;; or a single image/string/number/boolean (in which case it gets selected automatically)
;; NOTE: for non-displayable choices, shows a question mark
;; - display-value displays one image/string/number and the given value, if it is displayable (e.g. image/string/number), returns the given value
;; NOTE: for non-displayable values, shows an empty-image
;; - display-read-number reads a number and returns it, if it is not a number returns #f
;; - display-info displays one image/string/number
;; - display-info-timer displays one image/string/number for x ticks and closes automatically
;; You can move coursor and selector with arrowkeys and delete characters with backspace-key
;; Enter returns the editor contents, selected item or value
;; =================
;; Constants:
;#lang racket ; comment out in WeScheme
;(require 2htdp/image) ; comment out in WeScheme
;(require 2htdp/universe) ; comment out in WeScheme
;(require "big-crunch.rkt") ; comment out in WeScheme
(provide display-read
display-read-number
display-select
display-value
display-info
display-info-timer)
(define BUFFER-SIZE 30)
(define TEXT-X 8)
;; default color and size for the text editor field
(define COLOR "blue")
(define SIZE 20)
;; default color and size for the text user wants to display
;; default line-lenght for the displayed string
(define TEXT-SIZE 30)
(define TEXT-COLOR "black")
(define LINE-LENGTH 30)
(define SELECTOR-COLOR "red")
;; render-text : String -> Image
;; converts a string into an image (defines font, size, color and style)
(define (render-text s)
(text/font s SIZE COLOR "Courier New" 'modern 'normal 'normal #f))
;; editor window dimensions are set according to used font SIZE and BUFFER-SIZE
(define HEIGHT (+ (image-height (render-text "m")) 5))
(define WIDTH (+ (* (sub1 BUFFER-SIZE) (image-width (render-text "m"))) (* 2 TEXT-X)))
(define TEXT-Y (/ HEIGHT 2))
(define CURSOR-IMG (rectangle 1 (+ SIZE 3) "solid" "red"))
(define MTS (empty-scene WIDTH HEIGHT))
(define MARGIN 15)
(define NON-DISPLAYABLE (text "?" 30 "black"))
(define MARGIN-IMG (rectangle WIDTH MARGIN 0 "white"))
;; =================
;; Data definitions:
;; Cursor is Natural [0, BUFFER-SIZE)
;; interp. the position of the cursor in the text buffer, which is visible on the screen
;; 0 is the first possible position (before any characters)
(define C1 0) ; first position before any characters on the screen
(define C2 1) ; after 1st character
(define C3 49) ; last position if BUFFER-SIZE is 50
#;
(define (fn-for-cursor c)
(... c))
(define-struct editor (textbuf curpos screenpos))
;; Editor is (make-editor String Cursor Natural)
;; interp. stores editor state:
;; - textbuf (String) stores the characters that user has entered
;; - curpos (Cursor) is the cursor position between the displayed characters
;; - screenpos (Natural) stores the index of the first displayed character from the textbuf (indexing starts from zero)
(define E1 (make-editor "" 0 0 )) ; empty editor, cursor in the beginning
(define E2 (make-editor "testing" 7 0 )) ; one word in the textbuffer with cursor in the end of the word
(define E3 (make-editor "testing that this works" 10 0 )) ; multiple words and cursor after the 10th character
(define E4 (make-editor "testing that this works also with longer strings like this" 10 8 ))
; multiple words and cursor after the 10th character,
; first displayed word is "that"
#;
(define (fn-for-editor e)
(... (editor-textbuf e) ;String
(editor-curpos e) ;Cursor
(editor-screenpos e) ;Natural
(editor-img e))) ;Image
(define-struct window (editor img active?))
;; Window is (make-window Editor Image Boolean)
;; interp. stores UI window state:
;; - editor (Editor), editor struct containing buffer and cursor info
;; - img (Image), user provided image to be displayed in the UI window
;; - active? (Boolean), when #true window is displayed, when set to #false window closes
(define W1 (make-window (make-editor "" 0 0) (circle 100 "solid" "red") #t)) ; normal window with image and empty editor
#;
(define (fn-for-window w)
(... (window-editor w) ;Editor
(window-img w) ;Image
(window-active? w))) ;Boolean
(define-struct selector (choices selected img active?))
;; Selector is (make-selector Selection Image Boolean)
;; interp. stores UI window state:
;; - choices (Selection), items to be selected by user
;; - selected (Number), index of the currently selected item, default is 0
;; - img (Image), user provided image to be displayed in the UI window
;; - active? (Boolean), when #true window is displayed, when set to #false window closes
(define MS1 (make-selector "OK" 0 (circle 100 "solid" "red") #t)) ; selector with one text choice
(define-struct info (item timer? timer-value active?))
;; Info is (make-info Image/String/Number Boolean Number Boolean)
;; interp. stores UI window state:
;; - item (Image/String/Number), user provided image to be displayed in the UI window
;; - timer?, tells if timer is active
;; - active? (Boolean), when #true window is displayed, when set to #false window closes
;; =================
;; Functions:
;; string-split : String -> list-of-String
;; NOTE: needed in WeScheme (comment out in DrRacket)
(define (string-split str)
(rec-string-split '() "" str))
;; rec-string-split : list-of-String String String -> list-of-string
;; splitting a string into a list of strings at each whitespace
;; NOTE: needed in WeScheme (comment out in DrRacket)
(define (rec-string-split str-list curstr str)
(cond [(and (<= (string-length str) 0)
(not (<= (string-length curstr) 0)))
(append str-list (list curstr))]
[(<= (string-length str) 0)
str-list]
[(and (string=? (substring str 0 1) " ")
(> (string-length curstr) 0))
(rec-string-split (append str-list (list curstr)) "" (substring str 1))]
[(string=? (substring str 0 1) " ")
(rec-string-split str-list curstr (substring str 1))]
[else
(rec-string-split str-list (string-append curstr (substring str 0 1)) (substring str 1))]))
;; print-text : String Number -> Image
;; splits the given string into list of strings and calls merge-words
(define (print-text text line-length)
(text->image (merge-words '() (string-split text) "" line-length)
line-length
empty-image))
;; merge-words : list-of-Strings list-of-Strings String Number -> list-of-Strings
;; combines words into lines
(define (merge-words word-list-ok word-list c-line line-length)
(if (empty? word-list)
(append word-list-ok (list c-line))
(cond [(< (+ (string-length c-line)(string-length (first word-list))) line-length)
(merge-words word-list-ok (rest word-list) (string-append c-line (first word-list) " ") line-length)]
[(> (string-length (first word-list)) line-length)
(if (= (string-length c-line) 0)
(merge-words (append word-list-ok (list (substring (first word-list) 0 (sub1 line-length))))
(cons (substring (first word-list) (sub1 line-length))(rest word-list))
c-line
line-length)
(merge-words (append word-list-ok
(list c-line)
(list (substring (first word-list) 0 (sub1 line-length))))
(cons (substring (first word-list) (sub1 line-length))(rest word-list))
""
line-length))
]
[else
(merge-words (append word-list-ok (list c-line)) word-list "" line-length)])))
;; strip-whitespace : String -> String
(define (strip-whitespace s)
(if (and (not (string=? s ""))
(string=? " " (substring s (- (string-length s) 1))))
(substring s 0 (- (string-length s) 1))
s))
;; text->image : list-of-Strings Number Image -> Image
;; converts a list of line strings into one image
(define (text->image lines line-length image)
(cond [(empty? lines)
image]
[(string? (first lines)) ;(<= (add1 line-length) (string-length (first lines))))
(text->image (rest lines)
line-length
(above/align "left" image (text (strip-whitespace (first lines)) TEXT-SIZE TEXT-COLOR)))]
[ else
(text->image (rest lines)
line-length
(above/align "left" image empty-image))]))
;; item->image : Any -> Image
(define (item->image item)
(cond [(number? item)
(print-text (number->string item) LINE-LENGTH)]
[(string? item)
(print-text item LINE-LENGTH)]
[(image? item)
item]
[else
NON-DISPLAYABLE]))
;; selected-item : Selector -> Image/String/Number or empty (= could not select anything)
(define (selected-item s)
(cond [(or (string? (selector-choices s))
(number? (selector-choices s))
(image? (selector-choices s)))
(selector-choices s)]
[(and (cons? (selector-choices s))(not (empty? s))(< (selector-selected s)(length (selector-choices s))))
(list-ref (selector-choices s) (selector-selected s))]
[else empty]))
;; display-read : Image or String or Number -> String
;; a function for displaying user provided image and opening editor for user input
(define (display-read item)
(editor-textbuf (window-editor (big-bang (make-window (make-editor "" 0 0) (item->image item) #t)
(to-draw render-window)
(on-key handle-key-window)
(stop-when stop?)))))
;; display-read-number : Image or String or Number -> Number/Boolean
;; a function for displaying user provided image and opening editor for user input
(define (display-read-number item)
(string->number (editor-textbuf (window-editor (big-bang (make-window (make-editor "" 0 0) (item->image item) #t)
(to-draw render-window)
(on-key handle-key-window)
(stop-when stop?))))))
;; display-no-read : Image or String or Number -> String
;; a function for displaying user provided image and opening editor for user input
(define (display-no-read item)
(editor-textbuf (window-editor (big-bang (make-window (make-editor "" 0 0) (item->image item) #t)
(to-draw render-just-image)
(on-key handle-key-just-image)
(stop-when stop?)))))
;; display-select : Image/String/Number List-of-Images/List-of-Strings/List-of-Numbers -> Image/String/Number
;; a function for displaying user provided image, string or number with additional selection "buttons"
;; returns the selected value
(define (display-select item selections)
(selected-item (big-bang (make-selector selections 0 (item->image item) #t)
(to-draw render-selector)
(on-key handle-key-selector)
(stop-when stop?))))
;; display-value : Image/String/Number Image/String/Number/Any -> Image/String/Number/Any
;; a function for displaying user the provided image, string or number in addition to the given value (only string, number or image is displayed)
;; returns the given value (also when it was non-displayable)
(define (display-value item value)
(selector-choices (big-bang (make-selector value 0 (item->image item) #t)
(to-draw render-values)
(on-key handle-key-selector)
(stop-when stop?))))
;; display-info : Image/String/Number -> Image/String/Number
;; a function for displaying user the provided image, string or number in addition to the given value (only string, number or image is displayed)
;; returns the given value (also when it was non-displayable)
(define (display-info item)
(info-item (big-bang (make-info item #f 0 #t)
(to-draw render-just-image)
(on-key handle-key-just-image)
(stop-when stop?))))
;; display-info-timer : Image/String/Number Number -> Image/String/Number
;; a function for displaying user the provided image, string or number in addition to the given value (only string, number or image is displayed)
;; returns the given value (also when it was non-displayable)
(define (display-info-timer item timer)
(info-item (big-bang (make-info item #t timer #t)
(to-draw render-just-image)
(on-key handle-key-just-image)
(on-tick handle-timer)
(stop-when stop?))))
;; stop? : Window/Selector -> Boolean
;; tests if the window should be closed
(define (stop? a)
(begin (display "checking stop")
(let ([stopp
(cond [(window? a)
(not (window-active? a))]
[(selector? a)
(not (selector-active? a))]
[(info? a)
(not (info-active? a))]
[else
#f])])
(begin (display (list "stop" stopp))
stopp))))
;; =================
;; render : Editor -> Image
;; displays the visible part of the textbuffer on the screen
(define (render e)
(place-image/align (beside (render-text (left-of-cursor (fit-to-screen e) (editor-curpos e)))
CURSOR-IMG
(render-text (right-of-cursor (fit-to-screen e)(editor-curpos e))))
TEXT-X
TEXT-Y
"left"
"center"
MTS))
;; fit-image : Image -> Image
;; scales the user image to fit the editor width
(define (fit-image img)
(cond [(= 0 (image-width img))
img]
[(> (image-width img) WIDTH)
(scale (/ (- WIDTH (* 2 MARGIN)) (image-width img)) img)]
[else img]))
;; render-window : Window -> Image
;; render the editor and image in the window
(define (render-window w)
(above (render-img (window-img w))
(render (window-editor w))))
;; render-just-image : Window/Selector -> Image
;; render the just image in the window/selector
(define (render-just-image a)
(cond [(window? a)
(render-img (window-img a))]
[(selector? a)
(render-img (selector-img a))]
[(info? a)
(render-img (render-value (info-item a)))]
[else
empty-image]))
;; render-img : Image -> Image
;; render the image in the window
(define (render-img img)
(cond [(> (image-width img) 0)
(above MARGIN-IMG
(fit-image img)
MARGIN-IMG)]
[else
MARGIN-IMG]))
;; render-selected : Image -> Image
(define (render-selected img)
(overlay (rectangle (image-width img)(image-height img) "outline" SELECTOR-COLOR)
img))
;; render-selections-rec : List-of-choices -> List-of-Images
(define (render-selections-rec c-list rendered selected round)
(cond [(empty? c-list)
rendered]
[(= selected round)
(render-selections-rec (rest c-list)
(append rendered (list (render-selected (item->image (first c-list)))))
selected
(add1 round))]
[else
(render-selections-rec (rest c-list)
(append rendered (list (item->image (first c-list))))
selected
(add1 round))]))
;; render-selections : Choice Number -> Image/List-of-Images
(define (render-selections c selected)
(cond [(or (string? c)(number? c))
(item->image c)]
[(image? c)
(render-img c)]
[(cons? c)
(render-selections-rec c empty selected 0)]
[else
NON-DISPLAYABLE]))
;; render-value : String/Number/Image -> Image
(define (render-value v)
(cond [(and (string? v)(not (= 0 (string-length v))))
(item->image v)]
[(number? v)
(item->image v)]
[(image? v)
(render-img v)]
[else
empty-image]))
;; render-images : Image/List-of-Images -> Image
(define (render-images img)
(cond [(cons? img)
(foldr above empty-image img)]
[(image? img)
img]
[else
NON-DISPLAYABLE]))
;; render-selector : Selector -> Image
(define (render-selector s)
(above (render-img (selector-img s))
(render-images (render-selections (selector-choices s) (selector-selected s)))))
;; render-values : Selector -> Image
(define (render-values s)
(above (render-img (selector-img s))
(render-value (selector-choices s))))
;; handle-timer : Info -> Info
(define (handle-timer i)
(if (<= (info-timer-value i) 0)
(make-info (info-item i) (info-timer? i) (info-timer-value i) #f)
(make-info (info-item i) (info-timer? i) (sub1 (info-timer-value i)) (info-active? i))))
;; Helper-functions:
;; =================
;; cut-left-side : Editor -> String
;; cuts off the characters that will not fit into the screen on the left side
(define (cut-left-side e)
(if (> (string-length (editor-textbuf e)) 0)
(substring (editor-textbuf e)
(editor-screenpos e))
(editor-textbuf e)))
;; cut-right-side : String -> String
;; cuts of the characters that will not fit on the screen on the right side
(define (cut-right-side s)
(if (> (string-length s) BUFFER-SIZE)
(substring s 0 (sub1 BUFFER-SIZE))
s))
;; fit-to-screen : Editor -> String
;; cuts off the the characters, which will not fit on the screen (left and right sides)
(define (fit-to-screen e)
(cut-right-side (cut-left-side e)))
;; left-of-cursor : String Cursor -> String
;; returns the part of string which is on the left side of the cursor
(define (left-of-cursor str pos)
(if (> (string-length str) pos)
(substring str 0 pos)
str))
;; right-of-cursor : String Cursor -> String
;; returns the part of string which is on the right side of the cursor
(define (right-of-cursor str pos)
(if (> (string-length str) pos)
(substring str pos)
""))
;; =================
;; handle-key : Editor Key -> Editor
;; move cursor to left with left arrow, to right with right arrow, remove characters with DEL
(define (handle-key e k)
(begin (display (list "hk" k))
(cond [(key=? k "left")
(move-cursor-to-left e)]
[(key=? k "right")
(move-cursor-to-right e)]
[(key=? k "\b")
(if (> (string-length (editor-textbuf e)) 0)
(delete-one-chr e)
e)]
[(key=? k "\r") e]
[(displayable-character? k)
(add-to-buffer e k)]
[else e])))
;; handle-key-window : Window Key -> Window
;; checks if return/enter has been pressed
(define (handle-key-window w k)
(cond [(key=? k "\r")
(begin (display "hkw found return")
(make-window (window-editor w) (window-img w) #f))]
[else
(make-window (handle-key (window-editor w) k)
(window-img w)
(window-active? w))]))
;; handle-key-just-image : Window/Selector/Info Key -> Window/Selector/Info
;; checks if return/enter has been pressed
(define (handle-key-just-image a k)
(cond [(and (window? a)(key=? k "\r"))
(make-window (window-editor a) (window-img a) #f)]
[(and (selector? a)(key=? k "\r"))
(make-selector (selector-choices a) (selector-selected a) (selector-img a) #f)]
[(and (info? a)(key=? k "\r"))
(make-info (info-item a) (info-timer? a)(info-timer-value a) #f)]
[else a]))
;; add : Number List Number -> Number
(define (add x list index)
(cond [(<= 0 (+ index x) (sub1 (length list)))
(+ index x)]
[else index]))
;; handle-key-selector : Selector Key -> Selector
;; checks if return/enter has been pressed
(define (handle-key-selector s k)
(cond [(key=? k "\r")
(make-selector (selector-choices s) (selector-selected s) (selector-img s) #f)]
[(and (cons? (selector-choices s))(key=? k "down"))
(make-selector (selector-choices s) (add 1 (selector-choices s)(selector-selected s)) (selector-img s) (selector-active? s))]
[(and (cons? (selector-choices s))(key=? k "up"))
(make-selector (selector-choices s) (add -1 (selector-choices s)(selector-selected s)) (selector-img s) (selector-active? s))]
[else
s]))
;; helper functions:
;; =================
;; delete-one-chr : Editor -> Editor
;; takes off one character to the left of the current cursor position, if there is a character
(define (delete-one-chr e)
(cond [(and (> (characters-left-of-cursor e) 0)(> (editor-screenpos e) 0))
(make-editor (delete-one-chr-left-of-cursor e)
(editor-curpos e)
(sub1 (editor-screenpos e)))]
[(> (characters-left-of-cursor e) 0)
(make-editor (delete-one-chr-left-of-cursor e)
(sub1 (editor-curpos e))
(editor-screenpos e))]
[else e]))
;; delete-one-chr-left-of-cursor : Editor -> String
;; takes off one character to the left of the current cursor position, if there is a character
(define (delete-one-chr-left-of-cursor e)
(string-append (delete-chr
(left-of-cursor (editor-textbuf e) (absolute-curpos e)))
(right-of-cursor (editor-textbuf e) (absolute-curpos e))))
;; delete-chr : String -> String
;; takes off the last character of the given string
(define (delete-chr s)
(substring s 0 (sub1 (string-length s))))
;; move-cursor-to-left : Editor -> Editor
;; moves cursor to the left one step, if there are more characters
(define (move-cursor-to-left e)
(cond [(> (editor-curpos e) 0)
(set-cursor-position e (sub1 (editor-curpos e)))]
[(and (= (editor-curpos e) 0)(> (characters-left-of-cursor e) 0))
(set-screen-position e (sub1 (editor-screenpos e)))]
[else e]))
;; characters-left-of-cursor : Editor -> Natural
;; tells how many characters there are on the left side of the cursor in the text buffer
(define (characters-left-of-cursor e)
(string-length (left-of-cursor (editor-textbuf e) (absolute-curpos e))))
;; characters-right-of-cursor : Editor -> Natural
;; tels how many characters there are on the right side of the cursor in the text buffer
(define (characters-right-of-cursor e)
(string-length (right-of-cursor (editor-textbuf e) (absolute-curpos e))))
;; absolute-curpos : Editor -> Natural
;; absolute position of the cursor in the text buffer
(define (absolute-curpos e)
(+ (editor-screenpos e)(editor-curpos e)))
;; move-cursor-to-right : Editor -> Editor
;; moves cursor to the right one step, if there are more characters
(define (move-cursor-to-right e)
(cond [(and (< (add1 (editor-curpos e)) BUFFER-SIZE)(> (characters-right-of-cursor e) 0))
(set-cursor-position e (add1 (editor-curpos e)))]
[(and (= (add1 (editor-curpos e)) BUFFER-SIZE)(> (characters-right-of-cursor e) 0))
(set-screen-position e (add1 (editor-screenpos e)))]
[else e]))
;; set-cursor-position : Editor Cursor -> Editor
;; setter for cursor position
(define (set-cursor-position e c)
(make-editor (editor-textbuf e)
c
(editor-screenpos e)))
;; set-screen-position : Editor Natural -> Editor
;; setter for screen position
(define (set-screen-position e sp)
(make-editor (editor-textbuf e)
(editor-curpos e)
sp))
;; add-to-buffer : Editor -> Editor
;; adds one character in the cursor position
(define (add-to-buffer e c)
(if (< (add1 (editor-curpos e)) BUFFER-SIZE)
(make-editor (string-append (left-of-cursor (editor-textbuf e) (absolute-curpos e))
c
(right-of-cursor (editor-textbuf e)(absolute-curpos e)))
(add1 (editor-curpos e))
(editor-screenpos e))
(make-editor (string-append (editor-textbuf e) c)
(editor-curpos e)
(add1 (editor-screenpos e)))))
;; displayable-character? : String -> Boolean
;; checks if the key that was pressed is a single character
(define (displayable-character? k)
(= (string-length k) 1))
| false |
6fdd614afe7cef3fed8047c8f13b0ab8949d01bb
|
222b42ba803bfecd4ec31166dd2be107a840f2bd
|
/macros/define-macro/do.scm
|
e83465a6aacff26a7c685acb7d01eaaa8f459678
|
[] |
no_license
|
ab3250/ablib
|
83512c2c2cadd0eb49ad534548c058e3ed119d4c
|
887c8661ce99e8edfe89bcf707400e55c3943dd4
|
refs/heads/master
| 2023-06-12T13:36:49.487467 | 2021-07-11T13:29:45 | 2021-07-11T13:29:45 | 384,955,137 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 320 |
scm
|
do.scm
|
;;;;;do
(define-macro do
(lambda (vars final . body)
(let ((loop (gensym)))
`(letrec
((,loop
(lambda ,(map car vars)
(if ,(car final)
,(if (null? (cdr final))
`(void)
(cadr final))
(begin
,@body
(,loop ,@(map caddr vars)))))))
(,loop ,@(map cadr vars))))))
;;;;
| false |
3af06af54b9dc2b21efdfe9228b036323126332d
|
7b2983fac7e5da6f579bb91f5da7165de4919b4d
|
/lib-r6rs/surfage/s98/os-environment-variables.mosh.sls
|
7181ccb1ce5de4c701e59502c887c042b1f95517
|
[
"X11-distribute-modifications-variant",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
okuoku/r7rs-bridge
|
8fbb0a4a9d69389240119fe7c42a06ba24b28149
|
845ac2ef01e2d9626e453ec92fa9b0dcd41473c0
|
refs/heads/master
| 2020-05-18T11:34:47.643057 | 2011-11-30T19:35:55 | 2011-11-30T19:35:55 | 2,670,878 | 11 | 2 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 221 |
sls
|
os-environment-variables.mosh.sls
|
(library (surfage s98 os-environment-variables)
(export
get-environment-variable
get-environment-variables)
(import
(only (system)
get-environment-variable
get-environment-variables)))
| false |
3d252adfe92130c468958b82aaf6b31a4112d707
|
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
|
/10.1/10.1-5.scm
|
2465fa78fe07f2b444877835f5a1f338a8235795
|
[] |
no_license
|
mrinalabrol/clrs
|
cd461d1a04e6278291f6555273d709f48e48de9c
|
f85a8f0036f0946c9e64dde3259a19acc62b74a1
|
refs/heads/master
| 2021-01-17T23:47:45.261326 | 2010-09-29T00:43:32 | 2010-09-29T00:43:32 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 501 |
scm
|
10.1-5.scm
|
(require-extension syntax-case check)
(require '../10.1/section)
(import* section-10.1
make-deque
enqueue-head!
enqueue-tail!
dequeue-head!
dequeue-tail!
queue-data)
(let ((queue (make-deque (make-vector 6 #f) 0 0)))
(enqueue-tail! queue 4)
(enqueue-tail! queue 1)
(enqueue-head! queue 3)
(check (dequeue-tail! queue) => 1)
(enqueue-tail! queue 8)
(check (dequeue-head! queue) => 3)
(check (queue-data queue) => '#(8 1 #f #f #f 3)))
| false |
f5edd839e5108fbcb9cd7c8a4386482b9ee5957e
|
bdfa935097ef39f66c7f18856accef422ef39128
|
/parts/qa0/tree/scheme/backend.ss
|
4e78c6009f5d193ccc5049b2e23d2c40f3502cf2
|
[
"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 | 2,496 |
ss
|
backend.ss
|
;; Backend generator
#fload "sfc.sf"
#fload "error.ss"
#fload "cenv.ss"
;;
;; (provide complex->back-end)
;; (provide emit-back-end)
;; (provide be-out-type*)
;; (provide be-load-type)
;; (provide C-collect-args)
;; (provide machine-*-*)
;;
(define (complex->back-end ast env)
((ce-lookup env 'back-end "Back end transformer not found") ast env))
(define (emit-back-end ast env)
((ce-lookup env 'be-emit "Code emitter not found") ast env))
(define (be-out-type* env name)
(ce-lookup-x env 'be-op-type* name
"Unknown operation ~a in be-op-type*" name))
(define (be-load-type env load-op)
(ce-lookup-x env 'be-load-type load-op
"Unknown load operation ~a in be-load-type" load-op))
(define (C-collect-args arg-name* arg-type* new-var env)
(cond
[(null? arg-name*) env]
[else (let* ([env (ce-bind-x env 'back-end (car arg-name*)
(list (new-var) (car arg-type*)))])
(C-collect-args (cdr arg-name*) (cdr arg-type*) new-var env))]))
(define (machine-*-* int-size int-align pointer-size pointer-align env op* load*)
(let* ([env (ce-add-type env 'int "size_t" int-size int-align)]
[env (ce-add-type env 'pointer "unsigned char *" pointer-size pointer-align)]
[env (ce-add-type env 'float "float" 4 4)]
[env (ce-add-type env 'double "double" 8 8)]
[env (ce-add-type env 'vector-float "vector float" 8 8)]
[env (ce-add-type env 'vector-double "vector double" 16 16)]
[env (ce-add-type env 'complex-float "float _Complex" 8 8)]
[env (ce-add-type env 'complex-double "double _Complex" 16 16)]
[Nc (or (string->number (or (getenv "Nc") "3")) 3)]
[env (ce-add-const env '*colors* Nc)]
[env (ce-add-const env '*dim* 4)]
[env (ce-add-const env '*clovers* (* 2 Nc))]
[env (ce-add-const env '*fermion-dim* 4)]
[env (ce-add-const env '*projected-fermion-dim* 2)])
(let loop ([env env] [op* op*])
(cond
[(null? op*)
(let loop ([env env] [load* load*])
(cond
[(null? load*) env]
[else (loop (ce-bind-x env 'be-load-type (caar load*)
(cadar load*))
(cdr load*))]))]
[else (loop (ce-bind-x env 'be-op-type* (caar op*) (cdar op*))
(cdr op*))]))))
| false |
e960b2baffdf5d18a5850787536656fd8551f958
|
6838bac9a2c58698df1ed964b977ac0ab8ee6c55
|
/legacy/nocko.scm
|
824ef948d83ec59f34d3c97809eaef4cbec508e2
|
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
jpt4/nocko
|
4be73b1945927bcb50fd16ebffa35736aa9a9d07
|
d12d569adc0c39e4fc5cfdbdd8c4b833f493cee2
|
refs/heads/master
| 2023-06-07T21:38:15.084127 | 2023-06-02T03:59:31 | 2023-06-02T03:59:31 | 36,998,031 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,330 |
scm
|
nocko.scm
|
;; nocko.scm jpt4 UTC20150621
;; nocko, miniKanren relational nock interpreter
;; set-up nocko execution environment, with specializations
(define (nconfig op)
(case op
['all (maximalist)] ;; hof-nevalo.scm, everything
['aux (utilities)] ;; nocko auxiliary programs
['hof (higher-of-nevalo)] ;; (nevalo) using hof-nevalo.scm
['min (core)] ;; hof-nevalo.scm, mk dependencies
['trw (term-rw-nevalo)] ;; (nevalo) using trw-nevalo.scm
['zum (examples)] ;; example nocko programs
[else (maximalist)])) ;; default to 'all
(define (maximalist)
(begin
(core)
(utilities)
(examples)))
(define (core)
(begin
(load "miniKanren-with-symbolic-constraints/mk.scm")
(load "miniKanren-with-symbolic-constraints/numbers.scm")
(load "portability.scm")
(load "hof-nevalo.scm")
(load "nevalo-wrapper.scm")))
(define (examples)
(begin
(load "clever-meta-nocko.scm")
(load "dec.scm")
(load "quine.scm")))
(define (higher-of-nevalo)
(load "hof-nevalo.scm"))
(define (term-rw-nevalo)
(load "trw-nevalo.scm"))
(define (utilities)
(begin
(load "convert.scm")
(load "nock.scm")
(load "test-suite.scm")))
| false |
0bb5025eb31e98c13275f5ec2b7aa35250a9233c
|
2b540259d6a0b3195cb6b71a6f987447885328b2
|
/lib/grime/grime_test.scm
|
2692a0b822427315632c1decd206c68cc17403d9
|
[] |
no_license
|
katsuya94/grime
|
fd3f2cf6ac4c561188350110d796a50c754c5427
|
b9f9760a920ff2f1f37cde2c04a46d2e5f6b1ea3
|
refs/heads/master
| 2021-06-21T13:14:19.544615 | 2019-05-05T04:18:14 | 2019-05-05T04:18:14 | 143,479,534 | 2 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,405 |
scm
|
grime_test.scm
|
(import (grime))
(define (assert-true condition)
(unless condition (error "assertion failed")))
(define (assert-equal actual expected)
(assert-true (equal? actual expected)))
(define-syntax unhygienic
(lambda (stx)
(syntax-case stx ()
[(k e)
(with-syntax [(y (datum->syntax #'k 'y))]
#'(let [(y 'dirty)] e))])))
(define-syntax syntax-rules-test-simple
(syntax-rules ()
[(_) 'foo]))
(define-syntax with-marked-id
(lambda (stx)
(syntax-case stx ()
[(_ e) #'(let [(id #f)] e)])))
(define x #f)
; when
(set! x #f)
(when #t (set! x #t))
(assert-equal x #t)
(set! x #f)
(when #f (set! x #t))
(assert-equal x #f)
; unless
(set! x #f)
(unless #t (set! x #t))
(assert-equal x #f)
(set! x #f)
(unless #f (set! x #t))
(assert-equal x #t)
; let*
(let* [(x 'foo)]
(assert-equal x 'foo))
(let* [(x 'foo) (y 'bar)]
(assert-equal x 'foo)
(assert-equal y 'bar))
(let* [(x 'foo) (y x)]
(assert-equal x 'foo)
(assert-equal y 'foo))
; letrec*
(set! x #f)
(letrec* [(x 'foo) (y (lambda () x))]
(assert-equal (y) 'foo))
; let
(let [(x 'foo)]
(assert-equal x 'foo))
(let [(x 'foo) (y 'bar)]
(assert-equal x 'foo)
(assert-equal y 'bar))
(set! x #f)
(let [(x 'foo) (y x)]
(assert-equal x 'foo)
(assert-equal y #f))
; datum->syntax
(unhygienic
(assert-equal y 'dirty))
; syntax-rules
(assert-equal (syntax-rules-test-simple) 'foo)
| true |
101cc035df9773a903fe0ce38fb8c5353a436156
|
6eaa87ed57fab28bb4b3b95a1aa721978947f3ec
|
/examples/fib.scm
|
0f003ed73f633e8fe50abb8afe93fa0a17734023
|
[
"MIT"
] |
permissive
|
seven1m/scheme-vm
|
d8b28d79faf400e260c445c2e72aaf2a78182c92
|
00cdee125690429c16b1e5b71b180a6899ac6a58
|
refs/heads/master
| 2021-01-21T16:53:03.742073 | 2018-04-17T01:06:45 | 2018-04-17T01:06:45 | 27,324,674 | 9 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 348 |
scm
|
fib.scm
|
(import (scheme base))
(define (fib n)
(if (< n 2)
n
(+
(fib (- n 1))
(fib (- n 2)))))
(define (fib2 n)
(letrec ((f (lambda (n1 n2 c)
(if (= c n)
n2
(f n2 (+ n1 n2) (+ c 1))))))
(f 0 1 1)))
(write-string (fib 8))
(newline)
(write-string (fib2 8))
(newline)
| false |
ff4cfedcaefe8eb20ba1bc2e2e8fe47c1950c425
|
f2a4ce6f955de3033e7e8005be8667ef6ee70bc5
|
/2.ss
|
211dc09f7b52e102b5ff1fbd1b6b6304932a54ff
|
[] |
no_license
|
Borderce/CSSE304
|
94d40151c9ada634ccf468a72c70dc8f9d3c7d79
|
c071a3765848e4a9532c52bd423ae032bf7a7877
|
refs/heads/master
| 2021-01-20T03:28:59.425314 | 2016-04-27T04:52:55 | 2016-04-27T04:52:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,934 |
ss
|
2.ss
|
;Bo Peng Assignment 2
;Problem 1
(define fact
(lambda (num) (if
(eq? num 0)
1
(* (fact (- num 1)) num))))
;Problem 1b
(define choose
(lambda (1st 2nd)
(/ (fact 1st) (* (fact 2nd) (fact (- 1st 2nd))))))
;Problem 2
(define range
(lambda (f l) (if
(< f l)
(cons f (range (+ 1 f) l))
'())))
;Problem 3
(define eq-helper-2
(lambda (ls) (if
(null? ls)
#t
(and (car ls)(eq-helper-2 (cdr ls)))
)))
(define eq-helper
(lambda (ele l)
(map not
(map (lambda (x) (equal? ele x)) l))))
(define set?
(lambda (l) (if
(or (null? l) (null? (cdr l)) )
#t
(if
(eq-helper-2(eq-helper (car l) (cdr l)))
(set? (cdr l))
#f
))))
;Program 4
(define sum-of-squares
(lambda (l)
(if
(null? l)
0
(+ (* (car l) (car l)) (sum-of-squares (cdr l)))
)))
;Program 5
(define make-vec-from-points
(lambda (p1 p2) (map - p2 p1)))
;Program 6
(define dot-product
(lambda (p1 p2) (apply + (map * p1 p2))))
;Program 7
(define square
(lambda (x) (* x x)))
(define vec-length
(lambda (ls)
(sqrt(+ (square (car ls)) (square (cadr ls)) (square (caddr ls))))))
;Program 8
(define distance
(lambda (1st 2nd)
(sqrt (apply + (map square (map - 2nd 1st))))))
;Program 9
(define cross-helper
(lambda (ul ur ll lr)
(- (* ul lr) (* ur ll))))
(define cross-product
(lambda (1st 2nd)
(list
(cross-helper (cadr 1st) (caddr 1st) (cadr 2nd) (caddr 2nd))
(- 0 (cross-helper (car 1st) (caddr 1st) (car 2nd) (caddr 2nd)))
(cross-helper (car 1st) (cadr 1st) (car 2nd) (cadr 2nd))
)))
;Program 10
(define parallel?
(lambda (1st 2nd)
(equal? 0 (sum-of-squares(cross-product 1st 2nd)))))
;Program 11
(define collinear-helper
(lambda (lst)
(and (equal? (car lst) (cadr lst)) (equal? (cadr lst) (caddr lst)))))
(define collinear?
(lambda (1st 2nd 3rd)
(collinear-helper (map /(map - 2nd 1st) (map - 3rd 2nd)))))
| false |
fbe2e5f27ba55bdf41869cb226c4210ca0061747
|
1ed47579ca9136f3f2b25bda1610c834ab12a386
|
/sec1/sec1.2.2-change.scm
|
7a99925bb17637a495c3988cccec97972092ff37
|
[] |
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 | 1,068 |
scm
|
sec1.2.2-change.scm
|
; back here from q2.19 -- charge with list
; 1ドルの両替に、50, 25, 10, 5, 1セント硬貨で何通りの表し方があるか。
; 硬貨をある順に並べたとき、
; n種類の硬貨で金額aを両替しようとすると
;
; * 最初の種類の硬貨意外を使う場合の数
; +
; * n種類の硬貨を使う、金額 a-d (d: 最初の硬貨の額面金額) を両替する場合の数
;
; という和で表される。
(define (count-change amount)
(cc amount 5))
(define (cc amount kinds-of-coins)
(cond ((= amount 0) 1)
((or (< amount 0) (= kinds-of-coins 0)) 0)
(else (+ (cc amount
(- kinds-of-coins 1))
(cc (- amount
(first-denomination kinds-of-coins))
kinds-of-coins)))))
(define (first-denomination kinds-of-coins)
(cond ((= kinds-of-coins 1) 1)
((= kinds-of-coins 2) 5)
((= kinds-of-coins 3) 10)
((= kinds-of-coins 4) 25)
((= kinds-of-coins 5) 50)
)
)
(print (count-change 100))
| false |
1e3bc38e89b5a40adb4802dc5bf92a73cd3e21dc
|
801a158ca6e2ba7651907c347fefc2930f327141
|
/tests/test0/test-bm.ss
|
1dd2fcbd76506d7cdbd75400c43129b9827a210c
|
[
"MIT"
] |
permissive
|
evilbinary/duck-compiler
|
8782cc049b9175902bdb482ba4aff5107aace193
|
8c64a521f012aa6b2b7b9385f11976b216cc07e0
|
refs/heads/master
| 2021-07-06T07:44:33.933316 | 2020-10-25T04:02:36 | 2020-10-25T04:02:36 | 195,368,722 | 29 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,386 |
ss
|
test-bm.ss
|
(define (compute-last-occ p)
(let ((last-occ (make-vector 128 -1)))
(let loop ((len (- (string-length p) 1))
(i 0))
(if (< i len)
(begin
(vector-set! last-occ (char->integer (string-ref p i)) i)
; (printf "char=~a int=~a i=~a\n"
; (string-ref p i)
; (char->integer (string-ref p i))
; i
; )
;(printf "==>~a\n" last-occ )
(loop len (+ i 1))
)
)
)
last-occ
))
(define (bmh t p)
(let ((last-occ (compute-last-occ p))
(i0 0)
(n (string-length t))
(m (string-length p))
(j -1)
(ret -1)
(is-not-ret #t)
)
; (printf "vec=>~a" last-occ)
; (print-last-occ last-occ)
(let loop ()
(if (< i0 (- n m))
(begin
(set! j (- m 1))
; (printf "i0=~a j=~a\n" i0 j)
(let loop2 ()
(if (char=? (string-ref p j) (string-ref t (+ i0 j)) )
(begin
(set! j (- j 1))
(if (< j 0)
(begin
(set! is-not-ret #f)
; (printf "ret====>~a\n" i0)
(set! ret i0) )
(loop2)
))))
(if is-not-ret
(begin
(set! i0 (+ i0
(- m 1)
(- (vector-ref last-occ
(char->integer (string-ref t (+ i0 m -1))) ) ) ))
; (printf "i0=~a val=>~a char=>~a\n"
; i0
; (vector-ref last-occ
; (char->integer (string-ref t (+ i0 m -1))) )
; (string-ref t (+ i0 m -1)) )
(loop)))
)))
ret))
(define (print-last-occ last-occ)
(let loop ((i (char->integer #\a)) (j 0) )
(if (<= i (char->integer #\z))
(begin
(printf "~a ~a;" (integer->char i) (vector-ref last-occ i))
(set! j (+ j 1))
(if (= 0 (/ j 13))
(newline)
)
(loop (+ i 1) j)
)
)
)
)
(let ((l (compute-last-occ "abacbb" ) ))
(print-last-occ l)
(printf "b=>~a\n" (vector-ref l (char->integer #\b)))
;(printf "last-occ =>~a" l)
)
(bmh "abacaxbaccabacbbaabb" "abacbb")
| false |
b8bcbdef53fa962b53b72bc5d004807c8f817585
|
72f761ae4ce62922cc5b6003afbd785a554c7705
|
/lib/control-operators/testing.sls
|
7ee5c0f8045465d13d5102d03ce1f77c953476e1
|
[] |
no_license
|
pre-srfi/control-operators
|
66ee281fd834ee14a0469e4d653004bf24a1bfb5
|
f17333ec535bd4a8732a256423a4a304dd414b19
|
refs/heads/master
| 2023-07-02T18:36:59.879377 | 2021-08-08T08:34:36 | 2021-08-08T08:34:36 | 378,713,951 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,300 |
sls
|
testing.sls
|
#!r6rs
;; Copyright (C) Marc Nieper-Wißkirchen (2021). All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. 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.
(library (control-operators testing)
(export test-begin test-end test)
(import (rnrs (6))
(control-operators define-who)
(only (control-operators) run))
(define *count* 0)
(define *fail* #f)
(define test-begin
(lambda (name)
(display "# Starting test ")
(display name)
(newline)))
(define test-end
(lambda ()
(display "1..")
(display *count*)
(newline)
(when *fail*
(exit #f))))
(define-syntax/who test
(lambda (stx)
(syntax-case stx ()
[(_ expected-expr test-expr)
#'(test #f expected-expr test-expr)]
[(_ name expected-expr test-expr)
#'(let-values ([expected expected-expr]
[result (run (lambda () test-expr))])
(do-test name expected result))]
[_
(syntax-violation who "invalid syntax" stx)])))
(define do-test
(lambda (name expected result)
(set! *count* (fx+ *count* 1))
(if (equal? expected result)
(display "ok ")
(begin
(set! *fail* #t)
(display "not ok ")))
(display *count*)
(when name
(display " - ")
(display name))
(newline))))
;; Local Variables:
;; mode: scheme
;; End:
| true |
2888beac8e257cfcb859961a11f9d17946638fd6
|
557c51d080c302a65e6ef37beae7d9b2262d7f53
|
/workspace/scheme-tester/notes/pl-17.scm
|
7febf903fb534f902875df0a51fdd58e0598dca7
|
[] |
no_license
|
esaliya/SchemeStack
|
286a18a39d589773d33e628f81a23bcdd0fc667b
|
dcfa1bbfa63b928a7ea3fc244f305369763678ad
|
refs/heads/master
| 2020-12-24T16:24:08.591437 | 2016-03-08T15:30:37 | 2016-03-08T15:30:37 | 28,023,003 | 3 | 4 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,864 |
scm
|
pl-17.scm
|
;----------------------------------------------------------------
; Registerization and Trampolining
; ---------------------------------------------------------------
;----------------------------------------------------------------
; Test macro (taken happily from the assignment itself :))
; ---------------------------------------------------------------
(define-syntax test
(syntax-rules ()
((_ title tested-expression expected-result)
(let* ((expected expected-result)
(produced tested-expression))
(if (equal? expected produced)
(printf "~s works!\n" title)
(error
'test
"Failed ~s: ~a\nExpected: ~a\nComputed: ~a"
title 'tested-expression expected produced))))))
; Test and expected lists
(define test-list-a '(1 2 3 8 9 8 7))
(define expected-list-a '(1 2 3 9 7))
(define test-list-b '(1 (2 3) (8 (9 (8) 7))))
(define expected-list-b '(1 (2 3) ((9 ()7))))
;----------------------------------------------------------------
; The good-old-style rember*8
; ---------------------------------------------------------------
(define rember*8
(lambda (l)
(cond
[(null? l) '()]
[(pair? (car l)) (cons (rember*8 (car l)) (rember*8 (cdr l)))]
[(eq? (car l) 8) (rember*8 (cdr l))]
[else (cons (car l) (rember*8 (cdr l)))])))
; test cases for the direct style rember*8
(test "direct-rember*8/a"
(rember*8 test-list-a)
expected-list-a)
(test "direct-rember*8/b"
(rember*8 test-list-b)
expected-list-b)
;----------------------------------------------------------------
; The cpsed rember*8, i.e. rember*8-cps
; ---------------------------------------------------------------
(define rember*8-cps
(lambda (l k)
(cond
[(null? l) (k '())]
[(pair? (car l)) (rember*8-cps (car l) (lambda (a) (rember*8-cps (cdr l) (lambda (d) (k (cons a d))))))]
[(eq? (car l) 8) (rember*8-cps (cdr l) k)]
[else (rember*8-cps (cdr l) (lambda (d) (k (cons (car l) d))))])))
; test cases for the cpsed rember*8-cps
(test "cpsed-rember*8-cps/a"
(rember*8-cps test-list-a (lambda (v) v))
expected-list-a)
(test "cpsed-rember*8-cps/b"
(rember*8-cps test-list-b (lambda (v) v))
expected-list-b)
;----------------------------------------------------------------
; The R.I. rember*8-cps, i.e. rember*8-cps-ri
; ---------------------------------------------------------------
(define rember*8-cps-ri
(lambda (l k)
(cond
[(null? l) (apply-k k '())]
[(pair? (car l)) (rember*8-cps-ri (car l) (outer-k l k))]
[(eq? (car l) 8) (rember*8-cps-ri (cdr l) k)]
[else (rember*8-cps-ri (cdr l) (inner-k (car l) k))])))
(define empty-k
(lambda ()
`(mt-k)))
(define inner-k
(lambda (a k)
`(inner-k ,a ,k)))
(define outer-k
(lambda (l k)
`(outer-k ,l ,k)))
(define apply-k
(lambda (k v)
(pmatch k
[(mt-k) v]
[(inner-k ,a ,k) (apply-k k (cons a v))]
[(outer-k ,l ,k) (rember*8-cps-ri (cdr l) (inner-k v k))])))
; test cases for the R.I. rember*8-cps-ri
(test "R.I.-rember*8-cps-ri/a"
(rember*8-cps-ri test-list-a (empty-k))
expected-list-a)
(test "R.I.-rember*8-cps-ri/b"
(rember*8-cps-ri test-list-b (empty-k))
expected-list-b)
;----------------------------------------------------------------
; The registerized rember*8-cps-ri, i.e. rember*8-cps-ri-reg
; ---------------------------------------------------------------
; registers
(define *l*)
(define *k*)
(define *v*)
(define rember*8-cps-ri-reg
(lambda () ; remember we originally had l and k as parameters
(cond
[(null? *l*) (begin (set! *k* *k*) (set! *v* '()) (apply-k-reg))] ; the tail call (apply-k) is like go-to
[(pair? (car *l*)) (begin (set! *k* (outer-k *l* *k*)) (set! *l* (car *l*)) (rember*8-cps-ri-reg))]
[(eq? (car *l*) 8) (begin (set! *k* *k*) (set! *l* (cdr *l*)) (rember*8-cps-ri-reg))]
[else (begin (set! *k* (inner-k (car *l*) *k*)) (set! *l* (cdr *l*)) (rember*8-cps-ri-reg))])))
; No need to redefine the same data strucutral constructors for empty-k, inner-k, and outer-k
;;(define empty-k
;; (lambda ()
;; `(mt-k)))
;;(define inner-k
;; (lambda (a k)
;; `(inner-k ,a ,k)))
;;(define outer-k
;; (lambda (l k)
;; `(outer-k ,l ,k)))
(define apply-k-reg
(lambda () ; remember we original had k and v as parameters
(pmatch *k*
[(mt-k) *v*]
[(inner-k ,a ,k) (begin (set! *k* k) (set! *v* (cons a *v*)) (apply-k-reg))]
[(outer-k ,l ,k) (begin (set! *k* (inner-k *v* k)) (set! *l* (cdr l)) (rember*8-cps-ri-reg))])))
; test cases for the R.I. rember*8-cps-ri
(test "registerized-rember*8-cps-ri-reg/a"
(begin (set! *k* (empty-k)) (set! *l* test-list-a) (rember*8-cps-ri-reg))
expected-list-a)
(test "registerized-rember*8-cps-ri-reg/b"
(begin (set! *k* (empty-k)) (set! *l* test-list-b) (rember*8-cps-ri-reg))
expected-list-b)
;----------------------------------------------------------------
; First driver program for the registerized rember*8-cps-ri-reg
; ---------------------------------------------------------------
(define rember*8-cps-ri-reg-driver-a
(lambda (l)
(begin
(set! *k* (empty-k))
(set! *l* l)
(rember*8-cps-ri-reg))))
; test cases for first driver
(test "rember*8-cps-ri-reg-driver-a"
(rember*8-cps-ri-reg-driver-a test-list-a)
expected-list-a)
(test "rember*8-cps-ri-reg-driver-a"
(rember*8-cps-ri-reg-driver-a test-list-b)
expected-list-b)
;----------------------------------------------------------------
; Second driver program for the registerized rember*8-cps-ri-reg
; ---------------------------------------------------------------
; Introduce a register for program counter *pc*
(define *pc*)
(define rember*8-cps-ri-reg-b
(lambda () ; remember we originally had l and k as parameters
(cond
[(null? *l*) (begin (set! *k* *k*) (set! *v* '()) (set! *pc* apply-k-reg-b) (*pc*))] ; the tail call (apply-k) is like go-to
[(pair? (car *l*)) (begin (set! *k* (outer-k *l* *k*)) (set! *l* (car *l*)) (set! *pc* rember*8-cps-ri-reg-b) (*pc*))]
[(eq? (car *l*) 8) (begin (set! *k* *k*) (set! *l* (cdr *l*)) (set! *pc* rember*8-cps-ri-reg-b) (*pc*))]
[else (begin (set! *k* (inner-k (car *l*) *k*)) (set! *l* (cdr *l*)) (set! *pc* rember*8-cps-ri-reg-b) (*pc*))])))
(define apply-k-reg-b
(lambda () ; remember we original had k and v as parameters
(pmatch *k*
[(mt-k) *v*]
[(inner-k ,a ,k) (begin (set! *k* k) (set! *v* (cons a *v*)) (set! *pc* apply-k-reg-b) (*pc*))]
[(outer-k ,l ,k) (begin (set! *k* (inner-k *v* k)) (set! *l* (cdr l)) (set! *pc* rember*8-cps-ri-reg-b) (*pc*))])))
(define rember*8-cps-ri-reg-driver-b
(lambda (l)
(begin
(set! *k* (empty-k))
(set! *l* l)
(set! *pc* rember*8-cps-ri-reg-b)
(*pc*))))
; test cases for second driver
(test "rember*8-cps-ri-reg-driver-b"
(rember*8-cps-ri-reg-driver-b test-list-a)
expected-list-a)
(test "rember*8-cps-ri-reg-driver-b"
(rember*8-cps-ri-reg-driver-b test-list-b)
expected-list-b)
;----------------------------------------------------------------
; Third driver program with trampoline for the registerized
; rember*8-cps-ri-reg
; ---------------------------------------------------------------
(define rember*8-cps-ri-reg-c
(lambda () ; remember we originally had l and k as parameters
(cond
[(null? *l*) (begin (set! *k* *k*) (set! *v* '()) (set! *pc* apply-k-reg-c))] ; the tail call (apply-k) is like go-to
[(pair? (car *l*)) (begin (set! *k* (outer-k *l* *k*)) (set! *l* (car *l*)) (set! *pc* rember*8-cps-ri-reg-c))]
[(eq? (car *l*) 8) (begin (set! *k* *k*) (set! *l* (cdr *l*)) (set! *pc* rember*8-cps-ri-reg-c))]
[else (begin (set! *k* (inner-k (car *l*) *k*)) (set! *l* (cdr *l*)) (set! *pc* rember*8-cps-ri-reg-c))])))
(define apply-k-reg-c
(lambda () ; remember we original had k and v as parameters
(pmatch *k*
[(mt-k, exit) (exit *v*)]
[(inner-k ,a ,k) (begin (set! *k* k) (set! *v* (cons a *v*)) (set! *pc* apply-k-reg-c))]
[(outer-k ,l ,k) (begin (set! *k* (inner-k *v* k)) (set! *l* (cdr l)) (set! *pc* rember*8-cps-ri-reg-c))])))
; We have to define a new empty-k-b
(define empty-k-exit
(lambda (exit)
`(mt-k ,exit)))
; Trampoline
(define trampoline
(lambda ()
(*pc*)
(trampoline)))
(define rember*8-cps-ri-reg-driver-c
(lambda (l)
(call/cc (lambda (exit)
(begin
(set! *k* (empty-k-exit exit))
(set! *l* l)
(set! *pc* rember*8-cps-ri-reg-c)
(trampoline))))))
; test cases for second driver
(test "rember*8-cps-ri-reg-driver-c"
(rember*8-cps-ri-reg-driver-c test-list-a)
expected-list-a)
(test "rember*8-cps-ri-reg-driver-c"
(rember*8-cps-ri-reg-driver-c test-list-b)
expected-list-b)
| true |
d5ecfeab2123a5add276d701b8cfb285fd59f9be
|
bef125b941c10223d93fbf4bd1b6ef52450ed400
|
/tool/example/kaulakys2006.ss
|
0fa1a5edae935c7f78cd0c50f565186ec4fe1cb6
|
[
"MIT"
] |
permissive
|
flintproject/Flint
|
7cc2cf62ff6981974be19a04f04f0d4558a7027a
|
35e9460cbeaa4f781c4737ecd6db8116bd09436d
|
refs/heads/master
| 2023-07-06T10:07:20.734112 | 2022-12-21T09:08:00 | 2022-12-21T09:08:00 | 32,972,376 | 11 | 6 |
MIT
| 2020-09-07T23:22:55 | 2015-03-27T07:06:48 |
C++
|
UTF-8
|
Scheme
| false | false | 796 |
ss
|
kaulakys2006.ss
|
;; Equation (9) and (10) of:
;; Kaulakys, B., Ruseckas, J., Gontis, V. & Alaburda, M. Nonlinear stochastic models of 1/f noise and power-law distributions. Physica A: Statistical Mechanics and its Applications 365, 217–221 (2006).
(define-model kaulakys2006
(variable t :independent :real)
(variable X :real :default 1)
(variable W :Wiener)
(parameter mu :real :default 0)
(parameter sigma :real :default 1)
(parameter gamma :real :default 1/2)
(parameter eta :real :default '(minus 5/2 mu))
(parameter Gamma :real :default '(minus 1 (divide gamma (power sigma 2))))
(eq (differential X)
(plus (times Gamma
(power X (minus (times 2 eta) 1))
(differential t))
(times (power X eta)
(differential W)))))
| false |
a1ae5985617a63de4445ebe6f78ecc999d44e286
|
c693dbc183fdf13b8eeab4590b91bb6cac786a22
|
/scheme/list.scm
|
90611b7124943af5ff2a434a140c8c1fc123621d
|
[] |
no_license
|
qianyan/functional-programming
|
4600a11400176978244f7aed386718614428fd13
|
34ba5010f9bf68c1ef4fa41ce9e6fdb9fe5a10b5
|
refs/heads/master
| 2016-09-01T21:09:32.389073 | 2015-08-14T07:58:59 | 2015-08-14T07:58:59 | 26,963,148 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 435 |
scm
|
list.scm
|
(define nums (list 1 3 2 4 1))
(define (sum list_of_values)
(if (= 1 (length list_of_values))
(car list_of_values)
(+ (car list_of_values)
(sum (cdr list_of_values)))))
; swap the order of second and third number
(define (swap-2-3 x)
(list (car x)
(caddr x)
(cadr x)))
(define six_over_three '(/ 6 3))
(eval six_over_three) ;=> 2
(define switch (swap-2-3 six_over_three))
(eval switch) ;=>1/2
| false |
d3419021baf476fc31f53490c6d1c6651d6f5f3a
|
8a0660bd8d588f94aa429050bb8d32c9cd4290d5
|
/sitelib/asn.1/der/encode.scm
|
72b53b2b9e6d846519fabe39e6f926e533525ef6
|
[
"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 | 3,363 |
scm
|
encode.scm
|
;;; -*- Scheme -*-
;;;
;;; types.scm - ASN.1 der encoder
;;;
;;; Copyright (c) 2009-2012 Takashi Kato <[email protected]>
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;
(library (asn.1 der encode)
(export der-write-object
der-write-encoded
der-write-tag
der-encode)
(import (rnrs)
(clos user)
(asn.1 der tags))
(define-generic der-encode)
(define (write-null p)
(put-u8 p NULL)
(put-u8 p #x00))
(define-syntax rash (identifier-syntax bitwise-arithmetic-shift-right))
(define (write-length len p)
(cond ((> len 127)
(let ((size (do ((size 1 (+ size 1))
(val (rash len 8) (rash val 8)))
((zero? val) size))))
(put-u8 p (bitwise-ior size #x80))
(do ((i (* (- size 1) 8) (- i 8)))
((< i 0))
(put-u8 p (bitwise-and (rash len i) #xff)))))
(else (put-u8 p len))))
(define-method der-write-object ((o <object>) (p <port>))
(if (null? o) ;; TODO '() or #f?
(write-null p)
(der-encode o p)))
(define-method der-write-encoded
((tag <integer>) (bytes <bytevector>) (p <port>))
;; assume tag is u8
(put-u8 p tag)
(write-length (bytevector-length bytes) p)
(put-bytevector p bytes))
(define-method der-write-encoded
((flags <integer>) (tag-no <integer>) (bytes <bytevector>) (p <port>))
(der-write-tag flags tag-no p)
(write-length (bytevector-length bytes) p)
(put-bytevector p bytes))
(define (der-write-tag flags tag-no p)
(cond ((< tag-no 31) (put-u8 p (bitwise-ior flags tag-no)))
(else
(put-u8 p (bitwise-ior flags #x1f))
(if (< tag-no 128)
(put-u8 p tag-no)
(let ((stack (make-bytevector 5))
(pos 4))
(bytevector-u8-set! stack pos (bitwise-and tag-no #x7f))
(let loop ((ntag-no (rash tag-no 7))
(pos (- pos 1)))
(bytevector-u8-set! stack pos
(bitwise-ior (bitwise-and ntag-no #x7f)
#x80))
(if (> ntag-no 127)
(loop (rash ntag-no 7) (- pos 1))
(put-bytevector p stack pos))))))))
)
| true |
90c2057767833fd9924e42c01cf6061184439acc
|
923209816d56305004079b706d042d2fe5636b5a
|
/sitelib/http/authentication/basic-rule.scm
|
0aad3f7f78ec311aa5a3caa9419bcf5671b90e57
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
tabe/http
|
4144cb13451dc4d8b5790c42f285d5451c82f97a
|
ab01c6e9b4e17db9356161415263c5a8791444cf
|
refs/heads/master
| 2021-01-23T21:33:47.859949 | 2010-06-10T03:36:44 | 2010-06-10T03:36:44 | 674,308 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 687 |
scm
|
basic-rule.scm
|
(library (http authentication basic-rule)
(export challenge
credentials)
(import (rnrs (6))
(http abnf)
(only (http basic-rule) quoted-string token))
;; auth-scheme = token
(define auth-scheme token)
;; auth-param = token "=" ( token | quoted-string )
(define auth-param (seq token (char->rule #\=) (bar token quoted-string)))
;; challenge = auth-scheme 1*SP 1#auth-param
(define challenge (seq auth-scheme (rep+ SP) (num+ auth-param)))
;; from RFC 2617 Errata:
;; credentials = auth-scheme ( token | quoted-string | #auth-param )
(define credentials (seq auth-scheme *LWS (bar token quoted-string (num* auth-param))))
)
| false |
c2404211b2c186e7c21a517ac00bde09b7554563
|
d10590821cfa35282206cd32acf430746cfca02d
|
/ipc.scm
|
b9ebb83ea89da89c366ddf2304bd0c234a024062
|
[] |
no_license
|
kdltr/ensemble
|
606349ff62916c97dfcee4bdce03418eca1d2112
|
82e09a20e646f59f055abdc3f8664339760b351f
|
refs/heads/master
| 2021-06-07T06:44:15.767523 | 2021-05-30T13:06:06 | 2021-05-30T13:06:06 | 100,152,678 | 4 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,702 |
scm
|
ipc.scm
|
;; (define-ipc-spec NAME RECEIVER ANNOTATED-DSSSL-LAMBDA-LIST)
;; Annonated lambda list element: (name type)
;; Before including this file:
;; (begin-for-syntax
;; (define *ipc-receiver* (quote frontend/backend))
;; (define *ipc-send-procedure* (quote whatever)))
(begin-for-syntax
(import srfi-1 srfi-69)
(define (type->predicate type)
(case type
((integer) 'exact-integer?)
((*) 'any?)
(else
(symbol-append type '?))))
;; name -> (lambda-list type-declaration predicates)
(define *ipc-specs* (make-hash-table)))
(define (any? o) #t)
(define-syntax define-ipc-spec
(ir-macro-transformer
(lambda (exp inject compare)
(let ((receiver (cadr exp))
(spec (caddr exp)))
(if (compare receiver *ipc-receiver*)
(cons 'define-ipc-receiver spec)
(cons 'define-ipc-sender spec))))))
(define-syntax define-ipc-receiver
(ir-macro-transformer
(lambda (exp inject compare)
(let* ((name (strip-syntax (cadr exp)))
(typed-args (cddr exp))
(arg-names (map (lambda (p) (strip-syntax (car p))) typed-args))
(arg-types (map (lambda (p) (strip-syntax (cadr p))) typed-args))
(arg-predicates (map type->predicate arg-types)))
(hash-table-set! *ipc-specs*
name
(list arg-names
arg-types
arg-predicates))
'(void)))))
(define-syntax define-ipc-implementation
(ir-macro-transformer
(lambda (exp inject compare)
(let* ((signature (cadr exp))
(name (strip-syntax (car signature)))
(args (cdr signature))
(body (cddr exp))
(proc-name (inject (symbol-append '|ipc-impl:| name)))
(spec (hash-table-ref *ipc-specs* name))
(types (cadr spec))
(predicates (caddr spec)))
(assert (equal? (car spec) (map strip-syntax args)))
`(begin
(: ,proc-name (,@types -> *))
(define ,proc-name
(lambda ,args
,@(map
(lambda (arg pred)
`(assert (,pred ,arg)))
args
predicates)
,@body))
(hash-table-set! ,*ipc-hash-table* ',name ,proc-name))))))
(define-syntax define-ipc-sender
(ir-macro-transformer
(lambda (exp inject compare)
(let* ((name (cadr exp))
(typed-args (cddr exp))
(args (map car typed-args))
(types (map cadr typed-args))
(assertions (map
(lambda (arg type)
;; (assert (type-pred? arg))
`(assert (,(type->predicate (strip-syntax type)) ,arg)))
args
types))
(proc-name (inject (symbol-append '|ipc:| (strip-syntax name)))))
`(begin
(: ,proc-name (,@types -> *))
(define ,proc-name
(lambda ,args
,@assertions
(,*ipc-send-procedure*
(list ',name ,@args)))))))))
;; Backend -> Frontend
;; ===================
(define-ipc-spec frontend
(notifications (room-id symbol)
(new-hls integer)
(new-notifs integer)))
(define-ipc-spec frontend
(read-marker (room-id symbol)
(event-id symbol)))
(define-ipc-spec frontend
(room-name (room-id symbol)
(room-name string)))
(define-ipc-spec frontend
(room-members (room-id symbol)
(members list)))
(define-ipc-spec frontend
(message (room-id symbol)
(message list)))
(define-ipc-spec frontend
(message-before (room-id symbol)
(event-id symbol)
(message list)))
(define-ipc-spec frontend
(remove (room-id symbol)
(event-id symbol)))
(define-ipc-spec frontend
(info (message string)))
;; Frontend -> backend
;; ===================
(define-ipc-spec backend
(message:text (room-id symbol)
(str string)))
(define-ipc-spec backend
(message:emote (room-id symbol)
(str string)))
(define-ipc-spec backend
(mark-last-message-as-read (room-id symbol)))
(define-ipc-spec backend
(fill-hole (room-id symbol)
(event-id symbol)
(count integer)))
(define-ipc-spec backend
(login (server string)
(username string)
(password string)))
(define-ipc-spec backend
(join-room (room string)))
(define-ipc-spec backend
(leave-room (room-id string)))
(define-ipc-spec backend
(stop))
| true |
aeeb6cccc62eb344f327d9c10fcea47782cdd47f
|
0011048749c119b688ec878ec47dad7cd8dd00ec
|
/src/005/solution.scm
|
366419ca1768d551ab563ded5741942eeffb87b0
|
[
"0BSD"
] |
permissive
|
turquoise-hexagon/euler
|
e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5
|
852ae494770d1c70cd2621d51d6f1b8bd249413c
|
refs/heads/master
| 2023-08-08T21:01:01.408876 | 2023-07-28T21:30:54 | 2023-07-28T21:30:54 | 240,263,031 | 8 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 126 |
scm
|
solution.scm
|
(import
(euler))
(define (solve n)
(apply lcm (range 1 n)))
(let ((_ (solve 20)))
(print _) (assert (= _ 232792560)))
| false |
8c7bf6c9125573023db027e83b6ec173e50a5ce5
|
6b8bee118bda956d0e0616cff9ab99c4654f6073
|
/schcuda/driver_types_h.ss
|
ebee13df7d476236b49d5df875b0df64e9314b0c
|
[] |
no_license
|
skchoe/2012.Functional-GPU-Programming
|
b3456a92531a8654ae10cda622a035e65feb762d
|
56efdf79842fc465770214ffb399e76a6bbb9d2a
|
refs/heads/master
| 2016-09-05T23:42:36.784524 | 2014-05-26T17:53:34 | 2014-05-26T17:53:34 | 20,194,204 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,752 |
ss
|
driver_types_h.ss
|
(module driver_types_h mzscheme
(require scheme/foreign
"cuda-libs.ss")
#|/*******************************************************************************
* *
* *
* *
*******************************************************************************/
|#
;/*DEVICE_BUILTIN*/
(provide _cudaError)
(define _cudaError
(_enum
'(cudaSuccess = 0
cudaErrorMissingConfiguration
cudaErrorMemoryAllocation
cudaErrorInitializationError
cudaErrorLaunchFailure
cudaErrorPriorLaunchFailure
cudaErrorLaunchTimeout
cudaErrorLaunchOutOfResources
cudaErrorInvalidDeviceFunction
cudaErrorInvalidConfiguration
cudaErrorInvalidDevice
cudaErrorInvalidValue
cudaErrorInvalidPitchValue
cudaErrorInvalidSymbol
cudaErrorMapBufferObjectFailed
cudaErrorUnmapBufferObjectFailed
cudaErrorInvalidHostPointer
cudaErrorInvalidDevicePointer
cudaErrorInvalidTexture
cudaErrorInvalidTextureBinding
cudaErrorInvalidChannelDescriptor
cudaErrorInvalidMemcpyDirection
cudaErrorAddressOfConstant
cudaErrorTextureFetchFailed
cudaErrorTextureNotBound
cudaErrorSynchronizationError
cudaErrorInvalidFilterSetting
cudaErrorInvalidNormSetting
cudaErrorMixedDeviceExecution
cudaErrorCudartUnloading
cudaErrorUnknown
cudaErrorNotYetImplemented
cudaErrorMemoryValueTooLarge
cudaErrorInvalidResourceHandle
cudaErrorNotReady
cudaErrorStartupFailure = 127;0x7f
cudaErrorApiFailureBase = 10000)))
;/*DEVICE_BUILTIN*/
(provide _cudaMemcpyKind)
(define _cudaMemcpyKind
(_enum '(cudaMemcpyHostToHost = 0
cudaMemcpyHostToDevice
cudaMemcpyDeviceToHost
cudaMemcpyDeviceToDevice)))
;;/*DEVICE_BUILTIN*/
;struct cudaDeviceProp
;{
; char name[256];
; size_t totalGlobalMem;
; size_t sharedMemPerBlock;
; int regsPerBlock;
; int warpSize;
; size_t memPitch;
; int maxThreadsPerBlock;
; int maxThreadsDim[3];
; int maxGridSize[3];
; size_t totalConstMem;
; int major;
; int minor;
; int clockRate;
; size_t textureAlignment;
;};
(provide _cudaDeviceProp)
(define-cstruct _cudaDeviceProp
([name _pointer]
[totalGlobalMem _size_t]
[sharedMemPerBlock _size_t]
[regsPerBlock _int]
[warpSize _int]
[memPitch _size_t]
[maxThreadsPerBlock _int]
[maxThreadsDimX _int]; int[3];
[maxThreadsDimY _int];
[maxThreadsDimZ _int];
[maxGridSizeX _int]; int[2]
[maxGridSizeY _int]
[totalConstMem _size_t]
[major _int]
[minor _int]
[clockRate _int]
[textureAlignment _size_t]
))
#|
#define cudaDevicePropDontCare \
{ \
{'\0'}, /* char name[256]; */ \
0, /* size_t totalGlobalMem; */ \
0, /* size_t sharedMemPerBlock; */ \
0, /* int regsPerBlock; */ \
0, /* int warpSize; */ \
0, /* size_t memPitch; */ \
0, /* int maxThreadsPerBlock; */ \
{0, 0, 0}, /* int maxThreadsDim[3]; */ \
{0, 0, 0}, /* int maxGridSize[3]; */ \
0, /* size_t totalConstMem; */ \
-1, /* int major; */ \
-1, /* int minor; */ \
0, /* int clockRate; */ \
0, /* size_t textureAlignment; */ \
}
|#
#|
/*******************************************************************************
* *
* SHORTHAND TYPE DEFINITION USED BY RUNTIME API *
* *
*******************************************************************************/
|#
;/*DEVICE_BUILTIN*/
;typedef enum cudaError cudaError_t;
(provide _cudaError_t)
(define _cudaError_t _cudaError)
;/*DEVICE_BUILTIN*/
;typedef int cudaStream_t;
(provide _cudaStream_t)
(define _cudaStream_t _int)
(provide _cudaStream_t-ptr)
(define _cudaStream_t-ptr _pointer)
;/*DEVICE_BUILTIN*/
;typedef int cudaEvent_t;
(provide _cudaEvent_t)
(define _cudaEvent_t _int)
(provide _cudaEvent_t-ptr)
(define _cudaEvent_t-ptr _pointer)
)
| false |
b694e3469fca4e51b950bae3bbb5b4dffed30d33
|
86a7d9ada5a7978cc6b3dc51c73a61abf82a6023
|
/src/svg-color.ss
|
faab6fc710353147b91f710683a5acb14ad4b112
|
[] |
no_license
|
themetaschemer/rackscad
|
6b249559ae9dbced4c12d3562284a41ab0265fe4
|
8915919c24bb93a63d13546610871bd11a823411
|
refs/heads/master
| 2021-06-26T07:31:04.723127 | 2017-09-15T15:32:41 | 2017-09-15T15:32:41 | 103,672,527 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,676 |
ss
|
svg-color.ss
|
#lang racket
(require "utils.ss")
(require rackunit)
(define color-names
`(("aliceblue" 240 248 255)
("antiquewhite" 250 235 215)
("aqua" 0 255 255)
("aquamarine" 127 255 212)
("azure" 240 255 255)
("beige" 245 245 220)
("bisque" 255 228 196)
("black" 0 0 0)
("blanchedalmond" 255 235 205)
("blue" 0 0 255)
("blueviolet" 138 43 226)
("brown" 165 42 42)
("burlywood" 222 184 135)
("cadetblue" 95 158 160)
("chartreuse" 127 255 0)
("chocolate" 210 105 30)
("coral" 255 127 80)
("cornflowerblue" 100 149 237)
("cornsilk" 255 248 220)
("crimson" 220 20 60)
("cyan" 0 255 255)
("darkblue" 0 0 139)
("darkcyan" 0 139 139)
("darkgoldenrod" 184 134 11)
("darkgray" 169 169 169)
("darkgreen" 0 100 0)
("darkgrey" 169 169 169)
("darkkhaki" 189 183 107)
("darkmagenta" 139 0 139)
("darkolivegreen" 85 107 47)
("darkorange" 255 140 0)
("darkorchid" 153 50 204)
("darkred" 139 0 0)
("darksalmon" 233 150 122)
("darkseagreen" 143 188 143)
("darkslateblue" 72 61 139)
("darkslategray" 47 79 79)
("darkslategrey" 47 79 79)
("darkturquoise" 0 206 209)
("darkviolet" 148 0 211)
("deeppink" 255 20 147)
("deepskyblue" 0 191 255)
("dimgray" 105 105 105)
("dimgrey" 105 105 105)
("dodgerblue" 30 144 255)
("firebrick" 178 34 34)
("floralwhite" 255 250 240)
("forestgreen" 34 139 34)
("fuchsia" 255 0 255)
("gainsboro" 220 220 220)
("ghostwhite" 248 248 255)
("gold" 255 215 0)
("goldenrod" 218 165 32)
("gray" 128 128 128)
("grey" 128 128 128)
("green" 0 128 0)
("greenyellow" 173 255 47)
("honeydew" 240 255 240)
("hotpink" 255 105 180)
("indianred" 205 92 92)
("indigo" 75 0 130)
("ivory" 255 255 240)
("khaki" 240 230 140)
("lavender" 230 230 250)
("lavenderblush" 255 240 245)
("lawngreen" 124 252 0)
("lemonchiffon" 255 250 205)
("lightblue" 173 216 230)
("lightcoral" 240 128 128)
("lightcyan" 224 255 255)
("lightgoldenrodyellow" 250 250 210)
("lightgray" 211 211 211)
("lightgreen" 144 238 144)
("lightgrey" 211 211 211)
("lightpink" 255 182 193)
("lightsalmon" 255 160 122)
("lightseagreen" 32 178 170)
("lightskyblue" 135 206 250)
("lightslategray" 119 136 153)
("lightslategrey" 119 136 153)
("lightsteelblue" 176 196 222)
("lightyellow" 255 255 224)
("lime" 0 255 0)
("limegreen" 50 205 50)
("linen" 250 240 230)
("magenta" 255 0 255)
("maroon" 128 0 0)
("mediumaquamarine" 102 205 170)
("mediumblue" 0 0 205)
("mediumorchid" 186 85 211)
("mediumpurple" 147 112 219)
("mediumseagreen" 60 179 113)
("mediumslateblue" 123 104 238)
("mediumspringgreen" 0 250 154)
("mediumturquoise" 72 209 204)
("mediumvioletred" 199 21 133)
("midnightblue" 25 25 112)
("mintcream" 245 255 250)
("mistyrose" 255 228 225)
("moccasin" 255 228 181)
("navajowhite" 255 222 173)
("navy" 0 0 128)
("oldlace" 253 245 230)
("olive" 128 128 0)
("olivedrab" 107 142 35)
("orange" 255 165 0)
("orangered" 255 69 0)
("orchid" 218 112 214)
("palegoldenrod" 238 232 170)
("palegreen" 152 251 152)
("paleturquoise" 175 238 238)
("palevioletred" 219 112 147)
("papayawhip" 255 239 213)
("peachpuff" 255 218 185)
("peru" 205 133 63)
("pink" 255 192 203)
("plum" 221 160 221)
("powderblue" 176 224 230)
("purple" 128 0 128)
("red" 255 0 0)
("rosybrown" 188 143 143)
("royalblue" 65 105 225)
("saddlebrown" 139 69 19)
("salmon" 250 128 114)
("sandybrown" 244 164 96)
("seagreen" 46 139 87)
("seashell" 255 245 238)
("sienna" 160 82 45)
("silver" 192 192 192)
("skyblue" 135 206 235)
("slateblue" 106 90 205)
("slategray" 112 128 144)
("slategrey" 112 128 144)
("snow" 255 250 250)
("springgreen" 0 255 127)
("steelblue" 70 130 180)
("tan" 210 180 140)
("teal" 0 128 128)
("thistle" 216 191 216)
("tomato" 255 99 71)
("turquoise" 64 224 208)
("violet" 238 130 238)
("wheat" 245 222 179)
("white" 255 255 255)
("whitesmoke" 245 245 245)
("yellow" 255 255 0)
("yellowgreen" 154 205 50)))
(define/provide (color-name->rgb name)
(let ([name (ensure-string name)])
(dict-ref color-names (string-downcase name) #f)))
(module+ test
(check-equal? (color-name->rgb "yellow") '(255 255 0))
(check-equal? (color-name->rgb "yellowgreen") '(154 205 50))
(check-equal? (color-name->rgb "noname") #f))
| false |
53495a71af3503be7486fc3ba969436e02dc683e
|
e19664cde79ead45038fd77c333a863d0c091b9b
|
/queue.scm
|
afd53e29c83d71c66c053470acf685a60667a78d
|
[] |
no_license
|
spearalot/SchemeLib
|
602a3aabbc8325ba443bb6524c4ca0bb0e66b657
|
6881f8d6b2cf781aade34c718fd29508241d66eb
|
refs/heads/master
| 2016-09-03T07:13:51.887016 | 2012-01-16T22:16:23 | 2012-01-16T22:16:23 | 3,194,693 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,279 |
scm
|
queue.scm
|
(define (make-queue)
'(() . ()))
(define (queue-empty? q)
(and (null? (car q)) (null? (cdr q))))
(define (queue-member? x q)
(define (list-member? x lst)
(if (null? lst) #f
(if (= x (car lst)) #t
(list-member? x (cdr lst)))))
(or (list-member? x (car q))
(list-member? x (cdr q))))
(define (queue-in x q)
(cons (car q) (cons x (cdr q))))
(define (queue-out q)
(if (null? (car q))
(queue-out (cons (reverse (cdr q)) '()))
(values (caar q) (cons (cdar q) (cdr q)))))
(define (make-pqueue)
(make-tree))
(define (pqueue-empty? q)
(tree-empty? q))
(define (pqueue-in p x q)
(let ((y (tree-ref p q)))
(if (null? y)
(tree-set-splay p (queue-in x (make-queue)) q)
(tree-set-splay p (queue-in x y) q))))
(define (pqueue-out q)
(let ((y (tree-min q)))
(call-with-values (lambda () (queue-out (tree-value y)))
(lambda (v yp)
(if (queue-empty? yp)
(values v (tree-remove-splay (tree-key y) q))
(values v (tree-set-splay (tree-key y) yp q)))))))
(define (pqueue-member? x q)
(if (tree-empty? q) #f
(not (null? (tree-find (lambda (k v) (queue-member? x v)) q)))))
| false |
cd962b5036aaaa16a79f28599a6623efa0a632b4
|
dd4cc30a2e4368c0d350ced7218295819e102fba
|
/vendored_parsers/tree-sitter-elm/queries/injections.scm
|
83f8245caa2b39a7317d3fdbb46c585fde0abdad
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
Wilfred/difftastic
|
49c87b4feea6ef1b5ab97abdfa823aff6aa7f354
|
a4ee2cf99e760562c3ffbd016a996ff50ef99442
|
refs/heads/master
| 2023-08-28T17:28:55.097192 | 2023-08-27T04:41:41 | 2023-08-27T04:41:41 | 162,276,894 | 14,748 | 287 |
MIT
| 2023-08-26T15:44:44 | 2018-12-18T11:19:45 |
Rust
|
UTF-8
|
Scheme
| false | false | 99 |
scm
|
injections.scm
|
; Parse glsl where defined
((glsl_content) @injection.content
(#set! injection.language "glsl"))
| false |
75281b31793eb8df4e8f52e88695c463d28fcb50
|
53b12a47b6a5329efff3f674c5df5f92d2cbb09f
|
/library/Scheme/ndigits.ss
|
144760d2f7678e1bee39afff1f4df352ef3ee859
|
[] |
no_license
|
absop/SchemeMathBench
|
11aac8b1d552107f0e9812d61f37b3657442daee
|
64a01c6c81b659f43e210162eb36af27ad9105fd
|
refs/heads/master
| 2021-09-01T19:57:27.603056 | 2021-08-22T12:44:10 | 2021-08-22T12:44:10 | 227,276,292 | 3 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,160 |
ss
|
ndigits.ss
|
;;; Chez's built-in logarithm function
;;; is quite slow for big integers, so I
;;; written the following logarithm function
;;; to compute (log base n) approximately.
(define logarithm
(lambda (base n)
(let ([binary-length (integer-length n)])
(define (decimal-part)
(if (< binary-length 64)
(/ n (ash 1 (1- binary-length)))
(/ (bitwise-bit-field n
(- binary-length 64)
binary-length)
(ash 1 63))))
(* (+ binary-length -1 (log (decimal-part) 2))
(log 2 base)))))
(define ndigits
(let ([$ndigits
(lambda (n base)
(if (> n 1)
(let ([logxy (logarithm base n)])
(let ([result (ceiling logxy)])
(flonum->fixnum
(if (fl<= (abs (- logxy result)) 1e-15)
(1+ result)
result))))
1))])
(case-lambda
[(n) ($ndigits n 10)]
[(n base) ($ndigits n base)])))
#|
(load "for.ss")
(for i in range(100):
(printf "ndigits(~a) = ~a\n" i (ndigits i)))
|#
| false |
60519e24bddf5fb17cdcc222b9231ffe42c51650
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/component-model/derived-property-descriptor.sls
|
c4a9a2a551cb0ac253a00e94e5a3cc68e856b5b9
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,468 |
sls
|
derived-property-descriptor.sls
|
(library (system component-model derived-property-descriptor)
(export new
is?
derived-property-descriptor?
set-component-type
set-read-only
set-property-type
should-serialize-value?
reset-value
set-value
get-value
can-reset-value?
component-type
is-read-only?
property-type)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.ComponentModel.DerivedPropertyDescriptor
a
...)))))
(define (is? a)
(clr-is System.ComponentModel.DerivedPropertyDescriptor a))
(define (derived-property-descriptor? a)
(clr-is System.ComponentModel.DerivedPropertyDescriptor a))
(define-method-port
set-component-type
System.ComponentModel.DerivedPropertyDescriptor
SetComponentType
(System.Void System.Type))
(define-method-port
set-read-only
System.ComponentModel.DerivedPropertyDescriptor
SetReadOnly
(System.Void System.Boolean))
(define-method-port
set-property-type
System.ComponentModel.DerivedPropertyDescriptor
SetPropertyType
(System.Void System.Type))
(define-method-port
should-serialize-value?
System.ComponentModel.DerivedPropertyDescriptor
ShouldSerializeValue
(System.Boolean System.Object))
(define-method-port
reset-value
System.ComponentModel.DerivedPropertyDescriptor
ResetValue
(System.Void System.Object))
(define-method-port
set-value
System.ComponentModel.DerivedPropertyDescriptor
SetValue
(System.Void System.Object System.Object))
(define-method-port
get-value
System.ComponentModel.DerivedPropertyDescriptor
GetValue
(System.Object System.Object))
(define-method-port
can-reset-value?
System.ComponentModel.DerivedPropertyDescriptor
CanResetValue
(System.Boolean System.Object))
(define-field-port
component-type
#f
#f
(property:)
System.ComponentModel.DerivedPropertyDescriptor
ComponentType
System.Type)
(define-field-port
is-read-only?
#f
#f
(property:)
System.ComponentModel.DerivedPropertyDescriptor
IsReadOnly
System.Boolean)
(define-field-port
property-type
#f
#f
(property:)
System.ComponentModel.DerivedPropertyDescriptor
PropertyType
System.Type))
| true |
d510ffc9e9c85fc29ba6bf51fac3775844b2ec6a
|
3c9983e012653583841b51ddfd82879fe82706fb
|
/etng-r2/notes/tmp.scm
|
17b3193eed2f9421ce5d18b8e4446a036858f5b7
|
[] |
no_license
|
spdegabrielle/smalltalk-tng
|
3c3d4cffa09541b75524fb1f102c7c543a84a807
|
545343190f556edd659f6050b98036266a270763
|
refs/heads/master
| 2020-04-16T17:06:51.884611 | 2018-08-07T16:18:20 | 2018-08-07T16:18:20 | 165,763,183 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 287 |
scm
|
tmp.scm
|
(define (folding-map f acc l)
(cond
((null? l) '())
((pair? l)
(let ((new-acc (f acc (car l))))
(cons new-acc
(folding-map f new-acc (cdr l)))))))
(define (reduce-map f l)
(cond
((null? l) '())
((pair? l) (cons (car l) (folding-map f (car l) (cdr l))))))
| false |
dbb8427011adf8fc48b75f2d03566fce26da5d09
|
2d868c9428b8f4772d2ede375a3492b3b6885e1d
|
/Metacircular Evaluator, Part 1/4.16.scm
|
6875cc0e12b46693d2e61cf2efa43880371cc5ba
|
[] |
no_license
|
transducer/sicp
|
2428223945da87836fa2a82c02d965061717ae95
|
2cec377aa7805edfd7760c643c14127e344ee962
|
refs/heads/master
| 2021-06-06T20:06:47.156461 | 2016-09-16T22:05:02 | 2016-09-16T22:05:02 | 25,219,798 | 1 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,507 |
scm
|
4.16.scm
|
#lang scheme
;; In this exercise we implement the method just described for interpreting internal
;; definitions. We assume that the evaluator supports let (see exercise 4.6).
;; a. Change lookup-variable-value (section 4.1.3) to signal an error if the value
;; it finds is the symbol *unassigned*.
(define (lookup-variable-value var env)
(define (env-loop env)
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars))
(let ((val (car vals)))
(if (eq? val '*unassigned*)
(error "value is *unassigned*" var)
val)))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
;; b. Write a procedure scan-out-defines that takes a procedure body and returns an
;; equivalent one that has no internal definitions, by making the transformation
;; described above.
(define (scan-out-defines expr)
(let ((vars (cadr expr))
(body (cddr expr)))
(make-lambda vars
; loop over body,
; store all definition names and bodies of the defines
; once finished looping transform those into lets
; where the rest is added to the body
(let body-transform ((body-elements body)
(definition-names '())
(definition-bodies '())
(rest-of-body '()))
(if (null? body-elements)
(transform-define-into-let definition-names
definition-bodies
rest-of-body)
(let ((current-element (car body-elements)))
(if (tagged-list? current-element 'define)
(body-transform (cdr body-elements)
(cons (get-definition-name current-element)
definition-names)
(cons (get-definition-body current-element)
definition-bodies)
rest-of-body)
(body-transform (cdr body-elements)
definition-names
definition-bodies
(cons current-element rest-of-body)))))))))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (get-definition-name expr)
(cadr expr))
(define (get-definition-body expr)
(caddr expr))
(define (transform-define-into-let definition-names definition-bodies rest-of-body)
(list (append (list 'let (make-unassigned-vars definition-names))
; We need to flatten the lists once
(append (make-sets definition-names definition-bodies)
rest-of-body))))
(define (make-unassigned-vars vars)
(let aux ((var-elements vars)
(unassigned-vars '()))
(if (null? var-elements)
unassigned-vars
(aux (cdr var-elements)
(cons (list (car var-elements) ''*unassigned*) unassigned-vars)))))
(define (make-sets vars vals)
(let aux ((var-elements vars)
(val-elements vals)
(sets '()))
(if (null? var-elements)
sets
(aux (cdr var-elements)
(cdr val-elements)
(cons (list 'set! (car var-elements) (car val-elements)) sets)))))
(define (make-lambda parameters body)
(cons 'lambda (cons parameters body)))
; testing
(scan-out-defines '(lambda (a b)
(define u 'u)
(define v 'v)
'e1))
; => (lambda (a b)
; (let ((u '*unassigned*)
; (v '*unassigned*))
; (set! u 'u)
; (set! v 'v)
; 'e1))
;; c. Install scan-out-defines in the interpreter, either in make-procedure or in
;; procedure-body (see section 4.1.3). Which place is better? Why?
; Install it into make-procedure. Feels better semantically (something is made).
(define (make-procedure parameters body env)
(list 'procedure parameters (scan-out-defines body) env))
| false |
a43be29f6043a00360bba897ab38fc0570556e0e
|
ab2b756cdeb5aa94b8586eeb8dd5948b7f0bba27
|
/src/lisp2/sqrt.scm
|
c1cefa835bccf698e7d8b1adf318318a2762d8d9
|
[] |
no_license
|
stjordanis/chalang
|
48ff69d8bc31da1696eae043e66c628f41035b5a
|
a728e6bb9a60ac6eca189ee7d6873a891825fa9a
|
refs/heads/master
| 2021-07-31T22:26:45.299432 | 2021-03-09T13:06:56 | 2021-03-09T13:06:56 | 142,876,387 | 0 | 0 | null | 2018-07-30T13:03:00 | 2018-07-30T13:03:00 | null |
UTF-8
|
Scheme
| false | false | 710 |
scm
|
sqrt.scm
|
(define (average x y)
(mul_rat (add_rat x y)
(makerat 1 2)))
;(average (makerat 1 2))
; (makerat 1 3))))
(define (improve x guess)
(average guess (div_rat x guess)))
;(improve (makerat 2 1))
; (makerat 2 1))))
(define (good_enough guess x)
(<rat (pos_diff_rat
(square_rat guess)
x)
(makerat 1 100)))
;(good_enough (makerat 20001 15000))
; (makerat 4 1))))
(define (sqrt2 X Guess)
(cond ((good_enough Guess X) Guess)
(true (sqrt2 X (improve X Guess)))))
(define (sqrt X)
(sqrt2 X 1))
(sqrt 9)
| false |
27c3434cf494bc2cb405e49479139831ddc896c2
|
6f7d64ca4d09ff3e2cf9be5c9822ba3161ede163
|
/srfi-87.egg
|
024a5cc0762083d77fa9093120291b41d61c728f
|
[
"MIT"
] |
permissive
|
diamond-lizard/srfi-87
|
41c77d3b41e31dd100fc670be1db54f612713fc7
|
931c155242f126a4e66cbd9dfd7a508259e26fe5
|
refs/heads/main
| 2023-01-24T09:08:42.525366 | 2020-11-21T02:32:51 | 2020-11-21T02:32:51 | 314,715,665 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 265 |
egg
|
srfi-87.egg
|
;;; srfi-87.egg -*- Scheme -*- vim: ft=scheme:
((author "Chongkai Zhu")
(maintainer "Sergey Goldgaber")
(synopsis "SRFI-87: => in case clauses")
(version "0.1")
(category lang-exts)
(test-dependencies test)
(license "BSD")
(components (extension srfi-87)))
| false |
3b37a6e1a2b318d18072253990a8374c37a5fbac
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/code-dom/compiler/compiler-collection.sls
|
b2406871d1bcd4e5aa699c1821ee21d2f4aae5da
|
[] |
no_license
|
futsuki/ironscheme-port
|
2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5
|
4e7a81b0fbeac9a47440464988e53fb118286c54
|
refs/heads/master
| 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,466 |
sls
|
compiler-collection.sls
|
(library (system code-dom compiler compiler-collection)
(export new
is?
compiler-collection?
get-compiler-info-for-extension
get
get-language-from-extension
get-compiler-info-for-language
get-key
all-keys
collection-type
item
item
compiler-infos)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new
System.CodeDom.Compiler.CompilerCollection
a
...)))))
(define (is? a) (clr-is System.CodeDom.Compiler.CompilerCollection a))
(define (compiler-collection? a)
(clr-is System.CodeDom.Compiler.CompilerCollection a))
(define-method-port
get-compiler-info-for-extension
System.CodeDom.Compiler.CompilerCollection
GetCompilerInfoForExtension
(System.CodeDom.Compiler.CompilerInfo System.String))
(define-method-port
get
System.CodeDom.Compiler.CompilerCollection
Get
(System.CodeDom.Compiler.Compiler System.String)
(System.CodeDom.Compiler.Compiler System.Int32))
(define-method-port
get-language-from-extension
System.CodeDom.Compiler.CompilerCollection
GetLanguageFromExtension
(System.String System.String))
(define-method-port
get-compiler-info-for-language
System.CodeDom.Compiler.CompilerCollection
GetCompilerInfoForLanguage
(System.CodeDom.Compiler.CompilerInfo System.String))
(define-method-port
get-key
System.CodeDom.Compiler.CompilerCollection
GetKey
(System.String System.Int32))
(define-field-port
all-keys
#f
#f
(property:)
System.CodeDom.Compiler.CompilerCollection
AllKeys
System.String[])
(define-field-port
collection-type
#f
#f
(property:)
System.CodeDom.Compiler.CompilerCollection
CollectionType
System.Configuration.ConfigurationElementCollectionType)
(define-field-port
item
#f
#f
(property:)
System.CodeDom.Compiler.CompilerCollection
Item
System.CodeDom.Compiler.Compiler)
(define-field-port
item
#f
#f
(property:)
System.CodeDom.Compiler.CompilerCollection
Item
System.CodeDom.Compiler.CompilerInfo)
(define-field-port
compiler-infos
#f
#f
(property:)
System.CodeDom.Compiler.CompilerCollection
CompilerInfos
System.CodeDom.Compiler.CompilerInfo[]))
| true |
5f57f4ed51448558fa24e09ade9249189d45c884
|
c2e2ffee9e12a078bc59ed32dfe441e5d018807c
|
/bench/nqueens.digamma-ir.scm
|
42893315a7243537819bf00993357ea1c05b0838
|
[
"BSD-2-Clause"
] |
permissive
|
fujita-y/digamma
|
3fb3bdb8d24b05b6e809863c17cf2a3cb1aac53c
|
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
|
refs/heads/master
| 2022-06-03T01:29:22.084440 | 2022-03-15T03:30:35 | 2022-03-15T03:30:35 | 59,635,079 | 32 | 3 |
BSD-2-Clause
| 2020-02-10T23:40:16 | 2016-05-25T05:58:28 |
C++
|
UTF-8
|
Scheme
| false | false | 1,806 |
scm
|
nqueens.digamma-ir.scm
|
((close
(2 0 . loop)
(=n.iloc (0 . 0) 0)
(if.true
(ret.iloc 0 . 1))
(push.n+.iloc (0 . 0) -1)
(push.iloc.0 . 0)
(iloc.0 . 1)
(push.cons)
(apply.gloc.of |loop`21*|))
(set.gloc.of |loop`21*|)
(close
(3 0 . my-try)
(iloc.0 . 0)
(if.null?
(iloc.0 . 1)
(if.null?.ret.const . 1)
(ret.const . 0))
(call
(call
(push.car.iloc (0 . 0))
(push.const . 1)
(push.iloc.0 . 2)
(apply.gloc.of |ok?`16*|))
(if.true
(push.cdr.iloc (0 . 0))
(push.iloc.0 . 1)
(push.subr.gloc.of append 2)
(push.const . ())
(push.car.iloc (0 . 0))
(iloc.0 . 2)
(push.cons)
(apply.gloc.of |my-try`16*|))
(ret.const . 0))
(push)
(call
(push.cdr.iloc (0 . 0))
(push.car.iloc (0 . 0))
(iloc.0 . 1)
(push.cons)
(push.iloc.0 . 2)
(apply.gloc.of |my-try`16*|))
(push)
(ret.subr.gloc.of +))
(set.gloc.of |my-try`16*|)
(close
(3 0 . ok?)
(iloc.0 . 2)
(if.null?.ret.const . #t)
(push.car.iloc (0 . 2))
(push.iloc.0 . 0)
(push.iloc.0 . 1)
(push.subr.gloc.of + 2)
(subr.gloc.of = 2)
(if.true.ret.const . #f)
(push.car.iloc (0 . 2))
(push.iloc.0 . 0)
(push.iloc.0 . 1)
(push.subr.gloc.of - 2)
(subr.gloc.of = 2)
(if.true.ret.const . #f)
(push.iloc.0 . 0)
(push.n+.iloc (0 . 1) 1)
(push.cdr.iloc (0 . 2))
(apply.gloc.of |ok?`16*|))
(set.gloc.of |ok?`16*|)
(close (1 0 . |1-to|)
(push.iloc.0 . 0)
(push.const . ())
(apply.gloc.of |loop`21*|))
(set.gloc.of |1-to`16*|)
(close
(1 0 . nqueens)
(call
(push.iloc.0 . 0)
(apply.gloc.of |1-to`16*|))
(push)
(push.const . ())
(push.const . ())
(apply.gloc.of |my-try`16*|))
(set.gloc.of nqueens)
(ret.const.unspec))
| false |
a26754a3de2dc5b540c57d77ceebe239af1be4c2
|
defeada37d39bca09ef76f66f38683754c0a6aa0
|
/System/system/media/system-sounds.sls
|
de75832f7ea769bc495bd9561dc376e74746ee42
|
[] |
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 | 980 |
sls
|
system-sounds.sls
|
(library (system media system-sounds)
(export is? system-sounds? asterisk beep exclamation hand question)
(import (ironscheme-clr-port))
(define (is? a) (clr-is System.Media.SystemSounds a))
(define (system-sounds? a) (clr-is System.Media.SystemSounds a))
(define-field-port
asterisk
#f
#f
(static: property:)
System.Media.SystemSounds
Asterisk
System.Media.SystemSound)
(define-field-port
beep
#f
#f
(static: property:)
System.Media.SystemSounds
Beep
System.Media.SystemSound)
(define-field-port
exclamation
#f
#f
(static: property:)
System.Media.SystemSounds
Exclamation
System.Media.SystemSound)
(define-field-port
hand
#f
#f
(static: property:)
System.Media.SystemSounds
Hand
System.Media.SystemSound)
(define-field-port
question
#f
#f
(static: property:)
System.Media.SystemSounds
Question
System.Media.SystemSound))
| false |
b48e1a3872ec8667060b12f625be1d6bfcb3b016
|
a7a99f1f9124d23b04558fdac002f9153079b9c0
|
/tests/modules/syntax.ss
|
62b28957e628072988a9f44e60b5172cf9225bca
|
[] |
no_license
|
stuhlmueller/sine
|
a451c3803283de220f3475dba4c6c1fcde883822
|
ce6ec938e8f46c31925f23b557284405c1ba0b11
|
refs/heads/master
| 2016-09-06T10:23:19.360983 | 2012-07-20T21:09:59 | 2012-07-20T21:10:11 | 3,517,254 | 4 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 176 |
ss
|
syntax.ss
|
#!r6rs
(import (rnrs)
(scheme-tools)
(sine syntax))
(pretty-print
(sexpr->syntax '(let* ([x 1]
[y 2])
(+ x y))))
| false |
64688d69592af6d2c670e7029e7d9bc4183938df
|
e75694971a8d65a860e49d099aba868e1b7ec664
|
/b5.scm
|
1f3246d50856e049158081dd31c2fa673f3a528b
|
[] |
no_license
|
telnet23/sicp
|
d29088e1bdef7ede3cf5805559e0edb3b0ef54fe
|
a85fa7f17c7485163c9484ed5709d6ec64e87aaa
|
refs/heads/master
| 2023-02-20T09:20:38.216645 | 2019-04-30T20:15:12 | 2019-04-30T20:15:12 | 331,790,140 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,602 |
scm
|
b5.scm
|
"problem 1."
(define (filter f lst)
(cond ((null? lst) (list))
((f (car lst)) (cons (car lst)
(filter f (cdr lst))))
(else (filter f (cdr lst)))))
"problem 2."
(define (fun-not f)
(lambda (a) (not (f a))))
"problem 3."
(define (map-consecutive f a b)
(if (> a b)
(list)
(cons (f a) (map-consecutive f (+ a 1) b))))
"problem 4. (a)"
(define (is-prefix? x y)
(or (null? x)
(and (not (null? y))
(= (car x) (car y))
(is-prefix? (cdr x) (cdr y)))))
"problem 4. (b)"
(define (is-sublist? x y)
(or (is-prefix? x y)
(and (not (null? y))
(is-sublist? x (cdr y)))))
"problem 4. (c)"
(define (longest-common-prefix x y)
(if (or (null? x)
(null? y)
(not (= (car x) (car y))))
(list)
(cons (car x) (longest-common-prefix (cdr x) (cdr y)))))
"problem 5."
(define (nested-reverse lst)
(define (iterate accumulator remaining)
(if (null? remaining)
accumulator
(iterate (cons (if (list? (car remaining))
(iterate (car remaining) (list))
(car remaining))
accumulator)
(cdr remaining))))
(iterate lst (list)))
"problem 6. (a)"
(define (every? f lst)
(or (null? lst)
(and (f (car lst))
(every? f (cdr lst)))))
"problem 6. (b)"
(define (some? f lst)
(and (not (null? lst))
(or (f (car lst))
(some? f (cdr lst)))))
"problem 6. (c)"
(define (notany? f lst)
(not (some? f lst)))
"problem 7. (a)"
(define (position lst v)
(define (loop i remaining)
(cond ((null? remaining) -1)
((equal? (car remaining) v) i)
(else (loop (+ i 1) (cdr remaining)))))
(loop 1 lst))
"problem 7. (b)"
(define (value-at-position lst k)
(define (loop i remaining)
(cond ((null? remaining) "list too short")
((= i k) (car remaining))
(else (loop (+ i 1) (cdr remaining)))))
(loop 1 lst))
"problem 7. (c)"
(define (prime? n)
(define (divisor a) (= (modulo n a) 0))
(define (smooth k)
(and (>= k 2)
(or (divisor k)
(smooth (- k 1)))))
(and (> n 1)
(not (smooth (floor (sqrt n))))))
(define (nth-prime-between a b n)
(value-at-position (filter prime? (map-consecutive (lambda (x) x) a b)) n))
"problem 8. (a)"
(define (tailmap f lst)
(if (null? lst)
(list)
(cons (f lst) (tailmap f (cdr lst)))))
"problem 8. (b)"
(define (reduce f lst init)
(if (null? lst)
init
(f (car lst) (reduce f (cdr lst) init))))
| false |
3342ee4c3eecd5b7f3fb8fdbe7be7fe139bcf9fb
|
ffb05b145989e01da075e2a607fb291955251f46
|
/artima/scheme/scheme25.ss
|
6390b6cf77097ee023bf83fc2aebaa7bd5183700
|
[] |
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 | 12,354 |
ss
|
scheme25.ss
|
#|Back to macros
=====================================================================
.. _homoiconicity: http://en.wikipedia.org/wiki/Homoiconicity
.. _15: http://www.artima.com/weblogs/viewpost.jsp?thread=249681
.. _MetaPython: http://metapython.org/
.. _Logix: http://www.livelogix.net
.. _Dylan: http://en.wikipedia.org/wiki/Dylan_programming_language
.. _PLOT: http://users.rcn.com/david-moon/PLOT/
Macros are the reason why I first became interested in Scheme, five or
six years ago. At the time - as at any time - there was a bunch of
people trolling in comp.lang.python, arguing for the addition of macros
to the language. Of course most Pythonistas opposed the proposal.
At the time I had no idea of the advantages/disadvantages of
macros and I felt quite ignorant and powerless to argue. I
never liked to feel ignorant, so I decided to learn macros, especially
Scheme macros, because they are the state of the art for what concerns
the topic.
Nowadays I have some arguments to back up the position against macros.
I have two main objections, one technical (less important) and one
political (more important).
The technical reason is that I do not believe in macros for languages
without S-expressions. There are plenty of examples of macro systems
without S-expressions - for instance Dylan_ or PLOT_ in the Lisp
world and Logix_ and MetaPython_ in the Python world, but none of
them ever convinced me. Scheme macros are much better because of
the homoiconicity_ of the language ("homoiconicity" is just a big word for
the *code is data* concept). [Notice that technically Scheme macros work on syntax
objects and not directly on S-expressions like traditional Lisp
macros, but this is a subtle point I will discuss when talking about
hygiene; I can skip it for the moment being.]
I have already stated in episode 12_ my political objection, i.e. my
belief that macros have a high cost in terms of complication of the
language (look how complicated the R6RS module system is!). Moreover,
code based on macros tends to be too clever, difficult to debug, and
sometime idiosyncratic; I do not want to maintain code such kind of code
in a typical enterprise context, with programmers of any kind of competence.
Sometimes I wish that even Python was a simpler language!
There is a difference between *simpler* and *dumber*, of course.
I am *not* implying that every enterprise should
adopt only enterprise-oriented languages; as a matter of fact
various cutting edge enterprises are taking advantage of
non-conventional and/or research-oriented languages, but I see them as
exceptions to the general rule.
My opinion is based on the fact that on my daily work (I use Python
exclusively there) I have never felt the need for macros. For
instance, I had occasion to write both small declarative languages and
small command-oriented languages, but they were so simple that I had
no need for Scheme macros. Actually, judging from my past
experience, I think extremely unlikely that I will ever need something
as sophisticated as Scheme macros in my daily work. The one thing
that I miss in Python which Scheme has is *pattern matching*, not
macros.
Having said that, I do not think that macros are worthless, and actually
I think they are extremely useful and important in another domain,
i.e. in the domain of design and research about programming
languages. Scheme is certainly not the only language where you can experiment
with language design, it is just the best language for this kind of
tasks, at least in my humble opinion.
For instance, a few months ago I have described
an experiment I did with the Python meta object protocol, in
order to change how the object system work, and replace
multiple inheritance with traits_. Even if in Python it is possible to
customize the object system, I do not thing the approach is optimal,
because changing the semantics without changing the syntax
does not feel right. In Scheme I could have implemented the same
with a custom syntax and in a somewhat less magical way.
I am interested with this
kind of experiments, even if I will never use them in
production code, and I use Scheme in preference for such purposes.
.. _traits: http://www.artima.com/weblogs/viewpost.jsp?thread=246488
Writing your own programming language
----------------------------------------
The major interest of Scheme macros for me lies in the fact that they
*enable every programmer to write her own programming language*.
I think this is a valuable thing. Anybody who has got opinions
about language design, or about how an object system should should work, or
questions like "what would a language look like if it had feature X?",
can solve his doubts by implementing the feature with macros.
Notice that I recognize that perhaps not everybody should design its
own programming language, and that certainly not everybody should
*distribute* its own personal language. Nevertheless, I think
everybody can have opinions about language design. Experimenting
with macrology can help to put to test such opinions and to learn
something.
The easiest approach is to start from a Domain Specific
Language (DSL), which does not need to be a fully grown programming
language. For instance, in the Python world
everybody is implementing his own templating language to generate web
pages. In my opinion, this a good thing *per se*, the problem is that
everybody is distributing his own language so that there is a bit of
anarchy.
Even for what concerns fully grown programming languages we see nowadays
an explosion of new languages, especially for the Java and
the .NET platforms, since it is relatively easy to implement a new
language there. However, it still takes a substantial amount of work.
On the other hand, writing a custom language embedded in Scheme by
means of macros is much easier. I see Scheme as an excellent platform
for implementing languages and experimenting with new ideas.
There is a `quote of Ian Bicking`_ about Web frameworks which struck me:
*Sometimes Python is accused of having too many web frameworks. And
it's true, there are a lot. That said, I think writing a framework is
a useful exercise. It doesn’t let you skip over too much without
understanding it. It removes the magic. So even if you go on to use
another existing framework (which I'd probably advise you do), you'
ll be able to understand it better if you've written something like it
on your own.*
You can the replace the words "web framework" with "programming
language" and the quote still makes sense. You should read my
*Adventures* in this spirit: the ambition of the series is to give to
the readers the technical competence to write small Scheme-embedded
languages by means of macros. Even if you are not going to design your
own language, macros will help you to understand how languages work.
Personally I am interested in the technical competence, *I do not want
to write a new language*. There are already lots of languages out
there, and writing a real language is a lot of grunt work, because it
means writing debugging tools, good error messages, wondering about
portability, interacting with an user community, et cetera et cetera.
.. _quote of Ian Bicking: http://pythonpaste.org/webob/do-it-yourself.html
.. _12: http://www.artima.com/weblogs/viewpost.jsp?thread=240836
Recursive macros with accumulators
----------------------------------------------------------
The goal of learning macros well enough to implement a programming
language is an ambitious one; it is not something I can attain in one
episode of the Adventures, nor in six. However, one episode is enough
to explain at least one useful technique which is commonly used in
Scheme macrology and which is good to know in order to reach our final
goal, in time.
The technique I will discuss in this episode is writing recursive
macros with accumulators. In Scheme it is common to introduce an
auxiliary variable to store a value which is passed in a loop - we
discussed it in episode 6_ when talking about tail call optimization:
the same trick can be used in macros, at expand-time instead that at
run-time.
.. image:: scarab.png
In order to give an example I will define a macro *cond minus*
(``cond-``) which works like ``cond``, but with less parenthesis.
Here is an example:
.. code-block:: scheme
(cond-
cond-1? return-1
cond-2? return-2
...
else return-default)
should expand to:
.. code-block:: scheme
(cond
(cond-1? return-1)
(cond-2? return-2)
...
(else return-default))
Here is a solution, which makes use of an accumulator and of an auxiliary
macro ``cond-aux``:
$$COND-
The code above should be clear. The auxiliary macro ``cond-aux``
is recursive: it works by collecting the arguments ``x1, x2, ..., xn``
in the accumulator ``(acc ...)``. If the number of arguments is even,
at some point we end up having collected all the arguments in the
accumulator, which is then expanded into a standard conditional; if
the number of arguments is even, at some point we end up having
collected all the arguments except one, and a ``"Mismatched pairs"``
exception is raised. The user-visible macro ``cond-`` just calls
``cond-aux`` by setting the initial value of the accumulator to ``()``.
The entire expansion and error checking is made at compile time.
Here is an example of usage::
> (let ((n 1))
(cond- (= n 1) ; missing a clause
(= n 2) 'two
(= n 3) 'three
else 'unknown))
Unhandled exception:
Condition components:
1. &who: cond-
2. &message: "Mismatched pairs"
3. &syntax:
form: (((= n 1) (= n 2)) ('two (= n 3)) ('three else) 'unknown)
subform: 'unknown
A trick to avoid auxiliary macros
----------------------------------------------------------------
I have nothing against auxiliary macros, however sometimes you may
want to keep all the code in a single macro. This is useful if you are
debugging a macro since an auxiliary macro is usually not
exported. The trick is to introduce a literal to defined the helper
macro inside the main macro. Here is how it would work in this example:
$$COND2
If you do not want to use a literal identifier, you can use a literal string
instead:
$$COND3
These tricks are quite common in Scheme macros: we may even call them
design patterns. In my opinion the best reference
detailing these techniques and others is the `Syntax-Rules Primer
for the Merely Eccentric`_, by `Joe Marshall`_. The title is a play on the essay
`An Advanced Syntax-Rules Primer for the Mildly Insane`_ by
Al Petrofsky.
.. image:: mad-scientist.jpg
Marshall's essay is quite nontrivial, and it is intended for expert
Scheme programmers. On the other hand, it is child play compared to
Petrofsky's essay, which is intended for foolish Scheme wizards ;)
.. _An Advanced Syntax-Rules Primer for the Mildly Insane: http://groups.google.com/group/comp.lang.scheme/browse_frm/thread/86c338837de3a020/eb6cc6e11775b619?#eb6cc6e11775b619
.. _6: http://www.artima.com/weblogs/viewpost.jsp?thread=240198
.. _Syntax-Rules Primer for the Merely Eccentric: http://www.xs4all.nl/~hipster/lib/scheme/gauche/define-syntax-primer.txt
.. _Joe Marshall: http://funcall.blogspot.com/
|#
(import (rnrs) (sweet-macros))
;;COND-
(def-syntax cond-aux
(syntax-match ()
(sub (cond-aux (acc ...))
#'(cond acc ...))
(sub (cond-aux (acc ...) x1)
#'(syntax-violation 'cond- "Mismatched pairs" '(acc ... x1) 'x1))
(sub (cond-aux (acc ...) x1 x2 x3 ...)
#'(cond-aux (acc ... (x1 x2)) x3 ...))
))
(def-syntax (cond- x1 x2 ...)
(cond-aux () x1 x2 ...))
;;END
;;COND3
(define-syntax cond-
(syntax-match ()
(sub (cond- "aux" (acc ...))
(cond acc ...))
(sub (cond- "aux" (acc ...) x)
(syntax-violation 'cond- "Mismatched pairs" '(acc ... x) 'x))
(sub (cond- "aux" (acc ...) x1 x2 x3 ...)
(cond- "aux" (acc ... (x1 x2)) x3 ...))
(sub (cond- x1 x2 ...)
(cond- "aux" () x1 x2 ...))))
;;END
;;COND2
(define-syntax cond-
(syntax-match (aux)
(sub (cond- aux (acc ...))
(cond acc ...))
(sub (cond- aux (acc ...) x1)
(syntax-violation 'cond- "Mismatched pairs" '(acc ... x1) 'x1))
(sub (cond- aux (acc ...) x1 x2 x3 ...)
(cond- aux (acc ... (x1 x2)) x3 ...))
(sub (cond- x1 x2 ...)
(cond- aux () x1 x2 ...))))
;;END
| true |
7963ef7230afaa9e39bddadd17dda72571c636b2
|
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
|
/queries/meson/highlights.scm
|
f687f5ae074dd82b40daaabfd8261830fef658fd
|
[
"Apache-2.0"
] |
permissive
|
nvim-treesitter/nvim-treesitter
|
4c3c55cbe6ff73debcfaecb9b7a0d42d984be3e6
|
f8c2825220bff70919b527ee68fe44e7b1dae4b2
|
refs/heads/master
| 2023-08-31T20:04:23.790698 | 2023-08-31T09:28:16 | 2023-08-31T18:19:23 | 256,786,531 | 7,890 | 980 |
Apache-2.0
| 2023-09-14T18:07:03 | 2020-04-18T15:24:10 |
Scheme
|
UTF-8
|
Scheme
| false | false | 810 |
scm
|
highlights.scm
|
(comment) @comment
(number) @number
(bool) @boolean
(identifier) @variable
[
"("
")"
"{"
"}"
"["
"]"
] @punctuation.bracket
[
":"
","
"."
] @punctuation.delimiter
[
"and"
"not"
"or"
"in"
] @keyword.operator
[
"="
"=="
"!="
"+"
"/"
"/="
"+="
"-="
">"
">="
] @operator
(ternaryoperator
["?" ":"] @conditional.ternary)
[
"if"
"elif"
"else"
"endif"
] @conditional
[
"foreach"
"endforeach"
(keyword_break)
(keyword_continue)
] @repeat
(string) @string
"@" @punctuation.special
(normal_command
command: (identifier) @function)
(pair
key: (identifier) @property)
(escape_sequence) @string.escape
((identifier) @variable.builtin
(#any-of? @variable.builtin
"meson"
"host_machine"
"build_machine"
"target_machine"
))
| false |
ae248d22a007ba906630ea002c5a1ed35a292e86
|
37c1f21a70b9cb194b6f6327759367f853e0253e
|
/7b.ss
|
c4505231ef882b1c4e6003f77d871422d78ec5bb
|
[] |
no_license
|
aok8/CSSE304
|
b12b8875b94d09d0ee11c66764d0c6f1e92f3b51
|
b297f47a7f90b19e75af3e3b8a2af34456fb8d9a
|
refs/heads/master
| 2021-10-11T13:02:51.506480 | 2019-01-26T02:15:31 | 2019-01-26T02:15:31 | 162,036,500 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 2,061 |
ss
|
7b.ss
|
;Alain Kouassi
;CSSE304
;Assignment7b
;#5
(define (slist-map proc slist)
(let x ([slist slist])
(cond
[(null? slist) '()]
[(symbol? (car slist)) (cons (proc (car slist)) (x (cdr slist)))]
[else (cons (x (car slist)) (x (cdr slist)))])))
(define (slist-reverse slist)
(let rev ([slist slist])
(cond
[(null? slist) '()]
[(symbol? (car slist)) (append (rev (cdr slist)) (list (car slist)))]
[else (append (rev (cdr slist)) (list (rev (car slist))))])))
(define (slist-paren-count slist)
(+ 2(let paren ([slist slist])
(cond
[(null? slist) 0]
[(symbol? (car slist)) (+ 0 (paren (cdr slist)))]
[else (+ 2 (paren (car slist)) (paren (cdr slist)))]))))
(define (slist-depth slist)
(let total ([slist slist] [depth 1])
(cond
[(null? slist) depth]
[(symbol? (car slist)) (total (cdr slist) depth)]
[else (max (total (car slist) (+ depth 1)) (total (cdr slist) depth))])))
(define (slist-symbols-at-depth slist d)
(let symbols ([slist slist] [depth 1])
(cond
[(null? slist) '()]
[(and (symbol? (car slist)) (= d depth)) (append (list (car slist)) (symbols (cdr slist) depth))]
[(symbol? (car slist)) (symbols (cdr slist) depth)]
[else (append (symbols (car slist) (+ depth 1)) (symbols (cdr slist) depth))])))
;#6
(define (path-to slist symbol)
(let path ([slist slist] [lst '()])
(cond
[(null? slist) #f]
[(and (symbol? (car slist)) (equal? symbol (car slist))) (append lst '(car) )]
[(symbol? (car slist)) (path (cdr slist) (append lst '(cdr)))]
;(path (car slist) (append lst '(car))) (path (cdr slist) (append lst '(cdr)))
[else (or (path (car slist) (append lst '(car))) (path (cdr slist) (append lst '(cdr))))])))
;#7
(define compose
(case-lambda
[() (lambda (x) x)]
[(first . rest)
(let ([composed-rest (apply compose rest)])
(lambda (x) (first (composed-rest x))))]))
(define make-c...r
(lambda (proc)
(apply compose (map eval (map checker (string->list proc))))))
(define checker
(lambda (proc)
(cond
[(equal? #\a proc) 'car]
[(equal? #\d proc) 'cdr])))
| false |
8748aff6fe46923ca2b93387cedcff356d1007cc
|
c63772c43d0cda82479d8feec60123ee673cc070
|
/ch2/01.scm
|
21f8d004ad9e689c1dc89dc3578c2c6db3757502
|
[
"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,637 |
scm
|
01.scm
|
#lang racket
(define (make-rat n d)
(if (or (and (< n 0) (< d 0)) (and (> n 0) (< d 0)))
(make-rat (- n) (- d))
(let ((g (gcd n d)))
(cons (/ n g) (/ d g)))))
(define (numer x) (car x))
(define (denom x) (cdr x))
; Use exer 2.04 solution
; (define (make-rat n d)
; (if (or (and (< n 0) (< d 0)) (and (> n 0) (< d 0)))
; (make-rat (- n) (- d))
; (let ((g (gcd n d)))
; (lambda (z) (z (/ n g) (/ d g))))))
; (define (numer z) (z (lambda (a b) a)))
; (define (denom z) (z (lambda (a b) b)))
(define (print x)
(display (numer x))
(display "/")
(display (denom x))
(newline))
(define (add-rat x y)
(make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (numer x) (numer y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (numer x) (denom y))
(* (denom x) (numer y))))
(define (equal-rat? x y)
(= (* (numer x) (denom y))
(* (denom x) (numer y))))
(define rat13 (make-rat 1 -3))
(print rat13)
(print (add-rat rat13 rat13))
(print (make-rat 1 3))
(print (make-rat -1 -3))
(print (make-rat 1 -3))
(print (make-rat -1 3))
(define *one-half* (make-rat 1 2))
(define *one-third* (make-rat 1 3))
(print (add-rat *one-half* *one-third*))
(print (sub-rat *one-half* *one-third*))
(print (mul-rat *one-half* *one-third*))
(print (div-rat *one-half* *one-third*))
(equal-rat? (sub-rat *one-half* *one-third*)
(mul-rat *one-half* *one-third*))
| false |
75281f308ff4d6942acaccc20023b29cc96f1d98
|
be06d133af3757958ac6ca43321d0327e3e3d477
|
/qsort/qsort.scm
|
3f166a08ca276e2e04e1b2255fedca883c04d8f8
|
[] |
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 | 507 |
scm
|
qsort.scm
|
(define (filter f lis a)
(cond ((null? lis) '())
((f (car lis) a) (cons (car lis) (filter f (cdr lis) a)))
(else (filter f (cdr lis) a))))
(display (filter < '(1 2 3 4 5 6) 5)) (newline)
(display (filter < '(3 1 4 1 5 9 2 6 5) 3)) (newline)
(define (qsort lis)
(cond ((null? lis) '())
((= (length lis) 1) lis)
(else (append (qsort (filter < lis (car lis))) (filter = lis (car lis)) (qsort (filter > lis (car lis)))))))
(display (qsort '(3 1 4 1 5 9 2 6 5))) (newline)
| false |
371ed4bd004d97089d2880c3b189db230a245b24
|
ec5b4a92882f80b3f62eac8cbd059fb1f000cfd9
|
/imperative/old/!tests/bubblesort.ss
|
81d156f656144e6afd60d8faca6c0843aaae59a6
|
[] |
no_license
|
ggem/alpa
|
ee35ffc91d9f4b1d540ce8b2207595813e488e5f
|
4f53b888b5a5b4ffebd220c6e0458442325fbff2
|
refs/heads/master
| 2019-01-02T03:12:17.899768 | 2005-01-04T03:43:12 | 2005-01-04T03:43:12 | 42,612,681 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 535 |
ss
|
bubblesort.ss
|
(alpa-imp
(vars)
(definitions
(define (bubble-sort array)
(vars size i j j-1 tmp)
(set! size (vector-length array))
(set! i 1)
(while (< i size)
(set! j i)
(set! j-1 (- j 1))
(while (< j size)
(if (< (vector-ref array j) (vector-ref array j-1))
(begin
(set! tmp (vector-ref array j))
(vector-set! array j (vector-ref array j-1))
(vector-set! array j-1 tmp)))
(set! j (+ j 1)))
(set! i (+ i 1)))
(pretty-print array)))
(bubble-sort '#(9 7 5 3 1 8 6 4 2 0)))
| false |
8175059d02af4ef701618e5e25b4ea9d41c0fba0
|
cbe44707d3b7033b471b1796522227d7b009d38d
|
/sunny-rustify/scheme/lib/sunny/rust/module-tree.sld
|
f17b0b8c5a0457bde39317c310ea67439b9b31af
|
[] |
no_license
|
mbillingr/sunny-scheme
|
ebd5faa598ec9e8ebe56349f3ff6a42737513991
|
a54ee340428b7b070814cc9d4e1801f8e394db5c
|
refs/heads/master
| 2023-05-06T18:50:21.200131 | 2020-10-16T12:20:46 | 2020-10-16T12:20:46 | 282,292,876 | 0 | 0 | null | 2020-08-10T13:34:32 | 2020-07-24T18:44:06 |
Rust
|
UTF-8
|
Scheme
| false | false | 1,924 |
sld
|
module-tree.sld
|
(define-library (sunny rust module-tree)
(export make-module-tree-leaf
make-module-tree-node
module-tree-append-child!
module-tree-children
module-tree-find-child
module-tree-insert!
module-tree-leaf?
module-tree-libobj
module-tree-name
module-tree-set-children!)
(import (scheme base))
(begin
(define (make-module-tree-node name)
(cons name '()))
(define (make-module-tree-leaf name lib)
(cons name lib))
(define (module-tree-leaf? node)
(and (pair? node)
(symbol? (car node))
(not (null? (cdr node)))
(not (pair? (cdr node)))))
(define (module-tree-name node)
(car node))
(define (module-tree-children node)
(cdr node))
(define (module-tree-libobj node)
(cdr node))
(define (module-tree-set-children! node children)
(set-cdr! node children))
(define (module-tree-find-child node name)
(if (module-tree-leaf? node)
(error "called (module-tree-find-child) on leaf node" name node))
(assq name (module-tree-children node)))
(define (module-tree-append-child! node child)
(module-tree-set-children!
node
(cons child (module-tree-children node))))
(define (module-tree-insert! tree libname libobj)
(if (null? libname)
(error "invalid insert - empty libname"))
(let ((child (module-tree-find-child tree (car libname))))
(if child
(module-tree-insert! child (cdr libname) libobj)
(if (null? (cdr libname))
(module-tree-append-child! tree (make-module-tree-leaf (car libname) libobj))
(let ((new-node (make-module-tree-node (car libname))))
(module-tree-insert! new-node (cdr libname) libobj)
(module-tree-append-child! tree new-node))))))))
| false |
2a456ee7e763768ea17ac34a49fa73500e482698
|
710bd922d612840b3dc64bd7c64d4eefe62d50f0
|
/scheme/scheme-compiler/fasl.scm
|
a3b18b9ba0fb2b1d672fe70951940c59e9ba809b
|
[
"MIT"
] |
permissive
|
prefics/scheme
|
66c74b93852f2dfafd4a95e04cf5ec6b06057e16
|
ae615dffa7646c75eaa644258225913e567ff4fb
|
refs/heads/master
| 2023-08-23T07:27:02.254472 | 2023-08-12T06:47:59 | 2023-08-12T06:47:59 | 149,110,586 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 8,409 |
scm
|
fasl.scm
|
;;; fasl.scm -- FASL support procedures for reading/writing
;;; Constants ============================================================
(define fasl/fixnum 0)
(define fasl/true 1)
(define fasl/false 2)
(define fasl/char 3)
(define fasl/pair 4)
(define fasl/string 5)
(define fasl/vector 6)
(define fasl/bvec 7)
(define fasl/nil 8)
(define fasl/unspecific 9)
(define fasl/unbound 10)
(define fasl/symbol 11)
(define fasl/ref 12)
(define fasl/eof 14)
(define fasl/procedure 15)
(define fasl/negative-fixnum 16)
(define type/define 0)
(define type/syntax 1)
(define type/expr 2)
(define type/module 3) ;; <===== THIS IS NEW
;;; Writing FASL ==========================================================
(define (write-type type port)
(write-byte type port))
(define (write-byte b port)
(if (and (<= 0 b)
(<= b 255))
(display (ascii->char b) port)
(error "value ~a out of range in WRITE-BYTE" b)))
(define (write-long b port)
(if (and (<= 0 b)
(< b (* 256 65536)))
(let ((b32 (quotient b (* 256 65536)))
(b24 (modulo (quotient b (* 256 256)) 256))
(b16 (modulo (quotient b 256) 256))
(b8 (modulo b 256)))
(write-byte b32 port)
(write-byte b24 port)
(write-byte b16 port)
(write-byte b8 port))
(error "value ~a out of range in WRITE-LONG" b)))
(define (write-counted-string str port)
(let ((size (string-length str)))
(write-long size port)
(let loop ((i 0))
(if (< i size)
(begin (write-byte (char->ascii (string-ref str i)) port)
(loop (+ i 1)))))))
(define (write-fasl! template port)
; (display "FASL->") (display template) (newline)
(cond ((eof-object? template) (write-byte fasl/eof port))
((unbound-object? template) (write-byte fasl/unbound port))
((unspecific-object? template) (write-byte fasl/unspecific port))
((number? template)
(if (<= 0 template )
(begin
(write-byte fasl/fixnum port)
(write-long template port))
(begin
(write-byte fasl/negative-fixnum port)
(write-long (- 0 template) port))))
((eq? template #t) (write-byte fasl/true port))
((eq? template #f) (write-byte fasl/false port))
((char? template)
(write-byte fasl/char port)
(write-byte (char->ascii template) port))
((pair? template)
(write-byte fasl/pair port)
(write-fasl! (car template) port)
(write-fasl! (cdr template) port))
((string? template)
(write-byte fasl/string port)
(write-counted-string template port))
((bvec? template)
(write-byte fasl/bvec port)
(write-long (bvec-length template) port)
(let loop ((i 0))
(if (< i (bvec-length template))
(begin (write-byte (bvec-ref template i) port)
(loop (+ i 1))))))
((ref? template)
(write-byte fasl/ref port)
(write-counted-string (symbol->string (ref/name template)) port)
(write-counted-string (symbol->string (ref/module template)) port)) ; This is the module name
((vector? template)
(write-byte fasl/vector port)
(write-long (vector-length template) port)
(let loop ((i 0))
(if (< i (vector-length template))
(begin (write-fasl! (vector-ref template i) port)
(loop (+ i 1))))))
((eq? template '())
(write-byte fasl/nil port))
((symbol? template)
(write-byte fasl/symbol port)
(write-counted-string (symbol->string template) port))
; ((procedure? template)
; (write-byte fasl/procedure port)
; (write-long (procedure-length template) port)
; (let loop ((i 0))
; (if (< i (procedure-length template))
; (begin (write-fasl! (procedure-ref template i) port)
; (loop (+ i 1))))))
(else (error "don't know how to write FASL for ~a" template))))
;;; Reading FASL ==========================================================
(define (read-byte port)
(let ((byte (read-char port)))
(if (eof-object? byte)
byte
(char->ascii byte))))
(define read-long
(lambda (port)
(let ((h1 (char->ascii (read-char port)))
(h2 (char->ascii (read-char port)))
(h3 (char->ascii (read-char port)))
(h4 (char->ascii (read-char port))))
(+ (* (+ (* (+ (* 256 h1)
h2)
256)
h3)
256)
h4))))
(define read-counted-string
(lambda (port)
(let ((size (read-long port)))
(let ((str (make-string size #\1)))
(let ((loop #f))
(set! loop
(lambda (i)
(if (< i size)
(begin
(string-set! str i (read-char port))
(loop (+ i 1)))
str)))
(loop 0))))))
(define *fasl-reader* (make-vector 17 (lambda () 'undefined-fasl-reader)))
(define define-fasl-reader
(lambda (type body)
(vector-set! *fasl-reader* type body)))
(define-fasl-reader fasl/eof
(lambda (port) 'the-end-of-file-object))
(define-fasl-reader fasl/unbound
(lambda (port) (unbound-object)))
(define-fasl-reader fasl/unspecific
(lambda (port) (unspecific-object)))
(define-fasl-reader fasl/fixnum
(lambda (port)
(read-long port)))
(define-fasl-reader fasl/negative-fixnum
(lambda (port)
(- 0 (read-long port))))
(define-fasl-reader fasl/true
(lambda (port)
#t))
(define-fasl-reader fasl/false
(lambda (port)
#f))
(define-fasl-reader fasl/char
(lambda (port)
(read-char port)))
(define-fasl-reader fasl/pair
(lambda (port)
(let ((head (read-fasl port)))
(let ((tail (read-fasl port)))
(cons head tail)))))
(define-fasl-reader fasl/string read-counted-string)
(define-fasl-reader fasl/vector
(lambda (port)
(let ((size (read-long port)))
(let ((vec (make-vector size #f)))
(let ((loop #f))
(set! loop (lambda (index)
(if (< index size)
(begin
(vector-set! vec index (read-fasl port))
(loop (+ index 1)))
vec)))
(loop 0))))))
(define-fasl-reader fasl/procedure
(lambda (port)
(let ((size (read-long port)))
(let ((proc (make-procedure size)))
(let ((loop #f))
(set! loop (lambda (index)
(if (< index size)
(begin
(procedure-set! proc index (read-fasl port))
(loop (+ index 1)))
proc)))
(loop 0))))))
(define-fasl-reader fasl/bvec
(lambda (port)
(let ((size (read-long port)))
(let ((bvec (make-bvec size)))
(let ((loop #f))
(set! loop (lambda (index)
(if (< index size)
(begin
(bvec-set! bvec index (read-char port))
(loop (+ index 1)))
bvec)))
(loop 0))))))
(define-fasl-reader fasl/nil
(lambda (port)
'()))
(define-fasl-reader fasl/symbol
(lambda (port)
(string->symbol (read-counted-string port))))
(define-fasl-reader fasl/ref
(lambda (port)
(let* ((name (string->symbol (read-counted-string port)))
(module-name (string->symbol (read-counted-string port)))
(ref (lookup-ref name module-name)))
(if ref
ref
(let ((module (lookup-module module-name)))
(if module
(bind-ref! name (unbound-object) module)
(error "Module does not exists" module-name)))))))
(define read-fasl
(lambda (port)
(let ((byte (read-char port)))
(if (eof-object? byte)
byte
(let ((index (char->ascii byte)))
(if (< index (vector-length *fasl-reader*))
((vector-ref *fasl-reader* index) port)
(begin
(display "ERROR !!!!!!! Unknown fasl code")
(display (char->integer byte)))))))))
(define read-type
(lambda (port) (read-byte port)))
| false |
bc88e5550fa27c6b23f3e4479100cdcbd128ab57
|
bf96881df8d517f1d921e108bbf40dc06f4217ab
|
/2.ss
|
1d9a5fe418deeecb0c1e78aa375ec5c48b82fbf5
|
[] |
no_license
|
knispeja/PLC
|
4fd42834c53cea0d8568738e46250bc057ab3f1f
|
a2215f7c5dc9a80b288b9d35976de6bbdad705de
|
refs/heads/master
| 2021-03-19T14:10:57.582294 | 2016-05-03T01:46:42 | 2016-05-03T01:46:42 | 53,712,544 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 1,558 |
ss
|
2.ss
|
; Jacob Knispel
; Assignment 2
; -------------------
; Problem 1
; a)
(define fact
(lambda (n)
(if (zero? n)
1
(* n (fact (- n 1))))))
; b)
(define choose
(lambda (n k)
(/ (fact n)
(* (fact k) (fact (- n k))))))
; Problem 2
(define range
(lambda (m n)
(if (>= m n)
'()
(cons m (range (+ m 1) n)))))
; Problem 3
(define set?
(lambda (lst)
(if (null? lst)
#t
(if (member (car lst) (cdr lst))
#f
(set? (cdr lst))))))
; Problem 4
(define sum-of-squares
(lambda (lon)
(if (null? lon)
0
(+ (* (car lon) (car lon)) (sum-of-squares (cdr lon))))))
; Problem 5
(define make-vec-from-points
(lambda (p1 p2)
(if (null? p1)
'()
(cons (- (car p2) (car p1)) (make-vec-from-points (cdr p1) (cdr p2))))))
; Problem 6
(define dot-product
(lambda (v1 v2)
(if (null? v1)
0
(+ (* (car v1) (car v2)) (dot-product (cdr v1) (cdr v2))))))
; Problem 7
(define vec-length
(lambda (v)
(sqrt (sum-of-squares v))))
; Problem 8
(define distance
(lambda (p1 p2)
(vec-length (make-vec-from-points p1 p2))))
; Problem 9
(define cross-product
(lambda (v1 v2)
(list (- (* (cadr v1) (caddr v2)) (* (caddr v1) (cadr v2)))
(- (* (caddr v1) (car v2)) (* (car v1) (caddr v2)))
(- (* (car v1) (cadr v2)) (* (cadr v1) (car v2))))))
; Problem 10
(define parallel?
(lambda (v1 v2)
(= 0 (vec-length (cross-product v1 v2)))))
; Problem 11
(define collinear?
(lambda (p1 p2 p3)
(= 0 (vec-length (cross-product (make-vec-from-points p1 p2) (make-vec-from-points p1 p3))))))
| false |
9ce7c1e91a1cd91c651f176debc18e1affba2453
|
e416e369d47c01e5cb136d4eecdd89d9ec1d1102
|
/reading-list/the_little_schemer/07_friends_and_relations.scm
|
dd7b3faa3832f3f3bd4d160ba4764c9502ad33c8
|
[
"MIT"
] |
permissive
|
diminishedprime/old-.org
|
267315a8928ec59040298ed11b66e39b4758fe35
|
9aeed37c27a815e909ec40d33cb51571a38d1af0
|
refs/heads/master
| 2022-07-08T10:07:26.199068 | 2017-09-19T20:11:55 | 2017-09-19T20:11:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 6,059 |
scm
|
07_friends_and_relations.scm
|
(load "ls.scm") ;; => #<unspecified>
(define set?
(lambda (lat)
(cond
((null? lat) #t)
((member? (car lat) (cdr lat)) #f)
(else (set? (cdr lat)))))) ;; => #<unspecified>
(set? '(apple peaches apple plum)) ;; => #f
(set? '(apples peaches pears plums)) ;; => #t
(set? '()) ;; => #t
(set? '(apple 3 pear 4 9 apple 3 4)) ;; => #f
(define makeset
(lambda (lat)
(cond
((null? lat) '())
((member? (car lat) (cdr lat)) (makeset (cdr lat)))
(else (cons (car lat) (makeset (cdr lat))))))) ;; => #<unspecified>
(makeset '(apple peach pear peach plum apple lemon peach)) ;; => (pear plum apple lemon peach)
(define makeset
(lambda (lat)
(cond
((null? lat) '())
(else (cons (car lat)
(makeset (multirember (car lat)
(cdr lat)))))))) ;; => #<unspecified>
(makeset '(apple peach pear peach plum apple lemon peach)) ;; => (apple peach pear plum lemon)
(makeset '(apple 3 pear 4 9 apple 3 4)) ;; => (apple 3 pear 4 9)
(define subset?
(lambda (set1 set2)
(cond
((null? set1) #t)
((member? (car set1) set2) (subset? (cdr set1) set2))
(else #f)))) ;; => #<unspecified>
(subset? '(5 chicken wings)
'(5 hamburgers
2 pieces friend chicken and
light duckling wings)) ;; => #t
(subset? '(4 pounds of horseradish)
'(four pounds chicken and 5 ounces horseradish)) ;; => #f
(define subset?
(lambda (set1 set2)
(cond
((null? set1) #t)
(else (and (member? (car set1) set2)
(subset? (cdr set1) set2)))))) ;; => #<unspecified>
(subset? '(5 chicken wings)
'(5 hamburgers
2 pieces friend chicken and
light duckling wings)) ;; => #t
(subset? '(4 pounds of horseradish)
'(four pounds chicken and 5 ounces horseradish)) ;; => #f
(define eqset?
(lambda (set1 set2)
(and (subset? set1 set2)
(subset? set2 set1)))) ;; => #<unspecified>
(eqset? '(6 large chickens with wings)
'(6 chickens with large wings)) ;; => #t
(define intersect?
(lambda (set1 set2)
(cond
((null? set1) #f)
(else (or (member? (car set1) set2)
(intersect? (cdr set1) set2)))))) ;; => #<unspecified>
(intersect? '(stewed tomatoes and macaroni)
'(macaroni and cheese)) ;; => #t
(define intersect
(lambda (set1 set2)
(cond
((null? set1) '())
((member? (car set1) set2) (cons (car set1)
(intersect (cdr set1) set2)))
(else (intersect (cdr set1) set2))))) ;; => #<unspecified>
(intersect '(stewed tomatoes and macaroni)
'(macaroni and cheese)) ;; => (and macaroni)
(define union
(lambda (set1 set2)
(cond
((null? set1) '())
((member? (car set1) set2) (union (cdr set1) set2))
(else (cons (car set1)
(union (cdr set1) set2)))))) ;; => #<unspecified>
(union '(stewed tomatoes and macaroni casserole)
'(macaroni and cheese)) ;; => (stewed tomatoes casserole)
(define difference
(lambda (set1 set2)
(cond
((null? set1) '())
((member? (car set1) set2) (difference (cdr set1) set2))
(else (cons (car set1)
(difference (cdr set1) set2)))))) ;; => #<unspecified>
(difference '(stewed tomatoes and macaroni casserole)
'(macaroni and cheese)) ;; => (stewed tomatoes casserole)
(define intersectall
(lambda (l-set)
(cond
((null? (cdr l-set)) (car l-set))
(else (intersect (car l-set)
(intersectall (cdr l-set))))))) ;; => #<unspecified>
(intersectall '((a b c) (c a d e) (e f g h a b))) ;; => (a)
(intersectall '((6 pears and)
(3 peaches and 6 peppers)
(8 pears and 6 plums)
(and 6 prunes with some apples))) ;; => (6 and)
(define a-pair?
(lambda (x)
(cond
((atom? x) #f)
((null? x) #f)
((null? (cdr x)) #f)
((null? (cdr (cdr x))) #t)
(else #f)))) ;; => #<unspecified>
(a-pair? '(pear pear)) ;; => #t
(a-pair? '((2) (pair))) ;; => #t
(a-pair? '(full (house))) ;; => #t
(define first
(lambda (p)
(car p))) ;; => #<unspecified>
(define second
(lambda (p)
(car (cdr p)))) ;; => #<unspecified>
(define build
(lambda (s1 s2)
(cons s1 (cons s2 '())))) ;; => #<unspecified>
(define third
(lambda (p)
(car (cdr (cdr p))))) ;; => #<unspecified>
(define fun?
(lambda (rel)
(set? (firsts rel)))) ;; => #<unspecified>
(define revrel
(lambda (rel)
(cond
((null? rel) '())
(else (cons (build
(second (car rel))
(first (car rel)))
(revrel (cdr rel))))))) ;; => #<unspecified>
(revrel '((8 a) (pumpkin pie) (got sick))) ;; => ((a 8) (pie pumpkin) (sick got))
(define revpair
(lambda (pair)
(build (second pair)
(first pair)))) ;; => #<unspecified>
(define revrel
(lambda (rel)
(cond
((null? rel) '())
(else (cons (revpair (car rel))
(revrel (cdr rel))))))) ;; => #<unspecified>
(revrel '((8 a) (pumpkin pie) (got sick))) ;; => ((a 8) (pie pumpkin) (sick got))
(define seconds
(lambda (l)
(cond
((null? l) '())
(else (cons (second (car l))
(seconds (cdr l))))))) ;; => #<unspecified>
(define fullfun?
(lambda (fun)
(set? (seconds fun)))) ;; => #<unspecified>
(fullfun? '((8 3) (4 2) (7 6) (6 2) (3 4))) ;; => #f
(fullfun? '((8 3) (4 8) (7 6) (6 2) (3 4))) ;; => #t
(fullfun? '((grape raisin)
(plum prune)
(stewed prune))) ;; => #f
(fullfun? '((grape raisin)
(plum prune)
(stewed grape))) ;; => #t
(define one-to-one?
(lambda (fun)
(fun? (revrel fun)))) ;; => #<unspecified>
(one-to-one? '((8 3) (4 2) (7 6) (6 2) (3 4))) ;; => #t
(one-to-one? '((8 3) (4 8) (7 6) (6 2) (3 4))) ;; => #t
(one-to-one? '((grape raisin)
(plum prune)
(stewed prune))) ;; => #t
(one-to-one? '((grape raisin)
(plum prune)
(stewed grape))) ;; => #t
| false |
b7e31b87e530f6a48fc71d15f7f7630b37494cdf
|
7e0c613b8a2781aab692a5976b0e8896ac18b4fb
|
/ssh/private/serialize.sls
|
e1f6c24fa8105704156c7f54bd653f596504d7aa
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
atomontage/industria
|
f279fb71cc69032cc4084c1e2f09bfacefe2fc6c
|
f13b067ce3b8b82f09c5670a45dfde29da29c5fb
|
refs/heads/master
| 2021-01-22T12:13:08.369334 | 2019-05-26T18:07:25 | 2019-05-26T18:07:25 | 24,039,099 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 4,555 |
sls
|
serialize.sls
|
;; -*- mode: scheme; coding: utf-8 -*-
;; Copyright © 2010, 2011, 2012, 2018, 2019 Göran Weinholt <[email protected]>
;; SPDX-License-Identifier: MIT
#!r6rs
;; Private parsing and formatting
(library (industria ssh private serialize)
(export
get-record read-byte read-uint32
read-bytevector read-string read-name-list read-mpint
put-record put-bvstring put-name-list put-mpint
integer->mpint
get-uint32 get-mpint get-bytevector get-string put-string)
(import
(except (rnrs (6)) put-string)
(only (srfi :13 strings) string-join)
(srfi :26 cut)
(industria bytevectors)
(industria buffer)
(industria strings)
(struct pack))
(define (get-record b make field-types)
(define (read b type)
(case type
((string) (read-string b))
((bytevector) (read-bytevector b))
((uint32) (read-uint32 b))
((mpint) (read-mpint b))
((name-list) (read-name-list b))
((boolean) (positive? (read-byte b)))
((byte) (read-byte b))
((cookie)
(when (< (buffer-length b) 16)
(error 'get-record "short record" (buffer-length b)))
(let ((bv (subbytevector (buffer-data b)
(buffer-top b)
(+ (buffer-top b) 16))))
(buffer-seek! b 16)
bv))
(else
(error 'get-record "bug: unknown type" type))))
(do ((field 0 (+ field 1))
(types field-types (cdr types))
(ret '() (cons (read b (car types)) ret)))
((null? types) (apply make (reverse ret)))))
(define (read-byte b)
(let ((x (read-u8 b 0)))
(buffer-seek! b 1)
x))
(define (read-uint32 b)
(let ((x (read-u32 b 0)))
(buffer-seek! b 4)
x))
(define (read-bytevector b)
(let ((len (read-u32 b 0)))
(when (> len (buffer-length b))
(error 'read-bytevector "overlong string" len))
(buffer-seek! b 4)
(let ((bv (subbytevector (buffer-data b)
(buffer-top b)
(+ (buffer-top b) len))))
(buffer-seek! b len)
bv)))
(define (read-string b)
(utf8->string (read-bytevector b)))
(define (read-name-list b)
(let ((str (read-string b)))
(if (string=? str "")
'()
(string-split str #\,))))
(define (read-mpint b)
(let ((bv (read-bytevector b)))
(bytevector-sint-ref bv 0 (endianness big) (bytevector-length bv))))
;;; Formatting
(define (put-record p msg rtd field-types)
(do ((rtd (or rtd (record-rtd msg)))
(field 0 (+ field 1))
(types field-types (cdr types)))
((null? types))
(let ((v ((record-accessor rtd field) msg)))
(case (car types)
((string bytevector) (put-bvstring p v))
((uint32) (put-bytevector p (pack "!L" v)))
((mpint) (put-mpint p v))
((name-list) (put-name-list p v))
((boolean) (put-u8 p (if v 1 0)))
((byte) (put-u8 p v))
((cookie) (put-bytevector p v 0 16))
(else
(error 'put-record "bug: unknown type"
(car types)))))))
(define (put-bvstring p s)
(let ((bv (if (string? s) (string->utf8 s) s)))
(put-bytevector p (pack "!L" (bytevector-length bv)))
(put-bytevector p bv)))
(define (put-name-list p l)
(put-bvstring p (string-join l ",")))
(define (mpnegative? bv)
(and (> (bytevector-length bv) 1)
(fxbit-set? (bytevector-u8-ref bv 0) 7)))
(define (put-mpint p i)
(let ((bv (uint->bytevector i)))
(cond ((mpnegative? bv)
;; Prevent this from being considered a negative number
(put-bytevector p (pack "!L" (+ 1 (bytevector-length bv))))
(put-u8 p 0)
(put-bytevector p bv))
(else
(put-bytevector p (pack "!L" (bytevector-length bv)))
(put-bytevector p bv)))))
(define (integer->mpint int)
(call-with-bytevector-output-port
(cut put-mpint <> int)))
;;; Port-based parsing/formatting, mostly for keys
(define (get-uint32 p)
(get-unpack p "!L"))
(define (get-mpint p)
(let ((bv (get-bytevector-n p (get-unpack p "!L"))))
(when (mpnegative? bv)
(assertion-violation 'get-mpint
"Refusing to read a negative mpint"))
(bytevector->uint bv)))
(define (get-bytevector p)
(get-bytevector-n p (get-unpack p "!L")))
(define (get-string p)
(let ((bv (get-bytevector-n p (get-unpack p "!L"))))
(if (eof-object? bv)
bv
(utf8->string bv))))
(define (put-string p bv)
(put-bytevector p (pack "!L" (bytevector-length bv)))
(put-bytevector p bv)))
| false |
39982da245b1649aac126f9b9a040a04333cfff3
|
5eb631d9a0885a550b709c6e9f905066f6af531b
|
/ex/chap2/73.scm
|
775ebb363be677121b7576fe07ab37cd6b2dd1d5
|
[] |
no_license
|
hanpum/sicp
|
344cb6456daf2c2f6b002aa20dc3e177c34b18bd
|
454efaf28ee0f0487e372ede28f452eb762de404
|
refs/heads/master
| 2023-06-09T08:11:55.080048 | 2021-06-29T00:01:49 | 2021-06-29T00:01:49 | 381,190,193 | 0 | 0 | null | null | null | null |
UTF-8
|
Scheme
| false | false | 3,967 |
scm
|
73.scm
|
;;
;; ┌──────────────────────────────────────────────────────┐
;; │ │
;; │ ┌────────────────────┐ │
;; ├────────────────┤ APPLICATIONS ├────────────────┤
;; │ └────────────────────┘ │
;; │ │
;; │ ┌────────────────────┐ │
;; ├────────────────┤ interface api ├────────────────┤
;; │ └─┬────────────────┬─┘ │
;; │ implemation 1 │ ... │ implemation n │
;; │ │ │ │
;; └──────────────────┴────────────────┴──────────────────┘
;;
;; interface:
;; - opreator
;; - operands
;; - deriv
;;
;; implementations:
;; - sum: (+ a b c)
;; - product: (* a b c)
;; - exp: (** a b)
(load "math-utils")
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (install-sum)
(define (make-sum a1 a2)
(cond ((number=? a1 0) a2)
((number=? a2 0) a1)
((and (number? a1) (number a2)) (+ a1 a2))
(else (list '+ a1 a2))))
(define (addend e) (cadr e))
(define (augend e)
(let ((rest (cddr e)))
(if (length=? rest 1)
(car rest)
(append '(+) rest))))
(define (internal_deriv exp var)
(make-sum (deriv (addend exp) var)
(deriv (augend exp) var)))
(put 'deriv '+ internal_deriv)
(put 'make-sum 'any make-sum))
(define (install-product)
(define (multiplier expr) (cadr expr))
(define (multiplicand expr)
(let ((rest (cddr expr)))
(if (length=? rest 1)
(car rest)
(append '(*) rest))))
(define (make-product m1 m2)
(cond ((=number? m1 1) m2)
((=number? m2 1) m1)
((or (=number? m1 0) (=number? m2 0)) 0)
((and (number? m1) (number? m2)) (* m1 m2))
(else (list '* m1 m2))))
;; (f1*f2)' = f1'*f2 + f1*f2'
(define (internal_deriv exp var)
(let ((1st (multiplier exp))
(2nd (multiplicand exp)))
(make-sum
(make-product (deriv 1st var) 2nd)
(make-product 1st (deriv 2nd var)))))
(put 'deriv '* internal_deriv)
(put 'make-product 'any make-product))
(define (install-exp)
;;(define (expt? exp) (eq? '** (car exp)))
(define (base expr) (cadr expr))
(define (exponent expr) (caddr expr))
(define (make-expt base expr)
(cond ((=number? base 0) 0)
((=number? base 1) 1)
((=number? expr 0) 1)
((=number? expr 1) base)
((and (number? base) (number? expr)) (expt base expr))
(else (list '** base expr))))
;; (f1^n)' = n * f1^(n-1) * f1'
(define (internal_deriv expr var)
(let ((1st (base expr))
(2nd (exponent expr)))
(make-product 2nd
(make-product (make-expt 1st (- 2nd 1))
(deriv 1st var)))))
(put 'deriv '** internal_deriv)
(put 'make-expt 'any make-expt))
;; application
(install-sum)
(install-exp)
(install-product)
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp)
(if (same-variable? exp var) 1 0))
(else ((get 'deriv (operator exp)) (operands exp)
var))))
(println "~%begin testing of 73.scm")
(define (do-test exp var)
(println "deriv ~S on ~S: ~S" exp var (deriv exp var)))
(do-test '(+ x 3) 'x)
(do-test '(* x y) 'x)
(do-test '(* (* x y) (+ x 3)) 'x)
(do-test '(** x 5) 'x)
(do-test '(** (* x y) 5) 'x)
(println (deriv '(* x y (+ x 3)) 'x))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.