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
4f9e25fe8431b5c597de502ab87153652c0497fa
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/ws/passes/analyze_query/add-data-flow.ss
e06818c9773a0cb936c7e069c93d855746899a55
[ "BSD-3-Clause" ]
permissive
rrnewton/WaveScript
2f008f76bf63707761b9f7c95a68bd3e6b9c32ca
1c9eff60970aefd2177d53723383b533ce370a6e
refs/heads/master
2021-01-19T05:53:23.252626
2014-10-08T15:00:41
2014-10-08T15:00:41
1,297,872
10
2
null
null
null
null
UTF-8
Scheme
false
false
16,070
ss
add-data-flow.ss
;;;; .title Pass: Add Data Flow ;;;; .author Ryan Newton ;;;; This pass undoes the control indirection introduced by maps/filters/folds. ;;;; It explicitely attaches a table to the output program which binds ;;;; variable names to the expression that generates that data value. (module add-data-flow mzscheme (require "../../../plt/common.ss") (provide add-data-flow test-this test17b test-add-data-flow expr->allvars ;; TEMP: dfg? extend-dfg empty-dfg ) (chezimports ) ; (require "../plt/cheztrace.ss") (define worldsym 'THEWORLD) ;====================================================================== ;; I'm introducing the idea of a "Code Location" which currently is ;; just the decl ripped out of the letrec that contains the expression. ;; symbol, dfg -> codeloc (define (lookup s dfg) (let ([entry (assq s dfg)]) (match entry [#f (error 'lookup "No binding for ~s in ~s\n" s dfg )] [,other (DEBUGASSERT (codeloc? (cadr other))) (cadr other)] ;; Return the codeloc ))) (define (dfg? ls) (andmap (lambda (x) (match x [(,v ,cl) (and (symbol? v) (codeloc? cl))] ; [(,v ,ws) (and (symbol? v) (eq? worldsym ws))] [,else #f])) ls)) (define (codeloc? ls) (match ls [,ws (guard (eq? ws worldsym)) #t] [',ws (guard (eq? ws worldsym)) (error 'codeloc? "This shouldn't happen: got quoted worldsym")] [[,name ,ty (,annots ...) ,rhs] (and (symbol? name) (type? ty))] [,else #f])) (define (codeloc->expr x) (match x [,w (guard (eq? w worldsym)) #f] ;; No good answer for world. [[,__ ,___ ,____ ,expr] expr] [,other (error 'codeloc->expr "unmatched datum: ~s" other)])) (define extend-dfg (case-lambda [(dfg name* codeloc*) (DEBUGASSERT (and (list? name*) (andmap symbol? name*))) (DEBUGMODE (for-each (lambda (x) (ASSERT (codeloc? x))) codeloc*)) (append (map list name* codeloc*) dfg)] [(dfg binds) (extend-dfg dfg (map car binds) (map cadr binds)) ])) (define (empty-dfg) ()) ;; This is just used for debugging below. (define (expr->allvars e) (match e [(quote ,const) ()] [,var (guard (symbol? var)) ()] [(if ,[t] ,[c] ,[a]) (append t c a)] [(lambda ,v* ,ty* ,[bod]) (append v* bod)] [(lazy-letrec ,binds ,tail) (apply append (map car binds) (map expr->allvars (map last binds)))] [(,prim ,[rand*] ...) (guard (regiment-primitive? prim)) (apply append rand*)] [,unmatched (error 'expr->allvars "invalid syntax ~s" unmatched)] )) ;====================================================================== ;; Hack, this is non-null for a reason: (define-testing these-tests '([1 1])) (define add-data-flow (build-compiler-pass ;; This wraps the main function with extra debugging machinery 'add-data-flow `(input) `(output ) (let () (define process-primapp 0) (define global-tenv 'uninitialized) (define (letrec-extend-tenv tenv binds) (tenv-extend tenv (map car binds) (map cadr binds))) ;; The easiest way to proceed is to suck out all the types from ;; the whole program. Names are unique, so this is all the info ;; we need. (define (extract-whole-tenv expr) ; (regiment-generic-traverse ; (lambda (x autoloop) ; [(lambda ,v* ,ty* ,bod) ; (tenv-extend (loop bod) v* ty*) ; ]) ; ) (match expr [,atom (guard (atom? atom)) (empty-tenv)] [(quote ,_) (empty-tenv)] [(if ,[t] ,[c] ,[a]) (tenv-append t c a)] [(tupref ,n ,m ,[x]) x] [(lambda ,v* ,ty* ,[bod]) (tenv-extend bod v* ty*)] [(lazy-letrec ([,v* ,ty* ,annots* ,[rhs*]] ...) ,[bod]) (apply tenv-append (tenv-extend bod v* (map make-tcell ty*) #t) rhs*)] [(,prim ,[rand*] ...) (guard (regiment-primitive? prim)) (apply tenv-append rand*)] [,other (error 'extract-whole-tenv "bad regiment expression: ~s" other)] )) ;; Returns the inner simple expression that generates the return value. ;; Expression, DFG -> Codeloc ;; .param currentloc The current code-location for the expression being processed, ;; or #f if we're not inside the letrec yet. (define (get-tail expr currentloc env) (DEBUGASSERT (or currentloc (symbol? expr) (and (list? expr) (eq? 'lazy-letrec (car expr))))) (match expr [,const (guard (regiment-constant? const)) currentloc] [,var (guard (symbol? var)) (let ([cl (lookup var env)]) (get-region-tail (codeloc->expr cl) env))] ;; Redirect right through light-up. [(light-up ,rand) ; (inspect `(LU-tail ,rand)) (get-tail rand #f env)] [(lazy-letrec ,binds ,var) (ASSERT (symbol? var)) ;; The letrec body must already be lifted. ;; ERROR ERROR: Need to extend env. ;(inspect (assq var binds)) ;(get-tail (rac (rac (assq var binds))) env) (let ([cl (assq var binds)]) (get-tail (codeloc->expr cl) cl (extend-dfg env (map car binds) binds)))] ;; Can't go deeper: [(if ,test ,conseq ,altern) currentloc] [(tupref ,n ,m ,x) currentloc] [,expr currentloc])) ;; This takes an expression of type Region 'a, and tries to return ;; the piece of code which generates an *element* of that region. ;; Expression, Codeloc, DFG -> Codeloc (define (get-region-tail expr env) (DEBUGASSERT (dfg? env)) ;; The currentloc should only be false of the expr IS a letrec. ;(DEBUGASSERT (or currentloc (symbol? expr) (and (list? expr) (eq? 'lazy-letrec (car expr))))) (let ([result ;; If the type is Region, then the member elements are type ;; Node, and the only thing that generates that is the world itself. (if (let ([ty (recover-type expr global-tenv)]) (or (equal? ty 'Region) (equal? ty '(Area Node)))) worldsym (match expr [,var (guard (symbol? var)) (let ([cl (lookup var env)]) (get-region-tail (codeloc->expr cl) env))] [(quote ,const) (error 'get-region-tail "const: ~s" const)] [(lazy-letrec ,binds ,var) (let ([cl (assq var binds)]) (get-region-tail (codeloc->expr cl) env))] [(khood ,_ ,__) (error 'get-region-tail "Shouldn't get to this case, should have been caught above.")] [(rmap ,rat ,rand) (ASSERT (simple-expr? rand)) (if (regiment-primitive? rat) ;rat (error 'get-region-tail "non-eta'd primitive as rmap operator: ~a" rat) (let ([newrand (process-expr rand env)]) (match (or (and (symbol? rat) (codeloc->expr (lookup rat env))) rat) [(lambda (,v) ,ty ,expr) (get-tail expr #f env)])))] ;; HACK: ;; [2006.10.27] [(rintegrate ,rat ,zero ,strm) (let ([newrand (process-expr strm env)]) (match (or (and (symbol? rat) (codeloc->expr (lookup rat env))) rat) [(lambda (,node ,x ,st) ,ty ,expr) ;; Not quite right: (get-tail expr #f env)])) ] ;; An rfilter doesn't change the value-producing program point. [(rfilter ,rat ,rand) (get-region-tail rand env)] ;; The dataflow should go right through light-up, it's the identity function: [(light-up ,rand) ; (inspect `(LU ,rand)) (get-region-tail rand env)] [(liftsig ,areasig) (get-region-tail areasig env)] [,expr (error 'get-region-tail "unhandled expression: ~s\n" expr)] [,expr `(NOTHIN ,expr)]) )]) (DEBUGASSERT (or (codeloc? result) (eq? worldsym result))) result )) ;; This returns a list of [<Var> <Expr>] bindings associating variables ;; to the primitive application expressions that generate them. ;; .param expr The expression to process. ;; .param env The data-flow bindings established thus far. (define process-expr (lambda (expr env) (DEBUGASSERT (dfg? env)) (let ([result (match expr [(quote ,const) ()] [,var (guard (symbol? var)) ()] ;; TODO: FIXME: HANDLE SMAP AS WELL: [(,mapfun ,rat ,rand) (guard (memq mapfun '(rmap rfilter))) (let ([randbinds (process-expr rand env)]) ;(if (not (null? newbinds)) (inspect newbinds)) (match (or (and (symbol? rat) (codeloc->expr (lookup rat env))) rat) [(lambda (,v) ,ty ,bod) ;; First, produce a data-flow binding for the lambda's argument. (let* ([lambind `[,v ,(get-region-tail rand (extend-dfg env randbinds))]] [newbinds (cons lambind randbinds)]) ;; Now, produce bindings for the body of the lambda. (append (process-expr bod (extend-dfg env (list (car lambind)) (list (cadr lambind)))) newbinds) )] [,other (error 'add-data-flow:process-expr "could not find code for rator: ~s" rat)] ))] ;; This is just the identity function, cut right through it: ;[(light-up ;; We accumulate "data flow" information as we go through the bindings. ;; NOTE NOTE: This assumes that they're ordered and non-recursive. [(lazy-letrec ,binds ,tail) (DEBUGASSERT (symbol? tail)) ; (set! binds (delazy-bindings binds (list tail))) ;; The lack of free variables within lambdas makes this easy. ;; We scan down the whole list of bindings before we go into the lambdas in the RHSs. (let* ([letrecbinds (map list (map car binds) binds)] [newenv (extend-dfg env (map car binds) ;; For each binding, we bind to its tail expression. ;; DISABLING, not ready for this yet: binds #; (map (lambda (b) ; FIXME FIXME FIXME ;; Uh-oh, we should use newenv here! (get-tail (codeloc->expr b) b env)) binds))] [innerbinds (let declloop ([binds binds] [newbinds ()]) (if (null? binds) newbinds (match (car binds) [[,lhs ,ty ,annots ,rhs] ;; This RHS can only depend on dataflow information ;; INSIDE bindings that come before it: (let ([innards (process-expr rhs (extend-dfg newenv newbinds))]) (declloop (cdr binds) (append ;`([,lhs ,rhs]) innards newbinds)))])))]) ;; This should not happen: ;(DEBUGASSERT (null? (intersection (map car innerbinds) (map car letrecbinds)))) ;(inspect (vector (map car innerbinds) (map car letrecbinds))) (append innerbinds letrecbinds) ;(list-rem-dups (append innerbinds letrecbinds)) ;innerbinds )] [(lambda ,v* ,ty* ,[bod]) bod] [(if ,[t] ,[c] ,[a]) (append t c a)] [(tupref ,n ,m ,[x]) x] [(tuple ,[args] ...) (apply append args)] [(,prim ,[rand*] ...) (guard (regiment-primitive? prim)) (apply append rand*)] [,unmatched (error 'add-data-flow:process-expr "invalid syntax ~s" unmatched)])]) ;; Invariant: The result that we return should not overlap ;; with the environment that we take from above. Otherwise ;; we'd produce duplicates. ;; TEMP:: DISABLING THIS CHECK: ;; FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME #; (DEBUGMODE (let ([overlap (intersection (map car env) (map car result))]) (ASSERT (null? overlap)))) result))) ;; Doing some internal testing here: ;-------------------------------------------------------- (unless (null? these-tests) (set! these-tests (append `(["Just a letrec" (map car (,process-expr '(lazy-letrec ((resultofanonlambda_8 Int ((heartbeat #f)) '389)) resultofanonlambda_8) (,empty-dfg))) (resultofanonlambda_8)] ["Nested letrec on rhs" (map car (,process-expr '(lazy-letrec ((resultofanonlambda_8 Int () (lazy-letrec ((var_2 Int () '389)) var_2))) resultofanonlambda_8) (,empty-dfg))) ,(lambda (x) (set-eq? (list->set x) (list->set '(var_2 resultofanonlambda_8))))] ["Two bindings, one nested letrec" (map car (,process-expr '(lazy-letrec ([resultofanonlambda_8 Int () '89] [var_2 Int () (lazy-letrec ([foo Int () '100] [res1 Int () (_+_ foo '389)]) res1)] [res2 Int () (_+_ resultofanonlambda_8 var_2)]) res2) (,empty-dfg))) ,(lambda (x) (set-eq? (list->set x) (list->set '(foo res1 resultofanonlambda_8 var_2 res2))))] ["Data flow graph?" (,dfg? '((x ,worldsym) (f (f ('a -> 'a) () (lambda (x) ('b) x))) (v (v (Area Node) () (rmap f world))))) #t] ) these-tests))) ;-------------------------------------------------------- (lambda (expr) (match expr [(,input-language (quote (program (props ,proptable ...) (control-flow ,cfg ...) ,letexpr ,type))) (set! global-tenv (extract-whole-tenv letexpr)) (let ([dfg (process-expr letexpr (empty-dfg))]) ;; INVARIANT: Make sure we got all the bindings and only the bindings. ;; TEMP:: DISABLING THIS CHECK: ;; FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME FIXME #; (DEBUGMODE (let ([allvars (expr->allvars letexpr)]) (DEBUGASSERT (= (length allvars) (length dfg))) (DEBUGASSERT (set-equal? (list->set allvars) (list->set (map car dfg)))))) ;;(inspect global-tenv) `(,input-language (quote (program (props ,proptable ...) (control-flow ,cfg ...) (data-flow ,@dfg) ,letexpr ,type)))) ]))))) ;================================================================================ (define nested_testprog `(lang '(program (props ) (control-flow ) (lazy-letrec ([w (Area Node) () world] [h (Area (Area Node)) () (rmap (lambda (n) (Node) (lazy-letrec ([a (Stream Node) () (node->anchor n)] [kh (Area Node) () (khood a '2)]) kh)) w)] [getid (Node -> Int) () (lambda (nd) (Node) (nodeid nd))] [h2 (Area (Area Int)) () (rmap (lambda (r1) ((Area Node)) (lazy-letrec ([res_r1 (Area Int) () (rmap getid r1)]) res_r1)) h)] [v (Area Int) () (rmap (lambda (r2) ((Area Int)) (rfold _+_ '0 r2)) h2)] ) v) (Area Int)))) (define-testing test-this (default-unit-tester "Pass 17: Add data flow" (if (null? these-tests) '() (append these-tests `( ["Does it produce the right bindings on a simple example?" (,deep-assq 'data-flow (add-data-flow `(lang '(program (props ) (control-flow ) (lazy-letrec ([f ('a -> 'a) () (lambda (x) ('b) x)] [v (Area Node) () (rmap f world)]) v) (Area Node))))) ,(lambda (x) (and (pair? x) (not (null? x)) (set-equal? #; (map (lambda (b) (if (eq? worldsym (cadr b)) worldsym (list (car b) (last (cadr b))))) (cdr x)) #; `((v (rmap f world)) (x ,worldsym) (f (lambda (x) (_) x))) (list->set (cdr x)) (list->set `((x ,worldsym) (f (f ('a -> 'a) () (lambda (x) ('b) x))) (v (v (Area Node) () (rmap f world))))) )))] ["Now let's look at nested regions." (assq 'r2 (cdr (,deep-assq 'data-flow (add-data-flow ',nested_testprog)))) ;(r2 (rmap getid r1)) ;; [2006.04.04] Now it's bound to the code location with the canonical name: (r2 [res_r1 (Area Int) () (rmap getid r1)]) ] ["Make sure it generates all the bindings it should." (map car (cdr (,deep-assq 'data-flow (add-data-flow ',nested_testprog)))) ,(lambda (x) (set-equal? (list->set x) ;'(r2 nd r1 n h h2 getid v ret) (list->set '(r2 nd res_r1 r1 a kh n w h getid h2 v)) ))] ))))) (define test17b test-this) (define test-add-data-flow test-this) ) ;; End module ;(require pass17_add-data-flow) (test17b)
false
85de20b79068bb423f14af1378007dadd88312f9
fae4190f90ada065bc9e5fe64aab0549d4d4638a
/typed-scheme-lti/private/free-vars.ss
5b5d3b2bce312d565072261c7ddcac509ef3c9cf
[]
no_license
ilya-klyuchnikov/old-typed-racket
f161481661a2ed5cfc60e268f5fcede728d22488
fa7c1807231f447ff37497e89b25dcd7a9592f64
refs/heads/master
2021-12-08T04:19:59.894779
2008-04-13T10:54:34
2008-04-13T10:54:34
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,154
ss
free-vars.ss
(module free-vars mzscheme ;; this finds the free variables of fully-expanded mzscheme expressions ;; adapted from code by mflatt (require "planet-requires.ss") (require-libs) (require (lib "struct.ss")) (require (lib "kerncase.ss" "syntax") (lib "boundmap.ss" "syntax") (lib "list.ss") (lib "trace.ss")) (require-for-template mzscheme) (provide free-vars) ;; merge : (liftof (listof id)) -> (listof id) ;; merges lists of identifiers, removing module-identifier=? ;; duplicates (define (merge l) (cond [(null? l) null] [(null? (cdr l)) (car l)] [else (let ([m (make-module-identifier-mapping)]) (for-each (lambda (ids) (for-each (lambda (id) (module-identifier-mapping-put! m id #t)) ids)) l) (module-identifier-mapping-map m (lambda (k v) k)))])) ;; formals->boundmap : formals-stx -> bound-map-table ;; Parses a procedure "formals" and returns the binding ids ;; in a table (define (formals->boundmap f) (let ([ids (let loop ([f f]) (cond [(identifier? f) (list f)] [(pair? f) (cons (car f) (loop (cdr f)))] [(null? f) null] [(syntax? f) (loop (syntax-e f))]))] [b (make-bound-identifier-mapping)]) (for-each (lambda (id) (bound-identifier-mapping-put! b id #t)) ids) b)) ;; free-vars : expr-stx -> (listof id) ;; Returns a list of free lambda- and let-bound identifiers in a ;; given epression. The expression must be fully expanded. (define (free-vars e) (kernel-syntax-case e #f [id (identifier? #'id) (if (eq? 'lexical (identifier-binding #'id)) (list #'id) null)] [(#%datum . v) null] [(#%top . id) null] [(#%expression e) (free-vars #'e)] [(quote q) null] [(quote-syntax q) null] [(lambda formals expr ...) (let ([free (merge (map free-vars (syntax->list #'(expr ...))))] [bindings (formals->boundmap #'formals)]) (filter (lambda (id) (not (bound-identifier-mapping-get bindings id (lambda () #f)))) free))] [(case-lambda [formals expr ...] ...) (merge (map free-vars (syntax->list #'((lambda formals expr ...) ...))))] [(let-values ([(id ...) rhs] ...) expr ...) (merge (cons (free-vars #'(lambda (id ... ...) expr ...)) (map free-vars (syntax->list #'(rhs ...)))))] [(letrec-values ([(id ...) rhs] ...) expr ...) (free-vars #'(lambda (id ... ...) rhs ... expr ...))] [(_ expr ...) ;; if, begin, begin0, set!, #%app, #%variable-reference, with-continuation-mark (merge (map free-vars (syntax->list #'(expr ...))))] [_ (printf "~a~n~a~n~a~n" e #'#%datum (syntax-object->datum e)) (error "bad syntax")])) )
false
d5c48dd106fac099fc85c11484334f5c02e1bade
928e706795455cddbacba32cf039aa04e1576963
/compiler/tests/p03_syntax2scheme.test.sld
2ab242ec3da56077c99fe7e19a18eb54c71a2ea2
[ "MIT" ]
permissive
zaoqi-clone/loki
a26931aa773df35601099e59695a145a8cacf66c
a0edd3933a1d845d712b977a47504c8751a6201f
refs/heads/master
2020-07-01T21:52:28.446404
2019-08-08T02:31:46
2019-08-08T02:31:46
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,346
sld
p03_syntax2scheme.test.sld
(define-library (p03_syntax2scheme.test) (import (scheme base)) (import (scheme write)) (import (unit)) (import (shared)) (import (util)) (import (srfi 159)) (import (p02_attrs)) (import (p03_syntax2scheme)) (export test_p03_syntax2scheme) (begin (define (compile scheme) (p03_syntax2scheme (p02_attrs (scheme->mock-syntax scheme)))) (define (test-compile actual expected) (let ((out (compile actual))) (test-equal (show #f expected) expected out))) (define (test_p03_syntax2scheme) (test-group "p03_syntax2scheme" (test-compile 1 1) (test-compile #t #t) (test-compile '(begin (define test (lambda () 123)) (test)) `(begin (define ,(make-variable '$v1_test) (lambda () 123)) (,(make-variable '$v1_test)))) (test-compile '(begin (define define (lambda () 123)) (define)) `(begin (define ,(make-variable '$v1_define) (lambda () 123)) (,(make-variable '$v1_define)))) (test-compile '(begin (define a (lambda () 123)) (define b (lambda () 123)) (set! a 456) (set! b 456) (a b)) `(begin (define ,(make-variable '$v1_a) (lambda () 123)) (define ,(make-variable '$v2_b) (lambda () 123)) (set! ,(make-variable '$v1_a) 456) (set! ,(make-variable '$v2_b) 456) (,(make-variable '$v1_a) ,(make-variable '$v2_b)))) (test-compile '(begin (define test (lambda (xyz) (set! test 456) ($$prim$add xyz test))) (test 123)) `(begin (define ,(make-variable '$v1_test) (lambda (,(make-variable '$v2_xyz)) (set! ,(make-variable '$v1_test) 456) (,(make-intrinsic '$$prim$add) ,(make-variable '$v2_xyz) ,(make-variable '$v1_test)))) (,(make-variable '$v1_test) 123))) )) ))
false
098ae7bac7f4080e9632ffc54ba43bf17869ba54
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/srfi/160/uvector.scm
36f74512fb3772bb9681680a14cb946e5db889cc
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
10,053
scm
uvector.scm
(define (vector-empty? vec) (zero? (uvector-length vec))) (define (vector= . vecs) (let lp1 ((ls vecs)) (or (null? ls) (null? (cdr ls)) (let* ((v1 (car ls)) (v2 (cadr ls)) (len (uvector-length v1))) (and (= len (uvector-length v2)) (let lp2 ((i 0)) (or (>= i len) (and (= (uvector-ref v1 i) (uvector-ref v2 i)) (lp2 (+ i 1))))) (lp1 (cdr ls))))))) (define (reverse-list->uvector ls) (list->uvector (reverse ls))) (define (uvector-unfold f len seed) (let ((res (make-uvector len))) (let lp ((i 0) (seed seed)) (if (>= i len) res (call-with-values (lambda () (f i seed)) (lambda (x seed) (uvector-set! res i x) (lp (+ i 1) seed))))))) (define (uvector-unfold-right f len seed) (let ((res (make-uvector len))) (let lp ((i (- len 1)) (seed seed)) (if (< i 0) res (call-with-values (lambda () (f i seed)) (lambda (x seed) (uvector-set! res i x) (lp (- i 1) seed))))))) (define (vector-copy vec . o) (let ((start (if (pair? o) (car o) 0)) (end (if (and (pair? o) (pair? (cdr o))) (cadr o) (uvector-length vec)))) (uvector-unfold (lambda (i _) (values (uvector-ref vec (+ i start)) _)) (- end start) #f))) (define (vector-reverse-copy vec . o) (let ((start (if (pair? o) (car o) 0)) (end (if (and (pair? o) (pair? (cdr o))) (cadr o) (uvector-length vec)))) (uvector-unfold (lambda (i _) (values (uvector-ref vec (- end i 1)) _)) (- end start) #f))) (define (vector-concatenate vecs) (let* ((len (apply + (map uvector-length vecs))) (res (make-uvector len))) (let lp ((ls vecs) (i 0)) (if (null? ls) res (let ((v-len (uvector-length (car ls)))) (vector-copy! res i (car ls)) (lp (cdr ls) (+ i v-len))))))) (define (vector-append . vecs) (vector-concatenate vecs)) (define (vector-append-subvectors . o) (let lp ((ls o) (vecs '())) (if (null? ls) (vector-concatenate (reverse vecs)) (lp (cdr (cddr ls)) (cons (vector-copy (car ls) (cadr ls) (car (cddr ls))) vecs))))) (define (vector-fill! vec x . o) (let ((start (if (pair? o) (car o) 0)) (end (if (and (pair? o) (pair? (cdr o))) (cadr o) (uvector-length vec)))) (let lp ((i (- end 1))) (when (>= i start) (uvector-set! vec i x) (lp (- i 1)))))) (define (vector-swap! vec i j) (let ((tmp (uvector-ref vec i))) (uvector-set! vec i (uvector-ref vec j)) (uvector-set! vec j tmp))) (define (vector-reverse! vec . o) (let lp ((left (if (pair? o) (car o) 0)) (right (- (if (and (pair? o) (pair? (cdr o))) (cadr o) (uvector-length vec)) 1))) (cond ((>= left right) (if #f #f)) (else (vector-swap! vec left right) (lp (+ left 1) (- right 1)))))) (define (vector-copy! to at from . o) (let* ((start (if (pair? o) (car o) 0)) (end (if (and (pair? o) (pair? (cdr o))) (cadr o) (uvector-length from))) (limit (min end (+ start (- (uvector-length to) at))))) (if (<= at start) (do ((i at (+ i 1)) (j start (+ j 1))) ((>= j limit)) (uvector-set! to i (uvector-ref from j))) (do ((i (+ at (- end start 1)) (- i 1)) (j (- limit 1) (- j 1))) ((< j start)) (uvector-set! to i (uvector-ref from j)))))) (define (vector-reverse-copy! to at from . o) (let ((start (if (pair? o) (car o) 0)) (end (if (and (pair? o) (pair? (cdr o))) (cadr o) (uvector-length from)))) (vector-copy! to at from start end) (vector-reverse! to at (+ at (- end start))))) (define (vector-take vec n) (vector-copy vec 0 n)) (define (vector-take-right vec n) (vector-copy vec (- (uvector-length vec) n))) (define (vector-drop vec n) (vector-copy vec n)) (define (vector-drop-right vec n) (vector-copy vec 0 (- (uvector-length vec) n))) (define (vector-segment vec n) (let ((len (uvector-length vec))) (let lp ((i 0) (res '())) (if (>= i len) (reverse res) (lp (+ i n) (cons (vector-copy vec i (min (+ i n) len)) res)))))) (define (vector-fold kons knil vec1 . o) (let ((len (uvector-length vec1))) (if (null? o) (let lp ((i 0) (acc knil)) (if (>= i len) acc (lp (+ i 1) (kons acc (uvector-ref vec1 i))))) (let lp ((i 0) (acc knil)) (if (>= i len) acc (lp (+ i 1) (apply kons acc (uvector-ref vec1 i) (map (lambda (v) (uvector-ref v i)) o)))))))) (define (vector-fold-right kons knil vec1 . o) (let ((len (uvector-length vec1))) (if (null? o) (let lp ((i (- len 1)) (acc knil)) (if (negative? i) acc (lp (- i 1) (kons acc (uvector-ref vec1 i))))) (let lp ((i (- len 1)) (acc knil)) (if (negative? i) acc (lp (- i 1) (apply kons acc (uvector-ref vec1 i) (map (lambda (v) (uvector-ref v i)) o)))))))) (define (vector-map! f vec1 . o) (apply vector-fold (lambda (i . o) (uvector-set! vec1 i (apply f o)) (+ i 1)) 0 vec1 o)) (define (vector-map f vec1 . o) (let ((res (vector-copy vec1))) (apply vector-map! f res o) res)) (define (vector-for-each f vec1 . o) (apply vector-fold (lambda (acc . o) (apply f o) acc) (if #f #f) vec1 o)) (define (vector-count f vec1 . o) (apply vector-fold (lambda (sum . o) (+ sum (if (apply f o) 1 0))) 0 vec1 o)) (define (vector-cumulate f knil vec) (let* ((len (uvector-length vec)) (res (make-uvector len))) (let lp ((i 0) (acc knil)) (if (>= i len) res (let ((acc (f acc (uvector-ref vec i)))) (uvector-set! res i acc) (lp (+ i 1) acc)))))) (define (vector-index pred vec) (let ((len (uvector-length vec))) (let lp ((i 0)) (cond ((>= i len) #f) ((pred (uvector-ref vec i)) i) (else (lp (+ i 1))))))) (define (vector-index-right pred vec) (let lp ((i (- (uvector-length vec) 1))) (cond ((negative? i) #f) ((pred (uvector-ref vec i)) i) (else (lp (- i 1)))))) (define (vector-skip pred vec) (vector-index (lambda (x) (not (pred x))) vec)) (define (vector-skip-right pred vec) (vector-index-right (lambda (x) (not (pred x))) vec)) (define (vector-take-while vec pred) (vector-copy vec 0 (or (vector-skip pred vec) (uvector-length vec)))) (define (vector-take-while-right vec pred) (vector-copy vec (or (vector-skip-right pred vec) 0))) (define (vector-drop-while vec pred) (vector-copy vec (or (vector-index pred vec) 0))) (define (vector-drop-while-right vec pred) (vector-copy vec 0 (or (vector-index-right pred vec) (uvector-length vec)))) (define (vector-binary-search vec value cmp) (let lp ((lo 0) (hi (- (uvector-length vec) 1))) (and (<= lo hi) (let* ((mid (quotient (+ lo hi) 2)) (x (uvector-ref vec mid)) (y (cmp value x))) (cond ((< y 0) (lp lo (- mid 1))) ((> y 0) (lp (+ mid 1) hi)) (else mid)))))) (define (vector-any pred? vec1 . o) (let ((len (apply min (uvector-length vec1) (map uvector-length o)))) (let lp ((i 0)) (and (< i len) (or (apply pred? (uvector-ref vec1 i) (map (lambda (v) (uvector-ref v i)) o)) (lp (+ i 1))))))) (define (vector-every pred? vec1 . o) (let ((len (apply min (uvector-length vec1) (map uvector-length o)))) (let lp ((i 0)) (let ((x (apply pred? (uvector-ref vec1 i) (map (lambda (v) (uvector-ref v i)) o)))) (if (= i (- len 1)) x (and x (lp (+ i 1)))))))) (define (vector-partition pred? vec) (let* ((len (uvector-length vec)) (res (make-uvector len))) (let lp ((i 0) (left 0) (right (- len 1))) (cond ((= i len) (if (< left len) (vector-reverse! res left)) (values res left)) (else (let ((x (uvector-ref vec i))) (cond ((pred? x) (uvector-set! res left x) (lp (+ i 1) (+ left 1) right)) (else (uvector-set! res right x) (lp (+ i 1) left (- right 1)))))))))) (define (vector-filter pred vec) (list->uvector (reverse (vector-fold (lambda (ls elt) (if (pred elt) (cons elt ls) ls)) '() vec)))) (define (vector-remove pred vec) (vector-filter (lambda (x) (not (pred x))) vec)) (define (reverse-vector->list vec . o) (let ((vec (if (pair? o) (apply vector-copy vec o) vec))) (vector-fold (lambda (ls x) (cons x ls)) '() vec))) (define (reverse-list->vector ls) (list->uvector (reverse ls))) (define (uvector->vector vec . o) (list->vector (apply uvector->list vec o))) (define (vector->uvector vec . o) (list->uvector (apply vector->list vec o))) (define make-vector-generator (let ((eof (read-char (open-input-string "")))) (lambda (vec) (let ((i 0) (len (uvector-length vec))) (lambda () (if (>= i len) eof (let ((res (uvector-ref vec i))) (set! i (+ i 1)) res))))))) (define write-vector write)
false
9add8c30280f117fc2df9e6032088b64365dc6f6
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/net/mail/smtp-exception.sls
4c1838dc5c19f026b6828d85c62c872ccb2e45f7
[]
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
909
sls
smtp-exception.sls
(library (system net mail smtp-exception) (export new is? smtp-exception? get-object-data status-code-get status-code-set! status-code-update!) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Net.Mail.SmtpException a ...))))) (define (is? a) (clr-is System.Net.Mail.SmtpException a)) (define (smtp-exception? a) (clr-is System.Net.Mail.SmtpException a)) (define-method-port get-object-data System.Net.Mail.SmtpException GetObjectData (System.Void System.Runtime.Serialization.SerializationInfo System.Runtime.Serialization.StreamingContext)) (define-field-port status-code-get status-code-set! status-code-update! (property:) System.Net.Mail.SmtpException StatusCode System.Net.Mail.SmtpStatusCode))
true
9c809d4cc06f103d9bf59fa8b10df700849fcaa3
0bb7631745a274104b084f6684671c3ee9a7b804
/tests/unit-tests/01-fixnum/fxfirst_set_bit.scm
acca96b1ec40bafe2cfdd521de5ad9edf2dcdbac
[ "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
623
scm
fxfirst_set_bit.scm
(include "#.scm") (check-eqv? (##fxfirst-set-bit 1) 0) (check-eqv? (##fxfirst-set-bit 100) 2) (check-eqv? (##fxfirst-set-bit -1000) 3) (check-eqv? (fxfirst-set-bit 1) 0) (check-eqv? (fxfirst-set-bit 100) 2) (check-eqv? (fxfirst-set-bit -1000) 3) (check-tail-exn type-exception? (lambda () (fxfirst-set-bit 0.0))) (check-tail-exn type-exception? (lambda () (fxfirst-set-bit 0.5))) (check-tail-exn type-exception? (lambda () (fxfirst-set-bit 1/2))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (fxfirst-set-bit))) (check-tail-exn wrong-number-of-arguments-exception? (lambda () (fxfirst-set-bit 1 1)))
false
571d33ce070165e73d3c7e96befed61c59f31c36
2c01a6143d8630044e3629f2ca8adf1455f25801
/scheme-tools/implementation-specific.ss
6b1b54cdc5bfaa5df51fd2bf9d7b368ec53b7f68
[]
no_license
stuhlmueller/scheme-tools
e103fac13cfcb6d45e54e4f27e409adbc0125fe1
6e82e873d29b34b0de69b768c5a0317446867b3c
refs/heads/master
2021-01-25T10:06:33.054510
2017-05-09T19:44:12
2017-05-09T19:44:12
1,092,490
5
1
null
null
null
null
UTF-8
Scheme
false
false
533
ss
implementation-specific.ss
#!r6rs (library (scheme-tools implementation-specific) (export add1 sub1 assert command-line-arguments console-input-port environment eval exact->inexact format fprintf gensym inexact->exact interaction-environment make-parameter modulo parameterize pretty-print system time void) (import (scheme-tools implementation-specific general)) )
false
eacddc0b3ec30ff206bc939386583ebac53aac12
7b0df9640ae1b8e1172f0f90c5428b0802df8ed6
/rest-player.scm
b650803ddc76a995e368ac1cd64cab8bbf126b13
[]
no_license
erosness/sm-server
5954edfc441e773c605d2ac66df60bb983be01a3
cc302551e19f6d2b889a41ec28801004b0b28446
refs/heads/master
2020-08-31T13:23:03.670076
2016-02-18T19:10:55
2016-02-18T19:10:55
218,699,588
0
0
null
null
null
null
UTF-8
Scheme
false
false
11,016
scm
rest-player.scm
(module rest-player (player-seek-thread spotify-monitor-thread *pq*) (import chicken scheme data-structures) (import player rest ;; <-- (rest-server-port) playqueue) (use test restlib clojurian-syntax ports srfi-18 extras posix srfi-1 srfi-13 medea matchable) (import notify incubator) (define *pq* (make-pq)) (define ((change-callback path) oldval newval) (send-notification path newval)) (pq-add-current-change-listener *pq* (change-callback "/v1/player/current")) ;; alist of position, duration, paused etc (or '() if nothing is ;; playing) (define (player-pos-info) (if (player-pos) ;; <- active cplay? `((pos . ,(player-pos)) (duration . ,(player-duration)) (paused . ,(player-paused?))) '())) (define (player-information #!optional (current (pq-current *pq*))) (alist-merge current (player-pos-info) `((loop . ,(pq-loop? *pq*))))) ;; Manipulate current track. ;; POST: Looks for three keys; turi, paused, pos. ;; If turi is present adds this item to pq and starts playing. ;; If paused is present, toggles pause state ;; If pos is present, seek to that position ;; If loop is present, toggles loop state of pq ;; Returns: new value of current ;; GET: returns value of current with updated pos. (define-handler /v1/player/current (lambda () (if (current-json) (let* ((json-request (current-json)) (existing (pq-ref *pq* json-request)) (current (pq-current *pq*))) ;; Change track? (if (or (alist-ref 'turi json-request) (alist-ref 'id json-request)) (let ((queue-item (or existing (pq-add *pq* json-request)))) (pq-play *pq* queue-item #f) (set! current queue-item))) ;; Change pos? (and-let* ((pos (assoc 'pos json-request))) (player-seek (cdr pos))) ;; Change paused? (and-let* ((pause (assoc 'paused json-request))) (if (cdr pause) (player-pause) (player-unpause))) ;; Change loop? (and-let* ((loop (assoc 'loop json-request))) (pq-loop?-set! *pq* (cdr loop))) ;; Set and NOTIFY new current value (let ((new-current (player-information (alist-merge current json-request)))) (pq-current-set! *pq* new-current) new-current)) ;;else (player-information)))) ;; Adds an item to the back of the playqueue ;; Returns: the passed in item with a unique id added (define-handler /v1/player/pq/add (lambda () (let* ((json (current-json)) ;; either add a single track or a list of tracks (jsonlist (vector->list (if (vector? json) json (vector json))))) (list->vector (pq-add-list *pq* ;; HACK: delete loop cause it belongs ;; to pq's not tracks. see #99. (map (cut alist-delete 'loop <>) jsonlist)))))) ;; Removes and item referenced by id from the playqueue ;; Does nothing if id is not found in playqueue (define-handler /v1/player/pq/del (lambda () (and-let* ((json (current-json)) ((alist-ref 'id json))) (pq-del *pq* json) `((status . "ok"))))) ;; Removes every item from the playqueue and stops the player (define-handler /v1/player/pq/clear (lambda () (pq-clear *pq*) (player-quit) `((status . "ok")))) ;; Returns the playqueue (define-handler /v1/player/pq (lambda () (list->vector (pq-list *pq*)))) (define-handler /v1/player/next (lambda () (pq-play-next *pq* #t) (player-information))) (define-handler /v1/player/prev (lambda () (pq-play-prev *pq*) (player-information))) ;; ==================== seek position hearbeat ==================== (import notify) (use looper medea) ;; do this on every player hearbeat interval (define (player-thread-iteration) (if (playing?) ;; running and not paused? (send-notification "/v1/player/pos" (player-pos-info)))) (define player-seek-thread (thread-start! (make-thread (->> (lambda () (player-thread-iteration)) (loop/interval 1) (loop/exceptions (lambda (e) (pp `(error: ,(current-thread) ,(condition->list e))) #t)) (loop)) "player-seek-thread"))) ;; (thread-terminate! player-thread) ;; (thread-state player-thread) ;; don't block while reading anything from port p. port p must have an ;; associated filedescriptor. (define (make-nonblocking-input-port p) (make-input-port (lambda () (thread-wait-for-i/o! (port->fileno p)) (read-char p)) (lambda () (char-ready? p)) (lambda () (close-input-port p)))) (define (playing&active? event) (and (alist-ref 'playing? event) (alist-ref 'active? event))) ;; send a pretend-current notification to our apps. should keep ;; player-pane in sync with what Spotify is doing. (define (spotify-notification event) (pq-current-set! *pq* `((title . ,(alist-ref 'track event)) (subtitle . ,(alist-ref 'artist event)) (image . ,(alist-ref 'image event)) (type . "spotify") (pos . 0) (duration . ,(* 0.001 (alist-ref 'duration_ms event))) (paused . ,(not (playing&active? event)))))) (define (run-monitor-thread name body #!optional (interval 1)) (thread-start! (->> body (loop/interval 1) (loop/exceptions (lambda (e) (pp `(,(current-thread),(condition->list e))) (thread-sleep! 10) #t)) ; <-- keep going (loop) ((flip make-thread) name)))) ;; watch if spotify is playing. if it is, we pause our own cplay and ;; we "sneak" spotify album-cover art and player state in there using ;; spotify-notification. (begin (handle-exceptions e (void) (thread-terminate! spotify-monitor-thread)) (define spotify-monitor-thread (run-monitor-thread "spotify-monitor" (lambda () (let ((event (call-with-input-pipe "spotifyctl 7879 event" (o read make-nonblocking-input-port)))) (pp `(info ,(current-thread) event ,event)) (if (eof-object? event) (thread-sleep! 10) (when (playing&active? event) (player-pause) (spotify-notification event)))))))) ;; Read and broadcast DAB dynamic label if dab is running ;; Note that the dynamic label is only broadcasted through the notify ;; socket, you won't get it from (begin (use dab) (handle-exceptions e (void) (thread-terminate! dab/fm-notifier)) (define dab/fm-notifier (run-monitor-thread "dab/fm-notifier" (lambda () (and-let* (((pq-current *pq*)) (subtitle (match (alist-ref 'type (pq-current *pq*)) ("dab" (dab-dls)) ("fm" (fm-radio-text)) (else #f))) (content (alist-merge (player-information) `((subtitle . ,subtitle))))) (send-notification "/v1/player/current" content)) #t) ; <-- keep going ))) ;; ==================== BT NOTIFIER ==================== ;; ;; we get one line per item-notification from the BT agent. it ;; typically send this across the UART: ;; ;; IND:-A1Happiness ;; IND:-A2Jónsi & Alex ;; IND:-A3Riceboy Sleeps ;; IND:-A7561000ms ;; ;; these are our BT UART assumptions: ;; ;; 1. we don't know that the order is the same ;; 2. we don't know the timings of each line ;; 3. we don't expect a lot of lines coming in from the BT module ;; ;; wanting to be as robust as possible, we read line by line and pick ;; up song/artist/album into a state (like bt-notifier-artist). on ;; each line we update our state, and send the aggregated state to our ;; client because: ;; ;; the clients have a limitation: sending notifications with only ;; title and no subtitle, for example, will clear the subtitle field ;; in the display - so we can't send title alone. ;; ;; step 3 above means it should be safe to send one notify! on each ;; line (there are few of them and only when user changes ;; song/connects/disconnects. ;; ;; we also merge in the current (player-information) in the ;; notification, this prevents us from losing the static fields, most ;; noticeably 'image' and 'type' in the ui. ;; ;; parse lines like: ;; (IND-decompose "IND:-A1The Ludlows") ;; (IND-decompose "IND:-A2James Horner") ;; (IND-decompose "IND:-A3Legends Of The Fall Original Motion Picture Soundtrack") (define (IND-decompose line) ;; check for prefix and return the rest of the string if match (define (prefix str) (and (string-prefix? str line) (string-drop line (string-length str)))) (define ((labeler key) value) (list key value)) (cond ((prefix "IND:-A1") => (labeler 'song)) ((prefix "IND:-A2") => (labeler 'artist)) ((prefix "IND:-A3") => (labeler 'album)))) ;; aggregated bt-notifier state (define bt-notifier-artist #f) (define bt-notifier-album #f) (define bt-notifier-song #f) ;; update bt-notifier state ;; (IND-process! "IND:-A1PRefs Paradise") (define (IND-process! line) (match (IND-decompose line) (('song name) (set! bt-notifier-song name)) (('artist name) (set! bt-notifier-artist name)) (('album name) (set! bt-notifier-album name)) (else #f))) ;; use bt-notifier-* state and broadcast to clients (define (notify!) (let ((msg (alist-merge (player-information) `((title . ,(or bt-notifier-album "Bluetooth")) (subtitle . ,(or bt-notifier-song "")))))) (send-notification "/v1/player/current" msg))) (import process-cli) ;; TODO: dependency-graph is getting messy (define bt-port (open-input-file*/nonblock (file-open "/dev/ttymxc3" open/read))) (define (bt-notifier-iteration) (let ((line (read-line bt-port))) (IND-process! line) ;; update global vars (if (equal? "bt" (alist-ref 'type (pq-current *pq*))) (notify!)) (display (conc "bt-notifier: line " (with-output-to-string (cut write line))) (current-error-port)))) (begin (handle-exceptions e (void) (thread-terminate! bt-notifier)) (define bt-notifier (thread-start! (->> (lambda () (bt-notifier-iteration)) (loop/interval 1) (loop/exceptions (lambda (e) (pp `(error: ,(current-thread) ,(condition->list e))) #t)) (loop))))) )
false
31057bd99bae80fa195bda8e286dafb0e11c422b
08057c5b17633618982cdd1b4841f3fbc1ecacf5
/gauche-magic/index.scm
a360bc04d32ef64bb5367dc184828dbeedd60879
[ "BSD-2-Clause" ]
permissive
tabe/Gauche-magic
2e42e50dcac2b3ce0f3ad781bf81096257599040
09d5fa48939880c50bcbe2b697276943826c59ed
refs/heads/master
2020-04-08T19:24:35.348298
2008-07-17T01:34:17
2008-07-17T01:34:17
159,654,064
0
0
null
null
null
null
EUC-JP
Scheme
false
false
3,621
scm
index.scm
#!/usr/bin/env gosh (use file.util) (use fixedpoint.site) (use text.html-lite) (use text.tree) (// (magic "ftp://ftp.astron.com/pub/file/") (File::Type "http://search.cpan.org/~pmison/File-Type-0.22/lib/File/Type.pm") (File::MimeInfo::Magic "http://search.cpan.org/~pardus/File-MimeInfo-0.13/MimeInfo/Magic.pm") (Fileinfo "http://pecl.php.net/package/fileinfo") ) (define *last-update* "Wed Dec 06 2006") (define *gauche-magic-version* (file->string "../VERSION")) (define *gauche-magic-tarball-basename* (string-append "Gauche-magic-" *gauche-magic-version* ".tgz")) (define *gauche-magic-tarball-size* (file-size (string-append "../../" *gauche-magic-tarball-basename*))) (define *gauche-magic-tarball-url* *gauche-magic-tarball-basename*) (define (index lang) (let-syntax ((en/ja (syntax-rules () ((_ en ja) (if (string=? "en" lang) en ja))))) ((fixedpoint:frame "Gauche-magic") (html:p :id "lang_navi" (html:a :href (en/ja "index.html" "index.en.html") "[" (en/ja "Japanese" "English") "]")) (html:p :id "last_update" "Last update: " *last-update*) (html:p (html:dfn /Gauche-magic/) (en/ja (list " is an extension package of " /Gauche/ " which provides a binding of the " /magic/ " library.") (list " は " /Scheme/ " 処理系 " /Gauche/ " で " /magic/ " ライブラリを利用するための拡張パッケージです。"))) (html:h2 :style "border-bottom: 1px solid #bbbbbb;" (en/ja "News" "最新情報")) (html:ul (html:li "[2006-12-06] " (en/ja "Release 0.1.0." "バージョン 0.1.0 を公開しました。"))) (html:h2 :style "border-bottom: 1px solid #bbbbbb;" (en/ja "Features" "特徴")) (html:ul (html:li (en/ja "Getting the description of a given file with a magic database." "マジックデータベースを用いたファイル情報の取得。")) (html:li (en/ja "Checking and compiling a magic database." "マジックデータベースの整合性チェックとコンパイル。"))) (html:h2 :style "border-bottom: 1px solid #bbbbbb;" (en/ja "Requirements" "導入")) (html:p (en/ja "This package is for Gauche 0.8.7 or later." "このパッケージは Gauche 0.8.7 またはそれ以上で動作します。")) (html:ul (html:li (en/ja (list "It requires the " /magic/ " library (file-4.12 or higher) which has been installed.") (list "また別途 " /magic/ " ライブラリ(file バージョン 4.12 以上)がインストールされている必要があります。")))) (html:h2 :style "border-bottom: 1px solid #bbbbbb;" (en/ja "Download" "ダウンロード")) (html:p (html:a :href *gauche-magic-tarball-url* *gauche-magic-tarball-basename* " (" *gauche-magic-tarball-size* " bytes)")) (html:h2 :style "border-bottom: 1px solid #bbbbbb;" (en/ja "Documents" "文書")) (html:ul (html:li (html:a :href (en/ja "reference.en.html" "reference.ja.html") "Gauche-magic " (en/ja "Reference Manual" "リファレンスマニュアル")))) (html:h2 :style "border-bottom: 1px solid #bbbbbb;" (en/ja "Links" "リンク")) (html:ul (html:li /magic/) (html:li /File::Type/) (html:li /File::MimeInfo::Magic/) (html:li /Fileinfo/) (html:li (html:a :href (en/ja "http://httpd.apache.org/docs/2.2/en/mod/mod_mime_magic.html" "http://httpd.apache.org/docs/2.2/ja/mod/mod_mime_magic.html") "mod_mime_magic")) ) ))) (define (main args) (define (usage) (format (current-error-port) "usage: gosh ~a (en|ja)\n" *program-name*) (exit 1)) (when (< (length args) 2) (usage)) (write-tree (index (cadr args))) 0)
false
c7ae0b88c42bec0d9d42de34622852a97a67dcb7
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/zcomp/base/queue.scm
ea29e49c426e0e8062f60b7a7526726f31cf2e65
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
2,276
scm
queue.scm
#| -*-Scheme-*- $Header: queue.scm,v 1.2 88/08/31 10:36:49 jinx Exp $ $MIT-Header: queue.scm,v 1.1 87/03/19 00:44:32 GMT cph Exp $ Copyright (c) 1987 Massachusetts Institute of Technology This material was developed by the Scheme project at the Massachusetts Institute of Technology, Department of Electrical Engineering and Computer Science. Permission to copy this software, to redistribute it, and to use it for any purpose is granted, subject to the following restrictions and understandings. 1. Any copy made of this software must include this copyright notice in full. 2. Users of this software agree to make their best efforts (a) to return to the MIT Scheme project any improvements or extensions that they make, so that these may be included in future releases; and (b) to inform MIT of noteworthy uses of this software. 3. All materials developed as a consequence of the use of this software shall duly acknowledge such use, in accordance with the usual standards of acknowledging credit in academic research. 4. MIT has made no warrantee or representation that the operation of this software will be error-free, and MIT is under no obligation to provide any services, by way of maintenance, update, or otherwise. 5. In conjunction with products arising from the use of this material, there shall be no use of the name of the Massachusetts Institute of Technology nor of any adaptation thereof in any advertising, promotional, or sales literature without prior written consent from MIT in each case. |# ;;;; Simple Queue Abstraction (declare (usual-integrations)) (define (make-queue) (cons '() '())) (define-integrable (queue-empty? queue) (null? (car queue))) (define-integrable (queued? queue item) (memq item (car queue))) (define (enqueue! queue object) (let ((next (cons object '()))) (if (null? (cdr queue)) (set-car! queue next) (set-cdr! (cdr queue) next)) (set-cdr! queue next))) (define (dequeue! queue) (let ((next (car queue))) (if (null? (cdr next)) (begin (set-car! queue '()) (set-cdr! queue '())) (set-car! queue (cdr next))) (car next))) (define (queue-map! queue procedure) (define (loop) (if (not (queue-empty? queue)) (begin (procedure (dequeue! queue)) (loop)))) (loop))
false
6e76f20377ca225b53ddc7090453c508ef98e5ed
1c7b5b39d41b63322f16979b01492dfb162122e7
/lib/elegant-weapons/tester.scm
057b42349be05c26fae22f9dd41ef599f25984c4
[ "BSD-3-Clause-Open-MPI" ]
permissive
david135/elegant-weapons
83b144531959c1fea88e02735c2796eeb538eb7c
ce51432c614cdba5d2f12c7b5451af01095257a4
refs/heads/master
2021-01-22T16:13:42.004079
2015-11-03T21:53:29
2015-11-03T21:53:29
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,011
scm
tester.scm
(library (elegant-weapons tester) (export run-tests define-test-suite) (import (rnrs) (elegant-weapons compat)) (define tests (make-parameter '())) (define (register-test name test) (display "registering ") (display name) (newline) (tests (append (tests) (list (cons name test))))) (define-syntax define-test-suite (syntax-rules () ((_ suite-name (name test) ...) (define suite-name (let ((tests `((name . ,test) ...))) (lambda () (run-suite 'suite-name tests))))))) (define run-suite (lambda (name tests) (display "Running tests for ") (display name) (newline) (let loop ((tests tests) (successes 0) (failures 0)) (if (pair? tests) (call/cc (lambda (k) (let ((name (caar tests)) (test (cdar tests))) (display " Running test ") (display name) (display "...") (test (lambda () (display "failed") (newline) (k (loop (cdr tests) successes (+ 1 failures))))) (display "success") (newline) (loop (cdr tests) (+ 1 successes) failures)))) (values successes failures))))) (define run-tests (lambda suites (let loop ((suites suites) (successes 0) (failures 0)) (if (pair? suites) (let-values (((s f) ((car suites)))) (loop (cdr suites) (+ successes s) (+ failures f))) (begin (display "All tests completed.") (newline) (display successes) (display " successes, ") (display failures) (display " failures") (newline) (if (> failures 0) (error 'run-tests "Some tests failed"))))))) )
true
e125737f79053fa1a0ba1a878369d3d703997de1
f916d100a0510989b96deaa9d2d2f90d86ecc399
/slib/batch.scm
e797df63c797746c9dd0989c92418923f9bd03a2
[]
no_license
jjliang/UMB-Scheme
12fd3c08c420715812f933e873110e103236ca67
d8479f2f2eb262b94be6040be5bd4e0fca073a4f
refs/heads/master
2021-01-20T11:19:37.800439
2012-09-27T22:13:50
2012-09-27T22:13:50
5,984,440
2
0
null
null
null
null
UTF-8
Scheme
false
false
12,113
scm
batch.scm
;;; "batch.scm" Group and execute commands on various systems. ;Copyright (C) 1994, 1995 Aubrey Jaffer ; ;Permission to copy this software, to redistribute it, and to use it ;for any purpose is granted, subject to the following restrictions and ;understandings. ; ;1. Any copy made of this software must include this copyright notice ;in full. ; ;2. I have made no warrantee or representation that the operation of ;this software will be error-free, and I am under no obligation to ;provide any services, by way of maintenance, update, or otherwise. ; ;3. In conjunction with products arising from the use of this ;material, there shall be no use of my name in any advertising, ;promotional, or sales literature without prior written consent in ;each case. (require 'line-i/o) ;Just for write-line (require 'parameters) (require 'database-utilities) ;;(define (batch parms op . args) ??) (define (batch:port parms) (car (parameter-list-ref parms 'batch-port))) (define (batch:dialect parms) ; was batch-family (car (parameter-list-ref parms 'batch-dialect))) (define (batch:line-length-limit parms) (let ((bl (parameter-list-ref parms 'batch-line-length-limit))) (cond (bl (car bl)) (else (case (batch:dialect parms) ((unix) 1024) ((dos) 128) ((vms) 1024) ((system) 1024) ((*unknown*) -1)))))) (define (batch-line parms str) (let ((bp (parameter-list-ref parms 'batch-port)) (ln (batch:line-length-limit parms))) (cond ((not bp) (slib:error 'batch-line "missing batch-port parameter" parms)) ((>= (string-length str) ln) #f) (else (write-line str (car bp)) #t)))) ;;; add a Scheme batch-dialect? (define (batch:system parms . strings) (define port (batch:port parms)) (set! strings (batch:flatten strings)) (case (batch:dialect parms) ((unix) (batch-line parms (apply string-join " " strings))) ((dos) (batch-line parms (apply string-join " " strings))) ((vms) (batch-line parms (apply string-join " " "$" strings))) ((system) (write `(system ,(apply string-join " " strings)) port) (newline port) (system (apply string-join " " strings))) ((*unknown*) (write `(system ,(apply string-join " " strings)) port) (newline port) #f))) (define (batch:run-script parms . strings) (case (batch:dialect parms strings) ((unix) (batch:system parms strings name)) ((dos) (batch:system parms strings name)) ((vms) (batch:system parms (cons #\@ strings))) ((system) (batch:system parms strings name)) ((*unknown*) (batch:system parms strings name) #f))) (define (batch:comment parms . lines) (define port (batch:port parms)) (set! lines (batch:flatten lines)) (case (batch:dialect parms) ((unix) (every (lambda (line) (batch-line parms (string-append "# " line))) lines)) ((dos) (every (lambda (line) (batch-line parms (string-append "rem" (if (equal? " " line) ".") line))) lines)) ((vms) (every (lambda (line) (batch-line parms (string-append "$! " line))) lines)) ((system) (every (lambda (line) (batch-line parms (string-append "; " line))) lines)) ((*unknown*) (for-each (lambda (line) (batch-line parms (string-append ";;; " line)) (newline port)) lines) #f))) (define (batch:lines->file parms file . lines) (define port (batch:port parms)) (set! lines (batch:flatten lines)) (case (batch:dialect parms) ((unix) (batch-line parms (string-append "rm -f " file)) (every (lambda (string) (batch-line parms (string-append "echo '" string "'>>" file))) lines)) ((dos) (batch-line parms (string-append "DEL " file)) (every (lambda (string) (batch-line parms (string-append "ECHO" (if (equal? "" string) "." " ") string ">>" file))) lines)) ((vms) (and (batch-line parms (string-append "$DELETE " file)) (batch-line parms (string-append "$CREATE " file)) (batch-line parms (string-append "$DECK")) (every (lambda (string) (batch-line parms string)) lines) (batch-line parms (string-append "$EOD")))) ((system) (write `(delete-file ,file) port) (newline port) (delete-file file) (pretty-print `(call-with-output-file ,file (lambda (fp) (for-each (lambda (string) (write-line string fp)) ',lines))) port) (call-with-output-file file (lambda (fp) (for-each (lambda (string) (write-line string fp)) lines))) #t) ((*unknown*) (write `(delete-file ,file) port) (newline port) (pretty-print `(call-with-output-file ,file (lambda (fp) (for-each (lambda (string) (write-line string fp)) ,lines))) port) #f))) (define (batch:delete-file parms file) (define port (batch:port parms)) (case (batch:dialect parms) ((unix) (batch-line parms (string-append "rm -f " file)) #t) ((dos) (batch-line parms (string-append "DEL " file)) #t) ((vms) (batch-line parms (string-append "$DELETE " file)) #t) ((system) (write `(delete-file ,file) port) (newline port) (delete-file file)) ; SLIB provides ((*unknown*) (write `(delete-file ,file) port) (newline port) #f))) (define (batch:rename-file parms old-name new-name) (define port (batch:port parms)) (case (batch:dialect parms) ((unix) (batch-line parms (string-join " " "mv -f" old-name new-name))) ((dos) (batch-line parms (string-join " " "MOVE" "/Y" old-name new-name))) ((vms) (batch-line parms (string-join " " "$RENAME" old-name new-name))) ((system) (batch:extender 'rename-file batch:rename-file)) ((*unknown*) (write `(rename-file ,old-name ,new-name) port) (newline port) #f))) (define (batch:call-with-output-script parms name proc) (case (batch:dialect parms) ((unix) ((cond ((string? name) (lambda (proc) (let ((ans (call-with-output-file name proc))) (system (string-append "chmod +x " name)) ans))) ((output-port? name) (lambda (proc) (proc name))) (else (lambda (proc) (proc (current-output-port))))) (lambda (port) (write-line "#!/bin/sh" port) (cond ((and (string? name) (provided? 'bignum)) (require 'posix-time) (write-line (string-append "# \"" name "\" build script created " (ctime (current-time))) port))) (proc port)))) ((dos) ((cond ((string? name) (lambda (proc) (call-with-output-file (string-append name ".bat") proc))) ((output-port? name) (lambda (proc) (proc name))) (else (lambda (proc) (proc (current-output-port))))) (lambda (port) (cond ((and (string? name) (provided? 'bignum)) (require 'posix-time) (write-line (string-append "rem " name " build script created " (ctime (current-time))) port))) (proc port)))) ((vms) ((cond ((string? name) (lambda (proc) (call-with-output-file (string-append name ".COM") proc))) ((output-port? name) (lambda (proc) (proc name))) (else (lambda (proc) (proc (current-output-port))))) (lambda (port) (cond ((and (string? name) (provided? 'bignum)) (require 'posix-time) ;;(write-line ;; "$DEFINE/USER SYS$OUTPUT BUILD.LOG" port) (write-line (string-append "$! " name " build script created " (ctime (current-time))) port))) (proc port)))) ((system) ((cond ((string? name) (lambda (proc) (let ((ans (call-with-output-file name (lambda (port) (proc name))))) (system (string-append "chmod +x " name)) ans))) ((output-port? name) (lambda (proc) (proc name))) (else (lambda (proc) (proc (current-output-port))))) (lambda (port) (cond ((and (string? name) (provided? 'bignum)) (require 'posix-time) (write-line (string-append ";;; \"" name "\" build script created " (ctime (current-time))) port))) (proc port)))) ((*unknown*) ((cond ((string? name) (lambda (proc) (let ((ans (call-with-output-file name (lambda (port) (proc name))))) (system (string-append "chmod +x " name)) ans))) ((output-port? name) (lambda (proc) (proc name))) (else (lambda (proc) (proc (current-output-port))))) (lambda (port) (cond ((and (string? name) (provided? 'bignum)) (require 'posix-time) (write-line (string-append ";;; \"" name "\" build script created " (ctime (current-time))) port))) (proc port))) #f))) ;;; This little ditty figures out how to use a Scheme extension or ;;; SYSTEM to execute a command that is not available in the batch ;;; mode chosen. (define (batch:extender NAME BATCHER) (lambda (parms . args) (define port (batch:port parms)) (cond ((provided? 'i/o-extensions) ; SCM specific (write `(,NAME ,@args) port) (newline port) (apply (slib:eval NAME) args)) (else (let ((pl (make-parameter-list (map car parms)))) (adjoin-parameters! pl (cons 'batch-dialect (os->batch-dialect (parameter-list-ref parms 'platform)))) (system (call-with-output-string (lambda (port) (batch:call-with-output-script port (lambda (batch-port) (define new-parms (copy-tree pl)) (adjoin-parameters! new-parms (list 'batch-port batch-port)) (apply BATCHER new-parms args))))))))))) (define (replace-suffix str old new) (define (cs str) (let* ((len (string-length str)) (re (- len (string-length old)))) (cond ((string-ci=? old (substring str re len)) (string-append (substring str 0 re) new)) (else (slib:error 'replace-suffix "suffix doens't match:" old str))))) (if (string? str) (cs str) (map cs str))) (define (string-join joiner . args) (if (null? args) "" (apply string-append (car args) (map (lambda (s) (string-append joiner s)) (cdr args))))) (define (batch:flatten strings) (apply append (map (lambda (obj) (cond ((eq? "" obj) '()) ((string? obj) (list obj)) ((eq? #f obj) '()) ((null? obj) '()) ((list? obj) (batch:flatten obj)) (else (slib:error 'batch:flatten "unexpected type" obj "in" strings)))) strings))) (define batch:platform (software-type)) (cond ((and (eq? 'unix batch:platform) (provided? 'system)) (let ((file-name (tmpnam))) (system (string-append "uname > " file-name)) (set! batch:platform (call-with-input-file file-name read)) (delete-file file-name)))) (define batch:database #f) (define (os->batch-dialect os) ((((batch:database 'open-table) 'operating-system #f) 'get 'os-family) os)) (define (batch:initialize! database) (set! batch:database database) (define-tables database '(batch-dialect ((family atom)) () ((unix) (dos) (vms) (system) (*unknown*))) '(operating-system ((name symbol)) ((os-family batch-dialect)) (;;(3b1 *unknown*) (acorn *unknown*) (aix unix) (alliant *unknown*) (amiga *unknown*) (apollo unix) (apple2 *unknown*) (arm *unknown*) (atari.st *unknown*) (cdc *unknown*) (celerity *unknown*) (concurrent *unknown*) (convex *unknown*) (encore *unknown*) (harris *unknown*) (hp-ux unix) (hp48 *unknown*) (isis *unknown*) (linux unix) (mac *unknown*) (masscomp unix) (ms-dos dos) (mips *unknown*) (ncr *unknown*) (newton *unknown*) (next unix) (novell *unknown*) (os/2 dos) (prime *unknown*) (psion *unknown*) (pyramid *unknown*) (sequent *unknown*) (sgi *unknown*) (stratus *unknown*) (sun-os unix) (transputer *unknown*) (unicos unix) (unix unix) (vms vms) (*unknown* *unknown*) ))) ((database 'add-domain) '(operating-system operating-system #f symbol #f)) )
false
7c7765a913d9b7e11081e9b4f963457442dc2057
923209816d56305004079b706d042d2fe5636b5a
/sitelib/http/header-field/if-unmodified-since.scm
06a76442ecfc35d688c45d7e51594a3a90a97872
[ "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
298
scm
if-unmodified-since.scm
(library (http header-field if-unmodified-since) (export If-Unmodified-Since) (import (rnrs (6)) (http abnf) (http date-time)) ;;; 14.28 If-Unmodified-Since (define If-Unmodified-Since (seq (string->rule "If-Unmodified-Since") (char->rule #\:) *LWS HTTP-date)) )
false
0e7d9f8998773e0a5c0139249b78431f6d9c558e
4fd95c081ccef6afc8845c94fedbe19699b115b6
/chapter_1/1.18.scm
e4411909460fee37e6d27dbeee35aa6ac248835b
[ "MIT" ]
permissive
ceoro9/sicp
61ff130e655e705bafb39b4d336057bd3996195d
7c0000f4ec4adc713f399dc12a0596c770bd2783
refs/heads/master
2020-05-03T09:41:04.531521
2019-08-08T12:14:35
2019-08-08T12:14:35
178,560,765
1
0
null
null
null
null
UTF-8
Scheme
false
false
354
scm
1.18.scm
(define (double x) (* 2 x)) (define (halve x) (/ x 2)) (define (even? x) (= (remainder x 2) 0)) (define (iter-fast-mul a b) (fast-mul-iter a b 0)) (define (fast-mul-iter a b r) (cond ((< b 1) r) ((even? b) (fast-mul-iter (double a) (halve b) r)) (else (fast-mul-iter a (- b 1) (+ a r))))) (display (iter-fast-mul 10 15))
false
1bd8d5b1ef607fdb66867de61a124072e7dc1601
1e3480417b4da6395370dbe77c5f7e82e807f280
/smm-macro.scm
9680eb95abb02ac526c8784566abf8de34376308
[]
no_license
joshcox/send-more-money
dc3da6eb07ab83022df2773b41a23b187ca4849b
400f053dd1eae70d52ede55eab209477d558ed9a
refs/heads/master
2021-01-18T14:34:02.984733
2014-04-19T04:00:23
2014-04-19T04:00:23
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,209
scm
smm-macro.scm
(load "mk-util.scm") (define add/carryo2 (lambda (n1 n2 cin cout o) (fresh (sum) (pluso* n1 n2 cin sum) (/o sum (build-num 10) cout o)))) (define (rem-dup x* pred?) (cond ((null? x*) '()) ((memp (lambda (x) (pred? (car x*) x)) (cdr x*)) (rem-dup (cdr x*) pred?)) (else (cons (car x*) (rem-dup (cdr x*) pred?))))) ;;a fun macro that generates word problems of the sort ;;needs some work and to be updated with the newer version ;;of smm (define-syntax word-play (lambda (x) (syntax-case x (:) ((_ () () () : (fv* ...) (c* ...) (with* ...) (w* ...) (a/c* ...)) (with-syntax ([(fv* ...) (rem-dup (syntax->list #'(fv* ...)) free-identifier=?) ]) #'(lambda (q) (fresh (fv* ...) (fresh (c* ...) (== q `(,(list fv* ...) fv* ...)) (=/=* fv* ...) (withino c* ... '() '(1)) with* ... (withino w* ... '() '(1 0 0 1)) a/c* ...))))) ((_ (l1) (l2) (l3) : (fv* ...) (c* ... c) (with* ...) (w* ...) (a/c* ...)) #'(word-play () () () : (fv* ... l1 l2 l3) (c* ... c) (with* ...) (w* ... l1 l2 l3) ((add/carryo l1 l2 '() c l3) a/c* ...))) ((_ (l1 l1* ...) (l2 l2* ...) (l3 l3* ...) : (fv* ...) (c* ... c) (with* ...) (w* ...) (a/c* ...)) #'(word-play (l1* ...) (l2* ...) (l3* ...) : (fv* ... l1 l2 l3) (c* ... c c^) (with* ...) (l1 l2 l3 w* ...) ((add/carryo l1 l2 c^ c l3) a/c* ...))) ((_ (l1 l1* ...) (l2 l2* ...) (l3 l3^ l3* ...)) #'(word-play (l1* ...) (l2* ...) (l3* ...) : (l1 l2 l3 l3^) (c) ((withino l1 l2 l3 '(1) '(1 0 0 1))) (l3^) ((add/carryo l1 l2 c l3 l3^))))))) ;NEW MACRO ROAR! ;> (define chc (word-play (c a n) (h a z) (c a s h))) ;> (run 1 (q) (chc q)) ;() ;> ; ;> (define smm (word-play (s e n d) (m o r e) (m o n e y))) ;> (run 1 (q) (smm q)) ;(((1 0 0 1) (1) () (0 1 1) (0 0 0 1) (1 1 1) (1 0 1) (0 1))) ; ;> (define a (word-play (a) (b) (c d))) ;> (run 1 (q) (a q)) ;((((1 1) (1 0 0 1) (1) (0 1)) a b c d)) ;> (run 2 (q) (a q)) ;((((1 1) (1 0 0 1) (1) (0 1)) a b c d) ; (((0 0 1) (1 0 0 1) (1) (1 1)) a b c d))
true
74eadcfb20943a93284f695dd37275039318ab10
58381f6c0b3def1720ca7a14a7c6f0f350f89537
/Chapter 2/2.5/Ex2.86.scm
c7696f09a772f6ea96c18faf074161847442783c
[]
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
1,085
scm
Ex2.86.scm
#lang planet neil/sicp ;; INSTALLATION ;; External interface for Integer package (put 'square 'integer (lambda (x) (tag (* x x)))) (put 'arctan '(integer integer) (lambda (x y) (make-real (atan x y)))) (put 'sine 'integer (lambda (x) (make-real (sin x)))) (put 'cosine 'integer (lambda (x) (make-real (cos x)))) ;; Rational number package ;; External interface for Rational package (put 'square 'rational (lambda (x) (make-real (mul-rat x x)))) (put 'arctan '(rational rational) (lambda (x y) (make-real (atan (/ (numer x) (denom x)) (/ (numer y) (denom y)))))) (put 'sine 'rational (lambda (x) (make-real (sin (/ (numer x) (denom x)))))) (put 'cosine 'rational (lambda (x) (make-real (cos (/ (numer x) (denom x)))))) ;; Real number package ;; External interface for Real package (put 'square 'complex (lambda (x) (tag (* x x)))) (put 'arctan '(real real) (lambda (x y) (tag (atan x y)))) (put 'cosine '(real) (lambda (x) (tag (cos x)))) (put 'sine '(real) (lambda (x) (tag (sin x))))
false
ed80a2f399e7494a0291ff5fce6f68fa99c5af77
7666204be35fcbc664e29fd0742a18841a7b601d
/code/4-14.scm
440775c83d3bf4f1f49b3e01c538f2d12ad6decd
[]
no_license
cosail/sicp
b8a78932e40bd1a54415e50312e911d558f893eb
3ff79fd94eda81c315a1cee0165cec3c4dbcc43c
refs/heads/master
2021-01-18T04:47:30.692237
2014-01-06T13:32:54
2014-01-06T13:32:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
370
scm
4-14.scm
; 例如 (map display (list 1 2)) ; map接受到的参数为 ; (list ; (list 'primitive {[procedure display]} ) ; (list 1 2)) ; ; scheme原生的map会把第一个参数(display)当成一个[原生函数]直接作用于后续参数,因此会出错。 ; ; 而自定义的map会再次调用 apply 来执行display函数,因此可以正常工作。
false
8fcbf7b32ae532d5d150e3df7119a564c85bf36f
378e5f5664461f1cc3031c54d243576300925b40
/rsauex/home/services/git/hooks/dont-push-wip-commits.scm
43c40a2eb76b43e8a5497b11bb38c2d7a7e74f74
[]
no_license
rsauex/dotfiles
7a787f003a768699048ffd068f7d2b53ff673e39
77e405cda4277e282725108528874b6d9ebee968
refs/heads/master
2023-08-07T17:07:40.074456
2023-07-30T12:59:48
2023-07-30T12:59:48
97,400,340
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,446
scm
dont-push-wip-commits.scm
(define-module (rsauex home services git hooks dont-push-wip-commits) #:use-module ((ice-9 format)) #:use-module ((ice-9 match)) #:use-module ((ice-9 regex)) #:use-module ((rsauex script utils)) #:use-module ((srfi srfi-1)) #:use-module ((srfi srfi-1)) #:use-module ((srfi srfi-26)) #:use-module ((srfi srfi-69)) #:export (check)) (define zero (make-string 40 #\0)) (define wip-commit-regex "^\\(WIP\\|FIXUP\\|AMEND\\|SQUASH\\)") (define (find-wip-commits-in-range range) (invoke/capture-strings "git" "rev-list" "--regexp-ignore-case" "--grep" wip-commit-regex range)) (define (check . _) (let ((wip-commits (list))) (define (add-wip-commits commits) (set! wip-commits (lset-union string=? wip-commits commits))) (for-each (lambda (line) (match (string-split line #\space) ((local-ref local-oid _ remote-oid) (unless (string=? local-oid zero) (let ((range (if (string=? remote-oid zero) local-oid (string-append remote-oid ".." local-oid)))) (add-wip-commits (find-wip-commits-in-range range))))))) (get-lines (current-input-port))) (unless (null? wip-commits) (format #t "WIP commits found:~%~{ ~a~%~}" wip-commits) (exit 1))) (exit 0))
false
46981253a527e85c025313a0a68d9fd7a7c74b3e
710bd922d612840b3dc64bd7c64d4eefe62d50f0
/scheme/tool-sdoc/package.scm
bdc0d7b2969c7b7a404e2a4a474ab5300ab82777
[ "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
211
scm
package.scm
;;; package.scm -- package definition for sdoc tool (define-structure tool-sdoc (export) (open scheme-runtime scheme-posix) (doc "Scheme source documentation tool") (files markup.scm sdoc.scm))
false
6271cb4d6116a43e67c270ae6dd3348d62f586c1
ae0d7be8827e8983c926f48a5304c897dc32bbdc
/eval-sv/trunk/lib/eval-sv/cf-arity.scm
c89fe136388e806d18ff38ab6233be74643143a2
[ "MIT" ]
permissive
ayamada/copy-of-svn.tir.jp
96c2176a0295f60928d4911ce3daee0439d0e0f4
101cd00d595ee7bb96348df54f49707295e9e263
refs/heads/master
2020-04-04T01:03:07.637225
2015-05-28T07:00:18
2015-05-28T07:00:18
1,085,533
3
2
null
2015-05-28T07:00:18
2010-11-16T15:56:30
Scheme
EUC-JP
Scheme
false
false
3,959
scm
cf-arity.scm
;;; coding: euc-jp ;;; -*- scheme -*- ;;; vim:set ft=scheme ts=8 sts=2 sw=2 et: ;;; $Id$ ;;; "camouflage arity" module ;;; ;;; Copyright (c) 2008 Atsuo Yamada, 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. (define-module eval-sv.cf-arity (use srfi-1) (export solve-arity ; TODO: もっと良い名前を考える camouflage-arity )) (select-module eval-sv.cf-arity) ;; arityを解釈し、(複数存在する場合は「最も緩い条件」の)arity値を二値で返す。 ;; (methodの場合、正しくarityを作成して返す事が困難なので、この仕様とする) ;; TODO: 正しくは、「最も緩い条件」ではなく、複数のarity値がある場合は、 ;; arity値のmergeが必要になる。あとで実装し直す事。 (define (solve-arity proc) (define (arity->num+opt a) (if (arity-at-least? a) (list (arity-at-least-value a) #t) (list a #f))) (let1 a (arity proc) (cond ((null? a) (values 0 #t)) ; 一部のmethodで、これがある……dummy値を返す ((not (list? a)) (apply values (arity->num+opt a))) (else (let* ((arities a) (num+opts (map arity->num+opt arities)) ; '(num opt)のlist (sorted (sort num+opts (lambda (x y) (cond ;; 固定引数部分でまず判定 ((< (car x) (car y)) #t) ((< (car y) (car x)) #f) ;; 固定引数部分が同じなら、オプショナル引数で判定 ((cadr x) #t) ((cadr y) #f) (else #t))))) ) (apply values (car sorted))))))) ;; procが受け付けるarityを、指定条件のように見えるように偽装する (define (camouflage-arity arg-num has-optional? proc) (let* ( ;; オリジナルの引数シンボルのリスト(arg:1 arg:2) (arg-list (map (lambda (i) (string->symbol (format "arg:~d" i))) (iota arg-num))) ;; 末尾にoptional引数をつけたもの(arg:1 arg:2 . opt) (arg-list+ (apply list* (append arg-list (if has-optional? '(opt) '(()))))) ;; 適用可能な形にしたもの(list* arg:1 arg:2 opt) ;; (前述の条件により、optは常にlistなので、不完全listにはならない) (arg-list* `(list* ,@arg-list ,(if has-optional? 'opt '()))) ;; evalする式 (result `(lambda ,arg-list+ (apply ,proc ,arg-list*))) ) (eval result (current-module)))) (provide "eval-sv/cf-arity")
false
8d45bce72ee6feb82e5e388df62df4ca79a4b9b7
35cfef00df91c1f29998dd80462e37411f16d1af
/scheme/sum.scm
a895acbb4d2602b7e04f5c2f77dafbea5d9d96c6
[]
no_license
MgaMPKAy/m_Practice
34470e4b929a04806c447de8fc5cb332c7396b3e
e91ab06238d70346dd8fa5e2a974641789cac79f
refs/heads/master
2021-03-12T21:47:35.378972
2014-03-05T06:05:52
2014-03-05T06:05:52
1,124,381
0
0
null
null
null
null
UTF-8
Scheme
false
false
333
scm
sum.scm
(define m-sum (lambda (from to func) (if (> from to) 0 (+ (func from) (m-sum (+ from 1) to func))))) (define m-square (lambda (x) (* x x))) (define m-cube (lambda (x) (* x x x))) (define (sum L) (cond ((eq? L '()) 0) ((eq? (cdr L) '()) (car L)) (#t (+ (car L)(sum (cdr L)))))) (sum '(1 2 3))
false
f55afd9bbe0f5f00065937ecf5f27b31988059ae
cc6a300f6d5414a5e7173968c7a6be1f8a8425dc
/tests/t7.scm
9fc3ec72c9b67ab2be6ef559a0c33b3f4abe286c
[ "Artistic-2.0" ]
permissive
hdijkema/speme
2b4058164c8d59df721a7f54fa4f6c805e7e5621
e5d72c54d07af81e98f0f5e059f7180e36ff4f4a
refs/heads/master
2020-05-17T21:41:34.617879
2013-07-24T08:04:51
2013-07-24T08:04:51
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
217
scm
t7.scm
(package t7 0.1 (export f) (define (f x) (let loop ((y 0) (a x) (b (* a a))) (println a " - " b) (if (< y x) (+ (loop (+ y 1) a b) y) y))) )
false
cf325a2cb6ffdc828f047c8fc4d3859004769aec
7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107
/ex-3.71.scm
1f0471d01f4bbcca4a76951c11e8eaeb4cf1e500
[]
no_license
jiakai0419/sicp-1
75ec0c6c8fe39038d6f2f3c4c6dd647a39be6216
974391622443c07259ea13ec0c19b80ac04b2760
refs/heads/master
2021-01-12T02:48:12.327718
2017-01-11T12:54:38
2017-01-11T12:54:38
78,108,302
0
0
null
2017-01-05T11:44:44
2017-01-05T11:44:44
null
UTF-8
Scheme
false
false
1,393
scm
ex-3.71.scm
;;; Exercise 3.71. Numbers that can be expressed as the sum of two cubes in ;;; more than one way are sometimes called Ramanujan numbers, in honor of the ;;; mathematician Srinivasa Ramanujan.[70] Ordered streams of pairs provide an ;;; elegant solution to the problem of computing these numbers. To find ;;; a number that can be written as the sum of two cubes in two different ways, ;;; we need only generate the stream of pairs of integers (i,j) weighted ;;; according to the sum i^3 + j^3 (see exercise 3.70), then search the stream ;;; for two consecutive pairs with the same weight. Write a procedure to ;;; generate the Ramanujan numbers. The first such number is 1,729. What are ;;; the next five? (load "./sec-3.5.scm") (load "./ex-3.70.scm") (define (ramanujan-numbers) (define (cube x) (* x x x)) (define (weight ij) (+ (cube (car ij)) (cube (cadr ij)))) (define s (weighted-pairs integers integers weight)) (define (drop-unique s) (let go ([s s] [w0 0] [w1 (weight (stream-car s))]) (if (= w0 w1) (cons-stream w1 (go (stream-cdr s) w1 (weight (stream-car (stream-cdr s))))) (go (stream-cdr s) w1 (weight (stream-car (stream-cdr s)))) ))) (drop-unique s) ) (define s (ramanujan-numbers)) (do ((i 0 (+ i 1))) ((= i 30)) (print (stream-ref s i)))
false
29acdeee2a93060388ab79f24d48195c9d13bc2d
370b378f48cb3ddd94297240ceb49ff4506bc122
/2.3.scm
8d3678112c1396f34cb05d13f6c841c12fd09987
[]
no_license
valvallow/PAIP
7c0c0702b8c601f4e706b02eea9615d8fdeb7131
ee0a0bd445ef52c5fe38488533fd59a3eed287f0
refs/heads/master
2021-01-20T06:56:48.999920
2010-11-26T08:09:00
2010-11-26T08:09:00
798,236
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,104
scm
2.3.scm
(use srfi-27) (use gauche.parameter) (define *simple-grammar* (make-parameter '((sentene -> (noun-phrase verb-phrase)) (noun-phrase -> (article noun)) (verb-phrase -> (verb noun-phrase)) (article -> the a) (noun -> man ball woman table) (verb -> hit took saw liked)))) (define *grammar* *simple-grammar*) (define (rule-lhs rule) (car rule)) (define (rule-rhs rule) (cdr (cdr rule))) (define (rewrites category) (let1 ret (assoc category (*grammar*)) (if (list? ret) (rule-rhs ret) ret))) (define (mappend proc ls) (apply append (map proc ls))) (define (one-of set) (list (random-elt set))) (define (random-elt choices) (list-ref choices (random-integer (length choices)))) (define (generate phrase) (cond ((list? phrase)(mappend generate phrase)) ((rewrites phrase)(generate (random-elt (rewrites phrase)))) (else (list phrase)))) (generate 'sentene) ;; (the man saw a table) (generate 'sentene) ;; (a table liked the woman) ;; -------------------------------------------------------------------- (define (generate phrase) (cond ((list? phrase) (mappend generate phrase)) ((rewrites phrase) => (compose generate (pa$ random-elt))) (else (list phrase)))) (generate 'sentene) ;; (a table liked the ball) (generate 'sentene) ;; (a table saw a table) ;; -------------------------------------------------------------------- (define (generate phrase) (if (list? phrase) (mapend generate phrase) (let1 choices (rewrites phrase) (if choices (generate (random-elt choices)) (list phrase))))) (generate 'sentene) ;; (the table hit a woman) ;; -------------------------------------------------------------------- (define (generate phrase) (if (list? phrase) (mapend generate phrase) (if-let1 choices (rewrites phrase) (generate (random-elt choices)) (list phrase)))) (generate 'sentene) ;; (a ball liked a woman)
false
f8a4c25323fa9a0e168b7b881d3b1cef15e014c5
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/mono/xml/dtdnotation-declaration.sls
af5cf4361977105517bad370fb135b6a117a0059
[]
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,435
sls
dtdnotation-declaration.sls
(library (mono xml dtdnotation-declaration) (export is? dtdnotation-declaration? name-get name-set! name-update! public-id-get public-id-set! public-id-update! system-id-get system-id-set! system-id-update! local-name-get local-name-set! local-name-update! prefix-get prefix-set! prefix-update!) (import (ironscheme-clr-port)) (define (is? a) (clr-is Mono.Xml.DTDNotationDeclaration a)) (define (dtdnotation-declaration? a) (clr-is Mono.Xml.DTDNotationDeclaration a)) (define-field-port name-get name-set! name-update! (property:) Mono.Xml.DTDNotationDeclaration Name System.String) (define-field-port public-id-get public-id-set! public-id-update! (property:) Mono.Xml.DTDNotationDeclaration PublicId System.String) (define-field-port system-id-get system-id-set! system-id-update! (property:) Mono.Xml.DTDNotationDeclaration SystemId System.String) (define-field-port local-name-get local-name-set! local-name-update! (property:) Mono.Xml.DTDNotationDeclaration LocalName System.String) (define-field-port prefix-get prefix-set! prefix-update! (property:) Mono.Xml.DTDNotationDeclaration Prefix System.String))
false
052d97c53a9d51e61b900e6c8d9a27eb86071c0c
2543c5f8bef7548ce2ea5e805b74df61b953528a
/tutorial-thursday-3/my-let.scm
67345814485afe23616aae1996a51dd8f05b7349
[ "MIT" ]
permissive
edhowland/tutorial_transcripts
4776ca9ffd62bcbc71bc888a7c462bbd6ff4ac21
1a2c3ce46253790a1488a9a3e945531ecef2e774
refs/heads/master
2020-03-25T12:28:23.089618
2018-11-27T19:20:58
2018-11-27T19:20:58
143,778,009
1
0
null
null
null
null
UTF-8
Scheme
false
false
155
scm
my-let.scm
;;; my-let - macro of let binding form (print-gensym #f) (define-syntax my-let (syntax-rules () ((my-let ((x e)) body) ((lambda (x) body) e)) ))
true
163c7b9a6a81181d873b008f10f8b835047efd6f
fb9a1b8f80516373ac709e2328dd50621b18aa1a
/ch3/exercise3-17.scm
c9165b830bf4630cb8ad7e2cd870a9afd385b769
[]
no_license
da1/sicp
a7eacd10d25e5a1a034c57247755d531335ff8c7
0c408ace7af48ef3256330c8965a2b23ba948007
refs/heads/master
2021-01-20T11:57:47.202301
2014-02-16T08:57:55
2014-02-16T08:57:55
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
842
scm
exercise3-17.scm
;;3.17 (define (make-count-pairs walks) (define (count-pairs x) (cond ((not (pair? x)) 0) ((memq x walks) 0) (else (set! walks (cons x walks)) (+ (count-pairs (car x)) (count-pairs (cdr x)) 1)))) count-pairs) ;; memqについて ;; (memq x y) yにxが含まれていれば真、ないなら偽を返す ;; eq?で比べているので、参照先が違ってると同じでない (define CP (make-count-pairs '())) (define x (cons 'a (cons 'b (cons 'c '())))) (CP x) (display x) (define x (cons 'd (cons 'a '()))) (set-car! x (cons 'b (cdr x))) (CP x) ;gosh> 3 (display x) ;gosh> ((b a) a)#<undef> (define x (cons 'a (cons 'b (cons 'c '())))) (set-car! (cdr x) (cdr (cdr x))) (set-car! x (cdr x)) (CP x) ;gosh> 3 (display x) ;gosh> (((c) c) (c) c)#<undef>
false
1fd82595f219b602f2f3081ecad5d9a3d52ec156
e101b16ae26db45fb86e711d4d1d75702544646f
/AI.scm
277edb708f89dcf1137af87079539a82336c09c5
[]
no_license
kurageru-wm/AI
b62ae595e2c681f6f83de83faca3b75e92e058b0
6f67fd56b72c9b7f458deacc17db5b6938d8b19f
refs/heads/master
2021-01-18T20:12:24.816393
2012-04-24T13:42:31
2012-04-24T13:42:31
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
84
scm
AI.scm
(define-module AI (extend chase_evade.bresenham pattern.pattern)) (provide "AI")
false
f2b64d6a458bd3204cd8773ce5b301dbe677b128
9b0c653f79bc8d0dc87526f05bdc7c9482a2e277
/3/3-03.ss
474580ccd677b4753bd80caa3d77b4f619c4a2fa
[]
no_license
ndNovaDev/sicp-magic
798b0df3e1426feb24333658f2313730ae49fb11
9715a0d0bb1cc2215d3b0bb87c076e8cb30c4286
refs/heads/master
2021-05-18T00:36:57.434247
2020-06-04T13:19:34
2020-06-04T13:19:34
251,026,570
0
0
null
null
null
null
UTF-8
Scheme
false
false
668
ss
3-03.ss
(define (dn x) (display x) (newline)) (define true #t) (define false #f) ; ********************** (define (make-account balance password) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "sb")) (define (deposit amount) (set! balance (+ balance amount)) balance) (define (dispatch pwd m) (if (eq? pwd password) (cond ((eq? m 'withdraw) withdraw) ((eq? m 'deposit) deposit) (else "sb")) "sba")) dispatch) (define acc (make-account 100 'abc)) (dn ((acc 'abc 'withdraw) 40)) (dn ((acc 'def 'deposit) 50)) (exit)
false
9af59d5f604584a379a77a8884ea241eb209b239
ab2b756cdeb5aa94b8586eeb8dd5948b7f0bba27
/src/lisp/unused/function_lib.scm
e50aad3f0367b80de5e3f31f3d539b06838968fd
[]
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
3,950
scm
function_lib.scm
; this is a library for making functions at run-time. ; uses the r-stack to store the memory locations ; for the input of the functions we are currently ; processing. So the r-stack is used as a function ; call stack, one additional thing is added to r every ; time a function is called, and one thing is ; removed from r every time a function returns. (>r 500) ;start storing inputs to functions at 500, that way 1-499 are available for storing pointers to function definitions. (macro _pointer (X) ; look up a pointer to the xth variable being stored for the current function being processed (cond (((= X 0) '(r@)) (true '(+ r@ X))))) (macro _load_inputs (V N) ; store the inputs of the function into variables, ; the top of the r stack points to these variables. (cond (((= V ()) ()) ((= 0 N) '(nop r@ ! ,(_load_inputs (cdr V) 1))) (true '(nop ,(_pointer N) ! ,(_load_inputs (cdr V) (+ N 1))))))) ;1 2 3 ;(_load_inputs (a) 0) (macro _variable* (Var Code N) ;Replace each Var in Code with the input to the function (cond (((= Code ()) ()) (true (cons (cond (((is_list (car Code)) (_variable* Var (car Code) N)) ((= (car Code) Var) '(@ (_pointer N))) (true (car Code)))) (_variable* Var (cdr Code) N)))))) (macro _variables (Vars Code N) ; repeatedly use _variable* to replace ; each Var in Code with the inputs to the function, ; which are stored in the vm as variables. (cond (((= Vars ()) Code) (true (_variables (cdr Vars) (_variable* (car Vars) Code N) (+ N 1)))))) ;(import (eqs_lib.scm)) ;2 3 ;(_load_inputs (a b) 0) ;(macro test () ; (= ; '((+ 2 (@ r@))) ; (_variable* a '(+ 2 a) 0)) ;(test) ;(_variable* a (_variable* b '(a b) 0) 1) ;(_variables (b a) '(cons a b) 0) ;(_variable* a '(+ a 1) 0) ;0 (macro _call_stack* (Many Code) ; functions need to be able to call other functions. ; if function A calls function B, then when our ; program returns from function B, we need to ; remember the inputs for all the variables in ; function A, so we can process the rest of ; function A correctly. (cond (((= Many 0) Code) ;if a function has no inputs, then the call ; stack remains unchange. ((= Code ()) ()) ((is_list (car Code)) (cons (_call_stack* Many (car Code)) (_call_stack* Many (cdr Code)))) ((= (car Code) call) '(nop ,(cdr Code) (+ r@ Many) >r call r> drop)) (true (cons (car Code) (_call_stack* Many (cdr Code))))))) (macro _length (X) ;returns the length of list X at compile-time (cond (((= X ()) 0) (true (+ (_length (cdr X)) 1))))) (macro lambda (Vars Code) ; define a new function '(nop start_fun ,(_load_inputs Vars 0) (_call_stack* ,(_length Vars) ,(_variables (reverse Vars) '(Code) 0)) end_fun)) ;define stores the 32-byte function id into a variable ;be careful with define, if a different function gets stored into the variable, then you could end up calling different code than you had expected. Make sure that it is impossible for an attacker to edit the variable after the function is defined. (macro define (Name Vars Code) '(! ,(lambda Vars Code) Name)) (macro execute (Function Variables) (cons call (reverse (cons Function (reverse Variables))))) ;3 4 5 6 7 ;(lambda (x y) (+ 1 (+ x y))) ;(lambda (x y z) (+ x (+ z y ))) ;(_load_inputs (x y z) 0) ;(_length (x y z)) ;(_variables (z y x) '(+ z (+ y x)) 0) ;0 ;1 ;(1 2 3) ;(cons 1 (cons 2 (cons 3 ()))) ;(_length (1 1 5 1 1 1 1)) ;(_pointer 3) ; 4 ;4 3 (_load_inputs (a b) 0) ;(_variable* a '(+ a 1) 0) ;900 @ 5 + @ ;(_variable* a (_variable* b (a b) 0) 1) ;(_variables (a b) '(+ a (+ b 2)) 0) ;(_call_stack* 3 '(+ (+ a b) c)) ;3 (_load_inputs (x) 0)
false
73079a5b895306880b3a770ac193ed3467b07487
a4c92c308501adb439bbf856a7fbd25a1ff0328e
/pqueue.ss
fd193a31bae617a099987007e5fc24fbecf4bcbb
[ "WTFPL" ]
permissive
Matheritasiv/pqueue
91fc27c75dd464753e9d4c9ddff88a4e8fe33d1b
aab933f37e40a75962dd0e3dd1be3bf9b6266984
refs/heads/main
2023-03-28T08:49:06.887667
2021-04-07T13:29:46
2021-04-07T13:29:46
345,520,393
2
0
null
null
null
null
UTF-8
Scheme
false
false
46,558
ss
pqueue.ss
;{{{ Macro (define-syntax defopt (syntax-rules () [(_ (p x ... [y e]) b1 b2 ...) (define p (case-lambda [(x ...) (p x ... e)] [(x ... y) b1 b2 ...]))])) ;}}} ;{{{ Skew Heap (module sh% (make-sh sh-show sh-empty? sh-merge! sh-push! sh-pop! sh-node sh-mutate! sh-delete! list->sh) ;{{{ New heap (defopt (make-sh [p <]) (list p)) ;}}} ;{{{ Print tree (defopt (sh-show sh [tab '(1 3 1)]) (let* ([h #\x2500] [v #\x2502] [u #\x250c] [d #\x2514] ;[h #\-] [v #\|] [u #\/] [d #\\] [s #\space] [str "~a\x1b;[1m~a\x1b;[m~%"] [nps (car tab)] [ns (cadr tab)] [nss (caddr tab)] [sp (make-string (+ nps ns nss) s)] [hh (make-string (1- ns) h)] [ps (make-string nps s)] [ss (make-string nss s)] [uh (string-append ps (make-string 1 u) hh ss)] [dh (string-append ps (make-string 1 d) hh ss)] [vs (string-append ps (make-string 1 v) (make-string (1- ns) s) ss)]) (let loop ([st (cdr sh)] [lsp ps] [csp ps] [rsp ps]) (unless (null? st) (loop (cadr st) (string-append lsp sp) (string-append lsp uh) (string-append lsp vs)) (printf str csp (car st)) (loop (cddr st) (string-append rsp vs) (string-append rsp dh) (string-append rsp sp)))))) ;}}} ;{{{ Empty test (define (sh-empty? sh) (null? (cdr sh))) ;}}} ;{{{ Merge heap (define ($sh-merge! sh dt) (let ([lt? (car sh)]) (unless (null? dt) (set-cdr! sh (let ([n1 (cons '() (cons '() (cdr sh)))]) (let loop ([n1 n1] [n2 dt]) (let ([nr (cddr n1)]) (set-cdr! (cdr n1) (cadr n1)) (if (null? nr) (set-car! (cdr n1) n2) (let-values ([(n2 nr) (if (lt? (car n2) (car nr)) (values n2 nr) (values nr n2))]) (set-car! (cdr n1) n2) (loop n2 nr))))) (cadr n1))))) sh) (define (sh-merge! s1 s2) (if (not (equal? (car s1) (car s2))) (error 'sh-merge! "Incompatible order type")) ($sh-merge! s1 (cdr s2))) ;}}} ;{{{ Push to heap (define (sh-push! sh x) ($sh-merge! sh (list x '()))) ;}}} ;{{{ Pop from heap (define (sh-pop! sh) (let ([n (cdr sh)]) (if (null? n) (error 'sh-pop! "Empty heap")) (set-cdr! sh (cadr n)) ($sh-merge! sh (cddr n)) (car n))) ;}}} ;{{{ Search for a node in heap (define (sh-node sh p?) (let loop ([n (cdr sh)]) (if (null? n) #f (if (p? (car n)) n (or (loop (cadr n)) (loop (cddr n))))))) (define ($sh-trace sh p?) (let loop ([n (cdr sh)]) (if (null? n) '() (if (p? (car n)) (list n) (let ([l (loop (cadr n))]) (if (null? l) (let ([l (loop (cddr n))]) (if (null? l) '() (cons n l))) (cons n l))))))) ;}}} ;{{{ Mutate a node in heap (define ($sh-adjust-increase! tr lt?) (let* ([mh (car (last-pair tr))] [m (car mh)]) (let loop ([mh mh]) (let ([l (cadr mh)] [r (cddr mh)]) (cond [(cond [(and (null? l) (null? r)) #f] [(null? l) r] [(null? r) l] [else (if (lt? (car r) (car l)) r l)]) => (lambda (d) (when (lt? (car d) m) (set-car! mh (car d)) (set-car! d m) (loop d)))]))))) (define ($sh-adjust-decrease! tr lt?) (let* ([l (reverse tr)] [m (caar l)]) (let loop ([l l]) (let ([ll (cdr l)]) (if (and (not (null? ll)) (lt? m (caar ll))) (begin (set-car! (car l) (caar ll)) (loop ll)) (set-car! (car l) m)))))) (define (sh-mutate! sh p? mutator) (let ([tr ($sh-trace sh p?)]) (if (null? tr) #f (let ([lt? (car sh)] [t0 (car (last-pair tr))]) (cond [(let-values ([(v mutate) (mutator (car t0))]) (let-syntax ([prog1 (syntax-rules () [(_ v body ...) (let ([v& v]) body ... v&)])]) (cond [(not mutate) (prog1 (cond [(lt? (car t0) v) $sh-adjust-increase!] [(lt? v (car t0)) $sh-adjust-decrease!] [else #f]) (set-car! t0 v))] [(procedure? mutate) (prog1 (let ([v0 ((mutate 'accessor) (car t0))] [lt? (mutate 'lt)]) (cond [(lt? v0 v) $sh-adjust-increase!] [(lt? v v0) $sh-adjust-decrease!] [else #f])) ((mutate 'mutator) (car t0) v))] [(real? mutate) (cond [(positive? mutate) $sh-adjust-increase!] [(negative? mutate) $sh-adjust-decrease!] [else #f])] [else $sh-adjust-decrease!]))) => (lambda (f) (f tr lt?))]) sh)))) ;}}} ;{{{ Delete a node in heap (define (sh-delete! sh p?) (let ([tr ($sh-trace sh p?)]) (if (null? tr) #f (let ([n (cdr sh)]) (let loop ([l (reverse! tr)]) (let ([ll (cdr l)]) (unless (null? ll) (set-car! (car l) (caar ll)) (loop ll)))) (set-cdr! sh (cadr n)) ($sh-merge! sh (cddr n)) sh)))) ;}}} ;{{{ Make heap from list (defopt (list->sh l [op #f]) (fold-left (lambda (x y) (sh-push! x y)) (if op (make-sh op) (make-sh)) l)) ;}}} ) ;}}} ;{{{ Leftist Heap (module lh% (make-lh lh-show lh-empty? lh-merge! lh-push! lh-pop! lh-node lh-mutate! lh-delete! list->lh) ;{{{ Macro (define-syntax level-left (syntax-rules () [(_ n) (if (null? (cadr n)) -1 (cdaadr n))])) (define-syntax level-right (syntax-rules () [(_ n) (if (null? (cddr n)) -1 (cdaddr n))])) ;}}} ;{{{ New heap (defopt (make-lh [p <]) (list p)) ;}}} ;{{{ Print tree (defopt (lh-show lh [tab '(1 3 1)]) (let* ([h #\x2500] [v #\x2502] [u #\x250c] [d #\x2514] ;[h #\-] [v #\|] [u #\/] [d #\\] [s #\space] [str "~a\x1b;[3~d;1m~a\x1b;[m~%"] [nps (car tab)] [ns (cadr tab)] [nss (caddr tab)] [sp (make-string (+ nps ns nss) s)] [hh (make-string (1- ns) h)] [ps (make-string nps s)] [ss (make-string nss s)] [uh (string-append ps (make-string 1 u) hh ss)] [dh (string-append ps (make-string 1 d) hh ss)] [vs (string-append ps (make-string 1 v) (make-string (1- ns) s) ss)]) (let loop ([st (cdr lh)] [lsp ps] [csp ps] [rsp ps]) (unless (null? st) (loop (cadr st) (string-append lsp sp) (string-append lsp uh) (string-append lsp vs)) (printf str csp (let ([delta (- (level-left st) (level-right st))]) (cond [(positive? delta) 3] [(zero? delta) 9] [else 0])) (caar st)) (loop (cddr st) (string-append rsp vs) (string-append rsp dh) (string-append rsp sp)))))) ;}}} ;{{{ Empty test (define (lh-empty? lh) (null? (cdr lh))) ;}}} ;{{{ Merge heap (define ($lh-merge! lh dt) (let ([lt? (car lh)]) (set-cdr! lh (let loop ([n1 (cdr lh)] [n2 dt]) (cond [(null? n1) n2] [(null? n2) n1] [else (let-values ([(n1 n2) (if (lt? (caar n1) (caar n2)) (values n1 n2) (values n2 n1))]) (let* ([v0 (level-right n1)] [n (loop (cddr n1) n2)] [v (cdar n)]) (if (< (level-left n1) v) (begin (set-cdr! (cdr n1) (cadr n1)) (set-car! (cdr n1) n)) (set-cdr! (cdr n1) n)) (unless (= v0 v) (set-cdr! (car n1) (1+ (level-right n1))))) n1)])))) lh) (define (lh-merge! l1 l2) (if (not (equal? (car l1) (car l2))) (error 'lh-merge! "Incompatible order type")) ($lh-merge! l1 (cdr l2))) ;}}} ;{{{ Push to heap (define (lh-push! lh x) ($lh-merge! lh (list (cons x 0) '()))) ;}}} ;{{{ Pop from heap (define (lh-pop! lh) (let ([n (cdr lh)]) (if (null? n) (error 'lh-pop! "Empty heap")) (set-cdr! lh (cadr n)) ($lh-merge! lh (cddr n)) (caar n))) ;}}} ;{{{ Search for a node in heap (define (lh-node lh p?) (let loop ([n (cdr lh)]) (if (null? n) #f (if (p? (caar n)) n (or (loop (cadr n)) (loop (cddr n))))))) (define ($lh-trace lh p?) (let loop ([n (cdr lh)]) (if (null? n) '() (if (p? (caar n)) (list n) (let ([l (loop (cadr n))]) (if (null? l) (let ([l (loop (cddr n))]) (if (null? l) '() (cons n l))) (cons n l))))))) ;}}} ;{{{ Mutate a node in heap (define ($lh-adjust-increase! tr lt?) (let* ([mh (car (last-pair tr))] [m (caar mh)]) (let loop ([mh mh]) (let ([l (cadr mh)] [r (cddr mh)]) (cond [(cond [(and (null? l) (null? r)) #f] [(null? l) r] [(null? r) l] [else (if (lt? (caar r) (caar l)) r l)]) => (lambda (d) (when (lt? (caar d) m) (set-car! (car mh) (caar d)) (set-car! (car d) m) (loop d)))]))))) (define ($lh-adjust-decrease! tr lt?) (let* ([l (reverse tr)] [m (caaar l)]) (let loop ([l l]) (let ([ll (cdr l)]) (if (and (not (null? ll)) (lt? m (caaar ll))) (begin (set-car! (caar l) (caaar ll)) (loop ll)) (set-car! (caar l) m)))))) (define (lh-mutate! lh p? mutator) (let ([tr ($lh-trace lh p?)]) (if (null? tr) #f (let ([lt? (car lh)] [t0 (car (last-pair tr))]) (cond [(let-values ([(v mutate) (mutator (caar t0))]) (let-syntax ([prog1 (syntax-rules () [(_ v body ...) (let ([v& v]) body ... v&)])]) (cond [(not mutate) (prog1 (cond [(lt? (caar t0) v) $lh-adjust-increase!] [(lt? v (caar t0)) $lh-adjust-decrease!] [else #f]) (set-car! (car t0) v))] [(procedure? mutate) (prog1 (let ([v0 ((mutate 'accessor) (caar t0))] [lt? (mutate 'lt)]) (cond [(lt? v0 v) $lh-adjust-increase!] [(lt? v v0) $lh-adjust-decrease!] [else #f])) ((mutate 'mutator) (caar t0) v))] [(real? mutate) (cond [(positive? mutate) $lh-adjust-increase!] [(negative? mutate) $lh-adjust-decrease!] [else #f])] [else $lh-adjust-decrease!]))) => (lambda (f) (f tr lt?))]) lh)))) ;}}} ;{{{ Delete a node in heap (define (lh-delete! lh p?) (let ([tr ($lh-trace lh p?)]) (if (null? tr) #f (let ([n (cdr lh)]) (let loop ([l (reverse! tr)]) (let ([ll (cdr l)]) (unless (null? ll) (set-car! (caar l) (caaar ll)) (loop ll)))) (set-cdr! lh (cadr n)) ($lh-merge! lh (cddr n)) lh)))) ;}}} ;{{{ Make heap from list (defopt (list->lh l [op #f]) (fold-left (lambda (x y) (lh-push! x y)) (if op (make-lh op) (make-lh)) l)) ;}}} ) ;}}} ;{{{ Binomial Heap (module bh% (make-bh bh-show bh-empty? bh-merge! bh-push! bh-pop! bh-node bh-mutate! bh-delete! list->bh) ;{{{ New heap (defopt (make-bh [p <]) (list p)) ;}}} ;{{{ Print heap (defopt (bh-show bh [tab '(1 3 1)]) (let* ([h #\x2500] [v #\x2502] [u #\x251c] [d #\x2514] ;[h #\-] [v #\|] [u #\|] [d #\\] [s #\space] [str "~a\x1b;[1m~a\x1b;[m~%"] [nps (car tab)] [ns (cadr tab)] [nss (caddr tab)] [sp (make-string (+ nps ns nss) s)] [hh (make-string (1- ns) h)] [ps (make-string nps s)] [ss (make-string nss s)] [uh (string-append ps (make-string 1 u) hh ss)] [dh (string-append ps (make-string 1 d) hh ss)] [vs (string-append ps (make-string 1 v) (make-string (1- ns) s) ss)]) (unless (null? (cdr bh)) (let loop ([st (cdr bh)] [par (cons ps ps)] [pdr (cons ps ps)]) (let count ([st st]) (let* ([f (null? (cdr st))] [pr (if f par pdr)]) (printf str (car pr) (caar st)) (unless (null? (cdar st)) (loop (cdar st) (cons (string-append (cdr pr) dh) (string-append (cdr pr) sp)) (cons (string-append (cdr pr) uh) (string-append (cdr pr) vs)))) (unless f (count (cdr st))))))))) ;}}} ;{{{ Empty test (define (bh-empty? bh) (null? (cdr bh))) ;}}} ;{{{ Merge heap (define ($bh-merge! bh dt) (let ([lt? (car bh)]) (set-cdr! bh (let loop ([n1 (cdr bh)] [n2 dt] [f #f]) (cond [(null? n1) n2] [(null? n2) n1] [else (let ([s1 (length (cdar n1))] [s2 (length (cdar n2))]) (if (= s1 s2) (cons (let-values ([(t1 t2) (if (lt? (caar n1) (caar n2)) (values (car n1) (car n2)) (values (car n2) (car n1)))]) (set-cdr! t1 (cons t2 (cdr t1))) t1) (loop (cdr n1) (cdr n2) #f)) (let-values ([(n1 n2) (if (< s1 s2) (values n2 n1) (values n1 n2))]) (let ([n (loop (cdr n1) n2 #f)]) (if f (begin (set-cdr! n1 n) n1) (loop (list (car n1)) n #t))))))])))) bh) (define (bh-merge! b1 b2) (if (not (equal? (car b1) (car b2))) (error 'bh-merge! "Incompatible order type")) ($bh-merge! b1 (cdr b2))) ;}}} ;{{{ Push to heap (define (bh-push! bh x) ($bh-merge! bh (list (list x)))) ;}}} ;{{{ Pop from heap (define ($bh-min bh lt?) (let ([m #f] [mt '()]) (let loop ([last bh]) (let ([tree (cdr last)]) (unless (null? tree) (let ([v (caar tree)]) (when (or (null? mt) (lt? v m)) (set! mt last) (set! m v))) (loop tree)))) (values m mt))) (define (bh-pop! bh) (let-values ([(m mt) ($bh-min bh (car bh))]) (if (null? mt) (error 'bh-pop! "Empty heap")) (let ([d (cdadr mt)]) (set-cdr! mt (cddr mt)) ($bh-merge! bh d)) m)) ;}}} ;{{{ Search for a node in heap (define (bh-node bh p?) (let loop ([n (cdr bh)]) (let count ([n n]) (if (null? n) #f (if (p? (caar n)) n (or (loop (cdar n)) (count (cdr n)))))))) (define ($bh-trace bh p?) (let loop ([last bh]) (let count ([last last]) (let ([n (cdr last)]) (if (null? n) '() (if (p? (caar n)) (list last) (let ([l (loop (car n))]) (if (null? l) (count n) (cons last l))))))))) ;}}} ;{{{ Mutate a node in heap (define ($bh-adjust-increase! tr lt?) (let* ([mh (cadar (last-pair tr))] [mm (car mh)]) (let loop ([mh mh]) (let-values ([(m mt) ($bh-min mh lt?)]) (if (and (not (null? mt)) (lt? m mm)) (let ([mt (cadr mt)]) (set-car! mh m) (loop mt)) (set-car! mh mm)))))) (define ($bh-adjust-decrease! tr lt?) (let* ([l (reverse! (map cadr tr))] [m (caar l)]) (let loop ([l l]) (let ([ll (cdr l)]) (if (and (not (null? ll)) (lt? m (caar ll))) (begin (set-car! (car l) (caar ll)) (loop ll)) (set-car! (car l) m)))))) (define (bh-mutate! bh p? mutator) ;; `mutator` is a procedure that takes in an argument `v0` ;; standing for the data to be mutated and returns multi-values ;; `v mutate`. ;; If `mutate` is `#f`, then `v` is treated as the new data. ;; If `mutate` is a procedure, then it takes in a symbol and ;; returns a procedure: ;; * `(mutate 'accessor)` gives the accessor of the priority ;; value of data; ;; * `(mutate 'mutator)` gives the mutator of the priority ;; value of data; ;; * `(mutate 'lt)` gives the less-than predicate of the priority ;; value; ;; and `v` is treated as the new priority value. ;; In the cases below, the data should be mutated by the ;; procedure `mutator`. ;; If `mutate` is a real number, then its sign is used to ;; determine whether the priority value is to be increased or ;; decreased. ;; In other cases, the priority value is viewed to be decreased. (let ([tr ($bh-trace bh p?)]) (if (null? tr) #f (let ([lt? (car bh)] [adjust! $bh-adjust-decrease!] [t0 (cadar (last-pair tr))]) (let-values ([(v mutate) (mutator (car t0))]) (cond [(not mutate) (if (lt? (car t0) v) (set! adjust! $bh-adjust-increase!) (if (not (lt? v (car t0))) (set! adjust! #f))) (set-car! t0 v)] [(procedure? mutate) (let ([v0 ((mutate 'accessor) (car t0))] [lt? (mutate 'lt)]) (if (lt? v0 v) (set! adjust! $bh-adjust-increase!) (if (not (lt? v v0)) (set! adjust! #f)))) ((mutate 'mutator) (car t0) v)] [(real? mutate) (if (positive? mutate) (set! adjust! $bh-adjust-increase!) (if (zero? mutate) (set! adjust! #f)))])) (if adjust! (adjust! tr lt?)) bh)))) ;}}} ;{{{ Delete a node in heap (define (bh-delete! bh p?) (let ([tr ($bh-trace bh p?)]) (if (null? tr) #f (let ([mt (car tr)] [d (cdadar tr)]) (let loop ([l (reverse! (map cadr tr))]) (let ([ll (cdr l)]) (unless (null? ll) (set-car! (car l) (caar ll)) (loop ll)))) (set-cdr! mt (cddr mt)) ($bh-merge! bh d) bh)))) ;}}} ;{{{ Make heap from list (defopt (list->bh l [op #f]) (fold-left (lambda (x y) (bh-push! x y)) (if op (make-bh op) (make-bh)) l)) ;}}} ) ;}}} ;{{{ Fibonacci Heap (module fh% (make-fh fh-show fh-empty? fh-merge! fh-push! fh-pop! fh-node fh-mutate! fh-delete! list->fh) ;{{{ Macro (define-syntax list*& (lambda (x) (syntax-case x () [(_ head) #'(list* head)] [(name head remain ...) (with-syntax ([& (datum->syntax #'name '&)]) #'(let* ([& (list '())] [head& head] [remain& (list* remain ...)]) (set-car! & head&) (set-cdr! & remain&) &))]))) (define-syntax list& (lambda (x) (syntax-case x () [(name elems ...) (datum->syntax #'name (syntax->datum #'(list*& elems ... '())))]))) (define-syntax cons& (lambda (x) (syntax-case x () [(name a b) (datum->syntax #'name (syntax->datum #'(list*& a b)))]))) (define-syntax make-lr (syntax-rules (nil) [(_ nil r) (set-car! (cddr r) '())] [(_ l nil) (set-cdr! (cddr l) '())] [(_ l r) (let ([l& l] [r& r]) (set-cdr! (cddr l&) r&) (set-car! (cddr r&) l&))])) (define-syntax make-ud (syntax-rules (nil) [(_ nil d) (set-car! (cadr d) '())] [(_ u nil) (set-cdr! (cadr u) '())] [(_ u d) (let ([u& u] [d& d]) (set-cdr! (cadr u&) d&) (set-car! (cadr d&) u&))])) ;}}} ;{{{ Reusable vector (define ($make-rvector n) (let ([i 0] [vec '#()]) (lambda (operation) (case operation [size (lambda (size) (let ([old-size (vector-length vec)]) (if (and (<= size old-size) (< i (1- n))) (set! i (1+ i)) (let ([new-size (if (or (zero? old-size) (<= size old-size)) size (let loop ([s old-size]) (if (>= s size) s (loop (ceiling (* s 3/2))))))]) (set! i 0) (set! vec (make-vector new-size #f))))))] [ref (lambda (index) (let ([l (vector-ref vec index)]) (and l (= i (car l)) (cdr l))))] [set! (lambda (index v) (vector-set! vec index (cons i v)))])))) (define $rvector ($make-rvector 1024)) (define $rvector-size ($rvector 'size)) (define $rvector-ref ($rvector 'ref)) (define $rvector-set! ($rvector 'set!)) ;}}} ;{{{ New heap (defopt (make-fh [p <]) (list (cons p 0))) ;}}} ;{{{ Print heap (defopt (fh-show fh [tab '(1 3 1)]) (let* ([h #\x2500] [v #\x2502] [u #\x251c] [d #\x2514] ;[h #\-] [v #\|] [u #\|] [d #\\] [s #\space] [str "~a\x1b;[3~d;1m~a\x1b;[m~%"] [nps (car tab)] [ns (cadr tab)] [nss (caddr tab)] [sp (make-string (+ nps ns nss) s)] [hh (make-string (1- ns) h)] [ps (make-string nps s)] [ss (make-string nss s)] [uh (string-append ps (make-string 1 u) hh ss)] [dh (string-append ps (make-string 1 d) hh ss)] [vs (string-append ps (make-string 1 v) (make-string (1- ns) s) ss)]) (unless (null? (cdr fh)) (let loop ([head (cdr fh)] [par (cons ps ps)] [pdr (cons ps ps)]) (let count ([st head]) (let* ([f (eq? (cdddr st) head)] [pr (if f par pdr)]) (printf str (car pr) (if (cddar st) 3 9) (caar st)) (unless (null? (cdadr st)) (loop (cdadr st) (cons (string-append (cdr pr) dh) (string-append (cdr pr) sp)) (cons (string-append (cdr pr) uh) (string-append (cdr pr) vs)))) (unless f (count (cdddr st))))))))) ;}}} ;{{{ Empty test (define (fh-empty? fh) (null? (cdr fh))) ;}}} ;{{{ Merge heap (define ($fh-merge! fh dt) (unless (null? dt) (let ([lt? (caar fh)] [n1 (cdr fh)] [n2 dt]) (if (null? n1) (set-cdr! fh n2) (let-values ([(n1 n2) (if (lt? (caar n1) (caar n2)) (values n1 n2) (begin (set-cdr! fh n2) (values n2 n1)))]) (let ([n1t (caddr n1)] [n2t (caddr n2)]) (make-lr n2t n1) (make-lr n1t n2)))))) fh) (define (fh-merge! f1 f2) (if (not (equal? (caar f1) (caar f2))) (error 'fh-merge! "Incompatible order type")) (set-cdr! (car f1) (+ (cdar f1) (cdar f2))) ($fh-merge! f1 (cdr f2))) ;}}} ;{{{ Push to heap (define (fh-push! fh x) (set-cdr! (car fh) (1+ (cdar fh))) ($fh-merge! fh (list*& (list* x 0 #f) (list '()) & &))) ;}}} ;{{{ Pop from heap (define ($fh-extract! mt) (let ([mtd (cdadr mt)]) (let-values ([(ml mr) (if (eq? (caddr mt) mt) (values (caddr mtd) mtd) (values (caddr mt) (cdddr mt)))]) (if (null? mtd) (make-lr ml mr) (begin (make-lr ml mtd) (let loop ([n mtd]) (make-ud nil n) (set-cdr! (cdar n) #f) (if (eq? (cdddr n) mtd) (make-lr n mr) (loop (cdddr n)))))) mr))) (define ($fh-consolidate! fh) (let ([lt? (caar fh)] [mt (cdr fh)]) ($rvector-size (1+ (exact (floor (log (cdar fh) (/ (1+ (sqrt 5)) 2)))))) (let loop ([n mt]) (let* ([r (cdddr n)] [f (eq? r mt)] [nr (let loop ([n n]) (cond [($rvector-ref (cadar n)) => (lambda (m) (let-values ([(n1 n2) (if (lt? (caar n) (caar m)) (values n m) (values m n))]) (let ([n (cadar n1)]) ($rvector-set! n #f) (set-car! (cdar n1) (1+ n))) (let ([n1d (cdadr n1)]) (make-ud n1 n2) (set-cdr! (cdar n2) #f) (make-lr (caddr n2) (cdddr n2)) (if (eq? n2 mt) (set! mt (cdddr n2))) (if (null? n1d) (make-lr n2 n2) (begin (make-lr (caddr n1d) n2) (make-lr n2 n1d)))) (loop n1)))] [else ($rvector-set! (cadar n) n) n]))]) (if (and (eq? nr n) (lt? (caar n) (caadr fh))) (set-cdr! fh n)) (if (not f) (loop r)))))) (define (fh-pop! fh) (let ([mt (cdr fh)]) (if (null? mt) (error 'fh-pop! "Empty heap")) (let ([m (caar mt)] [n (1- (cdar fh))]) (set-cdr! (car fh) n) (if (zero? n) (set-cdr! fh '()) (begin (set-cdr! fh ($fh-extract! mt)) ($fh-consolidate! fh))) m))) ;}}} ;{{{ Search for a node in heap (define (fh-node fh p?) (let loop ([head (cdr fh)]) (let count ([n head]) (if (null? n) #f (if (p? (caar n)) n (or (loop (cdadr n)) (if (eq? (cdddr n) head) #f (count (cdddr n))))))))) ;}}} ;{{{ Mutate a node in heap (define ($fh-cut! fh node) (unless (null? (caadr node)) (let loop ([node node]) (let ([p (caadr node)]) (let ([deg (1- (cadar p))]) (set-car! (cdar p) deg) (if (eq? (cdadr p) node) (if (zero? deg) (make-ud p nil) (make-ud p (cdddr node)))) (if (positive? deg) (make-lr (caddr node) (cdddr node)))) (set-cdr! (cdar node) #f) (make-ud nil node) (make-lr (cadddr fh) node) (make-lr node (cdr fh)) (unless (null? (caadr p)) (if (cddar p) (loop p) (set-cdr! (cdar p) #t))))))) (define ($fh-adjust-increase! fh node) (let ([s (cdadr node)] [lt? (caar fh)] [m (caar node)]) (unless (null? s) (let loop ([n (cdddr s)]) (let ([r (cdddr n)]) (if (lt? (caar n) m) ($fh-cut! fh n)) (if (not (eq? n s)) (loop r))))) (if (eq? (cdr fh) node) ($fh-consolidate! fh)))) (define ($fh-adjust-decrease! fh node) (let ([p (caadr node)] [lt? (caar fh)] [m (caar node)]) (unless (null? p) (if (lt? m (caar p)) ($fh-cut! fh node))) (if (lt? m (caadr fh)) (set-cdr! fh node)))) (define ($fh-mutate! fh node mutator) (let ([lt? (caar fh)]) (cond [(let-values ([(v mutate) (mutator (caar node))]) (let-syntax ([prog1 (syntax-rules () [(_ v body ...) (let ([v& v]) body ... v&)])]) (cond [(not mutate) (prog1 (cond [(lt? (caar node) v) $fh-adjust-increase!] [(lt? v (caar node)) $fh-adjust-decrease!] [else #f]) (set-car! (car node) v))] [(procedure? mutate) (prog1 (let ([v0 ((mutate 'accessor) (caar node))] [lt? (mutate 'lt)]) (cond [(lt? v0 v) $fh-adjust-increase!] [(lt? v v0) $fh-adjust-decrease!] [else #f])) ((mutate 'mutator) (caar node) v))] [(real? mutate) (cond [(positive? mutate) $fh-adjust-increase!] [(negative? mutate) $fh-adjust-decrease!] [else #f])] [else $fh-adjust-decrease!]))) => (lambda (f) (f fh node))]) fh)) (define (fh-mutate! fh p? mutator) (let ([node (fh-node fh p?)]) (and node ($fh-mutate! fh node mutator)))) ;}}} ;{{{ Delete a node in heap (define ($fh-delete! fh node) (if (eq? (cdr fh) node) (fh-pop! fh) (begin ($fh-cut! fh node) (set-cdr! (car fh) (1- (cdar fh))) ($fh-extract! node))) fh) (define (fh-delete! fh p?) (let ([node (fh-node fh p?)]) (and node ($fh-delete! fh node)))) ;}}} ;{{{ Make heap from list (defopt (list->fh l [op #f]) (fold-left (lambda (x y) (fh-push! x y)) (if op (make-fh op) (make-fh)) l)) ;}}} ) ;}}} ;{{{ Pairing Heap (module ph% (make-ph ph-show ph-empty? ph-merge! ph-push! ph-pop! ph-node ph-mutate! ph-delete! list->ph) ;{{{ New heap (defopt (make-ph [p <]) (cons p #f)) ;}}} ;{{{ Print heap (defopt (ph-show ph [tab '(1 3 1)]) (let* ([h #\x2500] [v #\x2502] [u #\x251c] [d #\x2514] ;[h #\-] [v #\|] [u #\|] [d #\\] [s #\space] [str "~a\x1b;[1m~a\x1b;[m~%"] [nps (car tab)] [ns (cadr tab)] [nss (caddr tab)] [sp (make-string (+ nps ns nss) s)] [hh (make-string (1- ns) h)] [ps (make-string nps s)] [ss (make-string nss s)] [uh (string-append ps (make-string 1 u) hh ss)] [dh (string-append ps (make-string 1 d) hh ss)] [vs (string-append ps (make-string 1 v) (make-string (1- ns) s) ss)]) (when (cdr ph) (let loop ([st (cdr ph)] [par ps] [pdr ps]) (printf str par (car st)) (let count ([st (cdr st)]) (unless (null? st) (let-values ([(ar dr) (if (null? (cdr st)) (values dh sp) (values uh vs))]) (loop (car st) (string-append pdr ar) (string-append pdr dr))) (count (cdr st)))))))) ;}}} ;{{{ Empty test (define (ph-empty? ph) (not (cdr ph))) ;}}} ;{{{ Merge heap (define ($ph-pair! cl lt?) (if (null? cl) #f (let loop ([cl cl]) (if (null? (cdr cl)) (car cl) (loop (let loop ([cl cl] [rl '()]) (cond [(null? cl) rl] [(null? (cdr cl)) (cons (car cl) rl)] [else (let-values ([(a b) (if (lt? (caadr cl) (caar cl)) (values (cadr cl) (car cl)) (values (car cl) (cadr cl)))]) (set-cdr! a (cons b (cdr a))) (loop (cddr cl) (cons a rl)))]))))))) (define ($ph-merge! ph dt) (when dt (let ([n1 (cdr ph)] [n2 dt]) (set-cdr! ph (if (not n1) n2 ($ph-pair! (list n1 n2) (car ph)))))) ph) (define (ph-merge! p1 p2) (if (not (equal? (car p1) (car p2))) (error 'ph-merge! "Incompatible order type")) ($ph-merge! p1 (cdr p2))) ;}}} ;{{{ Push to heap (define (ph-push! ph x) ($ph-merge! ph (list x))) ;}}} ;{{{ Pop from heap (define (ph-pop! ph) (if (not (cdr ph)) (error 'ph-pop! "Empty heap")) (let ([m (cadr ph)]) (set-cdr! ph ($ph-pair! (cddr ph) (car ph))) m)) ;}}} ;{{{ Search for a node in heap (define (ph-node ph p?) (and (cdr ph) (let loop ([n (cdr ph)]) (if (p? (car n)) n (let count ([n (cdr n)]) (if (null? n) #f (or (loop (car n)) (count (cdr n))))))))) (define ($ph-trace ph p?) (let ([r (and (cdr ph) (let loop ([p #f] [b (list #f (cdr ph))] [n (cdr ph)]) (if (p? (car n)) (cons p b) (let count ([l n]) (if (null? (cdr l)) #f (or (loop n l (cadr l)) (count (cdr l))))))))]) (if r (values (car r) (cdr r)) (values #f #f)))) ;}}} ;{{{ Mutate a node in heap (define ($ph-adjust-increase! ph p b) (let* ([n (cadr b)] [v (car n)] [lt? (car ph)]) (set-cdr! ph ($ph-pair! (let loop ([l n] [r (list (cdr ph))]) (if (null? (cdr l)) r (if (lt? (caadr l) v) (let ([n (cadr l)]) (set-cdr! l (cddr l)) (loop l (cons n r))) (loop (cdr l) r)))) lt?)))) (define ($ph-adjust-decrease! ph p b) (let ([n (cadr b)]) (when (and p ((car ph) (car n) (car p))) (set-cdr! b (cddr b)) ($ph-merge! ph n) (void)))) (define (ph-mutate! ph p? mutator) (let-values ([(p b) ($ph-trace ph p?)]) (and b (let ([lt? (car ph)] [t0 (cadr b)]) (cond [(let-values ([(v mutate) (mutator (car t0))]) (let-syntax ([prog1 (syntax-rules () [(_ v body ...) (let ([v& v]) body ... v&)])]) (cond [(not mutate) (prog1 (cond [(lt? (car t0) v) $ph-adjust-increase!] [(lt? v (car t0)) $ph-adjust-decrease!] [else #f]) (set-car! t0 v))] [(procedure? mutate) (prog1 (let ([v0 ((mutate 'accessor) (car t0))] [lt? (mutate 'lt)]) (cond [(lt? v0 v) $ph-adjust-increase!] [(lt? v v0) $ph-adjust-decrease!] [else #f])) ((mutate 'mutator) (car t0) v))] [(real? mutate) (cond [(positive? mutate) $ph-adjust-increase!] [(negative? mutate) $ph-adjust-decrease!] [else #f])] [else $ph-adjust-decrease!]))) => (lambda (f) (f ph p b))]) ph)))) ;}}} ;{{{ Delete a node in heap (define (ph-delete! ph p?) (let-values ([(p b) ($ph-trace ph p?)]) (and b (begin (if (not p) (ph-pop! ph) (let ([n (cadr b)]) (set-cdr! b (cddr b)) (set-cdr! ph ($ph-pair! (cons (cdr ph) (cdr n)) (car ph))))) ph)))) ;}}} ;{{{ Make heap from list (defopt (list->ph l [op #f]) (fold-left (lambda (x y) (ph-push! x y)) (if op (make-ph op) (make-ph)) l)) ;}}} ) ;}}} ;{{{ Priority-Queue Type ;{{{ Operations Based On Skew Heap (module $pqueue-sh% (pqueue $ds-tag make-pqueue pqueue? $pqueue-length pqueue-op pqueue-empty? pqueue-merge! pqueue-push! pqueue-pop! pqueue-memp pqueue-mutate! pqueue-delete!) (import sh%) (define $ds-tag "sh") ;{{{ Definition (define-record-type (pqueue $make-pqueue pqueue?) (fields (mutable data)) (nongenerative) (sealed #t)) (define make-pqueue (case-lambda [() ($make-pqueue (make-sh))] [(l) ($make-pqueue (list->sh l))] [(l op) ($make-pqueue (list->sh l op))])) ;}}} ;{{{ Operations (define ($pqueue-length q) (let loop ([t (cdr (pqueue-data q))]) (if (null? t) 0 (+ 1 (loop (cadr t)) (loop (cddr t)))))) (define (pqueue-op q) (car (pqueue-data q))) (define (pqueue-empty? q) (sh-empty? (pqueue-data q))) (define (pqueue-merge! q1 q2) (sh-merge! (pqueue-data q1) (pqueue-data q2)) (set-cdr! (pqueue-data q2) '())) (define (pqueue-push! q x) (sh-push! (pqueue-data q) x) (void)) (define (pqueue-pop! q) (sh-pop! (pqueue-data q))) (define (pqueue-memp q p) (let ([node (sh-node (pqueue-data q) p)]) (cond [node => car] [else #f]))) (define (pqueue-mutate! q p m) (and (sh-mutate! (pqueue-data q) p m) #t)) (define (pqueue-delete! q p) (and (sh-delete! (pqueue-data q) p) #t)) ;}}} ) ;}}} ;{{{ Operations Based On Leftist Heap (module $pqueue-lh% (pqueue $ds-tag make-pqueue pqueue? $pqueue-length pqueue-op pqueue-empty? pqueue-merge! pqueue-push! pqueue-pop! pqueue-memp pqueue-mutate! pqueue-delete!) (import lh%) (define $ds-tag "lh") ;{{{ Definition (define-record-type (pqueue $make-pqueue pqueue?) (fields (mutable data)) (nongenerative) (sealed #t)) (define make-pqueue (case-lambda [() ($make-pqueue (make-lh))] [(l) ($make-pqueue (list->lh l))] [(l op) ($make-pqueue (list->lh l op))])) ;}}} ;{{{ Operations (define ($pqueue-length q) (let loop ([t (cdr (pqueue-data q))]) (if (null? t) 0 (+ 1 (loop (cadr t)) (loop (cddr t)))))) (define (pqueue-op q) (car (pqueue-data q))) (define (pqueue-empty? q) (lh-empty? (pqueue-data q))) (define (pqueue-merge! q1 q2) (lh-merge! (pqueue-data q1) (pqueue-data q2)) (set-cdr! (pqueue-data q2) '())) (define (pqueue-push! q x) (lh-push! (pqueue-data q) x) (void)) (define (pqueue-pop! q) (lh-pop! (pqueue-data q))) (define (pqueue-memp q p) (let ([node (lh-node (pqueue-data q) p)]) (cond [node => caar] [else #f]))) (define (pqueue-mutate! q p m) (and (lh-mutate! (pqueue-data q) p m) #t)) (define (pqueue-delete! q p) (and (lh-delete! (pqueue-data q) p) #t)) ;}}} ) ;}}} ;{{{ Operations Based On Binomial Heap (module $pqueue-bh% (pqueue $ds-tag make-pqueue pqueue? $pqueue-length pqueue-op pqueue-empty? pqueue-merge! pqueue-push! pqueue-pop! pqueue-memp pqueue-mutate! pqueue-delete!) (import bh%) (define $ds-tag "bh") ;{{{ Definition (define-record-type (pqueue $make-pqueue pqueue?) (fields (mutable data)) (nongenerative) (sealed #t)) (define make-pqueue (case-lambda [() ($make-pqueue (make-bh))] [(l) ($make-pqueue (list->bh l))] [(l op) ($make-pqueue (list->bh l op))])) ;}}} ;{{{ Operations #;(define ($pqueue-length q) (let loop ([t (cdr (pqueue-data q))]) (let count ([t t]) (if (null? t) 0 (+ 1 (loop (cdar t)) (count (cdr t))))))) (define ($pqueue-length q) (let loop ([t (cdr (pqueue-data q))]) (if (null? t) 0 (+ (expt 2 (length (cdar t))) (loop (cdr t)))))) (define (pqueue-op q) (car (pqueue-data q))) (define (pqueue-empty? q) (bh-empty? (pqueue-data q))) (define (pqueue-merge! q1 q2) (bh-merge! (pqueue-data q1) (pqueue-data q2)) (set-cdr! (pqueue-data q2) '())) (define (pqueue-push! q x) (bh-push! (pqueue-data q) x) (void)) (define (pqueue-pop! q) (bh-pop! (pqueue-data q))) (define (pqueue-memp q p) (let ([node (bh-node (pqueue-data q) p)]) (and node (caar node)))) (define (pqueue-mutate! q p m) (and (bh-mutate! (pqueue-data q) p m) #t)) (define (pqueue-delete! q p) (and (bh-delete! (pqueue-data q) p) #t)) ;}}} ) ;}}} ;{{{ Operations Based On Fibonacci Heap (module $pqueue-fh% (pqueue $ds-tag make-pqueue pqueue? $pqueue-length pqueue-op pqueue-empty? pqueue-merge! pqueue-push! pqueue-pop! pqueue-memp pqueue-mutate! pqueue-delete!) (import fh%) (define $ds-tag "fh") ;{{{ Definition (define-record-type (pqueue $make-pqueue pqueue?) (fields (mutable data)) (nongenerative) (sealed #t)) (define make-pqueue (case-lambda [() ($make-pqueue (make-fh))] [(l) ($make-pqueue (list->fh l))] [(l op) ($make-pqueue (list->fh l op))])) ;}}} ;{{{ Operations (define ($pqueue-length q) (cdar (pqueue-data q))) (define (pqueue-op q) (caar (pqueue-data q))) (define (pqueue-empty? q) (fh-empty? (pqueue-data q))) (define (pqueue-merge! q1 q2) (fh-merge! (pqueue-data q1) (pqueue-data q2)) (set-cdr! (pqueue-data q2) '()) (set-cdr! (car (pqueue-data q2)) 0)) (define (pqueue-push! q x) (fh-push! (pqueue-data q) x) (void)) (define (pqueue-pop! q) (fh-pop! (pqueue-data q))) (define (pqueue-memp q p) (let ([node (fh-node (pqueue-data q) p)]) (and node (caar node)))) (define (pqueue-mutate! q p m) (and (fh-mutate! (pqueue-data q) p m) #t)) (define (pqueue-delete! q p) (and (fh-delete! (pqueue-data q) p) #t)) ;}}} ) ;}}} ;{{{ Operations Based On Pairing Heap (module $pqueue-ph% (pqueue $ds-tag make-pqueue pqueue? $pqueue-length pqueue-op pqueue-empty? pqueue-merge! pqueue-push! pqueue-pop! pqueue-memp pqueue-mutate! pqueue-delete!) (import ph%) (define $ds-tag "ph") ;{{{ Definition (define-record-type (pqueue $make-pqueue pqueue?) (fields (mutable data)) (nongenerative) (sealed #t)) (define make-pqueue (case-lambda [() ($make-pqueue (make-ph))] [(l) ($make-pqueue (list->ph l))] [(l op) ($make-pqueue (list->ph l op))])) ;}}} ;{{{ Operations (define ($pqueue-length q) (let loop ([t (cdr (pqueue-data q))]) (if (not t) 0 (let count ([t (cdr t)]) (if (null? t) 1 (+ (loop (car t)) (count (cdr t)))))))) (define (pqueue-op q) (car (pqueue-data q))) (define (pqueue-empty? q) (ph-empty? (pqueue-data q))) (define (pqueue-merge! q1 q2) (ph-merge! (pqueue-data q1) (pqueue-data q2)) (set-cdr! (pqueue-data q2) #f)) (define (pqueue-push! q x) (ph-push! (pqueue-data q) x) (void)) (define (pqueue-pop! q) (ph-pop! (pqueue-data q))) (define (pqueue-memp q p) (let ([node (ph-node (pqueue-data q) p)]) (and node (car node)))) (define (pqueue-mutate! q p m) (and (ph-mutate! (pqueue-data q) p m) #t)) (define (pqueue-delete! q p) (and (ph-delete! (pqueue-data q) p) #t)) ;}}} ) ;}}} ;{{{ Data-Structure-Independent Operations (module pqueue% (make-pqueue pqueue? pqueue-op pqueue-empty? pqueue-merge! pqueue-push! pqueue-pop! pqueue-memp pqueue-mutate! pqueue-delete!) (import $pqueue-bh%) ;{{{ Definition (module () (record-writer (type-descriptor pqueue) (lambda (x p wr) (format p "#<pqueue #[~a ~d ~a]>" $ds-tag ($pqueue-length x) (pqueue-op x))))) ;}}} ) ;}}} ;}}} ;{{{ Test Utilities (module (sh-demo lh-demo bh-demo fh-demo ph-demo) ;{{{ Macro (define-syntax with-demo (lambda (x) (syntax-case x () [(_ body ...) (if (file-exists? "libdemo.so") #'(letrec ([demo-init (lambda () ((foreign-procedure "demo_init" () void)))] [demo-exit (lambda () ((foreign-procedure "demo_exit" () void)))] [iclean (lambda () (keyboard-interrupt-handler kbdi))] [isetup (lambda () (keyboard-interrupt-handler kbdi@))] [kbdi (keyboard-interrupt-handler)] [kbdi@ (lambda () (iclean) (kbdi) (demo-init) (isetup))]) (load-shared-object "./libdemo.so") (isetup) (demo-init) body ... (demo-exit) (iclean)) #'(begin (display "\x1b;[2J") body ... (void)))]))) (define-syntax make-demo (lambda (x) (syntax-case x () [(md name) (let* ([obj (syntax->datum #'name)] [argl (syntax->list (datum->syntax #'md (if (pair? obj) (cdr obj) '())))] [prefix (symbol->string (if (pair? obj) (car obj) obj))]) (with-syntax ([% (datum->syntax #'md (string->symbol (string-append prefix "%")))] [fun (datum->syntax #'md (string->symbol (string-append prefix "-demo")))] [show (datum->syntax #'md (string->symbol (string-append prefix "-show")))] [push! (datum->syntax #'md (string->symbol (string-append prefix "-push!")))] [pop! (datum->syntax #'md (string->symbol (string-append prefix "-pop!")))] [delete! (datum->syntax #'md (string->symbol (string-append prefix "-delete!")))] [node (datum->syntax #'md (string->symbol (string-append "make-" prefix)))]) #`(defopt (fun n [opt '(4 0.3)]) (import %) (with-demo (let* ([m (car opt)] [t (cadr opt)] [z (exact (floor t))] [f (exact (floor (* (- t z) 1e9)))] [pops (lambda (n) (shuffle (let loop ([n n] [l '()]) (if (positive? n) (loop (1- n) (cons n l)) l))))] [mops (lambda (n) (let ([l (pops n)]) (let loop ([l l] [r n] [t n]) (unless (zero? r) (if (positive? (car l)) (let ([ins (list-tail l (random t))]) (set-cdr! ins (cons (- (car l)) (cdr ins))) (loop (cdr l) (1- r) t)) (loop (cdr l) r (1- t))))) l))] [pre (lambda (x) (display "\x1b;[1J\x1b;[H") (show x) (sleep (make-time 'time-duration f z)) x)] [gen (lambda (f) (lambda (r l) (fold-left (lambda (x y) (pre (f x y))) r l)))] [pdemo (let ([f #f] [ins (gen push!)] [del (let ([f #f] [pop (gen (lambda (x y) (pop! x) x))] [rem (gen (lambda (x y) (delete! x (lambda (x) (= x y)))))]) (lambda (x y) (set! f (not f)) (if f (pop x y) (rem x y))))]) (lambda (x y) (set! f (not f)) (if f (ins x y) (del x y))))] [mdemo (let* ([f #f] [ins push!] [del #f] [pop (lambda (x y) (pop! x) x)] [rem (lambda (x y) (delete! x (lambda (x) (= x y))))] [mix (gen (lambda (x y) (if (positive? y) (ins x y) (del x (- y)))))]) (lambda (x y) (set! f (not f)) (set! del (if f pop rem)) (mix x y)))]) (let-values ([(n demo ops) (if (negative? n) (values (- n) mdemo mops) (values n pdemo pops))]) (fold-left demo (node #,@argl) (map ops (make-list m n)))))))))] [(md name names ...) #'(begin (md name) (md names ...))]))) ;}}} (define (shuffle l) (let* ([n (length l)] [ind (make-vector n)]) (let loop ([i 0]) (when (< i n) (vector-set! ind i i) (loop (1+ i)))) (let loop ([i n] [ll '()]) (if (positive? i) (let ([j (random i)]) (set! i (1- i)) (unless (= i j) (let ([x (vector-ref ind i)] [y (vector-ref ind j)]) (vector-set! ind i y) (vector-set! ind j x))) (loop i (cons (list-ref l (vector-ref ind i)) ll))) ll)))) (make-demo sh lh bh fh ph)) ;}}} (random-seed (time-nanosecond (current-time))) (import pqueue%)
true
35cac8574a1914464f551fe630669c50b6ed26b3
c42881403649d482457c3629e8473ca575e9b27b
/src/kahua/sandbox.scm
6cc70937cd0748b0e68e838015c57b66569aa5f8
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
kahua/Kahua
9bb11e93effc5e3b6f696fff12079044239f5c26
7ed95a4f64d1b98564a6148d2ee1758dbfa4f309
refs/heads/master
2022-09-29T11:45:11.787420
2022-08-26T06:30:15
2022-08-26T06:30:15
4,110,786
19
5
null
2015-02-22T00:23:06
2012-04-23T08:02:03
Scheme
UTF-8
Scheme
false
false
3,552
scm
sandbox.scm
;; Kahua sandbox ;; ;; this module is based on banyan/sandbox.scm ;; written by Shiro Kawai ([email protected]). ;; ;; Copyright(C) 2003-2007 by Shiro Kawai ([email protected]) ;; (define-module kahua.sandbox (use srfi-1) (use srfi-2) (use srfi-13) (use srfi-14) (use kahua.plugin) (use kahua.config) (export make-sandbox-module export-module enable-module-except disable-bindings) ) (select-module kahua.sandbox) (define-syntax export-module (syntax-rules () ((_ module) #f) ((_ module name . names) (begin (define name (with-module module name)) (export name) (export-module module . names))) )) (define-macro (enable-module-except module . names) (define (fold-bindings module proc knil) (let* ((mod (find-module module)) (exports (module-exports mod))) (if (pair? exports) (fold (lambda (name knil) (if (memq name names) knil (cons (proc name) knil))) knil exports) (hash-table-fold (module-table mod) (lambda (name val knil) (if (memq name names) knil (cons (proc name) knil))) knil) ))) `(begin ,@(fold-bindings module (lambda (symbol) `(define ,symbol (with-module ,module ,symbol))) '()))) (define-syntax disable-bindings (syntax-rules () ((_) #f) ((_ name . names) (begin (define (name . args) (errorf "~a can't be used within sandbox module" (unwrap-syntax 'name))) (disable-bindings . names))) )) (define (make-sandbox-module) (let ((m (make-module #f))) (eval `(begin (import kahua.sandbox) ;; this is a temporary setting for existing example applications. ;; includes non safe procedues. (use kahua.config) (use kahua.util) (use kahua.partcont) (use kahua.gsid) (use kahua.persistence) (use kahua.user) (use kahua.session) (use kahua.server) (use kahua.developer) (use kahua.elem) (use kahua.xml-template) ;; for class redefinition. ;; require is done at compile time but also clear ;; to need this module. ;; TODO: but why does autoload in sandbox module?? (require "gauche/redefutil") (export-module kahua.plugin use-plugin) ,@(if (kahua-secure-sandbox) '((disable-bindings open-input-file open-output-file call-with-input-file call-with-output-file with-input-from-file with-output-to-file load transcript-on transcript-off null-environment scheme-report-environment interaction-environment exit sys-exit sys-abort import require select-module with-module define-module define-in-module find-module)) '()) ;; override (define use use-plugin) ) m) ;; Now, this resets module precedence list of m to null, voiding ;; all bindings but explicitly incorporated ones. ; (eval '(extend null) m) m)) (provide "kahua/sandbox")
true
a0bd9710a69228fe02fd029f9c3e49f7f4118801
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/tests/read-dat4.scm
1772c91534d6b2fd91ccf5c5a755fb7bec011ecb
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
594
scm
read-dat4.scm
(define-symconst ;; comment line 1 ;; comment line 2 (sizeof:heap 8) (heap:base 0) (heap:limit 1) (heap:object-offset 2) (heap:words-per-page 3) (heap:shift-words-per-page 4) (heap:mask-words-per-page 5) (heap:next 6) (heap:type 7) (heap-type:fixed-alloc #xdeadface) (heap-type:var-alloc #xbaadf00d) (negative-number -2147483639) ;; comment a (sizeof:var-heap 12) (var-heap:hope 9) (var-heap:bitmap 10) (var-heap:pages 11) ;; comment b (sizeof:fixed-heap 10) (fixed-heap:free-list 8) (fixed-heap:next-fixed-heap 9) )
false
7a067f5b749f11ff7bbb788198524bbb463e005b
45ae9c8ebcf4d60bfb0652b5c5ee61927d34200f
/scheme/coroutine.scm
9cef17f4a823c90c9b06e082a634c5b133d5e392
[]
no_license
cohei/playground
478717ced20cd2abd80b82aa6e0b8096ffd5a0fc
e24bd3cc3d9261094383f109d28280eaca0167f3
refs/heads/master
2023-06-07T19:24:04.444164
2023-05-26T23:36:46
2023-05-26T23:36:46
146,145,527
0
0
null
2022-03-23T10:54:44
2018-08-26T02:36:41
Haskell
UTF-8
Scheme
false
false
796
scm
coroutine.scm
(load "queue.scm") (define process-queue (make-queue)) (define (coroutine thunk) (insert-queue! process-queue thunk)) (define (start) ((delete-queue! process-queue))) (define (pause) (call/cc (lambda (k) (coroutine (lambda () (k #f))) (start)))) (coroutine (lambda () (let loop ([i 0]) (if (< i 10) (begin (display (+ 1 i)) (display " ") (pause) (loop (+ 1 i))))))) (coroutine (lambda () (let loop ([i 0]) (if (< i 10) (begin (display (integer->char (+ i 97))) (display " ") (pause) (loop (+ 1 i))))))) (start)
false
f6d5db1b185ac81aa3f81d7b5a8c5b5c7a34d412
80db6ef9bf5fbdccf3852fb6498153de140c33a6
/src/boot.scm
99107d17c290a3a7b1ce8e5875092c9afddd4df9
[ "MIT" ]
permissive
siraben/zkeme80
5c95a7792916244269c4b3cc6c5cb77e55b4920b
5a0bf0578070b257b4dfeeb81de2a034315cb35b
refs/heads/master
2021-11-11T20:28:12.966299
2021-11-04T15:34:03
2021-11-04T15:34:03
162,269,074
221
12
MIT
2021-06-08T01:55:54
2018-12-18T10:13:01
Scheme
UTF-8
Scheme
false
false
1,039
scm
boot.scm
(define boot-asm `((label boot) (label shutdown) (di) (ld a 6) (out (4) a) (ld a #x81) (out (7) a) (ld sp 0) (call sleep) (label restart) (label reboot) (di) (ld sp 0) (ld a 6) (out (4) a) (ld a #x81) (out (7) a) (ld a 3) (out (#xe) a) (xor a) (out (#xf) a) (call unlock-flash) (xor a) (out (#x25) a) (dec a) (out (#x26) a) (out (#x23) a) (out (#x22) a) (call lock-flash) (ld a 1) (out (#x20) a) (ld a #b0001011) (out (3) a) (ld hl #x8000) (ld (hl) 0) (ld de #x8001) (ld bc #x7fff) (ldir) ;; Arbitrarily complicated macros! ,@(concat-map (lambda (x) `((ld a ,x) ;; (call #x50f) (call lcd-delay) (out (#x10) a))) '(5 1 3 #x17 #xb #xef)) ;; "main", after everything has been set up. ;; Just go straight to the Forth portion! ,@forth-asm (jp shutdown)))
false
437378c4120a1e5e25d0010548ae3444eeacaa1b
2c291b7af5cd7679da3aa54fdc64dc006ee6ff9b
/ch2/prob.2.84.scm
f7503d4e9c2d49616c5119a9d09db94bca659a23
[]
no_license
etscrivner/sicp
caff1b3738e308c7f8165fc65a3f1bc252ce625a
3b45aaf2b2846068dcec90ea0547fd72b28f8cdc
refs/heads/master
2021-01-10T12:08:38.212403
2015-08-22T20:01:44
2015-08-22T20:01:44
36,813,957
1
0
null
null
null
null
UTF-8
Scheme
false
false
1,250
scm
prob.2.84.scm
(load "prob.2.83.scm") (define (num-raises-to-top arg) (define (iter num-raises curr-arg) (let ((proc (get 'raise (list (type-tag curr-arg))))) (if proc (iter (+ 1 num-raises) (raise curr-arg)) num-raises))) (iter 0 arg)) (define (n-raises arg num-raises) (if (<= num-raises 0) arg (n-raises (raise arg) (- num-raises 1)))) (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (if (= (length args) 2) (let ((raises-a1 (num-raises-to-top (car args))) (raises-a2 (num-raises-to-top (cadr args))) (a1 (car args)) (a2 (cadr args))) (cond ((< raises-a1 raises-a2) (apply-generic op a1 (n-raises a2 (- raises-a2 raises-a1)))) ((< raises-a2 raises-a1) (apply-generic op (n-raises a1 (- raises-a1 raises-a2)) a2)) (else (error "Items are of incompatible types" (list op a1 a2))))) (error "No method for these types" (list op type-tags)))))))
false
4da4195a8942cd982d92918e6c32fef98f847839
ce567bbf766df9d98dc6a5e710a77870753c7d29
/base/chapter8/abstract-types-lang/interp.scm
eda30a12a465cd93c69c990646a35d3556741e80
[]
no_license
dott94/eopl
1cbe2d98c948689687f88e514579e66412236fc9
47fadf6f2aa6ca72c831d6e2e2eccbe673129113
refs/heads/master
2021-01-18T06:42:35.921839
2015-01-21T07:06:43
2015-01-21T07:06:43
30,055,972
1
0
null
2015-01-30T04:21:42
2015-01-30T04:21:42
null
UTF-8
Scheme
false
false
4,254
scm
interp.scm
(module interp (lib "eopl.ss" "eopl") (require "drscheme-init.scm") (require "lang.scm") (require "data-structures.scm") (require "environments.scm") (provide value-of-program value-of) ;;;;;;;;;;;;;;;; the interpreter ;;;;;;;;;;;;;;;; ;; value-of-program : Program -> Expval ;; Page: 284 (define value-of-program (lambda (pgm) (cases program pgm (a-program (module-defs body) (let ((env (add-module-defns-to-env module-defs (empty-env)))) ;; (eopl:pretty-print env) (value-of body env)))))) ;; add-module-defns-to-env : Listof(Defn) * Env -> Env ;; Page: 284 (define add-module-defns-to-env (lambda (defs env) (if (null? defs) env (cases module-definition (car defs) (a-module-definition (m-name iface m-body) (add-module-defns-to-env (cdr defs) (extend-env-with-module m-name (value-of-module-body m-body env) env))))))) ;; We will have let* scoping inside a module body. ;; We put all the values in the environment, not just the ones ;; that are in the interface. But the typechecker will prevent ;; anybody from using the extras. ;; value-of-module-body : ModuleBody * Env -> TypedModule ;; Page: 285, 320 (define value-of-module-body (lambda (m-body env) (cases module-body m-body (defns-module-body (defns) (simple-module (defns-to-env defns env))) ))) (define raise-cant-apply-non-proc-module! (lambda (rator-val) (eopl:error 'value-of-module-body "can't apply non-proc-module-value ~s" rator-val))) ;; defns-to-env : Listof(Defn) * Env -> Env ;; Page: 285, 303 (define defns-to-env (lambda (defns env) (if (null? defns) (empty-env) ; we're making a little environment (cases definition (car defns) (val-defn (var exp) (let ((val (value-of exp env))) ;; new environment for subsequent definitions (let ((new-env (extend-env var val env))) (extend-env var val (defns-to-env (cdr defns) new-env))))) ;; type definitions are ignored at run time (else (defns-to-env (cdr defns) env)) )))) ;; value-of : Exp * Env -> ExpVal (define value-of (lambda (exp env) (cases expression exp (const-exp (num) (num-val num)) (var-exp (var) (apply-env env var)) (qualified-var-exp (m-name var-name) (lookup-qualified-var-in-env m-name var-name env)) (diff-exp (exp1 exp2) (let ((val1 (expval->num (value-of exp1 env))) (val2 (expval->num (value-of exp2 env)))) (num-val (- val1 val2)))) (zero?-exp (exp1) (let ((val1 (expval->num (value-of exp1 env)))) (if (zero? val1) (bool-val #t) (bool-val #f)))) (if-exp (exp0 exp1 exp2) (if (expval->bool (value-of exp0 env)) (value-of exp1 env) (value-of exp2 env))) (let-exp (var exp1 body) (let ((val (value-of exp1 env))) (let ((new-env (extend-env var val env))) ;; (eopl:pretty-print new-env) (value-of body new-env)))) (proc-exp (bvar ty body) (proc-val (procedure bvar body env))) (call-exp (rator rand) (let ((proc (expval->proc (value-of rator env))) (arg (value-of rand env))) (apply-procedure proc arg))) (letrec-exp (ty1 proc-name bvar ty2 proc-body letrec-body) (value-of letrec-body (extend-env-recursively proc-name bvar proc-body env))) ))) ;; apply-procedure : Proc * ExpVal -> ExpVal (define apply-procedure (lambda (proc1 arg) (cases proc proc1 (procedure (var body saved-env) (value-of body (extend-env var arg saved-env)))))) )
false
13f2afe12e95af5ee9083ea0ffda402e826bc01f
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/runtime/rep.scm
64b7b908d02c87277c88ad62c7c9a141a392a411
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
10,564
scm
rep.scm
;;; -*-Scheme-*- ;;; ;;; ;;; Copyright (c) 1987 Massachusetts Institute of Technology ;;; ;;; This material was developed by the Scheme project at the ;;; Massachusetts Institute of Technology, Department of ;;; Electrical Engineering and Computer Science. Permission to ;;; copy this software, to redistribute it, and to use it for any ;;; purpose is granted, subject to the following restrictions and ;;; understandings. ;;; ;;; 1. Any copy made of this software must include this copyright ;;; notice in full. ;;; ;;; 2. Users of this software agree to make their best efforts (a) ;;; to return to the MIT Scheme project any improvements or ;;; extensions that they make, so that these may be included in ;;; future releases; and (b) to inform MIT of noteworthy uses of ;;; this software. ;;; ;;; 3. All materials developed as a consequence of the use of this ;;; software shall duly acknowledge such use, in accordance with ;;; the usual standards of acknowledging credit in academic ;;; research. ;;; ;;; 4. MIT has made no warrantee or representation that the ;;; operation of this software will be error-free, and MIT is ;;; under no obligation to provide any services, by way of ;;; maintenance, update, or otherwise. ;;; ;;; 5. In conjunction with products arising from the use of this ;;; material, there shall be no use of the name of the ;;; Massachusetts Institute of Technology nor of any adaptation ;;; thereof in any advertising, promotional, or sales literature ;;; without prior written consent from MIT in each case. ;;; ;;;; Read-Eval-Print Loop (declare (usual-integrations)) ;;;; Command Loops (define make-command-loop) (define push-command-loop) (define push-command-hook) (define with-rep-continuation) (define continue-rep) (define rep-continuation) (define rep-state) (define rep-level) (define abort->nearest) (define abort->previous) (define abort->top-level) (define top-level-driver-hook) (let () ;;; (define top-level-driver-hook) (define previous-driver-hook) (define nearest-driver-hook) (define current-continuation) (define current-state) (define current-level 0) ;; PUSH-COMMAND-HOOK is provided so that the Butterfly, in particular, ;; can add its own little code just before creating a REP loop (set! push-command-hook (lambda (startup driver state continuation) (continuation startup driver state (lambda () 'ignore)))) (set! make-command-loop (named-lambda (make-command-loop message driver) (define (driver-loop message) (driver-loop (with-rep-continuation (lambda (quit) (set! top-level-driver-hook quit) (set! nearest-driver-hook quit) (driver message))))) (set-interrupt-enables! interrupt-mask-gc-ok) (fluid-let ( ;;;;;;;;;;;;;;;;;;;;;;;;;;; (top-level-driver-hook) (nearest-driver-hook)) (driver-loop message)))) (set! push-command-loop (named-lambda (push-command-loop startup-hook driver initial-state) (define (restart entry-hook each-time) (let ((reentry-hook (call-with-current-continuation (lambda (again) (set! nearest-driver-hook again) (set-interrupt-enables! interrupt-mask-all) (each-time) (entry-hook) (loop))))) (set-interrupt-enables! interrupt-mask-gc-ok) (restart reentry-hook each-time))) (define (loop) (set! current-state (driver current-state)) (loop)) (fluid-let ((current-level (1+ current-level)) (previous-driver-hook nearest-driver-hook) (nearest-driver-hook) (current-state)) (push-command-hook startup-hook driver initial-state (lambda (startup-hook driver initial-state each-time) (set! current-state initial-state) (restart startup-hook each-time)))))) (set! with-rep-continuation (named-lambda (with-rep-continuation receiver) (call-with-current-continuation (lambda (raw-continuation) (let ((continuation (raw-continuation->continuation raw-continuation))) (fluid-let ((current-continuation continuation)) (receiver continuation))))))) (set! continue-rep (named-lambda (continue-rep value) (current-continuation (if (eq? current-continuation top-level-driver-hook) (lambda () (write-line value)) value)))) (set! abort->nearest (named-lambda (abort->nearest message) (nearest-driver-hook message))) (set! abort->previous (named-lambda (abort->previous message) ((if (null? previous-driver-hook) nearest-driver-hook previous-driver-hook) message))) (set! abort->top-level (named-lambda (abort->top-level message) (top-level-driver-hook message))) (set! rep-continuation (named-lambda (rep-continuation) current-continuation)) (set! rep-state (named-lambda (rep-state) current-state)) (set! rep-level (named-lambda (rep-level) current-level)) ) ; LET ;;;; Read-Eval-Print Loops (define *rep-base-environment*) (define *rep-current-environment*) (define *rep-base-syntax-table*) (define *rep-current-syntax-table*) (define *rep-base-prompt*) (define *rep-current-prompt*) (define *rep-base-input-port*) (define *rep-current-input-port*) (define *rep-base-output-port*) (define *rep-current-output-port*) (define *rep-keyboard-map*) (define *rep-error-hook*) (define (rep-environment) *rep-current-environment*) (define (rep-base-environment) *rep-base-environment*) (define (set-rep-environment! environment) (set! *rep-current-environment* environment) (environment-warning-hook *rep-current-environment*)) (define (set-rep-base-environment! environment) (set! *rep-base-environment* environment) (set! *rep-current-environment* environment) (environment-warning-hook *rep-current-environment*)) (define (rep-syntax-table) *rep-current-syntax-table*) (define (rep-base-syntax-table) *rep-base-syntax-table*) (define (set-rep-syntax-table! syntax-table) (set! *rep-current-syntax-table* syntax-table)) (define (set-rep-base-syntax-table! syntax-table) (set! *rep-base-syntax-table* syntax-table) (set! *rep-current-syntax-table* syntax-table)) (define (rep-prompt) *rep-current-prompt*) (define (set-rep-prompt! prompt) (set! *rep-current-prompt* prompt)) (define (rep-base-prompt) *rep-base-prompt*) (define (set-rep-base-prompt! prompt) (set! *rep-base-prompt* prompt) (set! *rep-current-prompt* prompt)) (define (rep-input-port) *rep-current-input-port*) (define (rep-output-port) *rep-current-output-port*) (define environment-warning-hook identity-procedure) (define rep-read-hook read) (define (rep-value-hook values-list) (let loop ((vals values-list)) (if vals (begin (write-line (car vals)) (loop (cdr vals)))))) (define make-rep) (define push-rep) (define reader-history) (define printer-history) (define (rep-transcript-read-hook expression) #f) (define (rep-transcript-value-hook value) #f) ;; The rep-make-hook and rep-push-hook are provided so that extra fluids can ;; be saved for each rep loop. These procedures are munged for commonlisp. (define (rep-make-hook thunk) (thunk)) (define (rep-push-hook thunk) (thunk)) (let () (set! make-rep (named-lambda (make-rep environment syntax-table prompt input-port output-port message) (fluid-let ((*rep-base-environment* environment) (*rep-base-syntax-table* syntax-table) (*rep-base-prompt* prompt) (*rep-base-input-port* input-port) (*rep-base-output-port* output-port) (*rep-keyboard-map* (keyboard-interrupt-dispatch-table)) (*rep-error-hook* (access *error-hook* error-system))) (rep-make-hook (lambda () (make-command-loop message rep-top-driver)))))) (define (rep-top-driver message) (push-rep *rep-base-environment* message *rep-base-prompt*)) (set! push-rep (named-lambda (push-rep environment message prompt) (fluid-let ((*rep-current-environment* environment) (*rep-current-syntax-table* *rep-base-syntax-table*) (*rep-current-prompt* prompt) (*rep-current-input-port* *rep-base-input-port*) (*rep-current-output-port* *rep-base-output-port*) (*current-input-port* *rep-base-input-port*) (*current-output-port* *rep-base-output-port*) ((access *error-hook* error-system) *rep-error-hook*)) (rep-push-hook (lambda () (with-keyboard-interrupt-dispatch-table *rep-keyboard-map* (lambda () (environment-warning-hook *rep-current-environment*) (push-command-loop message rep-driver (make-rep-state (make-history 5) (make-history 10)))))))))) (define with-values (make-primitive-procedure 'with-values)) (define (rep-driver state) (*rep-current-prompt*) (let ((object (let ((scode (let ((s-expression (rep-read-hook))) (rep-transcript-read-hook s-expression) (record-in-history! (rep-state-reader-history state) s-expression) (syntax s-expression *rep-current-syntax-table*)))) (with-new-history (lambda () (with-values (lambda () (scode-eval scode *rep-current-environment*)) list)))))) (record-in-history! (rep-state-printer-history state) object) (rep-transcript-value-hook object) (rep-value-hook object)) state) ;;; History Manipulation (define (make-history size) (let ((list (make-list size '()))) (append! list list) (vector history-tag size list))) (define history-tag '(REP-HISTORY)) (define (record-in-history! history object) (if (not (null? (vector-ref history 2))) (begin (set-car! (vector-ref history 2) object) (vector-set! history 2 (cdr (vector-ref history 2)))))) (define (read-history history n) (if (not (and (integer? n) (not (negative? n)) (< n (vector-ref history 1)))) (error "Bad argument: READ-HISTORY" n)) (list-ref (vector-ref history 2) (- (-1+ (vector-ref history 1)) n))) (define ((history-reader selector name) n) (let ((state (rep-state))) (if (rep-state? state) (read-history (selector state) n) (error "Not in REP loop" name)))) (define rep-state-tag "REP State") (define (make-rep-state reader-history printer-history) (vector rep-state-tag reader-history printer-history)) (define (rep-state? object) (and (vector? object) (not (zero? (vector-length object))) (eq? (vector-ref object 0) rep-state-tag))) (define rep-state-reader-history vector-second) (define rep-state-printer-history vector-third) (set! reader-history (history-reader rep-state-reader-history 'READER-HISTORY)) (set! printer-history (history-reader rep-state-printer-history 'PRINTER-HISTORY)) )
false
8067d6673a286c9b62affad1ad57cfa64ac3df91
5927f3720f733d01d4b339b17945485bd3b08910
/examples/user.filter
32ffe6291272b8d6338a6d452cd148aa344ea981
[]
no_license
ashinn/hato
85e75c3b6c7ca7abca512dc9707da6db3b50a30d
17a7451743c46f29144ce7c43449eef070655073
refs/heads/master
2016-09-03T06:46:08.921164
2013-04-07T03:22:52
2013-04-07T03:22:52
32,322,276
5
0
null
null
null
null
UTF-8
Scheme
false
false
509
filter
user.filter
;; sample ~/.hato/filter file -*- mode: scheme -*- ;; initial duplicate & spam checks (cond ((is-duplicate?) (print "discarding duplicate: " (Message-Id)) (discard)) ((not (white-list?)) (cond ((not (domain-key-verify)) (refuse)) ((> (spam-probability) 0.90) (refuse)) ((> (spam-probability) 0.60) (return "spam")) (else (white-list))))) ;; manual filtering & folder handling, etc. (cond ((member "[email protected]" (To)) "my-mail-list"))
false
95d15b2d413181913b0a4f1dcf234e4c261a6cc5
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/scheme/ephemeron.sld
185009283499ef171293c5f000400bcd522fee9f
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
60
sld
ephemeron.sld
(define-library (scheme ephemeron) (alias-for (srfi 124)))
false
a067091b8e2d9e8a627a3840f7928f724b007850
eef5f68873f7d5658c7c500846ce7752a6f45f69
/test/concurrency-termite.scm
76d8d8990555b43fa71f32f66b2f54f5d9cd78ee
[ "MIT" ]
permissive
alvatar/spheres
c0601a157ddce270c06b7b58473b20b7417a08d9
568836f234a469ef70c69f4a2d9b56d41c3fc5bd
refs/heads/master
2021-06-01T15:59:32.277602
2021-03-18T21:21:43
2021-03-18T21:21:43
25,094,121
13
3
null
null
null
null
UTF-8
Scheme
false
false
2,991
scm
concurrency-termite.scm
(load (spheres/util test)) ;;------------------------------------------------------------------------------- ;; Multiple-instance tests ;; Node 2 (define (spawn-gambit code #!key (flags-string #f) (verbose #f)) ;; This is a hack transforming all ' into ` since they work in all cases and makes ;; life easier when passed as a string with ' delimiters to bash (let ((quotes->semiquotes (lambda (string) (let ((length (string-length string)) (transformed (string-copy string))) (let recur ((n 0)) (if (< n length) (begin (if (eq? #\' (string-ref string n)) (string-set! transformed n #\`)) (recur (+ n 1))) transformed)))))) (let ((code-string (quotes->semiquotes (object->string (cons 'begin code))))) (and verbose (begin (println "gambit-eval-here input code: ") (pp code) (println "gambit-eval-here string: ") (print code-string))) (open-process (list path: "gsi" arguments: (if flags-string (list flags-string "-e" code-string) (list "-e" code-string)) stdout-redirection: #f))))) (spawn-gambit '((load (spheres/concurrency termite)) (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002)) (node-init node2) (thread-sleep! 6))) ;; Wait to make sure Gambit node2 is up and running (thread-sleep! 1) ;; Node 1 (load (spheres/concurrency termite)) (define node1 (make-node "localhost" 3001)) (define node2 (make-node "localhost" 3002)) (node-init node1) ;;(debug (current-node)) (on node2 (lambda () (write 'success) (newline) (println "Termite task migration test successful!"))) (define pid (spawn (lambda () (migrate-task node2) (termite-info 'migration-ok!)))) ;;------------------------------------------------------------------------------- ;; Single-instance tests (test-begin "termite" 1) (test-equal "single instance messaging" (let () (define (worker) (let* ((msg (?)) (pid (car msg)) (fun (cadr msg)) (arg (caddr msg))) (! pid (fun arg)))) (define (pmap fun lst) ;; spawn workers (for-each (lambda (x) (let ((p (spawn worker))) (! p (list (self) fun x)))) lst) ;; collect results (let loop ((i (length lst)) (result '())) (if (= 0 i) (reverse result) (loop (- i 1) (cons (?) result))))) (define (f x) (thread-sleep! x) x) (pmap f (list 1 2 3 2 1))) '(1 1 2 2 3)) (test-end)
false
1d94c0e11c7a2ed774c6d0f9371d38b78d3fa477
23122d4bae8acdc0c719aa678c47cd346335c02a
/pe/94.scm
15f68c58918718e16bfc2620d5f14f60c1bb8469
[]
no_license
Arctice/advent-of-code
9076ea5d2e455d873da68726b047b64ffe11c34c
2a2721e081204d4fd622c2e6d8bf1778dcedab3e
refs/heads/master
2023-05-24T23:18:02.363340
2023-05-04T09:04:01
2023-05-04T09:06:24
225,228,308
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,474
scm
94.scm
#!chezscheme (import (scheme) (pe)) ;; It is easily proved that no equilateral triangle exists with integral ;; length sides and integral area. However, the almost equilateral triangle ;; 5-5-6 has an area of 12 square units. ;; We shall define an almost equilateral triangle to be a triangle for which ;; two sides are equal and the third differs by no more than one unit. ;; Find the sum of the perimeters of all almost equilateral triangles with ;; integral side lengths and area and whose perimeters do not exceed one ;; billion (1,000,000,000). ;; √(a² - ((a+1)/2)²) * (a+1) * 0.5 (define (integer-triangle a c) (let ([s (* (- (* a a) (* c c 1/4)) (+ a 1) (+ a 1) 1/4)]) (square? s))) (define (square? x) (let-values ([[s r] (exact-integer-sqrt x)]) (zero? r))) (define (problem-94) (let next ([a 3] [count 0]) (let ([int-area (or (integer-triangle a (+ a 1)) (integer-triangle a (- a 1)))] [perimeter (* 3 a)]) (cond [(< 1000000000 perimeter) count] [int-area ;; (printf "~s-~s-~s: ~s\n" a a (+ 1 a) perimeter) (next (if (< 1000 a) (let ([next (inexact->exact (round (* a 3.73)))]) (if (even? next) (- next 1) next)) (+ a 2)) (+ count (+ perimeter (if (integer-triangle a (+ a 1)) 1 -1))))] [else (next (+ a 2) count)])))) (define answer-94 '3218c6bb59f2539ec39ad4bf37c10913)
false
2c1e4cdd617c4dbd48d066d761137d5371fa0835
eb32c279a34737c769d4e2c498a62c761750aeb5
/test/test-parser.scm
be7610e157160f222c957e76b78301d7576d21ce
[ "Apache-2.0" ]
permissive
theschemer/lyonesse
baaf340be710f68b84c1969befc6ddbd2be3739b
9d9624e3141ea3acaa670526cbe52c2d6546beef
refs/heads/master
2021-06-10T02:58:28.040995
2016-11-29T21:28:11
2016-11-29T21:28:11
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,142
scm
test-parser.scm
(import (rnrs (6)) (prefix (lyonesse testing) test:) (lyonesse aux-keyword) (lyonesse functional) (lyonesse parser) (lyonesse sexpr-builder simple)) (define (parse:error state input) (error parse:error "Error parsing." state input)) (define (parse:exit state input) state) (define-parser (parse:expr ch) [eof-object? parse:exit (sb:close-all)] [char-whitespace? parse:expr ()] [char-numeric? parse:number (sb:new-string (sb:add ch))] [($ memq <> '(#\- #\+ #\* #\/)) parse:expr (sb:new-symbol (sb:add ch) sb:close)] [else parse:error (sb:close-all)]) (define-parser (parse:number ch) [eof-object? parse:exit (sb:close-all)] [char-numeric? parse:number ((sb:add ch))] [char-whitespace? parse:expr (sb:close)] [else parse:error (sb:close-all)]) (test:unit "small parser" ([input (open-string-input-port "6 * 7")]) (test:that "we can read expression" (equal? '("6" * "7") (parse:expr (sb:start) input))))
false
3a23ac45445ee9952db7db0485dee1a405b8ca53
b62560d3387ed544da2bbe9b011ec5cd6403d440
/crates/steel-core/src/scheme/kernel.scm
eae8915af363721c0570e9fc6c2c9f88f4d744d8
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Apache-2.0" ]
permissive
mattwparas/steel
c6fb91b20c4e613e6a8db9d9310d1e1c72313df2
700144a5a1aeb33cbdb2f66440bbe38cf4152458
refs/heads/master
2023-09-04T03:41:35.352916
2023-09-01T03:26:01
2023-09-01T03:26:01
241,949,362
207
10
Apache-2.0
2023-09-06T04:31:21
2020-02-20T17:39:28
Rust
UTF-8
Scheme
false
false
18,521
scm
kernel.scm
;; The kernel for Steel. ;; This contains core forms that are expanded during the last phase of macro expansion ;; Macros that are exported from the kernel and applied on code externally are defined via ;; the form `(#%define-syntax <macro> <body>)`. ;; ;; This makes this function publicly available for the kernel to expand ;; forms with. ; (define *transformer-functions* (hashset)) (define-syntax #%define-syntax (syntax-rules () [(#%define-syntax (name arg) expr) (begin (register-macro-transformer! (symbol->string 'name)) (define (name arg) expr))] [(#%define-syntax (name arg) exprs ...) (begin (register-macro-transformer! (symbol->string 'name)) (define (name arg) exprs ...))] [(#%define-syntax name expr) (begin (register-macro-transformer! (symbol->string 'name)) (define name expr))])) ;; Kernal-lambda -> Used in the meantime while `lambda` finds its way out of the reserved keywords. (define-syntax klambda (syntax-rules () [(klambda () expr exprs ...) (#%plain-lambda () expr exprs ...)] [(klambda (x xs ...) expr exprs ...) (#%plain-lambda (x xs ...) expr exprs ...)] [(klambda x expr exprs ...) (#%plain-lambda x expr exprs ...)])) ;; Enumerate the given list starting at index `start` (define (enumerate start accum lst) (if (empty? lst) (reverse accum) (enumerate (+ start 1) (cons (list (car lst) start) accum) (cdr lst)))) (define (hash->list hm) (transduce (transduce hm (into-list)) (mapping (lambda (pair) ;; If we have a symbol as a key, that means we need to ;; quote it before we put it back into the map (if (symbol? (car pair)) ;; TODO: @Matt - this causes a parser error ;; (cons `(quote ,(car x)) (cdr x)) (list (list 'quote (car pair)) (list 'quote (cadr pair))) pair))) (flattening) (into-list))) (define (mutable-keyword? x) (equal? x '#:mutable)) (define (transparent-keyword? x) (equal? x '#:transparent)) (#%define-syntax (struct expr) (define unwrapped (syntax-e expr)) (define struct-name (syntax->datum (second unwrapped))) (define fields (syntax->datum (third unwrapped))) (define options (let ([raw (cdddr unwrapped)]) ; (displayln raw) (if (empty? raw) raw (map syntax->datum raw)))) (struct-impl struct-name fields options)) ;; Macro for creating a new struct, in the form of: ;; `(struct <struct-name> (fields ...) options ...)` ;; The options can consist of the following: ;; ;; Single variable options (those which their presence indicates #true) ;; - #:mutable ;; - #:transparent ;; ;; Other options must be presented as key value pairs, and will get stored ;; in the struct instance. They will also be bound to the variable ;; ___<struct-name>-options___ in the same lexical environment where the ;; struct was defined. For example: ;; ;; (Applesauce (a b c) #:mutable #:transparent #:unrecognized-option 1234) ;; ;; Will result in the value `___Applesauce-options___` like so: ;; (hash #:mutable #true #:transparent #true #:unrecognized-option 1234) ;; ;; By default, structs are immutable, which means setter functions will not ;; be generated. Also by default, structs are not transparent, which means ;; printing them will result in an opaque struct that does not list the fields (define (struct-impl struct-name fields options) ;; Add a field for storing the options, and for the index to the func (define field-count (length fields)) ;; Mark whether this is actually a mutable and transparent struct, and ;; then drain the values from the (define mutable? (contains? mutable-keyword? options)) (define transparent? (contains? transparent-keyword? options)) (define options-without-single-keywords (transduce options (filtering (lambda (x) (not (mutable-keyword? x)))) (filtering (lambda (x) (not (transparent-keyword? x)))) (into-list))) (define extra-options (hash '#:mutable mutable? '#:transparent transparent? '#:fields fields)) (when (not (list? fields)) (error! "struct expects a list of field names, found " fields)) (when (not (symbol? struct-name)) (error! "struct expects an identifier as the first argument, found " struct-name)) (when (odd? (length options-without-single-keywords)) (error! "struct options are malformed - each option requires a value")) ;; Update the options-map to have the fields included (let* ([options-map (apply hash options-without-single-keywords)] [options-map (hash-union options-map extra-options)] [maybe-procedure-field (hash-try-get options-map '#:prop:procedure)]) (when (and maybe-procedure-field (> maybe-procedure-field (length fields))) (error! "struct #:prop:procedure cannot refer to an index that is out of bounds")) `(begin (define ,(concat-symbols '___ struct-name '-options___) (hash ,@(hash->list options-map))) (define ,struct-name 'unintialized) (define ,(concat-symbols 'struct: struct-name) 'uninitialized) (define ,(concat-symbols struct-name '?) 'uninitialized) ,@(map (lambda (field) `(define ,(concat-symbols struct-name '- field) 'uninitialized)) fields) ;; If we're mutable, set up the identifiers to later be `set!` ;; below in the same scope ,@(if mutable? (map (lambda (field) `(define ,(concat-symbols 'set- struct-name '- field '!) 'unintialized)) fields) (list)) (let ([prototypes (make-struct-type (quote ,struct-name) ,field-count)]) (let ([struct-type-descriptor (list-ref prototypes 0)] [constructor-proto (list-ref prototypes 1)] [predicate-proto (list-ref prototypes 2)] [getter-proto (list-ref prototypes 3)] [setter-proto (list-ref prototypes 4)]) (set! ,(concat-symbols 'struct: struct-name) struct-type-descriptor) (#%vtable-update-entry! struct-type-descriptor ,maybe-procedure-field ,(concat-symbols '___ struct-name '-options___)) (set! ,struct-name constructor-proto) ,(new-make-predicate struct-name fields) ,@(new-make-getters struct-name fields) ;; If this is a mutable struct, generate the setters ,@(if mutable? (new-make-setters struct-name fields) (list)) void))))) (define (new-make-predicate struct-name fields) `(set! ,(concat-symbols struct-name '?) predicate-proto)) ; (define (new-make-constructor struct-name procedure-index fields) ; `(set! ; ,struct-name ; (lambda ,fields ; (constructor-proto ,(concat-symbols '___ struct-name '-options___) ,procedure-index ,@fields)))) (define (new-make-getters struct-name fields) (map (lambda (field) `(set! ,(concat-symbols struct-name '- (car field)) (lambda (this) (getter-proto this ,(list-ref field 1))))) (enumerate 0 '() fields))) (define (new-make-setters struct-name fields) (map (lambda (field) `(set! ,(concat-symbols 'set- struct-name '- (car field) '!) (lambda (this value) (setter-proto this ,(list-ref field 1) value)))) (enumerate 0 '() fields))) (define (%make-memoize f) (lambda n (let ([previous-value (%memo-table-ref %memo-table f n)]) (if (and (Ok? previous-value) (Ok->value previous-value)) (begin ; (displayln "READ VALUE: " previous-value " with args " n) (Ok->value previous-value)) (let ([new-value (apply f n)]) ; (displayln "SETTING VALUE " new-value " with args " n) (%memo-table-set! %memo-table f n new-value) new-value))))) (define *gensym-counter* 0) (define (gensym) (set! *gensym-counter* (+ 1 *gensym-counter*)) (string->symbol (string-append "##gensym" (to-string *gensym-counter*)))) ;; TODO: @Matt -> for whatever reason, using ~> plus (lambda (x) ...) generates a stack overflow... look into that (define (make-unreadable symbol) (~>> symbol (symbol->string) (string-append "##") (string->symbol))) ; (define (define-values bindings expr) ; `(begin ; (define ,(make-unreadable '#%proto-define-values-binding-gensym__) ; ,expr) ; ,@(map (lambda (binding-index-pair) ; `(define ,(car binding-index-pair) ; ,(list-ref binding-index-pair 1))) ; (enumerate 0 '() bindings)))) (#%define-syntax (define-values expr) ; (displayln expr) (define underlying (syntax-e expr)) (define bindings (syntax->datum (second underlying))) (define expression (third underlying)) (define unreadable-list-name (make-unreadable '#%proto-define-values-binding-gensym__)) `(begin (define ,unreadable-list-name ,expression) ,@(map (lambda (binding-index-pair) `(define ,(car binding-index-pair) (list-ref ,unreadable-list-name ,(list-ref binding-index-pair 1)))) (enumerate 0 '() bindings)))) (#%define-syntax (#%better-lambda expr) ; (displayln "Expanding: " expr) ; (displayln "unwrapping one level..." (syntax-e expr)) (quasisyntax (list 10 20 30))) ;; TODO: make this not so suspect, but it does work! (#%define-syntax (#%current-kernel-transformers expr) (cons 'list (map (lambda (x) (list 'quote x)) (current-macro-transformers!)))) (#%define-syntax (#%fake-lambda expr) (define underlying (syntax-e expr)) (define rest (cdr underlying)) ; (displayln rest) ; (displayln (syntax-e (list-ref rest 1))) (cons '#%plain-lambda rest)) ;; TODO: Come back to this once theres something to attach it to ; (define (@doc expr comment) ; (if (equal? (car expr) 'define) ; `(begin ; (define ,(concat-symbols '__doc- (second expr)) ,comment) ; ,expr ; ) ; expr)) ;; TODO: This is going to fail simply because when re-reading in the body of ;; expanded functions. The parser is unable to parse already made un-parseable ;; items. In this case, we should not re-parse the items, but rather ;; convert the s-expression BACK into a typed ast instead. ; (define (default-loop args found-pair) ; (cond [(empty? args) #f] ; [(pair? (car args)) (default-loop (cdr args) #t)] ; [else ; (if found-pair ; #t ; (default-loop (cdr args) #f))])) ; (define (non-default-after-default? args) ; (default-loop args #f)) ; (define (%test-lambda% args body) ; ; (->/c non-default-after-default? any/c any/c) ; (when (non-default-after-default? args) ; (error! "Non default argument occurs after a default argument")) ; (let ( ; (args-len (length args)) ; (non-default-bindings (filter (lambda (x) (not (pair? x))) args)) ; (bindings ; (transduce ; ;; Now we have attached the index of the list to the iteration ; args ; ;; extract out the arguments that have a default associated ; ;; So from the argument list like so: ; ;; (a b [c <expr>] [d <expr>]) ; ;; We will get out ([c <expr>] [d <expr>]) ; (filtering (lambda (x) (pair? x))) ; (enumerating) ; ;; Map to the let form of (binding expr) ; (mapping (lambda (x) ; ;; ( (x, expr), index ) ; ;; TODO: clean this up ; (let ((var-name (car (list-ref x 1))) ; (expr (car (cdr (list-ref x 1)))) ; (index (car x))) ; `(,var-name (let ((,var-name (try-list-ref !!dummy-rest-arg!! ,index))) ; (if ,var-name ,var-name ,expr)))))) ; (into-list)))) ; ; (displayln bindings) ; ;; TODO: Yes I understand this violates the macro writers bill of rights ; ;; that being said I'm only doing this as a proof of concept anyway so it can be rewritten ; ;; to be simpler and put the weight on the compiler later ; (if (equal? args-len (length non-default-bindings)) ; `(lambda ,args ,body) ; ; (displayln "hello world") ; `(lambda (,@non-default-bindings . !!dummy-rest-arg!!) ; ; (displayln !!dummy-rest-arg!!) ; (if (> (+ ,(length non-default-bindings) (length !!dummy-rest-arg!!)) ; ,args-len) ; (error! "Arity mismatch - function expected " ,args-len) ; void) ; (let (,@bindings) ,body))))) ; (define (keyword? symbol) ; (unless (symbol? symbol) (return! #false)) ; (let ((symbol-as-list (-> symbol (symbol->string) (string->list)))) ; (and (equal? (list-ref symbol-as-list 0) #\#) ; (equal? (list-ref symbol-as-list 1) #\:)))) ; (define (keyword? symbol) ; (and (symbol? symbol) (-> symbol (symbol->string) (starts-with? "#:")))) ; (define (drop-while pred? lst) ; (cond [(empty? lst) lst] ; [(pred? (car lst)) (drop-while pred? (cdr lst))] ; [else lst])) ; (define (take-while-accum pred? lst accum) ; (cond [(empty? lst) accum] ; [(pred? (car lst)) (take-while-accum pred? (cdr lst) (cons (car lst) accum))] ; [else accum])) ; (define (take-while pred? lst) ; (reverse (take-while-accum pred? lst '()))) ; (define (all func lst) ; (if (null? lst) ; #t ; (if (func (car lst)) ; (all func (cdr lst)) ; #f))) ; (define (contains? pred? lst) ; ; (displayln lst) ; (cond [(empty? lst) #f] ; [(pred? (car lst)) #t] ; [else (contains? pred? (cdr lst))])) ; (define (contains-keywords? args) ; (contains? keyword? args)) ; (define (contains-defaults? args) ; (contains? pair? args)) ; (define (%better-lambda% args body) ; (cond [(contains-keywords? args) (%lambda-keyword% args body)] ; [(contains-defaults? args) (%test-lambda% args body)] ; [else => `(#%plain-lambda ,args ,body)])) ; (define (%lambda-keyword% args body) ; ;; TODO: Using define here causes a bug with the internal define expansion ; ; (define keyword-args (drop-while (lambda (x) (not (keyword? x))) args)) ; (define keyword-args (drop-while (lambda (x) (not (keyword? x))) args)) ; (when (odd? (length keyword-args)) ; (error! "keyword arguments malformed - each option requires a value")) ; (define non-keyword-args (take-while (lambda (x) (not (keyword? x))) args)) ; (define keyword-map (apply hash keyword-args)) ; (when (not (all keyword? (hash-keys->list keyword-map))) ; (error! "Non keyword arguments found after the first keyword argument")) ; (define bindings ; (transduce ; keyword-map ; (mapping (lambda (x) ; (let* ((keyword (list-ref x 0)) ; (original-var-name (list-ref x 1)) ; (expr (if (pair? original-var-name) ; (list-ref original-var-name 1) ; original-var-name)) ; (var-name (if (pair? original-var-name) ; (list-ref original-var-name 0) ; original-var-name))) ; `(,var-name (let ((,var-name (hash-try-get !!dummy-rest-arg!! (quote ,keyword)))) ; (if (hash-contains? !!dummy-rest-arg!! (quote ,keyword)) ; ,var-name ; (if ; ,(pair? original-var-name) ; ,expr ; (error! ; "Function application missing required keyword argument: " ; (quote ,keyword))))))))) ; (into-list))) ; `(lambda (,@non-keyword-args . !!dummy-rest-arg!!) ; (let ((!!dummy-rest-arg!! (apply hash !!dummy-rest-arg!!))) ; (let (,@bindings) ,body)))) ; (let ((keyword-args (drop-while (lambda (x) (not (keyword? x))) args)) ; (non-keyword-args (take-while (lambda (x) (not (keyword? x))) args))) ; (when (odd? (length keyword-args)) ; (error! "keyword arguments malformed - each option requires a value")) ; (let ((keyword-map (apply hash keyword-args))) ; (when (not (all keyword? (hash-keys->list keyword-map))) ; (error! "Non keyword arguments found after the first keyword argument")) ; (let ((bindings ; (transduce ; keyword-map ; (mapping (lambda (x) ; (let* ((keyword (list-ref x 0)) ; (original-var-name (list-ref x 1)) ; (expr (if (pair? original-var-name) (list-ref original-var-name 1) original-var-name)) ; (var-name (if (pair? original-var-name) (list-ref original-var-name 0) original-var-name))) ; `(,var-name (let ((,var-name (hash-try-get !!dummy-rest-arg!! (quote ,keyword)))) ; (if (hash-contains? !!dummy-rest-arg!! (quote ,keyword)) ; ,var-name ; (if ; ,(pair? original-var-name) ; ,expr ; (error! "Function application missing required keyword argument: " (quote ,keyword))))))))) ; (into-list)))) ; `(lambda (,@non-keyword-args . !!dummy-rest-arg!!) ; (let ((!!dummy-rest-arg!! (apply hash !!dummy-rest-arg!!))) ; (let (,@bindings) ,body))))))) ; (define test (%lambda-keyword% (a b #:transparent [transparent #t]) (if transparent (begin (displayln "hello world") (+ a b)) (+ a b 10))))
true
24404accd503c199aac3857e94c7ce7e98c03d33
ea4e27735dd34917b1cf62dc6d8c887059dd95a9
/section3_3_exercise3_32.scm
790e70de72f5a75d1d540b3326b044fa3305d03c
[ "MIT" ]
permissive
feliposz/sicp-solutions
1f347d4a8f79fca69ef4d596884d07dc39d5d1ba
5de85722b2a780e8c83d75bbdc90d654eb094272
refs/heads/master
2022-04-26T18:44:32.025903
2022-03-12T04:27:25
2022-03-12T04:27:25
36,837,364
1
0
null
null
null
null
UTF-8
Scheme
false
false
7,669
scm
section3_3_exercise3_32.scm
; WARNING: this implementation is just for Exercise 3.32 ; It is not functional! ; s = sum, c = carry (define (half-adder a b s c) (let ((d (make-wire)) (e (make-wire))) (or-gate a b d) (and-gate a b c) (inverter c e) (and-gate d e s))) (define (full-adder a b c-in sum c-out) (let ((s (make-wire)) (c1 (make-wire)) (c2 (make-wire))) (half-adder b c-in s c1) (half-adder a s sum c2) (or-gate c1 c2 c-out))) (define (ripple-carry-adder alist blist slist c) (let ((clist (list c ))) ; the last carry will be in the end of the list (define (fill-clist n) (cond ((= n 0) 'done) (else (set! clist (cons (make-wire) clist)) (fill-clist (- n 1))))) (define (loop alist blist slist clist) (cond ((null? alist) 'done) (else (full-adder (car alist) (car blist) (car clist) ;c-in = current (car slist) (cadr clist)) ; c-out = next (loop (cdr alist) (cdr blist) (cdr slist) (cdr clist))))) (fill-clist (length alist)) (loop alist blist slist clist))) ; primitives (define (inverter in out) (define (inverter-in) (let ((new (logical-not (get-signal in)))) (after-delay inverter-delay (lambda () (set-signal! out new))))) (add-action! in inverter-in)) (define (logical-not s) (cond ((= s 0) 1) ((= s 1) 0) (else (warng "invalid signal" s)))) (define (and-gate a1 a2 output) (define (and-action-procedure) (let ((new-value (logical-and (get-signal a1) (get-signal a2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-value))))) (add-action! a1 and-action-procedure) (add-action! a2 and-action-procedure) 'ok) (define (logical-and s1 s2) (cond ((and (= s1 1) (= s2 1)) 1) ((= s1 0) 0) ((= s2 0) 0) (else (warng "invalid signal" s1 s2)))) (define (or-gate a1 a2 output) (define (or-action-procedure) (let ((new-value (logical-or (get-signal a1) (get-signal a2)))) (after-delay or-gate-delay (lambda () (set-signal! output new-value))))) (add-action! a1 or-action-procedure) (add-action! a2 or-action-procedure) 'ok) (define (logical-or s1 s2) (cond ((and (= s1 0) (= s2 0)) 0) ((= s1 1) 1) ((= s2 1) 1) (else (warng "invalid signal" s1 s2)))) (define (probe name wire) (add-action! wire (lambda () (display name) (display " ") (display (current-time the-agenda)) (display " New-value = ") (display (get-signal wire)) (newline) ))) ; wire object (define (make-wire) (let ((signal 0) (action-procs '())) (define (set-my-signal! new) (cond ((= signal new) 'done) (else (set! signal new) (call-each action-procs)))) (define (accept-action-proc! proc) (set! action-procs (cons proc action-procs)) (proc)) (define (dispatch m) (cond ((eq? m 'get-signal) signal) ((eq? m 'set-signal!) set-my-signal!) ((eq? m 'add-action!) accept-action-proc!) (else (error "Unknown operation - WIRE" m)))) dispatch)) (define (call-each procedures) (cond ((null? procedures) 'done) (else ((car procedures)) (call-each (cdr procedures))))) (define (get-signal wire) (wire 'get-signal)) (define (set-signal! wire new-value) ((wire 'set-signal!) new-value)) (define (add-action! wire action-proc) ((wire 'add-action!) action-proc)) ; helper (define (after-delay delay action) (add-to-agenda! (+ delay (current-time the-agenda)) action the-agenda)) (define (propagate) (cond ((empty-agenda? the-agenda) 'done) (else ((first-agenda-item the-agenda)) (remove-first-agenda-item! the-agenda) (propagate)))) ; agenda (define (make-agenda) (list 0)) (define (current-time agenda) (car agenda)) (define (set-current-time! agenda time) (set-car! agenda time)) (define (segments agenda) (cdr agenda)) (define (set-segments! agenda segments) (set-cdr! agenda segments)) (define (first-segment agenda) (car (segments agenda))) (define (rest-segments agenda) (cdr (segments agenda))) (define (empty-agenda? agenda) (null? (segments agenda))) (define (add-to-agenda! time action agenda) (define (belongs-before? segments) (or (null? segments) (< time (segment-time (car segments))))) (define (make-new-time-segment time action) (let ((q (make-stack))) (insert-stack! q action) (make-time-segment time q))) (define (add-to-segments! segments) (if (= (segment-time (car segments)) time) (insert-stack! (segment-stack (car segments)) action) (let ((rest (cdr segments))) (if (belongs-before? rest) (set-cdr! segments (cons (make-new-time-segment time action) (cdr segments))) (add-to-segments! rest))))) (let ((segments (segments agenda))) (if (belongs-before? segments) (set-segments! agenda (cons (make-new-time-segment time action) segments)) (add-to-segments! segments)))) (define (first-agenda-item agenda) (if (empty-agenda? agenda) (error "Agenda is empty -- FIRST-AGENDA-ITEM") (let ((first-seg (first-segment agenda))) (set-current-time! agenda (segment-time first-seg)) (top-stack (segment-stack first-seg))))) (define (remove-first-agenda-item! agenda) (let ((q (segment-stack (first-segment agenda)))) (delete-stack! q) (if (empty-stack? q) (set-segments! agenda (rest-segments agenda))))) ; time-segments (define (make-time-segment time queue) (cons time queue)) (define (segment-time s) (car s)) (define (segment-stack s) (cdr s)) ; stack (define (make-stack) (cons 'stack '())) (define (stack? stack) (and (pair? stack) (eq? 'stack (car stack)))) (define (empty-stack? stack) (if (not (stack? stack)) (error "Object not a stack:" stack) (null? (cdr stack)))) (define (insert-stack! stack elt) (cond ((not (stack? stack)) (error "Object not a stack:" stack)) (else (set-cdr! stack (cons elt (cdr stack))) stack))) (define (top-stack stack) (if (empty-stack? stack) (error "Stack underflow -- TOP") (cadr stack))) (define (delete-stack! stack) (if (empty-stack? stack) (error "Stack underflow -- DELETE") (set-cdr! stack (cddr stack))) stack) ; global definitions (define the-agenda (make-agenda)) (define inverter-delay 2) (define and-gate-delay 3) (define or-gate-delay 5) ; examples / test cases (newline) (display "TEST: and-gate") (newline) (define input-1 (make-wire)) (define input-2 (make-wire)) (define output (make-wire)) (probe 'and-output output) (set-signal! input-1 0) (set-signal! input-2 1) (and-gate input-1 input-2 output) (propagate) (set-signal! input-1 1) (set-signal! input-2 0) (propagate) ; using a regular queue, the final output value after change is 0 (expected) ; however, using a stack, the final output value is 1 ; so, in this case, a LIFO structure is not appropriate
false
5e4b5461f0553241e8455214782919e7d16f8946
ce567bbf766df9d98dc6a5e710a77870753c7d29
/ch9/33.scm
bd6000ce18796ff13069b5422b4a16f68e271510
[]
no_license
dott94/eopl
1cbe2d98c948689687f88e514579e66412236fc9
47fadf6f2aa6ca72c831d6e2e2eccbe673129113
refs/heads/master
2021-01-18T06:42:35.921839
2015-01-21T07:06:43
2015-01-21T07:06:43
30,055,972
1
0
null
2015-01-30T04:21:42
2015-01-30T04:21:42
null
UTF-8
Scheme
false
false
9,444
scm
33.scm
(load-relative "../libs/init.scm") (load-relative "./base/typed-oo/lang.scm") (load-relative "./base/typed-oo/test.scm") (load-relative "./base/typed-oo/store.scm") (load-relative "./base/typed-oo/interp.scm") (load-relative "./base/typed-oo/checker.scm") (load-relative "./base/typed-oo/environments.scm") (load-relative "./base/typed-oo/classes.scm") (load-relative "./base/typed-oo/static-classes.scm") (load-relative "./base/typed-oo/data-structures.scm") (load-relative "./base/typed-oo/static-data-structures.scm") (load-relative "./base/typed-oo/tests.scm") ;; (define debug? (make-parameter #t)) ;; these two function call on object have been done. ;; add is-static-class to test whether a symbol-name is class name. ;; see new stuff (define is-static-class (lambda (name) (if (assq name the-static-class-env) #t #f))) (define type-of (lambda (exp tenv) (cases expression exp (const-exp (num) (int-type)) (var-exp (var) (apply-tenv tenv var)) (diff-exp (exp1 exp2) (let ((type1 (type-of exp1 tenv)) (type2 (type-of exp2 tenv))) (check-equal-type! type1 (int-type) exp1) (check-equal-type! type2 (int-type) exp2) (int-type))) (sum-exp (exp1 exp2) (let ((type1 (type-of exp1 tenv)) (type2 (type-of exp2 tenv))) (check-equal-type! type1 (int-type) exp1) (check-equal-type! type2 (int-type) exp2) (int-type))) (zero?-exp (exp1) (let ((type1 (type-of exp1 tenv))) (check-equal-type! type1 (int-type) exp1) (bool-type))) (if-exp (test-exp true-exp false-exp) (let ((test-type (type-of test-exp tenv)) (true-type (type-of true-exp tenv)) (false-type (type-of false-exp tenv))) ;; these tests either succeed or raise an error (check-equal-type! test-type (bool-type) test-exp) (check-equal-type! true-type false-type exp) true-type)) (let-exp (ids rands body) (let ((new-tenv (extend-tenv ids (types-of-exps rands tenv) tenv))) (type-of body new-tenv))) (proc-exp (bvars bvar-types body) (let ((result-type (type-of body (extend-tenv bvars bvar-types tenv)))) (proc-type bvar-types result-type))) (call-exp (rator rands) (let ((rator-type (type-of rator tenv)) (rand-types (types-of-exps rands tenv))) (type-of-call rator-type rand-types rands exp))) (letrec-exp (proc-result-types proc-names bvarss bvar-typess proc-bodies letrec-body) (let ((tenv-for-letrec-body (extend-tenv proc-names (map proc-type bvar-typess proc-result-types) tenv))) (for-each (lambda (proc-result-type bvar-types bvars proc-body) (let ((proc-body-type (type-of proc-body (extend-tenv bvars bvar-types tenv-for-letrec-body)))) ;; !! (check-equal-type! proc-body-type proc-result-type proc-body))) proc-result-types bvar-typess bvarss proc-bodies) (type-of letrec-body tenv-for-letrec-body))) (begin-exp (exp1 exps) (letrec ((type-of-begins (lambda (e1 es) (let ((v1 (type-of e1 tenv))) (if (null? es) v1 (type-of-begins (car es) (cdr es))))))) (type-of-begins exp1 exps))) (assign-exp (id rhs) (check-is-subtype! (type-of rhs tenv) (apply-tenv tenv id) exp) (void-type)) (list-exp (exp1 exps) (let ((type-of-car (type-of exp1 tenv))) (for-each (lambda (exp) (check-equal-type! (type-of exp tenv) type-of-car exp)) exps) (list-type type-of-car))) ;; object stuff begins here (new-object-exp (class-name rands) (let ((arg-types (types-of-exps rands tenv)) (c (lookup-static-class class-name))) (cases static-class c (an-interface (method-tenv) (report-cant-instantiate-interface class-name)) (a-static-class (super-name i-names field-names field-types method-tenv) ;; check the call to initialize (type-of-call (find-method-type class-name 'initialize) arg-types rands exp) ;; and return the class name as a type (class-type class-name))))) (self-exp () (apply-tenv tenv '%self)) (method-call-exp (obj-exp method-name rands) (let ((arg-types (types-of-exps rands tenv)) (obj-type (type-of obj-exp tenv))) (type-of-call (find-method-type (type->class-name obj-type) method-name) arg-types rands exp))) (super-call-exp (method-name rands) (let ((arg-types (types-of-exps rands tenv)) (obj-type (apply-tenv tenv '%self))) (type-of-call (find-method-type (apply-tenv tenv '%super) method-name) arg-types rands exp))) ;;new stuff: obj-type is not a obj will report a error (cast-exp (exp class-name) (let ((obj-type (type-of exp tenv))) (if (is-static-class class-name) (if (class-type? obj-type) (class-type class-name) (report-bad-type-to-cast obj-type exp)) (error "error cast: ~s is not a class\n" class-name)))) ;; instanceof in interp.scm behaves the same way as cast: it ;; calls object->class-name on its argument, so we need to ;; check that the argument is some kind of object, but we ;; don't need to look at class-name at all. (instanceof-exp (exp class-name) (let ((obj-type (type-of exp tenv))) (if (is-static-class class-name) (if (class-type? obj-type) (bool-type) (report-bad-type-to-instanceof obj-type exp)) (error 'instanceof " ~s is not a class\n" class-name)))) ))) ;; (check "class c1 extends object ;; method int initialize () 1 ;; class c2 extends object ;; method int initialize () 2 ;; let p = proc (o : c1) instanceof o c3 in 11") ;; => error, for c3 is not a class ;; (check "class c1 extends object ;; method int initialize ()1 ;; method int get()2 ;; class c2 extends c1 ;; let f = proc (o : c2) send cast o c3 get() in (f new c2())") ;; => error , for c3 is not a class (run-all) (check-all) ;; case bad-instance-of-1 will got a error
false
7408143e9e07516d9e20d6dcbee0c07ec6818d97
ef9a581cee5913872323b67248607ef4d6493865
/compiler/If-Optimization.scm
494bd066849e459c59e13eb85fda1b3a8a6ae36c
[]
no_license
egisatoshi/scheme-compiler
c1ef8392c2a841913669a2eb8edaa825b9e99b96
01e6efbbc491c2f21c4a6009398977ded4009c20
refs/heads/master
2018-12-31T22:48:30.526683
2012-08-23T03:49:08
2012-08-23T03:49:08
5,518,662
10
1
null
null
null
null
UTF-8
Scheme
false
false
856
scm
If-Optimization.scm
;;; ;;; If Optimization ;;; (define-module If-Optimization (use srfi-1) (use srfi-11) (use util.match) (require "./Basic-Utility") (require "./CPS-Language") (require "./Propagation") (import Basic-Utility) (import CPS-Language) (import Propagation) (export if-optimize-count If-Optimize )) (select-module If-Optimization) (define if-optimize-count 0) (define if-optimize (lambda (exp) (match exp (('If (? imd? t) tc fc) (inc! if-optimize-count) (if t (if-optimize tc) (if-optimize fc))) (('If t tc fc) (let ((new-tc (if-optimize tc)) (new-fc (if-optimize fc))) `(If ,t ,new-tc ,new-fc))) (else (Propagate if-optimize exp))))) (define If-Optimize (lambda (program) (if-optimize program))) (provide "If-Optimization")
false
917b1e9c1704bd7620c0159fc3dc4bc6088928de
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/agave/glu/compat.chezscheme.sls
3731dbbef1485d4046307bdfcc2d4a1dbf96e765
[ "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
28,483
sls
compat.chezscheme.sls
;;; Ypsilon Scheme System ;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited. ;;; See license.txt for terms and conditions of use. ;;; Ported to Chez Scheme by Ed Cavazos ([email protected]) (library (agave glu compat) (export GLU_EXT_object_space_tess GLU_EXT_nurbs_tessellator GLU_FALSE GLU_TRUE GLU_VERSION_1_1 GLU_VERSION_1_2 GLU_VERSION_1_3 GLU_VERSION GLU_EXTENSIONS GLU_INVALID_ENUM GLU_INVALID_VALUE GLU_OUT_OF_MEMORY GLU_INCOMPATIBLE_GL_VERSION GLU_INVALID_OPERATION GLU_OUTLINE_POLYGON GLU_OUTLINE_PATCH GLU_NURBS_ERROR GLU_ERROR GLU_NURBS_BEGIN GLU_NURBS_BEGIN_EXT GLU_NURBS_VERTEX GLU_NURBS_VERTEX_EXT GLU_NURBS_NORMAL GLU_NURBS_NORMAL_EXT GLU_NURBS_COLOR GLU_NURBS_COLOR_EXT GLU_NURBS_TEXTURE_COORD GLU_NURBS_TEX_COORD_EXT GLU_NURBS_END GLU_NURBS_END_EXT GLU_NURBS_BEGIN_DATA GLU_NURBS_BEGIN_DATA_EXT GLU_NURBS_VERTEX_DATA GLU_NURBS_VERTEX_DATA_EXT GLU_NURBS_NORMAL_DATA GLU_NURBS_NORMAL_DATA_EXT GLU_NURBS_COLOR_DATA GLU_NURBS_COLOR_DATA_EXT GLU_NURBS_TEXTURE_COORD_DATA GLU_NURBS_TEX_COORD_DATA_EXT GLU_NURBS_END_DATA GLU_NURBS_END_DATA_EXT GLU_NURBS_ERROR1 GLU_NURBS_ERROR2 GLU_NURBS_ERROR3 GLU_NURBS_ERROR4 GLU_NURBS_ERROR5 GLU_NURBS_ERROR6 GLU_NURBS_ERROR7 GLU_NURBS_ERROR8 GLU_NURBS_ERROR9 GLU_NURBS_ERROR10 GLU_NURBS_ERROR11 GLU_NURBS_ERROR12 GLU_NURBS_ERROR13 GLU_NURBS_ERROR14 GLU_NURBS_ERROR15 GLU_NURBS_ERROR16 GLU_NURBS_ERROR17 GLU_NURBS_ERROR18 GLU_NURBS_ERROR19 GLU_NURBS_ERROR20 GLU_NURBS_ERROR21 GLU_NURBS_ERROR22 GLU_NURBS_ERROR23 GLU_NURBS_ERROR24 GLU_NURBS_ERROR25 GLU_NURBS_ERROR26 GLU_NURBS_ERROR27 GLU_NURBS_ERROR28 GLU_NURBS_ERROR29 GLU_NURBS_ERROR30 GLU_NURBS_ERROR31 GLU_NURBS_ERROR32 GLU_NURBS_ERROR33 GLU_NURBS_ERROR34 GLU_NURBS_ERROR35 GLU_NURBS_ERROR36 GLU_NURBS_ERROR37 GLU_AUTO_LOAD_MATRIX GLU_CULLING GLU_SAMPLING_TOLERANCE GLU_DISPLAY_MODE GLU_PARAMETRIC_TOLERANCE GLU_SAMPLING_METHOD GLU_U_STEP GLU_V_STEP GLU_NURBS_MODE GLU_NURBS_MODE_EXT GLU_NURBS_TESSELLATOR GLU_NURBS_TESSELLATOR_EXT GLU_NURBS_RENDERER GLU_NURBS_RENDERER_EXT GLU_OBJECT_PARAMETRIC_ERROR GLU_OBJECT_PARAMETRIC_ERROR_EXT GLU_OBJECT_PATH_LENGTH GLU_OBJECT_PATH_LENGTH_EXT GLU_PATH_LENGTH GLU_PARAMETRIC_ERROR GLU_DOMAIN_DISTANCE GLU_MAP1_TRIM_2 GLU_MAP1_TRIM_3 GLU_POINT GLU_LINE GLU_FILL GLU_SILHOUETTE GLU_SMOOTH GLU_FLAT GLU_NONE GLU_OUTSIDE GLU_INSIDE GLU_TESS_BEGIN GLU_BEGIN GLU_TESS_VERTEX GLU_VERTEX GLU_TESS_END GLU_END GLU_TESS_ERROR GLU_TESS_EDGE_FLAG GLU_EDGE_FLAG GLU_TESS_COMBINE GLU_TESS_BEGIN_DATA GLU_TESS_VERTEX_DATA GLU_TESS_END_DATA GLU_TESS_ERROR_DATA GLU_TESS_EDGE_FLAG_DATA GLU_TESS_COMBINE_DATA GLU_CW GLU_CCW GLU_INTERIOR GLU_EXTERIOR GLU_UNKNOWN GLU_TESS_WINDING_RULE GLU_TESS_BOUNDARY_ONLY GLU_TESS_TOLERANCE GLU_TESS_ERROR1 GLU_TESS_ERROR2 GLU_TESS_ERROR3 GLU_TESS_ERROR4 GLU_TESS_ERROR5 GLU_TESS_ERROR6 GLU_TESS_ERROR7 GLU_TESS_ERROR8 GLU_TESS_MISSING_BEGIN_POLYGON GLU_TESS_MISSING_BEGIN_CONTOUR GLU_TESS_MISSING_END_POLYGON GLU_TESS_MISSING_END_CONTOUR GLU_TESS_COORD_TOO_LARGE GLU_TESS_NEED_COMBINE_CALLBACK GLU_TESS_WINDING_ODD GLU_TESS_WINDING_NONZERO GLU_TESS_WINDING_POSITIVE GLU_TESS_WINDING_NEGATIVE GLU_TESS_WINDING_ABS_GEQ_TWO GLU_TESS_MAX_COORD gluBeginCurve gluBeginPolygon gluBeginSurface gluBeginTrim gluBuild1DMipmapLevels gluBuild1DMipmaps gluBuild2DMipmapLevels gluBuild2DMipmaps gluBuild3DMipmapLevels gluBuild3DMipmaps gluCheckExtension gluCylinder gluDeleteNurbsRenderer gluDeleteQuadric gluDeleteTess gluDisk gluEndCurve gluEndPolygon gluEndSurface gluEndTrim gluErrorString gluGetNurbsProperty gluGetString gluGetTessProperty gluLoadSamplingMatrices gluLookAt gluNewNurbsRenderer gluNewQuadric gluNewTess gluNextContour ;; gluNurbsCallback gluNurbsCallbackData gluNurbsCallbackDataEXT gluNurbsCurve gluNurbsProperty gluNurbsSurface gluOrtho2D gluPartialDisk gluPerspective gluPickMatrix gluProject gluPwlCurve ;; gluQuadricCallback gluQuadricDrawStyle gluQuadricNormals gluQuadricOrientation gluQuadricTexture gluScaleImage gluSphere gluTessBeginContour gluTessBeginPolygon ;; gluTessCallback gluTessEndContour gluTessEndPolygon gluTessNormal gluTessProperty gluTessVertex gluUnProject gluUnProject4) (import (chezscheme)) (define lib-name (case (machine-type) ((i3osx ti3osx) "OpenGL.framework/OpenGL") ; OSX x86 ((a6osx ta6osx) "OpenGL.framework/OpenGL") ; OSX x86_64 ((i3nt ti3nt) "glu32.dll") ; Windows x86 ((a6nt ta6nt) "glu64.dll") ; Windows x86_64 ((i3le ti3le) "libGLU.so.1") ; Linux x86 ((a6le ta6le) "libGLU.so.1") ; Linux x86_64 ((i3ob ti3ob) "libGLU.so.7.0") ; OpenBSD x86 ((a6ob ta6ob) "libGLU.so.7.0") ; OpenBSD x86_64 ((i3fb ti3fb) "libGLU.so") ; FreeBSD x86 ((a6fb ta6fb) "libGLU.so") ; FreeBSD x86_64 ((i3s2 ti3s2) "libGLU.so.1") ; Solaris x86 ((a6s2 ta6s2) "libGLU.so.1") ; Solaris x86_64 (else (assertion-violation #f "can not locate OpenGL library, unknown operating system")))) (define lib (load-shared-object lib-name)) ;; (define-syntax define-function ;; (syntax-rules () ;; ((_ ret name args) ;; (define name (c-function lib lib-name ret __stdcall name args))))) (define-syntax define-function (syntax-rules () ((_ ret name args) (define name (foreign-procedure (symbol->string 'name) args ret))))) ;;;; Extensions (define GLU_EXT_object_space_tess 1) (define GLU_EXT_nurbs_tessellator 1) ;;;; Boolean (define GLU_FALSE 0) (define GLU_TRUE 1) ;;;; Version (define GLU_VERSION_1_1 1) (define GLU_VERSION_1_2 1) (define GLU_VERSION_1_3 1) ;;;; StringName (define GLU_VERSION 100800) (define GLU_EXTENSIONS 100801) ;;;; ErrorCode (define GLU_INVALID_ENUM 100900) (define GLU_INVALID_VALUE 100901) (define GLU_OUT_OF_MEMORY 100902) (define GLU_INCOMPATIBLE_GL_VERSION 100903) (define GLU_INVALID_OPERATION 100904) ;;;; NurbsDisplay ;;;; GLU_FILL (define GLU_OUTLINE_POLYGON 100240) (define GLU_OUTLINE_PATCH 100241) ;;;; NurbsCallback (define GLU_NURBS_ERROR 100103) (define GLU_ERROR 100103) (define GLU_NURBS_BEGIN 100164) (define GLU_NURBS_BEGIN_EXT 100164) (define GLU_NURBS_VERTEX 100165) (define GLU_NURBS_VERTEX_EXT 100165) (define GLU_NURBS_NORMAL 100166) (define GLU_NURBS_NORMAL_EXT 100166) (define GLU_NURBS_COLOR 100167) (define GLU_NURBS_COLOR_EXT 100167) (define GLU_NURBS_TEXTURE_COORD 100168) (define GLU_NURBS_TEX_COORD_EXT 100168) (define GLU_NURBS_END 100169) (define GLU_NURBS_END_EXT 100169) (define GLU_NURBS_BEGIN_DATA 100170) (define GLU_NURBS_BEGIN_DATA_EXT 100170) (define GLU_NURBS_VERTEX_DATA 100171) (define GLU_NURBS_VERTEX_DATA_EXT 100171) (define GLU_NURBS_NORMAL_DATA 100172) (define GLU_NURBS_NORMAL_DATA_EXT 100172) (define GLU_NURBS_COLOR_DATA 100173) (define GLU_NURBS_COLOR_DATA_EXT 100173) (define GLU_NURBS_TEXTURE_COORD_DATA 100174) (define GLU_NURBS_TEX_COORD_DATA_EXT 100174) (define GLU_NURBS_END_DATA 100175) (define GLU_NURBS_END_DATA_EXT 100175) ;;;; NurbsError (define GLU_NURBS_ERROR1 100251) (define GLU_NURBS_ERROR2 100252) (define GLU_NURBS_ERROR3 100253) (define GLU_NURBS_ERROR4 100254) (define GLU_NURBS_ERROR5 100255) (define GLU_NURBS_ERROR6 100256) (define GLU_NURBS_ERROR7 100257) (define GLU_NURBS_ERROR8 100258) (define GLU_NURBS_ERROR9 100259) (define GLU_NURBS_ERROR10 100260) (define GLU_NURBS_ERROR11 100261) (define GLU_NURBS_ERROR12 100262) (define GLU_NURBS_ERROR13 100263) (define GLU_NURBS_ERROR14 100264) (define GLU_NURBS_ERROR15 100265) (define GLU_NURBS_ERROR16 100266) (define GLU_NURBS_ERROR17 100267) (define GLU_NURBS_ERROR18 100268) (define GLU_NURBS_ERROR19 100269) (define GLU_NURBS_ERROR20 100270) (define GLU_NURBS_ERROR21 100271) (define GLU_NURBS_ERROR22 100272) (define GLU_NURBS_ERROR23 100273) (define GLU_NURBS_ERROR24 100274) (define GLU_NURBS_ERROR25 100275) (define GLU_NURBS_ERROR26 100276) (define GLU_NURBS_ERROR27 100277) (define GLU_NURBS_ERROR28 100278) (define GLU_NURBS_ERROR29 100279) (define GLU_NURBS_ERROR30 100280) (define GLU_NURBS_ERROR31 100281) (define GLU_NURBS_ERROR32 100282) (define GLU_NURBS_ERROR33 100283) (define GLU_NURBS_ERROR34 100284) (define GLU_NURBS_ERROR35 100285) (define GLU_NURBS_ERROR36 100286) (define GLU_NURBS_ERROR37 100287) ;;;; NurbsProperty (define GLU_AUTO_LOAD_MATRIX 100200) (define GLU_CULLING 100201) (define GLU_SAMPLING_TOLERANCE 100203) (define GLU_DISPLAY_MODE 100204) (define GLU_PARAMETRIC_TOLERANCE 100202) (define GLU_SAMPLING_METHOD 100205) (define GLU_U_STEP 100206) (define GLU_V_STEP 100207) (define GLU_NURBS_MODE 100160) (define GLU_NURBS_MODE_EXT 100160) (define GLU_NURBS_TESSELLATOR 100161) (define GLU_NURBS_TESSELLATOR_EXT 100161) (define GLU_NURBS_RENDERER 100162) (define GLU_NURBS_RENDERER_EXT 100162) ;;;; NurbsSampling (define GLU_OBJECT_PARAMETRIC_ERROR 100208) (define GLU_OBJECT_PARAMETRIC_ERROR_EXT 100208) (define GLU_OBJECT_PATH_LENGTH 100209) (define GLU_OBJECT_PATH_LENGTH_EXT 100209) (define GLU_PATH_LENGTH 100215) (define GLU_PARAMETRIC_ERROR 100216) (define GLU_DOMAIN_DISTANCE 100217) ;;;; NurbsTrim (define GLU_MAP1_TRIM_2 100210) (define GLU_MAP1_TRIM_3 100211) ;;;; QuadricDrawStyle (define GLU_POINT 100010) (define GLU_LINE 100011) (define GLU_FILL 100012) (define GLU_SILHOUETTE 100013) ;;;; QuadricCallback ;;;; GLU_ERROR ;;;; QuadricNormal (define GLU_SMOOTH 100000) (define GLU_FLAT 100001) (define GLU_NONE 100002) ;;;; QuadricOrientation (define GLU_OUTSIDE 100020) (define GLU_INSIDE 100021) ;;;; TessCallback (define GLU_TESS_BEGIN 100100) (define GLU_BEGIN 100100) (define GLU_TESS_VERTEX 100101) (define GLU_VERTEX 100101) (define GLU_TESS_END 100102) (define GLU_END 100102) (define GLU_TESS_ERROR 100103) (define GLU_TESS_EDGE_FLAG 100104) (define GLU_EDGE_FLAG 100104) (define GLU_TESS_COMBINE 100105) (define GLU_TESS_BEGIN_DATA 100106) (define GLU_TESS_VERTEX_DATA 100107) (define GLU_TESS_END_DATA 100108) (define GLU_TESS_ERROR_DATA 100109) (define GLU_TESS_EDGE_FLAG_DATA 100110) (define GLU_TESS_COMBINE_DATA 100111) ;;;; TessContour (define GLU_CW 100120) (define GLU_CCW 100121) (define GLU_INTERIOR 100122) (define GLU_EXTERIOR 100123) (define GLU_UNKNOWN 100124) ;;;; TessProperty (define GLU_TESS_WINDING_RULE 100140) (define GLU_TESS_BOUNDARY_ONLY 100141) (define GLU_TESS_TOLERANCE 100142) ;;;; TessError (define GLU_TESS_ERROR1 100151) (define GLU_TESS_ERROR2 100152) (define GLU_TESS_ERROR3 100153) (define GLU_TESS_ERROR4 100154) (define GLU_TESS_ERROR5 100155) (define GLU_TESS_ERROR6 100156) (define GLU_TESS_ERROR7 100157) (define GLU_TESS_ERROR8 100158) (define GLU_TESS_MISSING_BEGIN_POLYGON 100151) (define GLU_TESS_MISSING_BEGIN_CONTOUR 100152) (define GLU_TESS_MISSING_END_POLYGON 100153) (define GLU_TESS_MISSING_END_CONTOUR 100154) (define GLU_TESS_COORD_TOO_LARGE 100155) (define GLU_TESS_NEED_COMBINE_CALLBACK 100156) ;;;; TessWinding (define GLU_TESS_WINDING_ODD 100130) (define GLU_TESS_WINDING_NONZERO 100131) (define GLU_TESS_WINDING_POSITIVE 100132) (define GLU_TESS_WINDING_NEGATIVE 100133) (define GLU_TESS_WINDING_ABS_GEQ_TWO 100134) (define GLU_TESS_MAX_COORD 1.0e150) ;; void gluBeginCurve (GLUnurbs* nurb) (define-function void gluBeginCurve (void*)) ;; void gluBeginPolygon (GLUtesselator* tess) (define-function void gluBeginPolygon (void*)) ;; void gluBeginSurface (GLUnurbs* nurb) (define-function void gluBeginSurface (void*)) ;; void gluBeginTrim (GLUnurbs* nurb) (define-function void gluBeginTrim (void*)) ;; GLint gluBuild1DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void* data) (define-function int gluBuild1DMipmapLevels (unsigned-int int int unsigned-int unsigned-int int int int void*)) ;; GLint gluBuild1DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLenum format, GLenum type, const void* data) (define-function int gluBuild1DMipmaps (unsigned-int int int unsigned-int unsigned-int void*)) ;; GLint gluBuild2DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void* data) (define-function int gluBuild2DMipmapLevels (unsigned-int int int int unsigned-int unsigned-int int int int void*)) ;; GLint gluBuild2DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLenum format, GLenum type, const void* data) (define-function int gluBuild2DMipmaps (unsigned-int int int int unsigned-int unsigned-int void*)) ;; GLint gluBuild3DMipmapLevels (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLint level, GLint base, GLint max, const void* data) (define-function int gluBuild3DMipmapLevels (unsigned-int int int int int unsigned-int unsigned-int int int int void*)) ;; GLint gluBuild3DMipmaps (GLenum target, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const void* data) (define-function int gluBuild3DMipmaps (unsigned-int int int int int unsigned-int unsigned-int void*)) ;; GLboolean gluCheckExtension (const GLubyte* extName, const GLubyte* extString) (define-function unsigned-8 gluCheckExtension (void* void*)) ;; void gluCylinder (GLUquadric* quad, GLdouble base, GLdouble top, GLdouble height, GLint slices, GLint stacks) (define-function void gluCylinder (void* double double double int int)) ;; void gluDeleteNurbsRenderer (GLUnurbs* nurb) (define-function void gluDeleteNurbsRenderer (void*)) ;; void gluDeleteQuadric (GLUquadric* quad) (define-function void gluDeleteQuadric (void*)) ;; void gluDeleteTess (GLUtesselator* tess) (define-function void gluDeleteTess (void*)) ;; void gluDisk (GLUquadric* quad, GLdouble inner, GLdouble outer, GLint slices, GLint loops) (define-function void gluDisk (void* double double int int)) ;; void gluEndCurve (GLUnurbs* nurb) (define-function void gluEndCurve (void*)) ;; void gluEndPolygon (GLUtesselator* tess) (define-function void gluEndPolygon (void*)) ;; void gluEndSurface (GLUnurbs* nurb) (define-function void gluEndSurface (void*)) ;; void gluEndTrim (GLUnurbs* nurb) (define-function void gluEndTrim (void*)) ;; const GLubyte* gluErrorString (GLenum error) (define-function void* gluErrorString (unsigned-int)) ;; void gluGetNurbsProperty (GLUnurbs* nurb, GLenum property, GLfloat* data) (define-function void gluGetNurbsProperty (void* unsigned-int void*)) ;; const GLubyte* gluGetString (GLenum name) (define-function void* gluGetString (unsigned-int)) ;; void gluGetTessProperty (GLUtesselator* tess, GLenum which, GLdouble* data) (define-function void gluGetTessProperty (void* unsigned-int void*)) ;; void gluLoadSamplingMatrices (GLUnurbs* nurb, const GLfloat* model, const GLfloat* perspective, const GLint* view) (define-function void gluLoadSamplingMatrices (void* void* void* void*)) ;; void gluLookAt (GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX, GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ) (define-function void gluLookAt (double double double double double double double double double)) ;; GLUnurbs* gluNewNurbsRenderer (void) (define-function void* gluNewNurbsRenderer ()) ;; GLUquadric* gluNewQuadric (void) (define-function void* gluNewQuadric ()) ;; GLUtesselator* gluNewTess (void) (define-function void* gluNewTess ()) ;; void gluNextContour (GLUtesselator* tess, GLenum type) (define-function void gluNextContour (void* unsigned-int)) ;; void gluNurbsCallbackData (GLUnurbs* nurb, GLvoid* userData) (define-function void gluNurbsCallbackData (void* void*)) ;; void gluNurbsCallbackDataEXT (GLUnurbs* nurb, GLvoid* userData) (define-function void gluNurbsCallbackDataEXT (void* void*)) ;; void gluNurbsCurve (GLUnurbs* nurb, GLint knotCount, GLfloat* knots, GLint stride, GLfloat* control, GLint order, GLenum type) (define-function void gluNurbsCurve (void* int void* int void* int unsigned-int)) ;; void gluNurbsProperty (GLUnurbs* nurb, GLenum property, GLfloat value) (define-function void gluNurbsProperty (void* unsigned-int float)) ;; void gluNurbsSurface (GLUnurbs* nurb, GLint sKnotCount, GLfloat* sKnots, GLint tKnotCount, GLfloat* tKnots, GLint sStride, GLint tStride, GLfloat* control, GLint sOrder, GLint tOrder, GLenum type) (define-function void gluNurbsSurface (void* int void* int void* int int void* int int unsigned-int)) ;; void gluOrtho2D (GLdouble left, GLdouble right, GLdouble bottom, GLdouble top) (define-function void gluOrtho2D (double double double double)) ;; void gluPartialDisk (GLUquadric* quad, GLdouble inner, GLdouble outer, GLint slices, GLint loops, GLdouble start, GLdouble sweep) (define-function void gluPartialDisk (void* double double int int double double)) ;; void gluPerspective (GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) (define-function void gluPerspective (double double double double)) ;; void gluPickMatrix (GLdouble x, GLdouble y, GLdouble delX, GLdouble delY, GLint *viewport) (define-function void gluPickMatrix (double double double double int)) ;; GLint gluProject (GLdouble objX, GLdouble objY, GLdouble objZ, const GLdouble* model, const GLdouble* proj, const GLint *view, GLdouble* winX, GLdouble* winY, GLdouble* winZ) (define-function int gluProject (double double double void* void* int void* void* void*)) ;; void gluPwlCurve (GLUnurbs* nurb, GLint count, GLfloat* data, GLint stride, GLenum type) (define-function void gluPwlCurve (void* int void* int unsigned-int)) ;; void gluQuadricDrawStyle (GLUquadric* quad, GLenum draw) (define-function void gluQuadricDrawStyle (void* unsigned-int)) ;; void gluQuadricNormals (GLUquadric* quad, GLenum normal) (define-function void gluQuadricNormals (void* unsigned-int)) ;; void gluQuadricOrientation (GLUquadric* quad, GLenum orientation) (define-function void gluQuadricOrientation (void* unsigned-int)) ;; void gluQuadricTexture (GLUquadric* quad, GLboolean texture) (define-function void gluQuadricTexture (void* unsigned-8)) ;; GLint gluScaleImage (GLenum format, GLsizei wIn, GLsizei hIn, GLenum typeIn, const void* dataIn, GLsizei wOut, GLsizei hOut, GLenum typeOut, GLvoid* dataOut) (define-function int gluScaleImage (unsigned-int int int unsigned-int void* int int unsigned-int void*)) ;; void gluSphere (GLUquadric* quad, GLdouble radius, GLint slices, GLint stacks) (define-function void gluSphere (void* double int int)) ;; void gluTessBeginContour (GLUtesselator* tess) (define-function void gluTessBeginContour (void*)) ;; void gluTessBeginPolygon (GLUtesselator* tess, GLvoid* data) (define-function void gluTessBeginPolygon (void* void*)) ;; void gluTessEndContour (GLUtesselator* tess) (define-function void gluTessEndContour (void*)) ;; void gluTessEndPolygon (GLUtesselator* tess) (define-function void gluTessEndPolygon (void*)) ;; void gluTessNormal (GLUtesselator* tess, GLdouble valueX, GLdouble valueY, GLdouble valueZ) (define-function void gluTessNormal (void* double double double)) ;; void gluTessProperty (GLUtesselator* tess, GLenum which, GLdouble data) (define-function void gluTessProperty (void* unsigned-int double)) ;; void gluTessVertex (GLUtesselator* tess, GLdouble* location, GLvoid* data) (define-function void gluTessVertex (void* void* void*)) ;; GLint gluUnProject (GLdouble winX, GLdouble winY, GLdouble winZ, const GLdouble* model, const GLdouble* proj, const GLint *view, GLdouble* objX, GLdouble* objY, GLdouble* objZ) (define-function int gluUnProject (double double double void* void* int void* void* void*)) ;; GLint gluUnProject4 (GLdouble winX, GLdouble winY, GLdouble winZ, GLdouble clipW, const GLdouble* model, const GLdouble* proj, const GLint *view, GLdouble nearVal, GLdouble farVal, GLdouble* objX, GLdouble* objY, GLdouble* objZ, GLdouble* objW) (define-function int gluUnProject4 (double double double double void* void* int double double void* void* void* void*)) ;; void gluNurbsCallback (GLUnurbs* nurb, GLenum which, _GLUfuncptr CallBackFunc) ;; (define gluNurbsCallback ;; (let ((thunk (c-function lib lib-name void __stdcall gluNurbsCallback (void* unsigned-int void*))) ;; (alist `((,GLU_NURBS_BEGIN int) ;; (,GLU_NURBS_VERTEX float) ;; (,GLU_NURBS_NORMAL float) ;; (,GLU_NURBS_COLOR float) ;; (,GLU_NURBS_TEXTURE_COORD float) ;; (,GLU_NURBS_END) ;; (,GLU_NURBS_BEGIN_DATA int void*) ;; (,GLU_NURBS_VERTEX_DATA float void*) ;; (,GLU_NURBS_NORMAL_DATA float void*) ;; (,GLU_NURBS_COLOR_DATA float void*) ;; (,GLU_NURBS_TEXTURE_COORD_DATA float void*) ;; (,GLU_NURBS_END_DATA void*) ;; (,GLU_NURBS_ERROR int)))) ;; (lambda (nurb which callback) ;; (if (procedure? callback) ;; (let ((lst (assv which alist))) ;; (or lst (assertion-violation 'gluNurbsCallback "invalid value in argument 2" (list nurb which callback))) ;; (thunk nurb which (make-stdcall-callback 'void (cdr lst) callback))) ;; (thunk nurb which callback))))) ;; void gluQuadricCallback (GLUquadric* quad, GLenum which, _GLUfuncptr CallBackFunc) ;; (define gluQuadricCallback ;; (let ((thunk (c-function lib lib-name void __stdcall gluQuadricCallback (void* unsigned-int void*)))) ;; (lambda (quad which callback) ;; (or (eqv? which GLU_ERROR) ;; (assertion-violation 'gluQuadricCallback "invalid value in argument 2" (list quad which callback))) ;; (if (procedure? callback) ;; (thunk quad which (make-stdcall-callback 'void '(unsigned-int) callback)) ;; (thunk quad which callback))))) ;; void gluTessCallback (GLUtesselator* tess, GLenum which, _GLUfuncptr CallBackFunc) ;; (define gluTessCallback ;; (let ((thunk (c-function lib lib-name void __stdcall gluTessCallback (void* unsigned-int void*))) ;; (alist `((,GLU_TESS_BEGIN unsigned-int) ;; (,GLU_TESS_BEGIN_DATA unsigned-int void*) ;; (,GLU_TESS_EDGE_FLAG uint8_t) ;; (,GLU_TESS_EDGE_FLAG_DATA uint8_t void*) ;; (,GLU_TESS_VERTEX void*) ;; (,GLU_TESS_VERTEX_DATA void* void*) ;; (,GLU_TESS_END) ;; (,GLU_TESS_END_DATA void*) ;; (,GLU_TESS_COMBINE void* void* void* void*) ;; (,GLU_TESS_COMBINE_DATA void* void* void* void* void*) ;; (,GLU_TESS_ERROR unsigned-int) ;; (,GLU_TESS_ERROR_DATA unsigned-int void*)))) ;; (lambda (tess which callback) ;; (if (procedure? callback) ;; (let ((lst (assv which alist))) ;; (or lst (assertion-violation 'gluTessCallback "invalid value in argument 2" (list tess which callback))) ;; (thunk tess which (make-stdcall-callback 'void (cdr lst) callback))) ;; (thunk tess which callback))))) ) ;[end]
true
53ff2847c70da7c973ec79805b5485b1af54db3b
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/tablegen/highlights.scm
b0b4b000c9c9067d25e9335f89cf360d21617a36
[ "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
1,668
scm
highlights.scm
; Preprocs (preprocessor_directive) @preproc ; Includes "include" @include ; Keywords [ "assert" "class" "multiclass" "field" "let" "def" "defm" "defset" "defvar" ] @keyword [ "in" ] @keyword.operator ; Conditionals [ "if" "else" "then" ] @conditional ; Repeats [ "foreach" ] @repeat ; Variables (identifier) @variable (var) @variable.builtin ; Parameters (template_arg (identifier) @parameter) ; Types (type) @type [ "bit" "int" "string" "dag" "bits" "list" "code" ] @type.builtin (class name: (identifier) @type) (multiclass name: (identifier) @type) (def name: (value (_) @type)) (defm name: (value (_) @type)) (defset name: (identifier) @type) (parent_class_list (identifier) @type (value (_) @type)?) (anonymous_record (identifier) @type) (anonymous_record (value (_) @type)) ((identifier) @type (#lua-match? @type "^_*[A-Z][A-Z0-9_]+$")) ; Fields (instruction (identifier) @field) (let_instruction (identifier) @field) ; Functions ([ (bang_operator) (cond_operator) ] @function (#set! "priority" 105)) ; Operators [ "=" "#" "-" ":" "..." ] @operator ; Literals (string) @string (code) @string.special (integer) @number (boolean) @boolean (uninitialized_value) @constant.builtin ; Punctuation [ "{" "}" ] @punctuation.bracket [ "[" "]" ] @punctuation.bracket [ "(" ")" ] @punctuation.bracket [ "<" ">" ] @punctuation.bracket [ "." "," ";" ] @punctuation.delimiter [ "!" ] @punctuation.special ; Comments [ (comment) (multiline_comment) ] @comment @spell ((comment) @preproc (#lua-match? @preproc "^.*RUN")) ; Errors (ERROR) @error
false
534df55f91997a58150cdf253c03be3d2b946cb5
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/old/chez/swl_flat_threads.ss
dfe62bead6396ff176f024b37a2ee4be5c5af75d
[ "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
2,214
ss
swl_flat_threads.ss
;;[2004.05.26] ;; This version is for use with the SchemeWidgetLibrary. ;(chez:module flat_threads (run-flat-threads yield-thread ; these-tests test-this) (define yield-thread thread-yield) ;; Using hefty granularity right now. ;; This defines the number of engine-ticks given each ;; thread in each time-slice. (define flat-threads-granularity 10) (define (run-flat-threads thks . time) (let ((timeout (if (null? time) #f (* 1000 (car time))))) ; (disp "starting flatthreads")(flush-output-port (current-output-port)) (let* ([channel (thread-make-msg-queue 'flat-threads-wait-queue)] [return-thread #f] [threads (map (lambda (thk) (thread-fork (lambda () ; (disp "running thread")(flush-output-port (current-output-port)) (thk) (thread-send-msg channel 'Thread_Done)) flat-threads-granularity)) thks)] [thread-ids (map thread-number threads)] [timeout-thread (if timeout (thread-fork (lambda () ; (disp "timer starting")(flush-output-port (current-output-port)) (thread-sleep (inexact->exact (round timeout))) ;a (disp "timer went off")(flush-output-port (current-output-port)) (thread-send-msg channel 'Threads_Timed_Out)) flat-threads-granularity) #f)]) ; (disp "SETTING UP THREADS") (flush-output-port (current-output-port)) (let loop ((counter (length threads))) ; (disp "loop " counter) (flush-output-port (current-output-port)) (if (zero? counter) (begin (if timeout-thread (thread-kill timeout-thread)) 'All_Threads_Returned) (case (thread-receive-msg channel) [(Thread_Done) (loop (sub1 counter))] [(Threads_Timed_Out) ;; Some might be already dead and this might error: (for-each thread-kill thread-ids) 'Threads_Timed_Out])))))) ;======================================================================= (define-testing these-tests (include "generic/testing/flat_threads.tests")) (define-testing test-this (default-unit-tester "swl_flat_threads.ss: simple interface for parallel computations" these-tests)) (define testswlflatthreads test-this) ;) ;; End module
false
5e43d69bbad15c95e8f1ca7eca94c1a624aeb580
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_3/exercise_3_77.scm
e9d06f274000e8e70aa7d50417074f4592b3262a
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
727
scm
exercise_3_77.scm
#lang racket ;; P242 - [练习 3.77] (require "stream.scm") (require "infinite_stream.scm") (define (integral delayed-integrand initial-value dt) (cons-stream initial-value (let ((integrand (force delayed-integrand))) (if (stream-null? integrand) the-empty-stream (integral (delay (stream-cdr integrand)) (+ (* dt (stream-car integrand)) initial-value) dt))))) (define (solve f y0 dt) (define y (integral (delay dy) y0 dt)) (define dy (stream-map f y)) y) ;;;;;;;;;;;;;;;;; (stream-ref (solve (lambda (y) y) 1 0.001) 1000) ; 2.716923932235896
false
8b9bfa9335f21ee03f189a26f421f8417fc405bd
9ba99213d2aac208dcd1bc86dddeed97a4d2577e
/cairo/examples/urman-tutorial-set-source-gradient.sps
9ade864f5a661055ce469b92930bdf42c181b201
[]
no_license
sahwar/psilab
19df7449389c8b545a0f1323e2bd6ca5be3e8592
16b60e4ae63e3405d74117a50cd9ea313c179b33
refs/heads/master
2020-04-19T15:17:47.154624
2010-06-10T17:39:35
2010-06-10T17:39:35
168,269,500
1
0
null
2019-01-30T03:00:41
2019-01-30T03:00:41
null
UTF-8
Scheme
false
false
1,285
sps
urman-tutorial-set-source-gradient.sps
(import (rnrs) (surfage s42 eager-comprehensions) (ypsilon cairo) (psilab cairo with-cairo)) (let ((surface (cairo_image_surface_create CAIRO_FORMAT_ARGB32 120 120))) (let ((cr (cairo_create surface))) (with-cairo cr (scale 120 120) (let ((radpat (cairo_pattern_create_radial 0.25 0.25 0.1 0.5 0.5 0.5))) (cairo_pattern_add_color_stop_rgb radpat 0 1.0 0.8 0.8) (cairo_pattern_add_color_stop_rgb radpat 1 0.9 0.0 0.0) (do-ec (: i 1 10) (do-ec (: j 1 10) (rectangle (- (/ i 10.0) 0.04) (- (/ j 10.0) 0.04) 0.08 0.08))) (set_source radpat) (fill)) (let ((linpat (cairo_pattern_create_linear 0.25 0.35 0.75 0.65))) (cairo_pattern_add_color_stop_rgba linpat 0.00 1 1 1 0) (cairo_pattern_add_color_stop_rgba linpat 0.25 0 1 0 0.5) (cairo_pattern_add_color_stop_rgba linpat 0.50 1 1 1 0) (cairo_pattern_add_color_stop_rgba linpat 0.75 0 0 1 0.5) (cairo_pattern_add_color_stop_rgba linpat 1.00 1 1 1 0) (rectangle 0.0 0.0 1 1) (set_source linpat) (fill)) (destroy))) (cairo_surface_write_to_png surface "set-source-gradient.png") (cairo_surface_destroy surface))
false
11100fca4c13b94465371c25e4bd8e97fbcbd687
e358b0cf94ace3520adff8d078a37aef260bb130
/simple/2.18.scm
210438fee1fbc5e4e9ee9f5d68bb5d641cff47f3
[]
no_license
dzhus/sicp
784766047402db3fad4884f7c2490b4f78ad09f8
090fa3228d58737d3558f2af5a8b5937862a1c75
refs/heads/master
2021-01-18T17:28:02.847772
2020-05-24T19:15:57
2020-05-24T20:56:00
22,468,805
0
0
null
null
null
null
UTF-8
Scheme
false
false
230
scm
2.18.scm
(define (list-reverse l) (if (null? (cdr l)) l ;; Using plain `cons` won't work — compare `(cons (list 4) 1)` ;; and `(append (list 4) (list 1))` results (append (list-reverse (cdr l)) (list (car l)))))
false
2b3fe20a00186b972ebafb258800eff856193db0
c763eaf97ffd7226a70d2f9a77465cbeae8937a8
/scheme/functional.scm
99b3632ecb0b80cfb1cde83d8a5a036f6a0c3def
[]
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
953
scm
functional.scm
(library (functional) (export inc dec iota receive compose id pipe) (import (rnrs (6)) (rename (cut) (cut $)) (only (srfi srfi-1) unfold)) (define (inc x) (+ x 1)) (define (dec x) (- x 1)) (define (iota n) (unfold ($ = <> n) id inc 0)) #| identity function | @(param x) any value | @(returns) @(ref x) |# (define (id x) x) ;;; (srfi :8 receive) (define-syntax receive (syntax-rules () ((_ <formals> <expr> <body> ...) (call-with-values (lambda () <expr>) (lambda <formals> <body> ...))))) #| compose functions | @(param f . rest) variadic list of functions | @(returns) functional composite of arguments |# (define (compose f . rest) (if (null? rest) f (let ((g (apply compose rest))) (lambda args (call-with-values ($ apply g args) f))))) (define (pipe start . fs) ((apply compose (reverse fs)) start)) )
true
481edf1e53040d1eea9abf0adaf81df82e741781
e0b29bfd6139cb1b7039b1bcb191c1f948243c61
/code/stages/read.scm
5680054f58062110003d88d1e6a3c51f71573dea
[]
no_license
acotis/serial-predicate-engine
6c33d2c8f4552f1bfcc7fcf8b405868e82148ee6
9e02baf711c0b7402da2eeb50b8644bf7b6e415f
refs/heads/master
2021-07-13T13:45:49.597227
2019-01-03T01:44:37
2019-01-03T01:44:37
147,992,280
2
1
null
2023-01-10T20:05:08
2018-09-09T04:16:13
Scheme
UTF-8
Scheme
false
false
714
scm
read.scm
#!/usr/bin/guile !# ;; File: read.scm ;; Purpose: Turn a raw input string into a list of cmavo & roots ;; Input: "to tu gi pai to hui" ;; Output: (to ru "gi" "pai" to "hui") (load "../utilities.scm") ;; Split the input into space-separated words (define (split-on-spaces string) (remove (lambda (s) (equal? s "")) (string-split string #\Space))) ;; Replace cmavo strings with their symbol counterparts (define (replace-cmavo-strings com) (map (lambda (s) (let ((sym (string->symbol s))) (if (member sym cmavo) sym s))) com)) ;; Perform the "read" stage on an input string. (define (stage-read input) (replace-cmavo-strings (split-on-spaces input)))
false
8a648fe3c71ca7e91f00879c873439f1c6a860f3
b8eb3fdd0e4e38a696c4013a8f91054df3f75833
/t/perf/eta/sqrt/d0.ss
008634fdefb2a7470893d4fb3f3e1e851187a0da
[ "Zlib" ]
permissive
lojikil/digamma
952a7bdf176227bf82b3583020bc41764b12d906
61c7ffdc501f207a84e5d47157c3c84e5882fa0d
refs/heads/master
2020-05-30T07:11:20.716792
2016-05-11T11:32:15
2016-05-11T11:32:15
58,539,277
6
3
null
null
null
null
UTF-8
Scheme
false
false
529
ss
d0.ss
(def (good-enough? guess x) (< (abs (- (* guess guess) x)) 0.001)) (def (average x y) (/ (+ x y) 2)) (def (improve guess x) (average guess (/ x guess))) (def (sqrt-iter guess x) (if (good-enough? guess x) guess (sqrt-iter (improve guess x) x))) (def (mysqrt x) (sqrt-iter 1.0 x)) (def (integ x acc step) (if (>= x 10000.0) acc (integ (+ x step) (+ acc (* step (mysqrt x))) step))) (def (scheme_main) (write (integ 0.0 0.0 .001)) (newline))
false
5d9084391c8d4a1671bf3d0cac644c88de0eec3d
e0b29bfd6139cb1b7039b1bcb191c1f948243c61
/code/stages/pretty-print.scm
fe54d338ef074097977914437925f9ae2cb80353
[]
no_license
acotis/serial-predicate-engine
6c33d2c8f4552f1bfcc7fcf8b405868e82148ee6
9e02baf711c0b7402da2eeb50b8644bf7b6e415f
refs/heads/master
2021-07-13T13:45:49.597227
2019-01-03T01:44:37
2019-01-03T01:44:37
147,992,280
2
1
null
2023-01-10T20:05:08
2018-09-09T04:16:13
Scheme
UTF-8
Scheme
false
false
5,616
scm
pretty-print.scm
#!/usr/bin/guile !# ;; File: pretty-print.scm ;; Purpose: Turn a list of predicates into a list of pretty ;; output strings. ;; Input: ( <lu to ru (lu to ru (gi) to (pai)) to (hui)> ;; <lu to ru (gi (pai)) to (hui)> … ) ;; Output: ( "lủ to ru lủ to ru gỉ na to pải na na to hủi" ;; "lủ to ru gỉ pâi na na to hủi" … ) (load "../utilities.scm") (load "../words.scm") (use-modules (srfi srfi-1)) (define marked-vowels '(( #\a . "āáǎảâàãa" ) ( #\e . "ēéěẻêèẽe" ) ( #\i . "īíǐỉîìĩı" ) ( #\o . "ōóǒỏôòõo" ) ( #\u . "ūúǔủûùũu" ))) (define vowel? (let ((vowels (map car marked-vowels))) (lambda (v) (member v vowels)))) ;; Add a diacritic mark to a single vowel, passed as a string (define (add-diacritic vowel tone) (string-ref (cdr (assv vowel marked-vowels)) (1- tone))) ;; Add a tone marking to the appropriate letter of a single word, ;; passed as a string (define (add-diacritics* letters tone) (let ((first-vowel (list-index vowel? letters))) (if (not first-vowel) letters (let* ((onset (take letters first-vowel)) (rime (drop letters first-vowel)) (first-consonant (list-index (lambda (l) (not (vowel? l))) rime))) (append onset (cons (add-diacritic (car rime) tone) (if first-consonant (append (take (cdr rime) (1- first-consonant)) (add-diacritics* (drop rime first-consonant) 1)) (cdr rime)))))))) (define (add-diacritics los tone) (if (list? los) (add-diacritics* los tone) (list->string (add-diacritics* (string->list los) tone)))) (define (add-tone word tone) (list->string (add-diacritics (string->list word) tone))) ;; Uakci's addition: convert number to its Toaq compound form. This is ;; to facilitate friendly dó variables, e.g., dóshī, dógū, etc. ;; Count from one to nine. (define (digit->toaq n) (let ((numbers '("" "shi" "gu" "saq" "jo" "fe" "ci" "diai" "roai" "nei"))) (list-ref numbers n))) (define (number->toaq n) (when (not (and (>= n 0) (< n 1e6) (integer? n))) (error "sorry, out of range")) (cond ((zero? n) "") ((>= n 1000) (string-append (number->toaq (quotient n 1000)) "biq" (number->toaq (remainder n 1000)))) (else (let* ((hundreds (quotient n 100)) (tens (quotient (remainder n 100) 10)) (ones (remainder n 10))) (string-append (digit->toaq hundreds) (if (zero? hundreds) "" "fue") (digit->toaq tens) (if (zero? tens) "" "hei") (digit->toaq ones)))))) ;; Return a printable form for a (do #n) or (jado #n) ;; expression, given n (define (printable-do n) (add-tone (string-append "do" (number->toaq n)) 2)) (define (printable-jado n) (string-append "ja " (printable-do n))) (define (printable-do-jado exp) (if (= 2 (length exp)) ;; (jado n) / (do n) case (if (eq? (car exp) 'jado) (printable-jado (cadr exp)) (printable-do (cadr exp))) (string-append "ja " (add-tone "do" 2)))) ;; (jado) case ;; Convert a whole canonic form plus a tone to a printable form (define (cf->string cf tone) (cond ((symbol? cf) ;; c, 0, 1, 2, A, B, ... (symbol->string cf)) ;; (do 1) and (jado 1) ((or (eq? (car cf) 'do) (eq? (car cf) 'jado)) (printable-do-jado cf)) ;; (li ((jado 1) (jado 2)) (...)) ((eq? (car cf) 'li) (string-join (append (list (add-tone "li" tone)) (map printable-do-jado (cadr cf)) (list "bi") (list (cf->string (caddr cf) 4))) " ")) ;; (pred args...) or (lu to RU ... to) (#t (let ((stone (if (equal? (car cf) "lu") 4 5))) (string-join (append (list (add-tone (car cf) tone)) (map (lambda (a) (cf->string a stone)) (cdr cf)) (list "na")) " "))))) ;; Pretty-print a whole predicate ;; Example: <[c 0] (dủa A B)> (define (remove-trailing-na str) (let ((len (string-length str))) (if (equal? "na" (substring str (- len 2))) (remove-trailing-na (string-trim-both (substring str 0 (- len 2)))) str))) (define (contains-fail? cf) (if (equal? 'fail cf) #t (if (pair? cf) (fold (lambda (a b) (or a b)) (map contains-fail? cf)) #f))) (define (pred->string pred) (if (contains-fail? (gcf pred)) "-" (format #f "<[~a] (~a)>" (string-join (map (lambda (type) (if (number? type) (number->string type) (symbol->string type))) (typelist pred)) " ") (remove-trailing-na (cf->string (gcf pred) 4))))) ;; Perform "pretty-print" stage on interpretation output. (define (stage-pretty-print interpret-output) (map pred->string interpret-output))
false
63926c58e4e76fd4ea9eb880836ec81a1f8884ce
defeada37d39bca09ef76f66f38683754c0a6aa0
/System.Xml/system/xml/serialization/soap-schema-exporter.sls
3f1acdce5f6e47d7c45c5c4fc3d6466b9c5b6317
[]
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,030
sls
soap-schema-exporter.sls
(library (system xml serialization soap-schema-exporter) (export new is? soap-schema-exporter? export-type-mapping export-members-mapping) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Xml.Serialization.SoapSchemaExporter a ...))))) (define (is? a) (clr-is System.Xml.Serialization.SoapSchemaExporter a)) (define (soap-schema-exporter? a) (clr-is System.Xml.Serialization.SoapSchemaExporter a)) (define-method-port export-type-mapping System.Xml.Serialization.SoapSchemaExporter ExportTypeMapping (System.Void System.Xml.Serialization.XmlTypeMapping)) (define-method-port export-members-mapping System.Xml.Serialization.SoapSchemaExporter ExportMembersMapping (System.Void System.Xml.Serialization.XmlMembersMapping System.Boolean) (System.Void System.Xml.Serialization.XmlMembersMapping)))
true
b03bb768830ad4122e8e112bc9008984006728ed
88386d7bf1842f8d5eba5ad5c65ff5ccb36b976f
/test/speech.scm
b95596692d005cd76590965122d143da6f1b9ca2
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
ysei/gauche-naoyat-lib
ab524e27c721a23d7d796f8cfac4a1b47137130a
0615815d1d05c4aa384da757b064e5fcb74a4033
refs/heads/master
2021-01-18T08:43:21.384621
2010-01-20T14:22:42
2010-01-20T14:22:42
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
369
scm
speech.scm
(use gauche.test) (use naoyat.test) (test-start "naoyat.mac.speech") (use naoyat.mac.speech) (test-module 'naoyat.mac.speech) (manual-test* "Ralph says コンニチワ" (lambda () (say-katakana-with-tune "Ralph" "3コ5ンニチワ"))) (manual-test* "Victoria says サヨウナラ" (lambda () (say-katakana-with-tune "Victoria" "3サ5ヨーナラ"))) (test-end)
false
b82e656e96294cd8be5ac1b13210e8678cca2e3a
7c7e1a9237182a1c45aa8729df1ec04abb9373f0
/sicp/1/3-3.scm
6188ce004bb03e333c0c0fad9ad5d97d93720714
[ "MIT" ]
permissive
coolsun/heist
ef12a65beb553cfd61d93a6691386f6850c9d065
3f372b2463407505dad7359c1e84bf4f32de3142
refs/heads/master
2020-04-21T15:17:08.505754
2012-06-29T07:18:49
2012-06-29T07:18:49
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,794
scm
3-3.scm
; Section 1.3.3 ; http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-12.html#%_sec_1.3.3 (load "../helpers") (exercise "1.35") ; Golden ratio as a fixed point (define (search f neg-point pos-point) (let ((midpoint (average neg-point pos-point))) (if (close-enough? neg-point pos-point) midpoint (let ((test-value (f midpoint))) (cond ((positive? test-value) (search f neg-point midpoint)) ((negative? test-value) (search f midpoint pos-point)) (else midpoint)))))) (define (close-enough? x y) (< (abs (- x y)) 0.001)) (define (half-interval-method f a b) (let ((a-value (f a)) (b-value (f b))) (cond ((and (negative? a-value) (positive? b-value)) (search f a b)) ((and (negative? b-value) (positive? a-value)) (search f b a)) (else (error "Values are not of opposite sign" a b))))) (define tolerance 0.00001) (define (fixed-point f first-guess) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try guess) (let ((next (f guess))) (if (close-enough? guess next) next (try next)))) (try first-guess)) (output '(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0)) ; 1.61803278688525 (exercise "1.36") ; Modified fixed-point that prints progress (define (fixed-point f first-guess) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try n guess) (display (+ n ": " guess)) (newline) (let ((next (f guess))) (if (close-enough? guess next) next (try (+ n 1) next)))) (try 1 first-guess)) ; Find solution of x^x = 1000 ; Don't begin at 1.0 since (log 1.0) = 0 (output '(fixed-point (lambda (x) (/ (log 1000) (log x))) 2.0)) ; 4.55553227080365, 34 guesses ; Add average damping (define (fixed-point f first-guess) (define (close-enough? v1 v2) (< (abs (- v1 v2)) tolerance)) (define (try n guess) (display (+ n ": " guess)) (newline) (let ((next (/ (+ guess (f guess)) 2))) (if (close-enough? guess next) next (try (+ n 1) next)))) (try 1 first-guess)) (output '(fixed-point (lambda (x) (/ (log 1000) (log x))) 2.0)) ; 4.55553755199982, 9 guesses (exercise "1.37") ; k-term finite continued fraction (define (cont-frac n d k) (define (term i) (if (= (- k 1) i) (+ (d i) (/ (n k) (d k))) (+ (d i) (/ (n (+ 1 i)) (term (+ 1 i)))))) (/ (n 1) (term 1))) (output '(/ 1 (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) 13))) ; 1.61802575107296 ; Tail-recursive version (define (cont-frac n d k) (define (iter i term) (if (= i 0) term (let ((x (n i)) (y (d i))) (iter (- i 1) (/ x (+ y term)))))) (iter k 0)) (output '(/ 1 (cont-frac (lambda (i) 1.0) (lambda (i) 1.0) 13))) (exercise "1.38") ; Euler's approximation for e (define e (+ 2 (cont-frac (lambda (i) 1.0) (lambda (i) (let ((x (+ 1 i))) (if (= 0 (remainder x 3)) (* 2 (/ x 3)) 1.0))) 20))) (output 'e) ; 2.71828182845905 (exercise "1.39") ; J.H. Lambert's tangent formula (define (tan-cf x k) (cont-frac (lambda (i) (if (= 1 i) x (- (expt x 2)))) (lambda (i) (- (* 2 i) 1)) k)) (define pi 3.14159) (output '(tan-cf 0 10)) ; 0.0 (output '(tan-cf (/ pi 8) 10)) ; 0.41421317376392 (output '(tan-cf (/ pi 4) 10)) ; 0.999998673205983 (output '(tan-cf (/ pi 2) 10)) ; 753695.994435399 (output '(tan-cf (* 3 (/ pi 4)) 10)) ; -1.00000398040374
false
774608de038de3410d77e092d4ac549c3068ebd8
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/runtime/interop-services/runtime-environment.sls
352d2b0b67d8f85241d17d25429ecb3b02c1baec
[]
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,358
sls
runtime-environment.sls
(library (system runtime interop-services runtime-environment) (export new is? runtime-environment? from-global-access-cache? get-system-version get-runtime-directory system-configuration-file) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Runtime.InteropServices.RuntimeEnvironment a ...))))) (define (is? a) (clr-is System.Runtime.InteropServices.RuntimeEnvironment a)) (define (runtime-environment? a) (clr-is System.Runtime.InteropServices.RuntimeEnvironment a)) (define-method-port from-global-access-cache? System.Runtime.InteropServices.RuntimeEnvironment FromGlobalAccessCache (static: System.Boolean System.Reflection.Assembly)) (define-method-port get-system-version System.Runtime.InteropServices.RuntimeEnvironment GetSystemVersion (static: System.String)) (define-method-port get-runtime-directory System.Runtime.InteropServices.RuntimeEnvironment GetRuntimeDirectory (static: System.String)) (define-field-port system-configuration-file #f #f (static: property:) System.Runtime.InteropServices.RuntimeEnvironment SystemConfigurationFile System.String))
true
825d23b5ff9a6dd524b8d1d864dfe28807ae01eb
4bd59493b25febc53ac9e62c259383fba410ec0e
/Scripts/Task/execute-a-markov-algorithm/scheme/execute-a-markov-algorithm.ss
5dc344ce3e3da512c842e21a12b3c0c7425b8fc7
[]
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
1,781
ss
execute-a-markov-algorithm.ss
(define split-into-lines (lambda (str) (let loop ((index 0) (result '())) (let ((next-index (string-index str #\newline index))) (if next-index (loop (+ next-index 1) (cons (substring str index next-index) result)) (reverse (cons (substring str index) result))))))) (define parse-rules (lambda (str) (let loop ((rules (split-into-lines str)) (result '())) (if (null? rules) (reverse result) (let ((rule (car rules))) (loop (cdr rules) (if (or (string=? rule "") (eq? (string-ref rule 0) #\#)) result (cons (let ((index (string-contains rule "->" 1))) (list (string-trim-right (substring rule 0 index)) (string-trim (substring rule (+ index 2))))) result)))))))) (define apply-rules (lambda (str rules) (let loop ((remaining rules) (result str)) (if (null? remaining) result (let* ((rule (car remaining)) (pattern (car rule)) (replacement (cadr rule)) (start (string-contains result pattern))) (if start (if (eq? #\. (string-ref replacement 0)) (string-replace result replacement start (+ start (string-length pattern)) 1) (apply-rules (string-replace result replacement start (+ start (string-length pattern))) rules)) (loop (cdr remaining) result)))))))
false
6af99bd5c25b6166e1ef67297bb3cc8a20c56862
eb32c279a34737c769d4e2c498a62c761750aeb5
/lyonesse/munsch/array.old.scm
24f3433cd25870e6c3e786b932c814141a4d005f
[ "Apache-2.0" ]
permissive
theschemer/lyonesse
baaf340be710f68b84c1969befc6ddbd2be3739b
9d9624e3141ea3acaa670526cbe52c2d6546beef
refs/heads/master
2021-06-10T02:58:28.040995
2016-11-29T21:28:11
2016-11-29T21:28:11
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,240
scm
array.old.scm
(library (lyonesse munsch array) (export make-array array? array-slice array-data array-type make-slice slice? slice-shape slice-stride slice-size slice-offset vector->array array->vector array-ref array-iterator array-set! array-shape array-data-ptr array-byte-size) (import (rnrs base (6)) (rnrs lists (6)) (rnrs control (6)) (rnrs records syntactic (6)) (rnrs io simple (6)) (only (srfi :1) unfold) (lyonesse functional) (lyonesse munsch nd-range) (lyonesse malloc) (only (chezscheme) foreign-ref foreign-set! foreign-sizeof unbox)) #|! Returns a new list where the `n`-th element is changed by mapping it | through `proc`. |# (define (list-mod lst n proc) (let loop ([lst lst] [n n] [result '()]) (cond [(null? lst) (reverse result)] [(zero? n) (loop (cdr lst) -1 (cons (proc (car lst)) result))] [else (loop (cdr lst) (- n 1) (cons (car lst) result))]))) #| Array helper routines ================================================= |# (define (data-alloc type n) (malloc (* n (foreign-sizeof type)))) (define (data-ref type data pos) (foreign-ref type (unbox data) (* (foreign-sizeof type) pos))) (define (data-set! type data pos value) (foreign-set! type (unbox data) (* (foreign-sizeof type) pos) value)) (define (size-and-stride shape) (let ([cum-prod (fold-right (lambda (x y) (cons (* x (car y)) y)) '(1) shape)]) (values (car cum-prod) (cdr cum-prod)))) (define (compute-stride shape) (let ([cum-prod (fold-right (lambda (x y) (cons (* x (car y)) y)) '(1) shape)]) (cdr cum-prod))) #| Working with slices =================================================== |# (define-record-type slice (fields shape stride size offset) (protocol (lambda (new) (case-lambda [(shape) (let-values ([(size stride) (size-and-stride shape)]) (new shape stride size 0))] [(shape stride size offset) (new shape stride size offset)])))) (define (slice-index slice idx) (fold-left (lambda (sum x y) (+ sum (* x y))) (slice-offset slice) (slice-stride slice) idx)) (define (slice-transpose slice) (make-slice (reverse (slice-shape slice)) (reverse (slice-stride slice)) (slice-shape slice) (slice-offset slice))) (define (slice-cut slice axis a b step) (let* ([offset (+ (slice-offset slice) (* a (list-ref (slice-stride slice) axis)))] [stride (list-mod (slice-stride slice) axis ($ * step <>))] [shape (list-mod (slice-shape slice) axis (thunk (div (- b a) (abs step))))] [size (fold-left * 1 shape)]) (make-slice shape stride size offset))) (define (slice-reverse slice axis) (let* ([offset (+ (slice-offset slice) (* (list-ref (slice-stride slice) axis) (- (list-ref (slice-shape slice) axis) 1)))] [stride (list-mod (slice-stride slice) axis ($ * -1 <>))]) (make-slice (slice-shape slice) stride (slice-size slice) offset))) #| Array routines ======================================================== |# (define-record-type array (fields type slice data) (protocol (lambda (new) (case-lambda [(type shape) (let ([slice (make-slice shape)]) (new type slice (data-alloc type (slice-size slice))))] [(type slice data) (new type slice data)])))) (define (array-ref a i) (data-ref (array-type a) (array-data a) (if (nd-range? i) (nd-range-offset i) i))) (define (array-set! a offset value) (data-set! (array-type a) (array-data a) offset value)) (define (array-data-ptr a) (unbox (array-data a))) (define (array-byte-size a) (* (foreign-sizeof (array-type a)) (slice-size (array-slice a)))) (define (array-shape a) (slice-shape (array-slice a))) (define (array-iterator a) (let ([s (array-slice a)]) (make-nd-range (slice-offset s) (slice-shape s) (slice-stride s)))) (define (vector-match-shape? vec shape) (cond [(and (null? shape) (not (vector? vec))) #t] [(not (vector? vec)) #f] [(= (vector-length vec) (car shape)) (for-all (compose ($ vector-match-shape? <> (cdr shape)) ($ vector-ref vec <>)) (iota (car shape)))] [else #f])) (define (vector->array type vec) (let ([shape (unfold (compose not vector?) vector-length ($ vector-ref <> 0) vec)]) (when (not (vector-match-shape? vec shape)) (error 'vector->array "Vector is not uniform." vec)) (letrec ([a (make-array type shape)] [copy! (lambda (r v) (if (vector? v) (let loop ([r r] [i 0]) (if (= i (vector-length v)) r (loop (copy! r (vector-ref v i)) (+ i 1)))) (begin (array-set! a r v) (+ r 1))))]) (copy! 0 vec) a))) (define (array->vector a) (letrec ([vec (make-vector (car (array-shape a)))] [copy! (lambda (r v s) (let loop ([r r] [i 0]) (if (= i (car s)) r (if (null? (cdr s)) (begin (vector-set! v i (array-ref a r)) (loop (nd-range-step r) (+ i 1))) (begin (vector-set! v i (make-vector (cadr s))) (loop (copy! r (vector-ref v i) (cdr s)) (+ i 1)))))))]) (copy! (array-iterator a) vec (array-shape a)) vec)) )
false
ebea6f362e5b5700783a85ffd082fd00510aec42
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/13-modules/prim_keyword.scm
9fa48240731666698a4d509eccd21aa8b531a2ae
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
332
scm
prim_keyword.scm
(include "#.scm") (check-same-behavior ("" "##" "~~lib/_prim-keyword#.scm") ;; Gambit (keyword->string 'a:) (keyword-hash 'a:) (keyword? 'a:) (keyword? "a") (keyword? 123) (string->keyword "a") (keyword->string (string->uninterned-keyword "a")) (uninterned-keyword? 'a:) (uninterned-keyword? (string->uninterned-keyword "a")) )
false
0ab0bc8bbc6e6f9c646cc71d61fbda8d977b7816
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/7/hoare-quicksort.scm
7c5f9ec9d097da3ee6ef6e9c7591f8d7befbe6d0
[]
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
747
scm
hoare-quicksort.scm
(define (hoare-partition! vector p r) (let ((x (vector-ref vector p)) (i p) (j r)) (call-with-current-continuation (lambda (return) (let loop () (let loop ((j-ref (vector-ref vector j))) (if (> j-ref x) (begin (set! j (- j 1)) (loop (vector-ref vector j))))) (let loop ((i-ref (vector-ref vector i))) (if (< i-ref x) (begin (set! i (+ i 1)) (loop (vector-ref vector i))))) (if (< i j) (begin (vector-swap! vector i j) (loop)) (return j))))))) (define (hoare-quicksort! vector p r) (quicksort-general! vector p r hoare-partition!))
false
3e993774a2ca58cbfcdcff27bdf8a55217d65e44
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/10.2/10.2-3.scm
576146197fdc2a8bffabb074d7415ee88ea77928
[]
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
309
scm
10.2-3.scm
(require-extension syntax-case check) (require '../10.2/section) (import section-10.2) (let* ((sentinel (make-sentinel)) (queue (make-slist-queue (make-slist sentinel) sentinel))) (slist-enqueue! queue 1) (slist-enqueue! queue 2) (slist-enqueue! queue 3) (check (slist-dequeue! queue) => 1))
false
f77f3963a7b6f5e9af4453fbdda63b3cf1e6e622
12fc725f8273ebfd9ece9ec19af748036823f495
/daemon/src/timer_generic_epoc.scm
dc77b71b38f71de8b9e0616f41435f27571c8a5a
[]
no_license
contextlogger/contextlogger2
538e80c120f206553c4c88c5fc51546ae848785e
8af400c3da088f25fd1420dd63889aff5feb1102
refs/heads/master
2020-05-05T05:03:47.896638
2011-10-05T23:50:14
2011-10-05T23:50:14
1,675,623
1
0
null
null
null
null
UTF-8
Scheme
false
false
5,494
scm
timer_generic_epoc.scm
#!/bin/sh #| # -*- scheme -*- exec mzscheme --name "$0" --eval "(require scheme (lib \"usual-4.ss\" \"common\") (file \"$0\")) (current-load-relative-directory (path-dirname (path->complete-path \"$0\"))) (main)" |# #lang scheme ;; CTimer objects are quite useful, and I believe we shall want a ;; language construct for defining subclasses. Or we might want to ;; create a concrete subclass of CTimer that is fairly general ;; purpose, and just use that one across the board. Indeed, here we ;; define just such a general purpose CTimer class. (require (lib "usual-4.ss" "common")) (require (lib "ast-util.scm" "wg")) (require (lib "compact.scm" "wg")) (require (lib "file-util.scm" "wg")) (require (lib "node-ctors.scm" "wg")) (require (lib "local-util.scm" "codegen")) (require (lib "active-object.scm" "codegen")) (define program-name (find-system-path 'run-file)) (define program-basename (path-drop-extension (path-basename program-name) ".scm")) (define program-1 (unit (basename program-basename) (includes (system-include "e32base.h")) (body (cxx-iface-line "class CTimerAo;") (class (name 'MTimerObserver) export (doc "A callback interface for CTimerAo.") (body (func (name 'HandleTimerEvent) (args (arg (name 'aOrig) (type (ptr-to 'CTimerAo))) (arg (name 'aError) (type 'TInt))) public pure virtual))) ;; We might want a construct for defining the construction ;; methods all in one go. Some kind of a sexp-based ;; specification could be given as an argument to it, for ;; parameterization. (let* ((class-name 'CTimerAo) (class-args (args (arg (name 'aInterface) (type (ref-to 'MTimerObserver))) (arg (name 'aPriority) (type 'TInt)))) (args-names (map ;; We might want to consider using the views library for ;; some extra abstraction when dealing with our exposed ;; AST nodes. (lambda (arg) (fget-reqd-nlist-elem-1 arg 'name)) (cdr class-args)))) (class (name class-name) (bases 'CTimer) export (doc "A fairly generic, concrete CTimer subclass that delivers timer events via a callback interface.") (body (func (name 'NewLC) public static leaving class-args (returns (type (ptr-to class-name))) (block (var (name 'object) (type (ptr-to class-name)) (init (leaving-new class-name args-names))) (call 'CleanupStack::PushL (list 'object)) (call-via 'object 'ConstructL) (return 'object))) (func (name 'NewL) public static leaving class-args (returns (type (ptr-to class-name))) (block (var (name 'object) (type (ptr-to class-name)) (init (call 'NewLC args-names))) (call 'CleanupStack::Pop) (return 'object))) (ctor private class-args (ctor-init-list (ctor-super 'CTimer '(aPriority)) (ctor-var 'iInterface '(aInterface))) (block ;; Apparently the superclass constructor does not do this. ao-scheduler-add-this)) (func (name 'RunL) private virtual leaving (block (call-on 'iInterface 'HandleTimerEvent (list 'this (call-on 'iStatus 'Int))))) ;; Must implement RunError if HandleTimerEvent may leave. As ;; per the current naming, we do not allow that. We could ;; have another variant of this class allowing for it, I ;; guess, and letting a RunError handler also be defined in ;; the interface. (var (name 'iInterface) (type (ref-to 'MTimerObserver)) private) ))) ))) ; end program-1 (define* (main) ;;(pretty-nl program-1) (generate-h-and-cpp program-1) ;;(dump-h-and-cpp program-1) ;;(dump-analyzed-ast program-1) ;;(dump-compiled-ast program-1) (void)) #| timer_generic_epoc.scm Copyright 2009 Helsinki Institute for Information Technology (HIIT) and the authors. All rights reserved. Authors: Tero Hasu <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |#
false
12601ca92e35ff9d1cab4a409ff3c3ac750397d0
f59b3ca0463fed14792de2445de7eaaf66138946
/section-3/3_34.scm
f7dbb62ba0b0b1b47e58b2939da21c6087a2bd18
[]
no_license
uryu1994/sicp
f903db275f6f8c2da0a6c0d9a90c0c1cf8b1e718
b14c728bc3351814ff99ace3b8312a651f788e6c
refs/heads/master
2020-04-12T01:34:28.289074
2018-06-26T15:17:06
2018-06-26T15:17:06
58,478,460
0
1
null
2018-06-20T11:32:33
2016-05-10T16:53:00
Scheme
UTF-8
Scheme
false
false
566
scm
3_34.scm
(load "./connector") (define (squarer a b) (multiplier a a b)) (define A (make-connector)) (define B (make-connector)) (squarer A B) (probe "A" A) (probe "B" B) (set-value! A 10 'user) ;; Probe: A = 10 ;; Probe: B = 100done -> 正しい (forget-value! A 'user) (set-value! B 400 'user) ;; Probe: B = 400done -> Aが表示されない ;; Aのみ値がセットされる場合3つ中2つ値が設定される ;; Bのみ値がセットされる場合3つ中1つしか値が設定されないので process-new-value 手続きのいずれにもヒットしない
false
e317106bb3b82d7d4acb010cbf2c923277052458
2fc7c18108fb060ad1f8d31f710bcfdd3abc27dc
/lib/equal-cip.scm
4dae3b936d4f97d5084cabea8873b4d519b7b5f6
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "CC0-1.0" ]
permissive
bakul/s9fes
97a529363f9a1614a85937a5ef9ed6685556507d
1d258c18dedaeb06ce33be24366932143002c89f
refs/heads/master
2023-01-24T09:40:47.434051
2022-10-08T02:11:12
2022-10-08T02:11:12
154,886,651
68
10
NOASSERTION
2023-01-25T17:32:54
2018-10-26T19:49:40
Scheme
UTF-8
Scheme
false
false
879
scm
equal-cip.scm
; Scheme 9 from Empty Space, Function Library ; By Nils M Holm, 2010 ; Placed in the Public Domain ; ; (equal-ci? object1 object2) ==> boolean ; ; EQUAL-CI? is like EQUAL?, but compares strings and characters ; using case-insensitive predicates whereas EQUAL? distinguishes ; case. ; ; Example: (equal-ci? '(#\A ("b")) '(#\a ("B"))) ==> #t (define (equal-ci? a b) (cond ((eq? a b) #t) ((and (pair? a) (pair? b)) (and (equal-ci? (car a) (car b)) (equal-ci? (cdr a) (cdr b)))) ((char? a) (and (char? b) (char-ci=? a b))) ((string? a) (and (string? b) (string-ci=? a b))) ((vector? a) (and (vector? b) (equal-ci? (vector->list a) (vector->list b)))) (else (eqv? a b))))
false
749fe932bac4a1e1c426ec5e082223a8c7d66606
cdd2116cb3ead4376fca76b1be8f1205b28808fa
/net/yahoo-jp.scm
a75f16641055c20b7b23bb36099fb0d53da89de3
[]
no_license
hirofumi/Gauche-net-yahoo-jp
664018841d4efae65a9750d0956811b0990b1ff7
ccfe557c6449ebb22d4a564ffaf5937726be3871
refs/heads/master
2021-01-22T01:04:43.839115
2012-11-27T14:03:33
2012-11-27T14:03:33
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,718
scm
yahoo-jp.scm
(define-module net.yahoo-jp (use gauche.parameter) (use rfc.http) (use rfc.uri) (use srfi-1) (use srfi-13) (use sxml.ssax) (use sxml.sxpath) (use sxml.tools) (use text.tree) (use util.list) (use util.match) (define map/index (with-module gauche.sequence map-with-index)) (export yj-application-id <yj-api-error> yj-api-error?)) (select-module net.yahoo-jp) (define yj-application-id (make-parameter "YahooDemo")) (define *namespaces* '("urn:yahoo:api" "urn:yahoo:jp:srch" "urn:yahoo:jp:srchmi" "urn:yahoo:jp:srchmv" "urn:yahoo:jp:srchunit" "urn:yahoo:jp:dir:tree" "urn:yahoo:jp:dir:srch" "urn:yahoo:jp:auc:category" "urn:yahoo:jp:auc:leaf" "urn:yahoo:jp:auc:sellinglist" "urn:yahoo:jp:auc:search" "urn:yahoo:jp:auc:item" "urn:yahoo:jp:auc:BidHistory" "urn:yahoo:jp:auc:BidHistoryDetail" "urn:yahoo:jp:auc:ShowQandA" "urn:yahoo:jp:auc:ShowRating" "urn:yahoo:jp:music:station" "urn:yahoo:jp:maps:tree" "urn:yahoo:jp:jlp" "urn:yahoo:jp:jlp:JIMService" "urn:yahoo:jp:jlp:FuriganaService" "urn:yahoo:jp:jlp:KouseiService" "urn:yahoo:jp:jlp:DAService" "urn:yahoo:jp:jlp:DAServiceSearch" "urn:yahoo:jp:news" "urn:yahoo:jp:cert" "urn:yahoo:jp:chiebukuro" "urn:yahoo:jp:itemSearch" "urn:yahoo:jp:categoryRanking" "urn:yahoo:jp:categorySearch" "urn:yahoo:jp:itemLookup" "urn:yahoo:jp:queryRanking" "urn:yahoo:jp:Content" "urn:yahoo:jp:getModule")) (define-condition-type <yj-api-error> <error> yj-api-error? (server #f) (request-uri #f) (status #f) (headers #f) (body #f)) (define (xml->sxml xml) (call-with-input-string xml (cut ssax:xml->sxml <> (map (cut cons #f <>) *namespaces*)))) (define /Error/Message (sxpath '(Error Message))) (define (make-message-pattern status) (string->regexp (string-append "<title>Yahoo! - " status " ([^<]+)"))) (define (extract-error-message status body) (guard (e (else (rxmatch-if ((make-message-pattern status) body) (#f message) message #f))) (string-trim-both (cadar (/Error/Message (xml->sxml body)))))) (define (make-error-message server request-uri status headers body) (let ((message (extract-error-message status body))) (tree->string (if (not message) `(,status) `(,status " " ,message))))) (define (yj-api-error server request-uri status headers body) (error <yj-api-error> :server server :request-uri request-uri :status status :headers headers :body body (make-error-message server request-uri status headers body))) (define (make-query arguments) (tree->string (map/index (lambda (i x) (let ((x* (uri-encode-string (x->string x)))) (cond ((zero? i) x*) ((even? i) (cons '& x*)) (else (cons '= x*))))) arguments))) (define (make-query/appid arguments) (make-query `(:appid ,(yj-application-id) ,@arguments))) (define-syntax request (syntax-rules (GET POST) ((_ GET server path query option ...) (http-get server (string-append path "?" query) option ...)) ((_ POST server path query option ...) (http-post server path query :Content-Type "application/x-www-form-urlencoded" option ...)))) (define-syntax define-api (syntax-rules () ((_ name method server path) (define (name . arguments) (let*-values (((query) (make-query/appid arguments)) ((status headers body) (request method server path query))) (unless (string=? status "200") (yj-api-error server query status headers body)) (let ((sxml (xml->sxml body))) (sxml:squeeze! sxml) sxml)))))) (define-syntax define&export-apis (syntax-rules () ((_ (server method path ...) ...) (begin (begin (define-api path method server (symbol->string 'path)) ...) ... (begin (export path) ...) ...)))) (define&export-apis ("search.yahooapis.jp" POST /WebSearchService/V1/webSearch /ImageSearchService/V1/imageSearch /VideoSearchService/V1/videoSearch /AssistSearchService/V1/webunitSearch) ("map.yahooapis.jp" GET /LocalSearchService/V1/LocalSearch) ("jlp.yahooapis.jp" POST /MAService/V1/parse /JIMService/V1/conversion /FuriganaService/V1/furigana /KouseiService/V1/kousei /DAService/V1/parse /DAService/V1/search) ("auctions.yahooapis.jp" POST /AuctionWebService/V1/CategoryTree /AuctionWebService/V1/CategoryLeaf /AuctionWebService/V1/SellingList /AuctionWebService/V1/Search /AuctionWebService/V1/AuctionItem /AuctionWebService/V1/BidHistory /AuctionWebService/V1/BidHistoryDetail /AuctionWebService/V1/ShowQandA /AuctionWebService/V1/ShowRating) ("shopping.yahooapis.jp" GET /ShoppingWebService/V1/itemSearch /ShoppingWebService/V1/categoryRanking /ShoppingWebService/V1/categorySearch /ShoppingWebService/V1/itemLookup /ShoppingWebService/V1/queryRanking /ShoppingWebService/V1/contentMatchItem /ShoppingWebService/V1/contentMatchRanking /ShoppingWebService/V1/getModule) ("news.yahooapis.jp" GET /NewsWebService/V1/Topics) ("chiebukuro.yahooapis.jp" GET /Chiebukuro/V1/questionSearch /Chiebukuro/V1/categoryTree) ("dir.yahooapis.jp" GET /Category/V1/Category /Category/V1/directorySearch) ("cert.yahooapis.jp" GET /MinnaCertWebService/V1/certList /MinnaCertWebService/V1/certDetail /MinnaCertWebService/V1/certExam) ("station.music.yahooapis.jp" GET /StationWebService/V1/ProgramList)) (provide "net.yahoo-jp")
true
d852a6ec55d5be1e03f16729cc7c54aa2d7482c4
cca999903bc2305da28e598c46298e7d31dbdef5
/src/web/collections/test/deforder.ss
0fceb4348c17f76d0bfea84bdc63976f0c3cde20
[ "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
837
ss
deforder.ss
(provide f1 f2 x y z foo) ;x has fwd ref to f1 ;f1 we know will bubble up because it's a fun def ;x will stay put (define x (f1)) ;check-expect will sink to the bottom (check-expect (f1) 3) ;f1 will bubble up because it's a fun def ;f1's body has fwd ref to y ;hopefully y will bubble higher than f1 (define (f1) (+ y 1)) ;y has no fwd ref ;will bubble up ahead of fun defs, since it's a nonfun def (define y 2) ;f2 will bubble up because it's a fun def ;f2's body has fwd ref to make-foo ;but make-foo is a struct def, so we know it'll bubble up ahead of even nonfun defs (define (f2) (make-foo)) ;z has fwd ref to make-foo, but no fwd ref to any regular fun def ;z will bubble up ahead of fun defs, but below struct defs (define z (make-foo)) ;foo and related defs will bubble up ahead of nonfun defs (define-struct foo ())
false
af9d7a67bb636123c9c7757a5838ddd6fbe7267b
23ff9f52226c27bd848a6382de15edf5b4b2c460
/ex-ndfa-tests.scm
b12297cc74f9b86bc826007695452a4eedae1dd5
[]
no_license
namin/metamk
db4c10bf297289345b84b9934b5767b79a73c585
8bc90b222987294baaf8464fccaa6a12c47005b0
refs/heads/master
2023-09-02T03:11:46.571987
2023-08-27T10:13:43
2023-08-27T10:13:43
14,932,255
27
3
null
null
null
null
UTF-8
Scheme
false
false
315
scm
ex-ndfa-tests.scm
(load "mk2.scm") (load "utils.scm") (load "vanilla.scm") (load "meta.scm") (load "ex-ndfa.scm") (load "test-check.scm") (test-check "accept-base" (run 3 (xs) (accept xs)) '(() (a b) (a b a b))) (test-check "accept-vanilla" (run 3 (xs) ((vanilla ndfa-clause) `(accept ,xs))) '(() (a b) (a b a b)))
false
7b95738c79e1c741d5daf37b7914399f9baa4511
4f30ba37cfe5ec9f5defe52a29e879cf92f183ee
/src/sasm/sasm-visitor.scm
272d39ae287dde5ab13901cd09af81b8a48e164c
[ "MIT" ]
permissive
rtrusso/scp
e31ecae62adb372b0886909c8108d109407bcd62
d647639ecb8e5a87c0a31a7c9d4b6a26208fbc53
refs/heads/master
2021-07-20T00:46:52.889648
2021-06-14T00:31:07
2021-06-14T00:31:07
167,993,024
8
1
MIT
2021-06-14T00:31:07
2019-01-28T16:17:18
Scheme
UTF-8
Scheme
false
false
14,339
scm
sasm-visitor.scm
;; sasm-visitor.scm ;; ;; AST visitor infrastructure for SASM. (need scheme/tag) (define-syntax sasm-node-visitor (syntax-rules (:preorder :postorder) ;; ;; preorder, postorder both specified ;; ((_ ((<node-variable> <node-type-1> <node-type-2> ...) (<property-variable> <property-name>) ...) (:preorder <preorder-body-1> <preorder-body> ...) (:postorder <postorder-body-1> <postorder-body> ...)) (lambda (<node-variable> traversal-pass) (if (or (tagged? '<node-type-1> <node-variable>) (tagged? '<node-type-2> <node-variable>) ...) (apply (lambda (<property-variable> ...) (case traversal-pass ((:preorder) <preorder-body-1> <preorder-body> ...) ((:postorder) <postorder-body-1> <postorder-body> ...) (else (error "Unrecognized traversal pass -- sasm-node-visitor" traversal-pass)))) (map (lambda (property-name) (sasm-ast-node-get-attribute <node-variable> property-name)) '(<property-name> ...))) #f))) ;; ;; only preorder specified ;; ((_ ((<node-variable> <node-type-1> <node-type-2> ...) (<property-variable> <property-name>) ...) (:preorder <preorder-body-1> <preorder-body> ...)) (sasm-node-visitor ((<node-variable> <node-type-1> <node-type-2> ...) (<property-variable> <property-name>) ...) (:preorder <preorder-body-1> <preorder-body> ...) (:postorder #f))) ;; ;; only postorder specified ;; ((_ ((<node-variable> <node-type-1> <node-type-2> ...) (<property-variable> <property-name>) ...) (:postorder <postorder-body-1> <postorder-body> ...)) (sasm-node-visitor ((<node-variable> <node-type-1> <node-type-2> ...) (<property-variable> <property-name>) ...) (:preorder #f) (:postorder <postorder-body-1> <postorder-body> ...))) ;; ;; no traversal ordering specified => postorder ;; ((_ ((<node-variable> <node-type-1> <node-type-2> ...) (<property-variable> <property-name>) ...) <body-1> <body> ...) (begin (sasm-node-visitor ((<node-variable> <node-type-1> <node-type-2> ...) (<property-variable> <property-name>) ...) (:preorder #f) (:postorder <body-1> <body> ...)))) )) (define-syntax sasm-ast-visitor (syntax-rules (:covering) ((_ (((<node-variable> <node-type-1> <node-type-2> ...) <args> ...) <body> ...) ...) (let ((<node-type-1> (sasm-node-visitor ((<node-variable> <node-type-1> <node-type-2> ...) <args> ...) <body> ...)) ...) (lambda (node traversal-pass) (case (get-tag node) ((<node-type-1> <node-type-2> ...) (apply <node-type-1> node traversal-pass '())) ... (else #f))))) ((_ :covering (((<node-variable> <node-type-1> <node-type-2> ...) <args> ...) <body> ...) ...) (let ((<node-type-1> (sasm-node-visitor ((<node-variable> <node-type-1> <node-type-2> ...) <args> ...) <body> ...)) ...) (lambda (node traversal-pass) (case (get-tag node) ((<node-type-1> <node-type-2> ...) (apply <node-type-1> node traversal-pass '())) ... (else (error "Unrecognized node type" (get-tag node) node)))))) )) (define-syntax define-sasm-ast-visitor (syntax-rules (define-case :covering) ((_ <visitor-name> (define-case ((<node-variable> <node-type-1> <node-type-2> ...) (<arg-name-1> <arg-type-1>) ...) <body> ...) ...) (define <visitor-name> (sasm-ast-visitor (((<node-variable> <node-type-1> <node-type-2> ...) (<arg-name-1> <arg-type-1>) ...) <body> ...) ...))) ((_ <visitor-name> :covering (define-case ((<node-variable> <node-type-1> <node-type-2> ...) (<arg-name-1> <arg-type-1>) ...) <body> ...) ...) (define <visitor-name> (sasm-ast-visitor :covering (((<node-variable> <node-type-1> <node-type-2> ...) (<arg-name-1> <arg-type-1>) ...) <body> ...) ...))) )) (define (sasm-visit-ast node visitor) (define (recurse current next) (meta-visitor next ':postorder)) (define-sasm-ast-visitor meta-visitor :covering (define-case ((program <sasm-program>) (statements :statements)) (visitor program ':preorder) (for-each (lambda (statement) (recurse program statement)) statements) (visitor program ':postorder)) (define-case ((member-function <sasm-member-function>)) (visitor member-function ':preorder) (visitor member-function ':postorder)) (define-case ((global-data <sasm-global-data-symbol>)) (visitor global-data ':preorder) (visitor global-data ':postorder)) (define-case ((global-data <sasm-global-data-integer>)) (visitor global-data ':preorder) (visitor global-data ':postorder)) (define-case ((global-data <sasm-global-data-string>)) (visitor global-data ':preorder) (visitor global-data ':postorder)) (define-case ((symconst <sasm-integer-symconst>)) (visitor symconst ':preorder) (visitor symconst ':postorder)) (define-case ((operand <register-reference>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <system-register-reference>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <integer-constant-operand>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <label-constant-operand>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <string-constant-operand>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <numbered-temporary-reference>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <named-temporary-reference>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <argument-reference>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <numbered-local-reference>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <symbolic-constant-operand>)) (visitor operand ':preorder) (visitor operand ':postorder)) (define-case ((operand <nested-operation-operand>) (nested-operation :operation)) (visitor operand ':preorder) (recurse operand nested-operation) (visitor operand ':postorder)) (define-case ((operation <sasm-operation>) (operands :operands)) (visitor operation ':preorder) (for-each (lambda (operand) (recurse operation operand)) operands) (visitor operation ':postorder)) (define-case ((instruction <sasm-perform-operation-instruction>) (operation :operation)) (visitor instruction ':preorder) (recurse instruction operation) (visitor instruction ':postorder)) (define-case ((instruction <sasm-assignment-instruction>) (destination :destination) (operand :operand)) (visitor instruction ':preorder) (recurse instruction destination) (recurse instruction operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-operation-assignment-instruction>) (destination :destination) (operation :operation)) (visitor instruction ':preorder) (recurse instruction destination) (recurse instruction operation) (visitor instruction ':postorder)) (define-case ((instruction <sasm-test-instruction>) (operation :operation)) (visitor instruction ':preorder) (recurse instruction operation) (visitor instruction ':postorder)) (define-case ((instruction <sasm-test-branch-instruction>) (label-operand :label-operand)) (visitor instruction ':preorder) (recurse instruction label-operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-operational-branch-instruction>) (operand :operand) (label-operand :label-operand)) (visitor instruction ':preorder) (recurse instruction label-operand) (recurse instruction operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-direct-goto-instruction>) (label-operand :label-operand)) (visitor instruction ':preorder) (recurse instruction label-operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-register-goto-instruction>) (register-operand :register-operand)) (visitor instruction ':preorder) (recurse instruction register-operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-save-register-instruction>) (register-operand :register-operand)) (visitor instruction ':preorder) (recurse instruction register-operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-restore-register-instruction>) (register-operand :register-operand)) (visitor instruction ':preorder) (recurse instruction register-operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-push-instruction>) (operand :operand)) (visitor instruction ':preorder) (recurse instruction operand) (visitor instruction ':postorder)) (define-case ((instruction <sasm-pop-instruction>) (destination :destination)) (visitor instruction ':preorder) (recurse instruction destination) (visitor instruction ':postorder)) (define-case ((instruction <sasm-clear-stack-instruction>)) (visitor instruction ':preorder) (visitor instruction ':postorder)) (define-case ((instruction <sasm-return-instruction>)) (visitor instruction ':preorder) (visitor instruction ':postorder)) (define-case ((instruction <sasm-return-and-clear-stack-instruction>)) (visitor instruction ':preorder) (visitor instruction ':postorder)) (define-case ((directive <sasm-label-definition-directive>)) (visitor directive ':preorder) (visitor directive ':postorder)) (define-case ((statement <sasm-class>) (member-functions :member-functions)) (visitor statement ':preorder) (for-each (lambda (member-function) (recurse statement member-function)) member-functions) (visitor statement ':postorder)) (define-case ((statement <sasm-global-data>) (data :global-data)) (visitor statement ':preorder) (for-each (lambda (datum) (recurse statement datum)) data) (visitor statement ':postorder)) (define-case ((statement <sasm-entry-point>)) (visitor statement ':preorder) (visitor statement ':postorder)) (define-case ((statement <sasm-symconst-table>) (entries :symconst-entries)) (visitor statement ':preorder) (for-each (lambda (entry) (recurse statement entry)) entries) (visitor statement ':postorder)) (define-case ((statement <sasm-class-info>)) (visitor statement ':preorder) (visitor statement ':postorder)) (define-case ((statement <sasm-export>)) (visitor statement ':preorder) (visitor statement ':postorder)) (define-case ((statement <sasm-extern>)) (visitor statement ':preorder) (visitor statement ':postorder)) (define-case ((statement <sasm-include>)) (visitor statement ':preorder) (visitor statement ':postorder)) (define-case ((function <sasm-function>) (instructions :instructions)) (visitor function ':preorder) (for-each (lambda (instruction) (recurse function instruction)) instructions) (visitor function ':postorder)) ) (recurse '() node)) ;; Syntax which defines a visitor and then runs a visit operation on ;; the specified tree where the body expressions may refer to a ;; specified "accumulate keyword" to accumulate results in a list. ;; (define-syntax sasm-visit-ast-with-accumulator (syntax-rules (define-case) ((_ <accumulate-keyword> <ast> (define-case <args> <body-1> <body-2> ...) ...) (let ((accumulate-result '())) (define (<accumulate-keyword> x) (set! accumulate-result (cons x accumulate-result))) (define-sasm-ast-visitor visitor (define-case <args> <body-1> <body-2> ...) ...) (sasm-visit-ast <ast> visitor) (reverse accumulate-result))))) (define-syntax sasm-filter-ast (syntax-rules () ((_ <ast> <type-1> <type-2> ...) (sasm-visit-ast-with-accumulator accumulate! <ast> (define-case ((node-1 <type-1>)) (accumulate! node-1)) (define-case ((node-2 <type-2>)) (accumulate! node-2)) ...))))
true
b3ae802af41ce5a9a86e7ff76a0bd92dcac35332
3c9983e012653583841b51ddfd82879fe82706fb
/r4/fusionstream.scm
a2d49a32eb7c9627e2e2c4cf44396e44c4431741
[]
no_license
spdegabrielle/smalltalk-tng
3c3d4cffa09541b75524fb1f102c7c543a84a807
545343190f556edd659f6050b98036266a270763
refs/heads/master
2020-04-16T17:06:51.884611
2018-08-07T16:18:20
2018-08-07T16:18:20
165,763,183
1
0
null
null
null
null
UTF-8
Scheme
false
false
5,460
scm
fusionstream.scm
(require srfi/9) (print-struct #t) (define previous-inspector (current-inspector)) (current-inspector (make-inspector)) (define-record-type stream (make-stream stepper state) stream? (stepper stream-stepper) (state stream-state)) (define-record-type done (make-done) done?) (define-record-type skip (make-skip next-state) skip? (next-state skip-next-state)) (define-record-type yield (make-yield value next-state) yield? (value yield-value) (next-state yield-next-state)) (define-record-type nothing (make-nothing) nothing?) (define-record-type just (make-just value) just? (value just-value)) (current-inspector previous-inspector) ;;--------------------------------------------------------------------------- (define (next s) ((stream-stepper s) (stream-state s))) (define (replace-state str s) (make-stream (stream-stepper str) s)) ;;--------------------------------------------------------------------------- ;; Stream constructors (define (return x) (make-stream (lambda (state) (if state (make-yield x #f) (make-done))) #t)) (define (range low high) (make-stream (lambda (state) (if (< state high) (make-yield state (+ state 1)) (make-done))) low)) ;;--------------------------------------------------------------------------- ;; Stream consumers, leading to values not (necessarily) of type stream (define (head s) (let ((step (next s))) (cond ((done? step) (error "head of empty stream")) ((skip? step) (head (skip-next-state step))) ((yield? step) (yield-value step))))) (define (tail s) (let ((step (next s))) (cond ((done? step) (error "tail of empty stream")) ((skip? step) (tail (skip-next-state step))) ((yield? step) (replace-state s (yield-next-state step)))))) ;; head-and-tail ? (define (foldr s knil kons) (let go ((state (stream-state s))) (let ((step ((stream-stepper s) state))) (cond ((done? step) knil) ((skip? step) (go (skip-next-state step))) ((yield? step) (f (yield-value step) (go (yield-next-state step)))))))) (define (foldl s knil kons) (let go ((knil knil) (state (stream-state s))) (let ((step ((stream-stepper s) state))) (cond ((done? step) knil) ((skip? step) (go knil (skip-next-state step))) ((yield? step) (go (f (yield-value step) knil) (yield-next-state step))))))) ;;--------------------------------------------------------------------------- ;; Stream transformers (define (map s f) (make-stream (lambda (state) (let ((step (next s))) (cond ((done? step) step) ((skip? step) step) ((yield? step) (make-yield (f (yield-value step)) (yield-next-state step)))))) (stream-state s))) (define (append s1 s2) (make-stream (lambda (state) (case (car state) ((left) (let ((step ((stream-stepper s1) (cdr state)))) (cond ((done? step) (make-skip (cons 'right (stream-state s2)))) ((skip? step) (make-skip (cons 'left (skip-next-state step)))) ((yield? step) (make-yield (yield-value step) (cons 'left (yield-next-state step))))))) ((right) (let ((step ((stream-stepper s2) (cdr state)))) (cond ((done? step) (make-done)) ((skip? step) (make-skip (cons 'right (skip-next-state step)))) ((yield? step) (make-yield (yield-value step) (cons 'right (yield-next-state step))))))))) (cons 'left (stream-state s1)))) (define (zip s1 s2) (make-stream (lambda (state) (let ((state1 (car state)) (state2 (cadr state)) (latch (caddr state))) (cond ((nothing? latch) (let ((step ((stream-stepper s1) state1))) (cond ((done? step) (make-done)) ((skip? step) (make-skip (list (skip-next-state step) state2 (make-nothing)))) ((yield? step) (make-skip (list (yield-next-state step) state2 (make-just (yield-value step)))))))) ((just? latch) (let ((step ((stream-stepper s1) state1))) (cond ((done? step) (make-done)) ((skip? step) (make-skip (list state1 (skip-next-state step) latch))) ((yield? step) (make-yield (list (just-value latch) (yield-value step)) (list state1 (yield-next-state step) (make-nothing)))))))))) (list (stream-state s1) (stream-state s2) (make-nothing)))) (define (concatmap s f) (make-stream (lambda (state) (let ((outerstate (car state)) (latch (cdr state))) (cond ((nothing? latch) (let ((step ((stream-stepper s) outerstate))) (cond ((done? step) (make-done)) ((skip? step) (make-skip (cons (skip-next-state step) latch))) ((yield? step) (make-skip (cons (yield-next-state step) (make-just (f (yield-value step))))))))) ((just? latch) (let* ((inners (just-value latch)) (step (next inners))) (cond ((done? step) (make-skip (cons outerstate (make-nothing)))) ((skip? step) (make-skip (cons outerstate (make-just (replace-state inners (skip-next-state step)))))) ((yield? step) (make-yield (yield-value step) (cons outerstate (make-just (replace-state inners (yield-next-state step)))))))))))) (cons (stream-state s) (make-nothing))))
false
9b5537fdfc242d732569e2c2d437b1fbe7b3d4aa
a74932f6308722180c9b89c35fda4139333703b8
/edwin48/scsh/event-distributor.scm
c168697fb374d4a881a94153b7ecdead3e6611c7
[]
no_license
scheme/edwin48
16b5d865492db5e406085e8e78330dd029f1c269
fbe3c7ca14f1418eafddebd35f78ad12e42ea851
refs/heads/master
2021-01-19T17:59:16.986415
2014-12-21T17:50:27
2014-12-21T17:50:27
1,035,285
39
10
null
2022-02-15T23:21:14
2010-10-29T16:08:55
Scheme
UTF-8
Scheme
false
false
2,594
scm
event-distributor.scm
;;; -*- mode: scheme; scheme48-package: event-distributor -*- ;;; ;;; Port MIT Scheme's event distributor (events.scm) to Scheme48 ;;; (define-record-type* event-distributor (%make-event-distributor events (lock) (receivers)) ()) (define (make-event-distributor) (%make-event-distributor (make-queue) #f '())) (define (make-receiver-modifier keyword) (lambda (event-distributor receiver) (if (not (event-distributor? event-distributor)) (error "Not an event distributor" event-distributor)) (enqueue! (event-distributor-events event-distributor) (cons keyword receiver)) (process-events! event-distributor))) (define (event-distributor/invoke! event-distributor . arguments) (enqueue! (event-distributor-events event-distributor) (cons 'INVOKE-RECEIVERS arguments)) (process-events! event-distributor)) (define add-event-receiver! (make-receiver-modifier 'ADD-RECEIVER)) (define remove-event-receiver! (make-receiver-modifier 'REMOVE-RECEIVER)) (define (process-events! event-distributor) (let ((old-lock unspecific)) (dynamic-wind (lambda () (let ((lock (event-distributor-lock event-distributor))) (set-event-distributor-lock! event-distributor #t) (set! old-lock lock) unspecific)) (lambda () (if (not old-lock) (queue-map! (event-distributor-events event-distributor) (lambda (event) (case (car event) ((INVOKE-RECEIVERS) (do ((receivers (event-distributor-receivers event-distributor) (cdr receivers))) ((null? receivers)) (apply (car receivers) (cdr event)))) ((ADD-RECEIVER) (let ((receiver (cdr event)) (receivers (event-distributor-receivers event-distributor))) (if (not (memv receiver receivers)) (set-event-distributor-receivers! event-distributor (append! receivers (list receiver)))))) ((REMOVE-RECEIVER) (set-event-distributor-receivers! event-distributor (delete! (cdr event) (event-distributor-receivers event-distributor) eqv?))) (else (error "Illegal event" event))))))) (lambda () (set-event-distributor-lock! event-distributor old-lock))))) (define (queue-map! queue procedure) (let ((empty (list 'EMPTY))) (let loop () (let ((item (without-interrupts (lambda () (if (queue-empty? queue) empty (dequeue! queue)))))) (if (not (eq? item empty)) (begin (procedure item) (loop)))))))
false
0a22893ee53ef54f087055a451c3f71798da5136
7666204be35fcbc664e29fd0742a18841a7b601d
/code/2-55.scm
7df2df6e3c764b6adaddefab3b47999dce494bdd
[]
no_license
cosail/sicp
b8a78932e40bd1a54415e50312e911d558f893eb
3ff79fd94eda81c315a1cee0165cec3c4dbcc43c
refs/heads/master
2021-01-18T04:47:30.692237
2014-01-06T13:32:54
2014-01-06T13:32:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
48
scm
2-55.scm
#lang racket (car ''ooxx) (car '(quote ooxx))
false
fc8e86eb6d7822b458355eb99824f497405c57c5
026beb778c2dd835189fa131c0770df49b8a7868
/lib/r7c-report/conditional/when.sls
c92c03ae139bd6a18f64646900a167c2acfb7078
[]
no_license
okuoku/r7c
8c51a19fba483aa3127136cbbc4fbedb8ea0798a
6c8522ac556e7e5c8e94b4deb29bbedb8aad4a84
refs/heads/master
2021-01-22T23:43:27.004617
2013-07-20T10:53:29
2013-07-20T10:53:29
11,394,673
2
0
null
null
null
null
UTF-8
Scheme
false
false
278
sls
when.sls
(library (r7c-report conditional when) (export when) (import (r7c-impl syntax core)) ;; Took from 7.3 Derived expression types (define-syntax when (syntax-rules () ((when test result1 result2 ...) (if test (begin result1 result2 ...))))) )
true
04e24cf4350b9da767566fe5bf99b16d422cc8cb
6b961ef37ff7018c8449d3fa05c04ffbda56582b
/bbn_cl/mach/cl/arith-defs-i.scm
0a9ff8658616408b77e6445ed71bfe8a434f6a06
[]
no_license
tinysun212/bbn_cl
7589c5ac901fbec1b8a13f2bd60510b4b8a20263
89d88095fc2a71254e04e57cf499ae86abf98898
refs/heads/master
2021-01-10T02:35:18.357279
2015-05-26T02:44:00
2015-05-26T02:44:00
36,267,589
4
3
null
null
null
null
UTF-8
Scheme
false
false
3,363
scm
arith-defs-i.scm
;;; ******** ;;; ;;; Copyright 1992 by BBN Systems and Technologies, A division of Bolt, ;;; Beranek and Newman Inc. ;;; ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice and this permission appear in all copies and in ;;; supporting documentation, and that the name Bolt, Beranek and Newman ;;; Inc. not be used in advertising or publicity pertaining to distribution ;;; of the software without specific, written prior permission. In ;;; addition, BBN makes no respresentation about the suitability of this ;;; software for any purposes. It is provided "AS IS" without express or ;;; implied warranties including (but not limited to) all implied warranties ;;; of merchantability and fitness. In no event shall BBN be liable for any ;;; special, indirect or consequential damages whatsoever resulting from ;;; loss of use, data or profits, whether in an action of contract, ;;; negligence or other tortuous action, arising out of or in connection ;;; with the use or performance of this software. ;;; ;;; ******** ;;; ;;; (proclaim '(insert-touches nil)) (export '(decode-float scale-float float-digits float-precision float-radix float-sign integer-decode-float)) ;;;================ ;;; DECODE-FLOAT ;;;================ ;;;Returns float integer float (cl-define DECODE-FLOAT-SIGN (make-primitive-procedure 'DECODE-FLOAT-SIGN)) (cl-define DECODE-FLOAT-MANTISSA (make-primitive-procedure 'DECODE-FLOAT-MANTISSA)) (cl-define DECODE-FLOAT-EXPONENT (make-primitive-procedure 'DECODE-FLOAT-EXPONENT)) (defun decode-float (float) (check-type float float) (values (decode-float-mantissa float) (decode-float-exponent float) (decode-float-sign float))) ;;;================ ;;; SCALE-FLOAT ;;;================ ;;;+++This not efficient ;;;+++LAS should write this one (defun scale-float (float integer) (check-type float float) (check-type integer integer) (* float (expt (float (float-radix float) float) integer))) ;;;================ ;;; FLOAT-RADIX ;;;================ (defun float-radix (f) (check-type f float) 2) ;;;================ ;;; FLOAT-SIGN ;;;================ (defun float-sign (float1 &optional (float2 (float 1 float1))) (check-type float1 float) (check-type float2 float) (if (eq (minusp float1) (minusp float2)) float2 (- float2))) ;;;================ ;;; FLOAT-DIGITS ;;;================ ;; This should do someting with different types of floats. (defun float-digits (f) (check-type f float) %long-float-mantissa-length) ;;;================ ;;; FLOAT-PRECISION ;;;================ (defun float-precision (f) (check-type f float) (if (zerop f) 0 (float-digits f))) ;;;================ ;;;INTEGER-DECODE-FLOAT ;;;================ ;;;Returns integer integer integer (cl-define INTEGER-DECODE-FLOAT-MANTISSA (make-primitive-procedure 'INTEGER-DECODE-FLOAT-MANTISSA)) (cl-define INTEGER-DECODE-FLOAT-EXPONENT (make-primitive-procedure 'INTEGER-DECODE-FLOAT-EXPONENT)) (defun integer-decode-float (float) (check-type float float) (values (INTEGER-DECODE-FLOAT-MANTISSA float) (INTEGER-DECODE-FLOAT-EXPONENT float) (decode-float-sign float)))
false
3bacf6a3ac01aab5cad392a248528f5e52d86a69
4a9bde514c789982d7dda8362cd50b9d7482913f
/Chapter2/sicp2.17-2.18.scm
c9b9ea9609fac3c66b160a1241a381038225624e
[]
no_license
atsfour/sicp
7e8e0deefa16201da6d01db34e24ad3245dbb052
f6f2818cbe440ac2ec557453945c0782e7267842
refs/heads/master
2020-03-30T08:12:36.638041
2015-12-03T15:50:47
2015-12-08T06:51:04
39,726,082
0
0
null
null
null
null
UTF-8
Scheme
false
false
615
scm
sicp2.17-2.18.scm
(define (list-ref items n) (if (= n 0) (car items) (list-ref (cdr items) (- n 1)))) (define (length items) (define (length-iter a count) (if (null? a) count (length-iter (cdr a) (+ count 1)))) (length-iter items 0)) (define (append list1 list2) (if (null? list1) list2 (cons (car list1) (append (cdr list1) list2)))) ; Exercise 2.17 (define (last-pair x) (if (null? (cdr x)) (car x) (last-pair (cdr x)))) ; Exercise 2.18 (define (reverse x) (if (null? x) () (append (reverse (cdr x)) (list (car x))))) (define sample (list 1 2 3))
false
fa042878349258c001536f2c92ebe0d8657c83f9
32130475e9aa1dbccfe38b2ffc562af60f69ac41
/02_01_03.scm
60940d9b074089aabb34d0978354908a214dad7a
[]
no_license
cinchurge/SICP
16a8260593aad4e83c692c4d84511a0bb183989a
06ca44e64d0d6cb379836d2f76a34d0d69d832a5
refs/heads/master
2020-05-20T02:43:30.339223
2015-04-12T17:54:45
2015-04-12T17:54:45
26,970,643
0
0
null
null
null
null
UTF-8
Scheme
false
false
300
scm
02_01_03.scm
(use test) (define (cons-new x y) (define (dispatch m) (cond ((= m 0) x) ((= m 1) y) (else (error "Argument not 0 or 1: CONS" m)))) dispatch) (define (car-new z) (z 0)) (define (cdr-new z) (z 1)) (let ((z (cons-new 1 2))) (test 1 (car-new z)) (test 2 (cdr-new z)))
false
a8c1cace84b9b566e235f85e706a92a54d0127e9
951b7005abfe3026bf5b3bd755501443bddaae61
/表格的表示.scm
1b465727e754a7f789ab65c6862ea773cbd09d40
[]
no_license
WingT/scheme-sicp
d8fd5a71afb1d8f78183a5f6e4096a6d4b6a6c61
a255f3e43b46f89976d8ca2ed871057cbcbb8eb9
refs/heads/master
2020-05-21T20:12:17.221412
2016-09-24T14:56:49
2016-09-24T14:56:49
63,522,759
2
0
null
null
null
null
UTF-8
Scheme
false
false
7,934
scm
表格的表示.scm
;一维表格 (define (make-table) (list '*table*)) (define (assoc key records) (cond ((null? records) #f) ((equal? (caar records) key) (car records)) (else (assoc key (cdr records))))) (define (lookup key table) (let ((result (assoc key (cdr table)))) (if result (cdr result) #f))) (define (insert! key value table) (let ((record (assoc key (cdr table)))) (if record (set-cdr! record value) (set-cdr! table (cons (cons key value) (cdr table))))) 'ok) ;二维表格 (define (lookup key1 key2 table) (let ((subtable (assoc key1 (cdr table)))) (if subtable (let ((record (assoc key2 (cdr subtable)))) (if record (cdr record) #f)) #f))) (define (insert! key1 key2 value table) (let ((subtable (assoc key1 (cdr table)))) (if subtable (let ((record (assoc key2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key2 value) (cdr subtable))))) (set-cdr! table (cons (list key1 (cons key2 value)) (cdr table))))) 'ok) ;创建局部表格 (define (make-table) (let ((table (list '*table*))) (define (assoc key records) (cond ((null? records) #f) ((equal? (caar records) key) (car records)) (else (assoc key (cdr records))))) (define (lookup key1 key2) (let ((subtable (assoc key1 (cdr table)))) (if subtable (let ((record (assoc key2 (cdr subtable)))) (if record (cdr record) #f)) #f))) (define (insert! key1 key2 value) (let ((subtable (assoc key1 (cdr table)))) (if subtable (let ((record (assoc key2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key2 value) (cdr subtable))))) (set-cdr! table (cons (list key1 (cons key2 value)) (cdr table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup) lookup) ((eq? m 'insert!) insert!) (else (error "Unknown operation")))) dispatch)) (define operation-table (make-table)) (define get (operation-table 'lookup)) (define put (operation-table 'insert!)) ;3.24 (define (make-table same-key?) (let ((table (list '*table*))) (define (assoc key records) (cond ((null? records) #f) ((same-key? (caar records) key) (car records)) (else (assoc key (cdr records))))) (define (lookup key1 key2) (let ((subtable (assoc key1 (cdr table)))) (if subtable (let ((record (assoc key2 (cdr subtable)))) (if record (cdr record) #f)) #f))) (define (insert! key1 key2 value) (let ((subtable (assoc key1 (cdr table)))) (if subtable (let ((record (assoc key2 (cdr subtable)))) (if record (set-cdr! record value) (set-cdr! subtable (cons (cons key2 value) (cdr subtable))))) (set-cdr! table (cons (list key1 (cons key2 value)) (cdr table))))) 'ok) (define (dispatch m) (cond ((eq? m 'lookup) lookup) ((eq? m 'insert!) insert!) (else (error "Unknown operation")))) dispatch)) (define operation-table (make-table (lambda (x y) (< (abs (- x y)) 0.1)))) (define get (operation-table 'lookup)) (define put (operation-table 'insert!)) ;3.25 (define (make-table) (let ((table (list '*table*))) (define (assoc key records) (cond ((null? records) #f) ((equal? (caar records) key) (car records)) (else (assoc key (cdr records))))) (define (lookup key) (define (lookup-iter key table) (cond ((and (null? key) (not (pair? (cdr table)))) (cdr table)) ((and (not (null? key)) (pair? (cdr table))) (let ((subtable (assoc (car key) (cdr table)))) (if subtable (lookup-iter (cdr key) subtable) #f))) (else #f))) (lookup-iter key table)) (define (make-entry key value) (if (null? (cdr key)) (cons (car key) value) (list (car key) (make-entry (cdr key) value)))) (define (insert! key value) (define (insert!-iter key value table) (if (not (pair? (cdr table))) (let ((new-entry (make-entry key value))) (set-cdr! table (list new-entry))) (let ((record (assoc (car key) (cdr table)))) (if record (if (null? (cdr key)) (set-cdr! record value) (insert!-iter (cdr key) value record)) (let ((new-entry (make-entry key value))) (set-cdr! table (cons new-entry (cdr table)))))))) (if (null? key) (error "empty key!") (insert!-iter key value table)) 'ok) (define (dispatch m) (cond ((eq? m 'lookup) lookup) ((eq? m 'insert!) insert!) (else (error "Unknown operation")))) dispatch)) (define operation-table (make-table)) (define get (operation-table 'lookup)) (define put (operation-table 'insert!)) ;3.26 (define (make-table equal-key? bigger-key?) (let ((table (list '*table*))) (define (make-record left-branch right-branch key value) (list left-branch right-branch key value)) (define (assoc key record) (cond ((null? record) #f) ((equal-key? key (caddr record)) record) ((bigger-key? key (caddr record)) (assoc key (cadr record))) (else (assoc key (car record))))) (define (lookup key) (let ((record (assoc key (cdr table)))) (if record (cadddr record) #f))) (define (insert! key value) (define (insert!-iter record) (cond ((equal-key? key (caddr record)) (set-car! (cdddr record) value)) ((bigger-key? key (caddr record)) (if (null? (cadr record)) (set-car! (cdr record) (make-record '() '() key value)) (insert!-iter (cadr record)))) (else (if (null? (car record)) (set-car! record (make-record '() '() key value)) (insert!-iter (car record)))))) (if (null? (cdr table)) (set-cdr! table (make-record '() '() key value)) (insert!-iter (cdr table))) 'ok) (define (dispatch m) (cond ((equal? m 'lookup) lookup) ((equal? m 'insert!) insert!) (else (error "wrong operation type!")))) dispatch)) (define operation-table (make-table = >)) (define put (operation-table 'insert!)) (define get (operation-table 'lookup)) ;3.27 (define (memoize f) (let ((operation-table (make-table = >))) (let ((put (operation-table 'insert!)) (get (operation-table 'lookup))) (lambda (x) (let ((previous-result (get x))) (or previous-result (let ((result (f x))) (put x result) result))))))) (define memo-fib (memoize (lambda (x) (cond ((= x 0) 0) ((= x 1) 1) (else (+ (memo-fib (- x 1)) (memo-fib (- x 2))))))))
false
fffb259c568aaed598d8209050911a6e58a2cc61
aec3146a144050e8ea821e4c185f1d3b76b3318a
/s9/lib/list-to-set.scm
bf3421c98c44e82e45fe53bb12a664f13ec0e058
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
joe9/s9fes-9front
c64b71726b83cc1623259852dbcfac34dd39a60e
a41167730a8a0e5ea394ff9a61a22866178fc648
refs/heads/master
2021-01-20T05:26:48.380087
2017-04-29T19:37:10
2017-04-29T19:37:10
89,784,392
2
0
null
null
null
null
UTF-8
Scheme
false
false
634
scm
list-to-set.scm
; Scheme 9 from Empty Space, Function Library ; By Nils M Holm, 2009 ; Placed in the Public Domain ; ; (list->set list) ==> list ; ; (load-from-library "list-to-set.scm") ; ; Convert list to set. A set is a list containing unique members. ; ; Example: (list->set '(a b c b c)) ==> (a b c) (define (list->set a) (letrec ((list->set2 (lambda (a r) (cond ((null? a) (reverse! r)) ((member (car a) r) (list->set2 (cdr a) r)) (else (list->set2 (cdr a) (cons (car a) r))))))) (list->set2 a '())))
false
59b53963d3a3e1c6c978d4e6238c3c274951ab6d
3686e1a62c9668df4282e769220e2bb72e3f9902
/ex3.5.scm
8c3d3b1314ff18b2f4c739ef0c5cbab84a0c9c79
[]
no_license
rasuldev/sicp
a4e4a79354495639ddfaa04ece3ddf42749276b5
71fe0554ea91994822db00521224b7e265235ff3
refs/heads/master
2020-05-21T17:43:00.967221
2017-05-02T20:32:06
2017-05-02T20:32:06
65,855,266
0
0
null
null
null
null
UTF-8
Scheme
false
false
878
scm
ex3.5.scm
(define (estimate-pi trials) (sqrt (/ 6 (monte-carlo trials cesaro-test)))) (define (rand) (random 1000) ) (define (cesaro-test) (= (gcd (rand) (rand)) 1)) (define (monte-carlo trials experiment) (define (iter trials-remaining trials-passed) (cond ((= trials-remaining 0) (/ trials-passed trials)) ((experiment) (iter (- trials-remaining 1) (+ trials-passed 1))) (else (iter (- trials-remaining 1) trials-passed)))) (iter trials 0)) (define (estimate-integral x1 x2 y1 y2 P trials) (define (random-in-range low high) (let ((range (- high low))) (+ low (random range)))) (* 1.0 (- x2 x1) (- y2 y1) (monte-carlo trials (lambda () (let ((x (random-in-range x1 x2)) (y (random-in-range y1 y2))) (P x y)))) ) ) (define (P x y) (<= (+ (* x x) (* y y)) 1) ) (estimate-integral -1 1 -1 1 P 10000)
false
91ad9d13adc8db6fa1e2b427369d8c8d25b774ef
f87e36a1ba00008d7e957c8595c86b5550af05b9
/ch4/common4.4.4.scm
ba10d3abf161c1e801efdc6b05f93a7d3c0f5718
[]
no_license
kouheiszk/sicp
1b528898f825c0716acce6bdb36d378dcb04afec
eeb2f7d7634284faa7158c373a848b84084cc8cb
refs/heads/master
2020-04-16T07:00:43.135389
2014-06-16T11:57:43
2014-06-16T11:57:43
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
642
scm
common4.4.4.scm
;; For stream (define-syntax cons-stream (syntax-rules () ((cons-stream h t) (cons h (delay t))))) (define (stream-car stream) (car stream)) (define (stream-cdr stream) (force (cdr stream))) (define the-empty-stream '()) (define (stream-null? stream) (null? stream)) (define (list->stream exp) (cond ((null? exp) the-empty-stream) (else (let ((first (car exp))) (if (null? first) the-empty-stream (cons-stream first (list->stream (cdr exp))))) ))) ;; For env (define the-empty-environment '()) (define user-initial-environment the-empty-environment)
true
757ed6adc6296b9606793debc2e835812292fbb9
e32bfa8a0694eafa93bcbd05d182875be9f8b3da
/src/main/scheme/arvyy/slf4j.sld
ffc01a19c6b26dc25950aa24988f695f9779be98
[]
no_license
arvyy/kawa-slf4j
bb81b8dd71f88cacd8f6722245ec2dc3eecd6bfb
378678708b321c024b8503ea22ae13a0f542fbf2
refs/heads/master
2023-02-08T23:31:57.463268
2020-12-26T15:43:13
2020-12-26T15:43:13
324,564,466
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,872
sld
slf4j.sld
(define-library (arvyy slf4j) (import (scheme base) (class org.slf4j Logger LoggerFactory) ) (export get-logger logger-name log-info info-enabled? log-debug debug-enabled? log-error error-enabled? log-trace trace-enabled? log-warn warn-enabled?) (begin (define (get-logger name ::String) ::Logger (LoggerFactory:getLogger name)) (define (logger-name logger ::Logger) ::String (logger:getName)) (define-syntax log-info (syntax-rules () ((_ logger message args ...) (when (info-enabled? logger) (logger:info message args ...))))) (define (info-enabled? logger ::Logger) ::boolean (logger:isInfoEnabled)) (define-syntax log-warn (syntax-rules () ((_ logger message args ...) (when (warn-enabled? logger) (logger:warn message args ...))))) (define (warn-enabled? logger ::Logger) ::boolean (logger:isWarnEnabled)) (define-syntax log-error (syntax-rules () ((_ logger message args ...) (when (error-enabled? logger) (logger:error message args ...))))) (define (error-enabled? logger ::Logger) ::boolean (logger:isErrorEnabled)) (define-syntax log-debug (syntax-rules () ((_ logger message args ...) (when (debug-enabled? logger) (logger:debug message args ...))))) (define (debug-enabled? logger ::Logger) ::boolean (logger:isDebugEnabled)) (define-syntax log-trace (syntax-rules () ((_ logger message args ...) (when (trace-enabled? logger) (logger:trace message args ...))))) (define (trace-enabled? logger ::Logger) ::boolean (logger:isTraceEnabled))))
true
b5b0afdff88000207f9042978c9fc8eb0f8f757d
5321534fcf799037a2434fbcc548a6e2ad437aac
/ch5.5.7-interfacing-compiler-to-evaluator/regsim.scm
88f41dcc7afc28546830388777df2c37a8c40add
[]
no_license
Rather-Iffy/sicp
f0f382eb25c5cd6a7976990392f8d0b63d629f18
c29b2582feee452ec0714fdc1eec6b406b94cd27
refs/heads/master
2021-06-05T16:18:14.329104
2016-08-15T05:51:51
2016-08-15T05:51:51
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
38
scm
regsim.scm
../ch5.2-register-simulator/regsim.scm
false
0e050ea5dcc1930527af4d1b2bcd5b3ebf4f029e
5fa722a5991bfeacffb1d13458efe15082c1ee78
/src/c3_50.scm
c3d16adced2a7eb3706d3908d7de9cdd88cc86be
[]
no_license
seckcoder/sicp
f1d9ccb032a4a12c7c51049d773c808c28851c28
ad804cfb828356256221180d15b59bcb2760900a
refs/heads/master
2023-07-10T06:29:59.310553
2013-10-14T08:06:01
2013-10-14T08:06:01
11,309,733
3
0
null
null
null
null
UTF-8
Scheme
false
false
181
scm
c3_50.scm
(import (rnrs) (stream) (utils)) (stream-display (stream-map square (list-stream 1 2 3))) (stream-display (stream-map + (list-stream 1 2 3) (list-stream 2 3 4)))
false
5ac4e783658fa8d8cd4b5ac67c1c5c5d3319fc4f
3659adcd6ed3b62c4a928adc17181c75d1cac58b
/snowtar.egg
5907c214ab535aced09f5a906a6afb149b53a904
[]
no_license
lassik/scheme-snowtar
ed1358dbca234e5be230b69e26447f080fd7f46b
83d9388a2470bf237d5365d71f78c4a849ae6582
refs/heads/master
2023-07-18T20:45:59.518266
2021-09-20T20:30:12
2021-09-20T20:30:12
408,489,281
3
1
null
null
null
null
UTF-8
Scheme
false
false
383
egg
snowtar.egg
;; -*- Scheme -*- ((synopsis "TAR file format packing and unpacking.") (category parsing) (license "LGPL-2.1-or-later") (author "Marc Feeley") (maintainer "Lassi Kortela") (dependencies miscmacros) (components (extension snowtar (source "snowtar.chicken.scm") (source-dependencies "snow-compatibility.scm" "tar.scm"))))
false
55dc5d85a86832c125f5241ca4f46ed5b8ac7c12
ac2a3544b88444eabf12b68a9bce08941cd62581
/tests/unit-tests/02-flonum/flmul.scm
d647d0a5bebb422d4ca71df2ff3c7e93cca1001f
[ "Apache-2.0", "LGPL-2.1-only" ]
permissive
tomelam/gambit
2fd664cf6ea68859d4549fdda62d31a25b2d6c6f
d60fdeb136b2ed89b75da5bfa8011aa334b29020
refs/heads/master
2020-11-27T06:39:26.718179
2019-12-15T16:56:31
2019-12-15T16:56:31
229,341,552
1
0
Apache-2.0
2019-12-20T21:52:26
2019-12-20T21:52:26
null
UTF-8
Scheme
false
false
1,033
scm
flmul.scm
(include "#.scm") (check-eqv? (##fl* 0.25 0.75) 0.1875) (check-eqv? (##fl* 0.25 -0.25) -0.0625) (check-eqv? (##fl* 0.25 -0.75) -0.1875) (check-eqv? (##fl* -0.25 0.75) -0.1875) (check-eqv? (##fl*) 1.0) (check-eqv? (##fl* 0.25) 0.25) (check-eqv? (##fl* 0.25 2.0) 0.5) (check-eqv? (##fl* 0.25 2.0 0.5) 0.25) (check-eqv? (##fl* 0.25 2.0 0.5 0.75) 0.1875) (check-eqv? (fl* 0.25 0.75) 0.1875) (check-eqv? (fl* 0.25 -0.25) -0.0625) (check-eqv? (fl* 0.25 -0.75) -0.1875) (check-eqv? (fl* -0.25 0.75) -0.1875) (check-eqv? (fl*) 1.0) (check-eqv? (fl* 0.25) 0.25) (check-eqv? (fl* 0.25 2.0) 0.5) (check-eqv? (fl* 0.25 2.0 0.5) 0.25) (check-eqv? (fl* 0.25 2.0 0.5 0.75) 0.1875) (check-tail-exn type-exception? (lambda () (fl* 1))) (check-tail-exn type-exception? (lambda () (fl* 1 4.2))) (check-tail-exn type-exception? (lambda () (fl* 0.5 9))) (check-tail-exn type-exception? (lambda () (fl* 9 0.5 4.2))) (check-tail-exn type-exception? (lambda () (fl* 0.5 9 4.2))) (check-tail-exn type-exception? (lambda () (fl* 0.5 4.2 9)))
false
000e51352efc7efe0251cfeee2b55c4d45f8e0b3
be06d133af3757958ac6ca43321d0327e3e3d477
/99problems/all.scm
395e90ae66f039da960b0725df1a4c94542e13ea
[]
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
24,476
scm
all.scm
(use srfi-1) (define (flatten lis) (cond ((pair? lis) (apply append (map flatten lis))) (else (list lis)))) ; 01.scm (define (single? lis) (if (null? lis) #f (null? (cdr lis)))) ; 02.scm (define (double? lis) (if (null? lis) #f (single? (cdr lis)))) ; 03.scm (define (longer? xs ys) (cond [(null? xs) #f] [(null? ys) #t] [else (longer? (cdr xs) (cdr ys))])) ; 04.scm (define (last lis) (list (car (reverse lis)))) (define (butlast lis) (reverse (cdr (reverse lis)))) ; 05.scm (define (take xs n) (let loop ((i 0) (lis xs) (ret '())) (cond ((null? lis) (reverse ret)) ((= i n) (reverse ret)) (else (loop (+ i 1) (cdr lis) (cons (car lis) ret)))))) ; 06.scm (define (drop lis n) (cond ((null? lis) '()) ((= n 0) lis) (else (drop (cdr lis) (- n 1))))) ; 07.scm (define (subseq xs n m) (take (drop xs n) (- m n))) ; 08.scm (define (butlastn xs n) (reverse (drop (reverse xs) n))) ; 09.scm (define (group lis n) (cond ((null? lis) '()) (else (cons (take lis n) (group (drop lis n) n))))) ; 10.scm (define (position x lis) (cond ((null? lis) #f) ((equal? x (car lis)) 0) (else (and (position x (cdr lis)) (+ 1 (position x (cdr lis))))))) ; 11.scm (define (count x lis) (cond ((null? lis) 0) ((equal? x (car lis)) (+ 1 (count x (cdr lis)))) (else (count x (cdr lis))))) ; 12.scm (define (sum-list lis) (cond ((null? lis) 0) (else (+ (car lis) (sum-list (cdr lis)))))) ; 13.scm (define (max-list lis) (if (null? lis) #f (let loop ((lis (cdr lis)) (ret (car lis))) (if (null? lis) ret (if (> (car lis) ret) (loop (cdr lis) (car lis)) (loop (cdr lis) ret)))))) (define (min-list lis) (if (null? lis) #f (let loop ((lis (cdr lis)) (ret (car lis))) (if (null? lis) ret (if (< (car lis) ret) (loop (cdr lis) (car lis)) (loop (cdr lis) ret)))))) ; 14.scm (define (adjacent? x y lis) (cond ((null? lis) #f) ((and (not (null? (cdr lis))) (equal? (car lis) x) (equal? (cadr lis) y)) #t) (else (adjacent? x y (cdr lis))))) (define (before? x y lis) (cond ((null? lis) #f) ((equal? x (car lis)) (member? y (cdr lis))) (else (before? x y (cdr lis))))) (define (member? x lis) (cond ((null? lis) #f) ((equal? x (car lis)) #t) (else (member? x (cdr lis))))) ; 16.scm (define (iota start end) (cond ((> start end) '()) (else (cons start (iota (+ 1 start) end))))) ; 17.scm (define (set-of-list lis) (cond ((null? lis) '()) ((member (car lis) (cdr lis)) (set-of-list (cdr lis))) (else (cons (car lis) (set-of-list (cdr lis)))))) ; 18.scm (define (union a b) (cond ((null? a) b) ((member (car a) b) (union (cdr a) b)) (else (cons (car a) (union (cdr a) b))))) ; 19.scm (define (intersection a b) (cond ((null? a) '()) ((member (car a) b) (cons (car a) (intersection (cdr a) b))) (else (intersection (cdr a) b)))) ; 20.scm (define (difference a b) (cond ((null? a) '()) ((member (car a) b) (difference (cdr a) b)) (else (cons (car a) (difference (cdr a) b))))) ; 21.scm (define (merge-list comp a b) (sort (append a b) comp)) ; 22.scm (define (merge-list comp a b) (sort (append a b) comp)) (define (merge-sort comp a lis) (cond ((null? lis) '()) ((comp a (car lis)) (merge-sort comp a (cdr lis))) (else (merge-list comp (list (car lis)) (merge-sort comp a (cdr lis)))))) ; 23.scm (define (prefix lis pref) (cond ((null? lis) #f) ((null? pref) #t) ((equal? (car lis) (car pref)) (prefix (cdr lis) (cdr pref))) (else #f))) ; 24.scm (define (suffix lis suf) (prefix (reverse lis) (reverse suf))) ; 25.scm (define (sublist sub lis) (cond ((null? sub) #t) ((null? lis) #f) ((equal? (take lis (length sub)) sub) #t) (else (sublist sub (cdr lis))))) ; 26.scm (define (member-tree x tree) (let loop ((lis tree)) (cond ((not (pair? lis)) (equal? x lis)) ((null? lis) #f) ((member-tree x (car lis)) #t) (else (loop (cdr lis)))))) ; 27.scm ; 再帰のみバージョン (define (count-leaf tree) (cond ((null? tree) 0) ((pair? tree) (+ (count-leaf (car tree)) (count-leaf (cdr tree)))) (else 1))) ; 28.scm (define (subst a b tree) (cond ((null? tree) '()) ((pair? tree) (cons (subst a b (car tree)) (subst a b (cdr tree)))) (else (if (equal? tree a) b tree)))) ; 29.scm (define (delete-nth lis n) (let loop ((i 0) (lis lis) (ret '())) (cond ((null? lis) ret) (else (loop (+ i 1) (cdr lis) (if (equal? i n) ret (append ret (list (car lis))))))))) (define (nth lis n) (if (not (pair? lis)) (error "not pair" lis) (let loop ((lis lis) (i 0)) (cond ((null? lis) '()) ((= i n) (car lis)) (else (loop (cdr lis) (+ i 1))))))) (define (permutation n lis) (let loop ((i 0) (ret '())) (cond ((null? lis) ret) ((= 1 (length lis)) (list lis)) ((= i (length lis)) ret) (else (loop (+ i 1) (append ret (map (lambda (x) (cons (nth lis i) x)) (permutation (- n 1) (delete-nth lis i))))))))) (define (repeat-perm n lis) (cond ((= n 0) '()) ((= n 1) (map (lambda (x) (list x)) lis)) (else (apply append (map (lambda (x) (map (lambda (y) (cons x y)) (repeat-perm (- n 1) lis))) lis))))) ; 31.scm (define (comb-num n r) (/ (/ (factorial n) (factorial r)) (factorial (- n r)))) (define (factorial n) (if (= n 0) 1 (* n (factorial (- n 1))))) ; 32.scm (define (combination n lis) (cond ((= n 1) (map (lambda (x) (list x)) lis)) (else (apply append (map (lambda (x) (map (lambda (y) (cons x y)) (combination (- n 1) (cdr (member x lis))))) lis))))) ; 33.scm (define (repeat-comb n lis) (cond ((= n 1) (map (lambda (x) (list x)) lis)) (else (apply append (map (lambda (x) (map (lambda (y) (cons x y)) (repeat-comb (- n 1) (member x lis)))) lis))))) ; 34.scm (define (split-nth lis n) (cond ((null? lis) (values '() '())) (else (let loop ((i 0) (p1 '()) (rest lis)) (cond ((= i n) (values p1 rest)) (else (loop (+ i 1) (append p1 (list (car rest))) (cdr rest)))))))) ; 35.scm (define (partition lis) (let loop ((i 0) (lis lis) (odds '()) (evens '())) (cond ((null? lis) (values (reverse odds) (reverse evens))) ((= 0 (mod i 2)) (loop (+ i 1) (cdr lis) (cons (car lis) odds) evens)) (else (loop (+ i 1) (cdr lis) odds (cons (car lis) evens)))))) ; 36.scm (define (split-find x lis) (let loop ((lis lis) (lis1 '())) (cond ((null? lis) (values (reverse lis1) '())) ((equal? (car lis) x) (values (reverse lis1) lis)) (else (loop (cdr lis) (cons (car lis) lis1)))))) ; 37.scm (define (split-ge x lis) (values (filter (lambda (y) (>= y x)) lis) (filter (lambda (y) (< y x)) lis))) ; 38.scm (define (pack lis) (cond ((null? lis) '()) ((null? (cdr lis)) (list (list (car lis)))) ((equal? (car lis) (cadr lis)) (let [(next (pack (cdr lis)))] (cons (cons (car lis) (car next)) (cdr next)))) (else (cons (list (car lis)) (pack (cdr lis)))))) ; 39.scm (define (successor? a b) (= a (- b 1))) (define (pack-num-list lis) (cond ((null? lis) '()) ((null? (cdr lis)) (list (car lis))) ((successor? (car lis) (cadr lis)) (let [(next (pack-num-list (cdr lis)))] (if (pair? (car next)) (cons [cons (car lis) (cdar next)] (cdr next)) (cons [cons (car lis) (car next)] (cdr next))))) (else (cons (car lis) (pack-num-list (cdr lis)))))) ; 40.scm (define (expand-pair pair) (iota (+ 1 (- (cdr pair) (car pair))) (car pair))) (define (expand-num-list lis) (cond ((null? lis) '()) ((pair? (car lis)) (append (expand-pair (car lis)) (expand-num-list (cdr lis)))) (else (cons (car lis) (expand-num-list (cdr lis)))))) ; 41.scm (define (encode lis) (cond ((null? lis) '()) ((null? (cdr lis)) (list (cons (car lis) 1))) ((equal? (car lis) (cadr lis)) (let ((next (encode (cdr lis)))) (cons (cons (car lis) (+ 1 (cdar next))) (cdr next)))) (else (let ((next (encode (cdr lis)))) (cons (cons (car lis) 1) next))))) ; 42.scm (define (decode lis) (apply append (map (lambda (pair) (repeat (car pair) (cdr pair))) lis))) (define (repeat x n) (let loop ((i 0) (result '())) (cond ((= i n) result) (else (loop (+ i 1) (cons x result)))))) ; 43.scm (define (any? pred lis) (cond ((null? lis) #f) ((pred (car lis)) #t) (else (any? pred (cdr lis))))) (define (every? pred lis) (cond ((null? lis) #t) ((pred (car lis)) (every? pred (cdr lis))) (else #f))) ; 44.scm (define (maplist f lis) (cond ((null? lis) '()) (else (cons (f lis) (maplist f (cdr lis)))))) ; 45.scm (define (foldr f init lis) (cond ((null? lis) init) (else (f (car lis) (foldr f init (cdr lis)))))) (define (for-each-list fn comb term xs) (foldr comb term (map fn xs))) ; 46.scm (define (mymap f lis) (for-each-list f cons '() lis)) (define (myfilter f lis) (apply append (for-each-list (lambda (x) (if (f x) (list x) '())) cons '() lis))) (define (myfold f init lis) (for-each-list (lambda (x) x) f init lis)) ; 47.scm (define (komachi) (let loop [(permlist (permutation 9 '(1 2 3 4 5 6 7 8 9))) (result '())] (cond ((null? permlist) (reverse result)) ((answer? (car permlist)) (loop (cdr permlist) (cons (car permlist) result))) (else (loop (cdr permlist) result))))) (define (calc-aux a b c) (/ a (+ (* 10 b) c))) (define (calc p) (+ (calc-aux (nth p 0) (nth p 1) (nth p 2)) (calc-aux (nth p 3) (nth p 4) (nth p 5)) (calc-aux (nth p 6) (nth p 7) (nth p 8)))) (define (answer? lis) (= 1 (numerator (calc lis)))) ; 48.scm (define (all=? lis) (cond ((null? lis) #t) (else (every (lambda (x) (= x (car lis))) lis)))) (define (get-nths lis nths) (map (lambda (n) (nth lis n)) nths)) (define (answer-48? lis) (= (apply + (get-nths lis '(0 1 2))) (apply + (get-nths lis '(3 4 5))) (apply + (get-nths lis '(6 7 8))) (apply + (get-nths lis '(0 3 6))) (apply + (get-nths lis '(1 4 7))) (apply + (get-nths lis '(2 5 8))) (apply + (get-nths lis '(0 4 8))) (apply + (get-nths lis '(2 4 6))))) (define (solve-48) (let loop ((perms (permutation (iota 9 1))) (result '())) (cond ((null? perms) result) ((answer-48? (car perms)) (loop (cdr perms) (cons (car perms) result))) (else (loop (cdr perms) result))))) (define (list-to-num lis) (let loop ((lis lis) (result 0)) (cond ((null? lis) result) (else (loop (cdr lis) (+ (* result 10) (car lis))))))) (define (slice lis start count) (take (drop lis start) count)) ;("W" "R" "O" "N" "G" "M" "I" "H" "T") (define all-chars (delete-duplicates (map symbol->string '(W R O N G M R I G H T)))) (define (list-index e lis) (if (null? lis) -1 (if (equal? (car lis) e) 0 (if (= (list-index e (cdr lis)) -1) -1 (+ 1 (list-index e (cdr lis))))))) (define (strrep->indexes s) (map (lambda (c) (charrep->index (list->string (list c)))) (string->list s))) (define (charrep->index c) (list-index c all-chars)) (define (strrep->num lis s) (list-to-num (map (lambda (i) (nth lis i)) (strrep->indexes s)))) (define (answer-49? lis) (= (* (strrep->num lis "WRONG") (strrep->num lis "M")) (strrep->num lis "RIGHT"))) (define (solve-49) (filter answer-49? (permutation (iota 9 1)))) ; 50.scm (define (sieve n) (let loop ((result '()) (x 2)) (cond ((> x n) (reverse result)) ((any (lambda (a) (= a 0)) (map (lambda (p) (mod x p)) result)) (loop result (+ x 1))) (else (loop (cons x result) (+ x 1)))))) ; 51.scm (define (xor p q) (or (and (not p) q) (and p (not q)))) ; 52.scm (define (half-adder p q) (values (xor p q) (and p q))) ; 53.scm (define (full-adder p q r) (receive (s c) (half-adder p q) (values (xor s r) (or (and p q) (and r (xor p q)))))) ; 54.scm (define (int->uint n m) (cond ((= m 0) '()) (else (append (int->uint (quotient n 2) (- m 1)) (list (if (= (mod n 2) 0) #f #t)))))) (define (uint->int x) (let loop ((result 0) (rest x)) (cond ((null? rest) result) (else (loop (+ (* 2 result) (if (car rest) 1 0)) (cdr rest)))))) ; 55.scm (define (bool-and a b) (if (and a b) #t #f)) (define (bool-or a b) (if (or a b) #t #f)) (define (bool-xor p q) (or (and (not p) q) (and p (not q)))) (define (uint-and i1 i2) (map (lambda (x) (apply bool-and x)) (zip i1 i2))) (define (uint-or i1 i2) (map (lambda (x) (apply bool-or x)) (zip i1 i2))) (define (uint-xor i1 i2) (map (lambda (x) (apply bool-xor x)) (zip i1 i2))) (define (uint-not i1) (map not i1)) ; 56.scm (define (uint-add i1 i2) (cond ((null? i1) (values i2 #f)) ((null? i2) (values i1 #f)) (else (receive (next-sum next-carry) (uint-add (cdr i1) (cdr i2)) (receive (s c) (full-adder (car i1) (car i2) next-carry) (values (cons s next-sum) c)))))) ; 57.scm (define (uint-inc i1) (uint-add i1 (append (make-list (- (length i1) 1) #f) (list #t)))) ; 58.scm (define (uint-neg x) (uint-inc (uint-not x))) (define (uint-sub x y) (receive (s c) (uint-add x (uint-neg y)) (values s (not c)))) ; 59.scm (define (remove-last lis) (let loop ((lis lis) (ret '())) (cond ((null? lis) (error "last: null lis")) ((null? (cdr lis)) (values (reverse ret) (car lis))) (else (loop (cdr lis) (cons (car lis) ret)))))) ;; 右論理シフト (define (uint-srl uint) (receive (ret last) (remove-last uint) (values (cons #f ret) last))) ;; 左論理シフト (define (uint-sll uint) (values (append (cdr uint) (list #f)) (car uint) )) ; 60.scm (define (set-nth lis n x) (append (take lis n) (list x) (drop lis (+ n 1)))) (define (make-word) '(#f #f #f #f #f #f #f #f)) ;; (define acc (make-word)) (define pc '(#f #f #f #f #f)) (define of '(#f)) (define (print-memory) (print "acc:" (map bool->int acc)) (print "pc:" (map bool->int pc)) (print "of" (map bool->int of)) (let loop ((i 0) (lis memory)) (cond ((null? lis) '()) (else (begin (print (if (< i 10) (string-append "0" (number->string i)) i) ":" (map bool->int (car lis))) (loop (+ i 1) (cdr lis))))))) (define (bool->int b) (cond ((list? b) (map bool->int b)) (b 1) (else 0))) (define (int->bool i) (if (= i 1) #t #f)) ;; メモリ (define memory (list ; program 1〜n(標準入力から読み込んだ値)を計算するプログラム (map int->bool '(1 1 1 0 0 0 0 1)) ; read (map int->bool '(1 0 0 1 1 1 0 1)) ; store to cnt (map int->bool '(0 1 1 1 1 1 1 0)) ; load from result (map int->bool '(0 0 1 1 1 1 0 1)) ; add cnt (map int->bool '(1 0 0 1 1 1 1 0)) ; store to result (map int->bool '(0 1 1 1 1 1 0 1)) ; load from cnt (map int->bool '(0 1 0 1 1 1 0 0)) ; sub 1 (map int->bool '(0 0 0 0 0 0 0 1)) ; jump (map int->bool '(0 1 1 1 1 1 1 0)) ; load from result (map int->bool '(1 1 1 0 0 0 1 0)) ; print (map int->bool '(1 1 1 0 0 0 0 0)) ; exit (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) (map int->bool '(0 0 0 0 0 0 0 0)) ; constants (map int->bool '(0 0 0 0 0 0 0 1)) ; 11100 1 (map int->bool '(0 0 0 0 0 0 0 0)) ; 11101 cnt (map int->bool '(0 0 0 0 0 0 0 0)) ; 11110 result (map int->bool '(0 0 0 0 0 0 0 0)) ; 11111 )) (define (int->uint n m) (cond ((= m 0) '()) (else (append (int->uint (quotient n 2) (- m 1)) (list (if (= (mod n 2) 0) #f #t)))))) (define (xor p q) (or (and (not p) q) (and p (not q)))) (define (half-adder p q) (values (xor p q) (and p q))) (define (full-adder p q r) (receive (s c) (half-adder p q) (values (xor s r) (or (and p q) (and r (xor p q)))))) (define (uint-add i1 i2) (cond ((not (= (length i1) (length i2))) (error (format "uint-add length not equal ~D ~D" (length i1) (length i2)))) ; 長さが違うと見つけにくいバグになるのでエラーを出すようにする ((null? i1) (values i2 #f)) ((null? i2) (values i1 #f)) (else (receive (next-sum next-carry) (uint-add (cdr i1) (cdr i2)) (receive (s c) (full-adder (car i1) (car i2) next-carry) (values (cons s next-sum) c)))))) (define (get-opcode command) (take command 3)) (define (get-operand command) (drop command 3)) (define (command-jump operand) (if (= (uint->int of) 1) #f (set! pc (uint-sub operand (int->uint 1 (length pc)))))) ; 自動PCインクリメントにより1増加するから、ここで-1しておく (define (command-add operand) (receive (s c) (uint-add acc (nth memory (uint->int operand))) (set! acc s) (set! of (list c)))) (define (command-sub operand) (receive (s c) (uint-sub acc (nth memory (uint->int operand))) (set! acc s) (set! of (list c)))) (define (command-load operand) (let ((n (uint->int operand))) (set! acc (nth memory n)))) (define (command-store operand) (let ((n (uint->int operand))) (set! memory (set-nth memory n acc)))) (define (command-sll operand) (print "not defined")) (define (command-srl operand) (print "not defined")) (define (command-svc operand) (cond ((= (uint->int operand) 0) (exit-cont)) ; exit ((= (uint->int operand) 1) (set! acc (int->uint (read) 8))) ; read ((= (uint->int operand) 2) (print "RESULT = " (uint->int acc))) ; print (error "invalid operand"))) (define (exec-command-at addr) (exec-command (nth memory (uint->int addr)))) (define (exec-and-increment-pc) (print "PC = " (bool->int pc)) (exec-command-at pc) (increment-pc!)) (define (exec-command command) (print "acc = " (bool->int acc)) (print "exec " (bool->int command)) (let ((opcode (get-opcode command)) (operand (get-operand command))) (cond ((equal? opcode '(#f #f #f)) (command-jump operand)) ((equal? opcode '(#f #f #t)) (command-add operand)) ((equal? opcode '(#f #t #f)) (command-sub operand)) ((equal? opcode '(#f #t #t)) (command-load operand)) ((equal? opcode '(#t #f #f)) (command-store operand)) ((equal? opcode '(#t #f #t)) (command-sll operand)) ((equal? opcode '(#t #t #f)) (command-srl operand)) ((equal? opcode '(#t #t #t)) (command-svc operand)) (else (error "invalid command"))))) (define (increment-pc!) (set! pc (uint-add pc '(#f #f #f #f #t)))) (define (times n proc) (let loop ((i 0)) (cond ((= i n) '()) (else (begin (proc) (loop (+ i 1))))))) ;; 仮想マシン実行開始 (define (run) (exec-and-increment-pc) (run)) ; 終了地点を保存しておく (define exit-cont '()) (call/cc (lambda (cont) (set! exit-cont cont))) ;(run) ; 67.scm (define (comp x y) (- x y)) (define (min-vector cp vec start end) (let loop ((i start) (min (vector-ref vec start)) (min-index start)) (cond ((>= i end) min-index) ((negative? (cp (vector-ref vec i) min)) (loop (+ i 1) (vector-ref vec i) i)) (else (loop (+ i 1) min min-index))))) (define (select-sort-vector cp vec) (let loop ((i 0)) (cond ((>= i (vector-length vec)) vec) (else (let* ((min-index (min-vector cp vec i (vector-length vec))) (tmp (vector-ref vec i))) (vector-set! vec i (vector-ref vec min-index)) (vector-set! vec min-index tmp) (loop (+ i 1))))))) ; 68.scm (define (quick-sort-vector cp vec) ) ; 69.scm (define (rpn lis) (rpn-aux lis '())) (define (rpn-aux lis stack) (cond ((null? lis) (car stack)) ((equal? (car lis) '+) (rpn-aux (cdr lis) (cons (+ (cadr stack) (car stack)) (cddr stack)))) ((equal? (car lis) '-) (rpn-aux (cdr lis) (cons (- (cadr stack) (car stack)) (cddr stack)))) ((equal? (car lis) '*) (rpn-aux (cdr lis) (cons (* (cadr stack) (car stack)) (cddr stack)))) ((equal? (car lis) '/) (rpn-aux (cdr lis) (cons (/ (cadr stack) (car stack)) (cddr stack)))) ((number? (car lis)) (rpn-aux (cdr lis) (cons (car lis) stack))) (else (car lis)))) ; 70.scm (define (expression lis) (parse-add lis)) (define (parse-number lis) (cond ((number? (car lis)) (values (car lis) (cdr lis))) ((list? (car lis)) (parse-add (car lis))) (else (error "parse-number error" (car lis))))) (define (parse-mul lis) (let loop ((result (parse-number lis)) (lis (cdr lis))) (cond ((null? lis) (values result '())) ((equal? (car lis) '*) (loop (* result (parse-number (cdr lis))) (cddr lis))) ((equal? (car lis) '/) (loop (/ result (parse-number (cdr lis))) (cddr lis))) (else (values result lis))))) (define (parse-add lis) (receive (t1 rest1) (parse-mul lis) (let loop ((result t1) (rest rest1)) (cond ((null? rest) result) ((equal? (car rest) '+) (receive (term rest2) (parse-mul (cdr rest)) (loop (+ result term) rest2))) ((equal? (car rest) '-) (receive (term rest2) (parse-mul (cdr rest)) (loop (- result term) rest2))) (else (error "parse-mul error" lis)))))) ; 71.scm (define (prefix->postfix lis) (if (pair? lis) (case (car lis) ((*) (append (prefix->postfix (cadr lis)) (prefix->postfix (caddr lis)) (list '*))) ((+) (append (prefix->postfix (cadr lis)) (prefix->postfix (caddr lis)) (list '+))) ((-) (append (prefix->postfix (cadr lis)) (prefix->postfix (caddr lis)) (list '-))) ((/) (append (prefix->postfix (cadr lis)) (prefix->postfix (caddr lis)) (list '/))) (else (list (car lis)))) (list lis))) ;72.scm (define (postfix->prefix lis) (let loop ((lis lis) (stack '())) (cond ((null? lis) stack) (else (case (car lis) ((+ - * /) (loop (cdr lis) (cons (list (car lis) (cadr stack) (car stack)) (cddr stack)))) (else (loop (cdr lis) (cons (car lis) stack)))))))) ; 74.scm (define (flatexpr lis) (cond ((not (pair? lis)) (list lis)) ((equal? (nth lis 1) '+) (if (>= 1 (get-expr-priority lis)) (apply append (list (flatexpr (car lis)) (list '+) (flatexpr (nth lis 2)))) lis)) ((equal? (nth lis 1) '*) (apply append (list (if (= 2 (get-expr-priority (car lis))) (flatexpr (car lis)) (list (car lis))) '(*) (if (= 2 (get-expr-priority (nth lis 2))) (flatexpr (nth lis 2)) (list (nth lis 2)))))) (else "not defined"))) (define (get-priority sym) (case sym ((+ -) 1) ((* /) 2) (else 0))) (define (get-expr-priority lis) (if (pair? lis) (get-priority (cadr lis)) (get-priority lis)))
false
257674493e86b3cd2cd2aaa9360e76335f8df8fe
bca7c3a1c6e6b4545c004cfc547d263a2103e51c
/srfi/december-27-07/compat-scheme48.scm
e2b9ebd26aef72d64c08fc45ba8cf385d70637af
[]
no_license
scheme-requests-for-implementation/srfi-72
f676b283eb9a6790194a248ab926396d85d6319c
27914524817a487d4ccd0100c846c0f8727a11dd
refs/heads/master
2020-12-13T12:50:17.457899
2020-08-11T17:56:42
2020-08-11T17:56:42
37,926,790
1
2
null
null
null
null
UTF-8
Scheme
false
false
3,538
scm
compat-scheme48.scm
;;;=============================================================================== ;;; ;;; Scheme48 compatibility file: ;;; ;;; Uncomment the appropriate LOAD command in examples.scm ;;; ;;;=============================================================================== ;; The file examples.scm can be run in an image in which ;; the following have been opened: ; ,open (modify records (prefix r:)) ; ,open (modify record-types (prefix rt:)) ; ,open handle ; ,open simple-signals ; ,open time ; ,open (modify pp (prefix pretty:)) ; ,open util ;; A numeric string that uniquely identifies this run in the universe ;; Essential for avoiding name conflicts when compiling separately ;; This is very risky and should be replaced! (define (ex:unique-token) (number->string (run-time))) ;; The letrec black hole and corresponding setter. (define ex:undefined 'undefined) (define ex:undefined-set! 'set!) ;; Single-character symbol prefixes. ;; No builtins may start with one of these. ;; If they do, select different values here. (define ex:guid-prefix "&") (define ex:free-prefix "~") ;; Just give this damn thing a binding (define assertion-violation (lambda args (apply error 'asserion-violation args))) (define pretty-print pretty:p) ;; These are only partial implementations for specific use cases needed. ;; Full implementations should be provided by host implementation. (define (memp proc ls) (cond ((null? ls) #f) ((pair? ls) (if (proc (car ls)) ls (memp proc (cdr ls)))) (else (assertion-violation 'memp "Invalid argument" ls)))) ; from util ;(define (filter p? lst) ; (if (null? lst) ; '() ; (if (p? (car lst)) ; (cons (car lst) ; (filter p? (cdr lst))) ; (filter p? (cdr lst))))) ; from util (define for-all every) ;(define (for-all proc l . ls) ; (or (null? l) ; (and (apply proc (car l) (map car ls)) ; (apply for-all proc (cdr l) (map cdr ls))))) ;; The best we can do in r5rs is make these no-ops (define (file-exists? fn) #f) (define (delete-file fn) (values)) ;; Only the most minimal extremely partial implementation ;; of r6rs records as needed for our specific use cases. ;; Note that most arguments are ignored. (define (make-record-type-descriptor name parent uid sealed? opaque? fields) (let ((field-names (map cadr (vector->list fields)))) (list (rt:make-record-type name field-names) field-names))) (define (record-predicate rtd) (rt:record-predicate (car rtd))) (define (make-record-constructor-descriptor rtd parent-constructor-descriptor protocol) rtd) (define (record-constructor cd) (rt:record-constructor (car cd) (cadr cd))) (define (record-accessor rtd k) (lambda (r) (r:record-ref r (+ k 1)))) ;; A rudimentary r6rs REPL. ;; Run it and then enter import commands, definitions, ;; libraries, programs as if you were in r6rs. ;; The examples in examples.scm can be run this ;; way without having to wrap them in (ex:repl '( --- )) ;; Exit to the usual scheme48 repl via (exit). (define (r6rs) (newline) (display "r6rs> ") (let ((exp (read))) ;; Fixme - use with-handlers properly (report-errors-as-warnings (lambda () (or (equal? exp '(exit)) (ex:repl (list exp)))) "R6RS-error:") (or (equal? exp '(exit)) (r6rs))))
false
a207dd2de6cd3ebc0d78678f5f89a46e5ab88c15
074200eeaf6a79a72dd17651fdb471b7c7fbf1b5
/framework/sandbox.scm
5975ca34f753f6a2cae058e420d5a13356a9c9da
[ "MIT" ]
permissive
big-data-europe/mu-query-rewriter
4b687636e39c3eeb12b45c1ababc6b6d331c7289
31da5b908d3c43179fc56c8be3c6d17e406faaa7
refs/heads/master
2018-06-29T12:19:42.584292
2018-05-31T13:31:03
2018-05-31T13:31:03
108,171,918
2
0
null
null
null
null
UTF-8
Scheme
false
false
17,386
scm
sandbox.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Test suite ;; prefix/namespace problems! (define (construct-intermediate-graph-rules graph) `(((@QueryUnit @Query) . ,rw/quads) ((CONSTRUCT) . ,(lambda (block bindings) (values `((INSERT (GRAPH ,graph ,@(cdr block)))) bindings))) (,values . ,rw/copy))) ;; could be abstracted & combined with select-query-rules (define (replace-dataset-rules graph) `(((@QueryUnit @Query) . ,rw/quads) ((GRAPH) . ,(rw/lambda (block) (cddr block))) ((@Prologue @SubSelect WHERE FILTER BIND |ORDER| |ORDER BY| |LIMIT|) . ,rw/copy) ((@Dataset) . ,(rw/lambda (block) (parameterize ((*default-graph* graph)) ; not used `((@Dataset ,@(make-dataset 'FROM (list graph) #f)))))) (,select? . ,rw/copy) (,triple? . ,rw/copy) (,list? . ,rw/list))) (define (test query #!optional (cleanup? #t)) (let ((rewritten-query (rewrite-query query (main-transformation-rules))) (intermediate-graph (expand-namespace (symbol-append '|rewriter:| (gensym 'graph))))) (log-message "Creating intermediate graph: ~A " intermediate-graph) (print (sparql-update (write-sparql (rewrite-query (if (procedure? (*read-constraint*)) ((*read-constraint*)) (*read-constraint*)) (construct-intermediate-graph-rules intermediate-graph))))) (parameterize ((*query-unpacker* sparql-bindings)) (let ((r1 (sparql-select (write-sparql rewritten-query))) (r2 (sparql-select (write-sparql (rewrite-query query (replace-dataset-rules intermediate-graph)))))) (log-message "~%==Expected Results==~%~A" r2) (log-message "~%==Actual Results==~%~A" r1) (when cleanup? (sparql-update (format "DELETE WHERE { GRAPH ~A { ?s ?p ?o } }" intermediate-graph))) (values r1 r2))))) (define (test-call _) (let* (($$query (request-vars source: 'query-string)) (body (read-request-body)) ($$body (let ((parsed-body (form-urldecode body))) (lambda (key) (and parsed-body (alist-ref key parsed-body))))) (query-string (or ($$query 'query) ($$body 'query) body)) (cleanup? (not (string-ci=? "false" (or ($$query 'cleanup) "true")))) (query (parse "test" query-string))) (let-values (((actual expected) (test query cleanup?))) `((expected . ,(list->vector expected)) (actual . ,(list->vector actual)) (equal . ,(equal? expected actual)))))) (define-rest-call 'POST '("test") test-call) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Sandbox (define (query-time-annotations annotations) (map (lambda (a) (match a ((key var vals) `(,key ,(string->symbol (string-join (map symbol->string vals))))) (else a))) (remove values? annotations))) (define (sandbox-call _) (let* ((body (read-request-body)) ($$body (let ((parsed-body (form-urldecode body))) (lambda (key) (and parsed-body (alist-ref key parsed-body))))) (query-string ($$body 'query)) (session-id (conc "\"" ($$body 'session-id) "\"")) (read-constraint-string ($$body 'readconstraint)) (write-constraint-string ($$body 'writeconstraint)) (read-constraint (parse-constraint (replace-headers read-constraint-string))) (write-constraint (parse-constraint (replace-headers write-constraint-string))) (query (parse "sandbox" query-string)) (fprops (map string->symbol (string-split (or ($$body 'fprops) "") ", "))) (qprops (map string->symbol (string-split (or ($$body 'qprops) "") ", "))) (transient-fprops (map string->symbol (string-split (or ($$body 'trfprops) "") ", "))) (transient-qprops (map string->symbol (string-split (or ($$body 'trqprops) "") ", "))) (query-fprops? (equal? "true" ($$body 'query-fprops))) (unique-vars (map string->symbol (string-split (or ($$body 'uvs) "") ", ")))) (parameterize ((*write-constraint* write-constraint) (*read-constraint* read-constraint) (*functional-properties* fprops) (*transient-functional-properties* transient-fprops) (*queried-properties* qprops) (*transient-queried-properties* transient-qprops) (*unique-variables* unique-vars) (*query-functional-properties?* query-fprops?)) (let-values (((rewritten-query bindings) (apply-constraints query))) (let* ((annotations (get-annotations rewritten-query bindings)) (qt-annotations (and annotations (query-time-annotations annotations)))) ;; (aquery (and annotations (annotations-query annotations rewritten-query))) (let-values (((aqueries annotations-pairs) (if annotations (annotations-queries annotations rewritten-query) (values #f #f)))) (let* ((annotations-query-strings (and aqueries (map write-sparql aqueries))) (queried-annotations (and annotations-query-strings (join (map (lambda (q) (query-annotations q annotations-pairs)) annotations-query-strings)))) ;;(queried-annotations (and aquery (query-annotations aquery annotations-pairs))) ;; (queried-annotations (and aquery (query-annotations aquery))) (functional-property-substitutions (get-binding/default 'functional-property-substitutions bindings '()))) (log-message "~%===Annotations===~%~A~%" annotations) (log-message "~%===Queried Annotations===~%~A~%" (and queried-annotations (format-queried-annotations queried-annotations))) `((rewrittenQuery . ,(format (write-sparql rewritten-query))) (annotations . ,(format-annotations qt-annotations)) (queriedAnnotations . ,(and queried-annotations (format-queried-annotations queried-annotations))))))))))) (define (apply-call _) (let* ((body (read-request-body)) ($$body (let ((parsed-body (form-urldecode body))) (lambda (key) (and parsed-body (alist-ref key parsed-body))))) (read-constraint-string ($$body 'readconstraint)) (write-constraint-string ($$body 'writeconstraint)) (fprops (map string->symbol (string-split (or ($$body 'fprops) "") ", "))) (qprops (map string->symbol (string-split (or ($$body 'qprops) "") ", "))) (transient-fprops (map string->symbol (string-split (or ($$body 'trfprops) "") ", "))) (transient-qprops (map string->symbol (string-split (or ($$body 'trqprops) "") ", "))) (query-fprops? (equal? "true" ($$body 'query-fprops))) (unique-vars (map string->symbol (string-split (or ($$body 'uvs) "") ", ")))) (log-message "~%Redefining read and write constraints~%") ;; brute-force redefining (set! *write-constraint* (make-parameter (parse-constraint write-constraint-string))) (set! *read-constraint* (make-parameter (parse-constraint read-constraint-string))) (set! *functional-properties* (make-parameter fprops)) (set! *queried-properties* (make-parameter qprops)) (set! *transient-functional-properties* (make-parameter transient-fprops)) (set! *transient-queried-properties* (make-parameter transient-qprops)) (set! *unique-variables* (make-parameter unique-vars)) (set! *query-functional-properties?* (make-parameter query-fprops?)) ;; (set! apply-constraints-with-form-cache* (rememoize apply-constraints-with-form-cache)) ;; (set! *query-forms* (make-hash-table)) `((success . "true")))) (define (format-queried-annotations queried-annotations) (list->vector (map (lambda (annotation) (match annotation ((key val) `((key . ,(symbol->string key)) (var . ,(write-uri val)))) (key `((key . ,(symbol->string key)))))) queried-annotations))) (define (format-annotations annotations) (list->vector (map (lambda (annotation) (match annotation ((`*values* rest) `((key . ,(format "~A" rest)))) ; fudging ((key var) `((key . ,(symbol->string key)) (var . ,(symbol->string var)))) (key `((key . ,(symbol->string key)))))) annotations))) (define-rest-call 'POST '("sandbox") sandbox-call) (define-rest-call 'POST '("apply") apply-call) (define-rest-call 'GET '("auth") (lambda (_) (let* ((session (header 'mu-session-id)) (results (sparql-select-unique "SELECT ?user WHERE { <~A> <http://mu.semte.ch/vocabularies/authorization/account> ?user }" session)) (user (and results (alist-ref 'user results)))) (if user `((user . ,(write-uri user))) `((user . #f)))))) (define-rest-call 'POST '("auth") (lambda (_) (let* ((body (read-request-body)) ($$body (let ((parsed-body (form-urldecode body))) (lambda (key) (and parsed-body (alist-ref key parsed-body))))) (user ($$body 'user)) (session-id (header 'mu-session-id))) (sparql-update "DELETE WHERE { GRAPH <http://mu.semte.ch/authorization> { ?s ?p ?o } }") (sparql-update "INSERT DATA { GRAPH <http://mu.semte.ch/authorization> { <~A> <http://mu.semte.ch/vocabularies/authorization/account> <~A> } }" session-id user)))) (define-rest-call 'POST '("proxy") (lambda (_) (let ((query (read-request-body))) (log-message "~%==Proxying Query==~%~A~%" (add-prefixes query)) (proxy-query "proxy" (add-prefixes query) (if (update-query? (parse "test" query)) (*sparql-update-endpoint*) (*sparql-endpoint*)))))) (define-rest-call 'DELETE '("clear") (lambda (_) (let ((graphs (delete-duplicates (append (get-all-graphs ((*read-constraint*))) (get-all-graphs ((*write-constraint*))))))) (sparql-update (write-sparql `(@UpdateUnit (@Update (@Prologue ,@(constraint-prologues)) (DELETE (GRAPH ?g (?s ?p ?o))) (WHERE (GRAPH ?g (?s ?p ?o)) (VALUES ?g ,@graphs))))))) ;; (conc "DELETE { " ;; " GRAPH ?g { ?s ?p ?o } " ;; "} " ;; "WHERE { " ;; " GRAPH ?g { ?s ?p ?o } " ;; " VALUES ?g { " ;; (string-join (map (cut format "~% ~A" <>) graphs)) ;; " } " ;; "}")) `((success . "true")))) (define (load-plugin name) (load (make-pathname (*plugin-dir*) name ".scm"))) (define (save-plugin name read-constraint-string write-constraint-string fprops transient-fprops qprops transient-qprops unique-vars query-fprops?) (let* ((replace (lambda (str) (irregex-replace/all "^[ \n]+" (irregex-replace/all "[\"]" str "\\\"") ""))) (read-constraint-string (replace read-constraint-string)) (write-constraint-string (and write-constraint-string (replace write-constraint-string))) (fprops (or fprops (*functional-properties*))) (transient-fprops (or transient-fprops (*transient-functional-properties*))) (unique-vars (map symbol->string (or unique-vars (*unique-variables*))))) (with-output-to-file (make-pathname (*plugin-dir*) name "scm") (lambda () (format #t "(*functional-properties* '~A)~%~%" fprops) (format #t "(*transient-functional-properties* '~A)~%~%" transient-fprops) (format #t "(*query-functional-properties?* ~A)~%~%" query-fprops?) (format #t "(*queried-properties* '~A)~%~%" qprops) (format #t "(*transient-queried-properties* '~A)~%~%" transient-qprops) (format #t "(*unique-variables* '~A)~%~%" unique-vars) (format #t "(*headers-replacements* '((\"<SESSION>\" mu-session-id uri)))~%~%") (format #t (conc "(define-constraint ~%" (if write-constraint-string " 'read \" ~%" " 'read/write \" ~%") read-constraint-string "\")~%~%")) (when write-constraint-string (format #t (conc "(define-constraint ~%" " 'write \" ~%" write-constraint-string " \")~%~%"))) )))) (define-rest-call 'POST '("plugin" name) (rest-call (name) (let* ((body (read-request-body)) ($$body (let ((parsed-body (form-urldecode body))) (lambda (key) (and parsed-body (alist-ref key parsed-body))))) (session-id (conc "\"" ($$body 'session-id) "\"")) (read-constraint-string ($$body 'readconstraint)) (write-constraint-string ($$body 'writeconstraint)) (fprops (map string->symbol (string-split (or ($$body 'fprops) "") ", "))) (qprops (map string->symbol (string-split (or ($$body 'qprops) "") ", "))) (transient-fprops (map string->symbol (string-split (or ($$body 'trfprops) "") ", "))) (transient-qprops (map string->symbol (string-split (or ($$body 'trqprops) "") ", "))) (query-fprops? (equal? "true" ($$body 'query-fprops))) (unique-vars (map string->symbol (string-split (or ($$body 'uvs) "") ", ")))) (save-plugin name read-constraint-string write-constraint-string fprops transient-fprops qprops transient-qprops unique-vars query-fprops?) `((success . "true"))))) (define-rest-call 'GET '("plugin") (lambda (_) `((plugins . ,(list->vector (sort (map pathname-file (glob (make-pathname (*plugin-dir*) "[a-zA-Z0-9]*.scm"))) string<=)))))) (define-rest-call 'GET '("plugin" name) (rest-call (name) (load-plugin name) (parameterize ((*write-annotations?* #t) (*headers-replacements* '())) `((readConstraint . ,(write-sparql (call-if (*read-constraint*)))) (writeConstraint . ,(write-sparql (call-if (*write-constraint*)))) (functionalProperties . ,(list->vector (map ->string (*functional-properties*)))) (queriedProperties . ,(list->vector (map ->string (*queried-properties*)))) (transientFunctionalProperties . ,(list->vector (map ->string (*transient-functional-properties*)))) (transientQueriedProperties . ,(list->vector (map ->string (*transient-queried-properties*)))) (queryFunctionalProperties . ,(*query-functional-properties?*)) (uniqueVariables . ,(list->vector (map ->string (*unique-variables*)))))))) (define-rest-call 'GET '("users") (lambda (_) (list->vector (map (lambda (user) `((uri . ,(write-uri (alist-ref 'user user))) (role . ,(write-uri (alist-ref 'role user))) (roleTitle . ,(alist-ref 'roleTitle user)) (name . ,(rdf->json (alist-ref 'name user))))) (sparql-select (conc "PREFIX muauth: <http://mu.semte.ch/vocabularies/authorization/>" "PREFIX dct: <http://purl.org/dc/terms/>" "SELECT DISTINCT ?user ?role ?roleTitle ?name " "WHERE { " " ?user muauth:hasRole ?role " " OPTIONAL { ?role dct:title ?roleTitle }" " OPTIONAL { " " { ?user dct:title ?name } " " UNION { ?user foaf:name ?name } " " } " "}" )))))) ;; (define (serve-file path) ;; (log-message "~%Serving ~A~%" path) ;; (call-with-input-file path ;; (lambda (port) ;; (read-string #f port)))) ;; (define (sandbox filename) ;; (let ((filename (if (equal? filename "") "index.html" filename))) ;; (if (feature? 'docker) ;; (make-pathname "/app/sandbox/" filename) ;; (make-pathname "./sandbox/" filename)))) ;; (define-rest-call 'GET '("sandbox") (lambda (_) (serve-file (sandbox "index.html")))) ;; ;; a way to do this directly in mu-chicken-support? ;; (define-rest-call 'GET '("sandbox" file) ;; (rest-call ;; (file) ;; (serve-file (sandbox file)))) ;; (define-rest-call 'GET '("sandbox" dir file) ;; (rest-call ;; (dir file) ;; (serve-file (sandbox (string-join (list dir file) "/"))))) ;; (define-rest-call 'GET '("sandbox" dir dir2 file) ;; (rest-call ;; (dir dir2 file) ;; (serve-file (sandbox (string-join (list dir dir2 file) "/")))))
false
58f4c975eedcf54ff16c73714ea7ada643fa14ce
5927f3720f733d01d4b339b17945485bd3b08910
/let-keywords.scm
98dc09009cf34b3a43f63b3dfd1ba626d0721c19
[]
no_license
ashinn/hato
85e75c3b6c7ca7abca512dc9707da6db3b50a30d
17a7451743c46f29144ce7c43449eef070655073
refs/heads/master
2016-09-03T06:46:08.921164
2013-04-07T03:22:52
2013-04-07T03:22:52
32,322,276
5
0
null
null
null
null
UTF-8
Scheme
false
false
1,966
scm
let-keywords.scm
;; let-keywords.scm -- portable syntax for keyword parameters ;; ;; Copyright (c) 2009 Alex Shinn. All rights reserved. ;; BSD-style license: http://synthcode.com/license.txt (module let-keywords (let-keywords*) (import scheme chicken) (define-syntax let-keys-error (syntax-rules () ((let-keys-error) #f))) (define-syntax let-keys* (syntax-rules () ((let-keys* ls (binds ...) ((var keyword default) . rest) . body) (let-keys* ls (binds ... (var keyword default)) rest . body)) ((let-keys* ls (binds ...) ((var default) . rest) . body) (let-keys* ls (binds ... (var var default)) rest . body)) ((let-keys* ls (binds ...) ((var) . rest) . body) (let-keys* ls (binds ... (var var #f)) rest . body)) ((let-keys* ls (binds ...) (var . rest) . body) (let-keys* ls (binds ... (var var #f)) rest . body)) ((let-keys* ls ((var keyword default) ...) () . body) (let ((tmp ls)) (let* ((var (cond ((memq (string->keyword (symbol->string 'keyword)) ls) => cadr) (else default))) ...) . body))) ((let-keys* ls ((var keyword default) ...) rest-var . body) (let ((undef (list 'undef))) (let ((var undef) ...) (let lp ((pls ls) (acc '())) (cond ((null? pls) (if (eq? var undef) (set! var default)) ... (let ((rest-var (reverse! acc))) . body)) (else (lp (cddr pls) (case (and (keyword? (car pls)) (string->symbol (keyword->string (car pls)))) ((keyword) (set! var (cadr pls)) acc) ... (else (cons (cadr pls) (cons (car pls) acc))))))))))) ((let-keys* . ?) (let-keys-error "malformed let-plist " (let-plist ?))))) (define-syntax let-keywords* (syntax-rules () ((let-keywords* ls specs . body) (let-keys* ls () specs . body)))) )
true
dd9d5f64b99ac8110b8a9c10bd6f92f263846ed9
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/surfage/s41/streams/primitive.sls
0c642faf0db3ecb9c57cdefd74f9d9ad7904d815
[ "MIT", "X11-distribute-modifications-variant" ]
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
3,595
sls
primitive.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 (surfage s41 streams primitive) (export stream-null stream-cons stream? stream-null? stream-pair? stream-car stream-cdr stream-lambda) (import (rnrs) (rnrs mutable-pairs)) (define-record-type (stream-type make-stream stream?) (fields (mutable box stream-promise stream-promise!))) (define-syntax stream-lazy (syntax-rules () ((lazy expr) (make-stream (cons 'lazy (lambda () expr)))))) (define (stream-eager expr) (make-stream (cons 'eager expr))) (define-syntax stream-delay (syntax-rules () ((stream-delay expr) (stream-lazy (stream-eager expr))))) (define (stream-force promise) (let ((content (stream-promise promise))) (case (car content) ((eager) (cdr content)) ((lazy) (let* ((promise* ((cdr content))) (content (stream-promise promise))) (if (not (eqv? (car content) 'eager)) (begin (set-car! content (car (stream-promise promise*))) (set-cdr! content (cdr (stream-promise promise*))) (stream-promise! promise* content))) (stream-force promise)))))) (define stream-null (stream-delay (cons 'stream 'null))) (define-record-type (stream-pare-type make-stream-pare stream-pare?) (fields (immutable kar stream-kar) (immutable kdr stream-kdr))) (define (stream-pair? obj) (and (stream? obj) (stream-pare? (stream-force obj)))) (define (stream-null? obj) (and (stream? obj) (eqv? (stream-force obj) (stream-force stream-null)))) (define-syntax stream-cons (syntax-rules () ((stream-cons obj strm) (stream-delay (make-stream-pare (stream-delay obj) (stream-lazy strm)))))) (define (stream-car strm) (cond ((not (stream? strm)) (error 'stream-car "non-stream")) ((stream-null? strm) (error 'stream-car "null stream")) (else (stream-force (stream-kar (stream-force strm)))))) (define (stream-cdr strm) (cond ((not (stream? strm)) (error 'stream-cdr "non-stream")) ((stream-null? strm) (error 'stream-cdr "null stream")) (else (stream-kdr (stream-force strm))))) (define-syntax stream-lambda (syntax-rules () ((stream-lambda formals body0 body1 ...) (lambda formals (stream-lazy (let () body0 body1 ...)))))))
true
1306e270c79cda01f72167d4639e67830f3211ca
defeada37d39bca09ef76f66f38683754c0a6aa0
/System/system/mono-not-supported-attribute.sls
b66a36a72102421cf19385ab0109f36a62db8c6e
[]
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
430
sls
mono-not-supported-attribute.sls
(library (system mono-not-supported-attribute) (export new is? mono-not-supported-attribute?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.MonoNotSupportedAttribute a ...))))) (define (is? a) (clr-is System.MonoNotSupportedAttribute a)) (define (mono-not-supported-attribute? a) (clr-is System.MonoNotSupportedAttribute a)))
true
a019827367ef72e27974b6b5a127bd9228bea45d
db0f911e83225f45e0bbc50fba9b2182f447ee09
/the-scheme-programming-language/3.6-libraries/homeworks/3.6.3.scm
8bba74d2e9bcaad2699eb106fe8e112ed1e5c81c
[]
no_license
ZhengHe-MD/learn-scheme
258941950302b4a55a1d5d04ca4e6090a9539a7b
761ad13e6ee4f880f3cd9c6183ab088ede1aed9d
refs/heads/master
2021-01-20T00:02:38.410640
2017-05-03T09:48:18
2017-05-03T09:48:18
89,069,898
0
0
null
null
null
null
UTF-8
Scheme
false
false
326
scm
3.6.3.scm
(define histogram (lambda (port distr) (for-each (lambda (n g) (put-datum port g) (put-string port ": ") (let loop ([n n]) (unless (= n 0) (put-char port #\*) (loop (- n 1)))) (put-string port "\n")) (map car distr) (map cadr distr))))
false
b60ada4f6a3af9333c18535bdf39351bc128c605
6c69f4c35bcecb0ab4642d75e01183d2ee4de8b9
/test/pseudo-transport.scm
0ff548275dccfc7ed492f1cb1c49093377ef5b7a
[ "MIT" ]
permissive
Lattay/chicken-meta-rpc
2c488928e7f288eef9bb30acc303b379e4ad24b8
a633b9870af384bc7926334156632a26159af624
refs/heads/master
2020-07-12T21:56:48.065087
2019-11-26T21:18:50
2019-11-26T21:18:50
204,916,209
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,988
scm
pseudo-transport.scm
(import scheme chicken.base) (import srfi-69) (import coops) (load "meta-rpc.interface.so") (import meta-rpc.interface) (load "test/tunnel.scm") (define-class <pseudo-transport> (<transport-client> <transport-server>) (in-serv out-serv in-cli out-cli (ready #f))) (define (make-pseudo-transport) (let-values (((in-serv out-cli) (make-tunnel-port)) ((in-cli out-serv) (make-tunnel-port))) (make <pseudo-transport> 'in-serv in-serv 'out-serv out-serv 'in-cli in-cli 'out-cli out-cli))) (define-method (one-shot? (o <pseudo-transport>)) #f) (define-method (ready? (o <pseudo-transport>)) (slot-value o 'ready)) (define-method (accept (o <pseudo-transport>)) (set! (slot-value o 'ready) #f) (values (slot-value o 'in-serv) (slot-value o 'out-serv))) (define-method (connect (o <pseudo-transport>)) (set! (slot-value o 'ready) #t) (values (slot-value o 'in-cli) (slot-value o 'out-cli))) ;;;;;;;;;;;;;;;;;;;;;;; (define-class <pseudo-transport-multi-co> (<transport-client> <transport-server>) ((ready #f) (connections '()))) (define (make-pseudo-transport-multi-co) (make <pseudo-transport-multi-co>)) (define-method (one-shot? (o <pseudo-transport-multi-co>)) #t) (define-method (ready? (o <pseudo-transport-multi-co>)) (slot-value o 'ready)) (define-method (accept (o <pseudo-transport-multi-co>)) (if (ready? o) (let ((co (car (slot-value o 'connections)))) (set! (slot-value o 'ready) #f) (values (car co) (cdr co))) (begin (error "Transport not ready.") (values #f #f)))) (define-method (connect (o <pseudo-transport-multi-co>)) (let-values (((in-serv out-cli) (make-tunnel-port)) ((in-cli out-serv) (make-tunnel-port))) (set! (slot-value o 'ready) #t) (set! (slot-value o 'connections) (cons (cons in-serv out-serv) (slot-value o 'connections))) (values in-cli out-cli)))
false
dd8a0b870b2c0a8a8ebac851482a4936b952818b
2ad98a56db786f1155d81cf455d37072af2bcb61
/fp/scheme/bonus-hw1/task5_sort.scm
ca07934218914ad5526fe6cdb2aedc27e1a03e06
[]
no_license
valentinvstoyanov/fmi
aa5a7d9a59f1f45238b04e6bcbad16d25ee8ade3
64f8ff2ae1cc889edfcf429ce0ca5353e4e23265
refs/heads/master
2023-01-05T05:57:37.300292
2020-11-06T21:47:27
2020-11-06T21:47:27
110,866,065
0
1
null
2019-12-14T13:36:10
2017-11-15T17:40:41
C++
UTF-8
Scheme
false
false
3,276
scm
task5_sort.scm
#lang racket ;Зад.5. a) Напишете генератор на списъци с подадена дължина и случайни елементи. ;b) Напишете функция, която проверява дали списък е сортиран. ;c) Напишете няколко (поне 4) алгоритъма за сортиране на списъци ; и проверете кой е по-бърз (при експерименти с различни размери на списъка). ; Напишете кратък текст, който описва вашите тестове, наблюдаваните резултати и направете заключения. (define (rnd-list n) (define (loop i res) (if (= i n) res (loop (+ 1 i) (cons (random 4294967087) res)))) (loop 0 '())) (define (sorted? l) (define (loop xs) (cond ((null? xs) #t) ((null? (cdr xs)) #t) ((or (= (car xs) (cadr xs)) (< (car xs) (cadr xs))) (sorted? (cdr xs))) (else #f))) (loop l)) (define (remove x xs) (cond ((null? xs) '()) ((= x (car xs)) (cdr xs)) (else (cons (car xs) (remove x (cdr xs)))))) (define (smallest xs) (apply min xs)) (define (selection-sort xs) (cond ((null? xs) '()) ((null? (cdr xs)) xs) (else (let* ((min-x (smallest xs)) (rest (remove min-x xs))) (cons min-x (selection-sort rest)))))) (define (insert-sorted x xs) (cond ((null? xs) (list x)) ((< (car xs) x) (cons (car xs) (insert-sorted x (cdr xs)))) (else (cons x xs)))) (define (insertion-sort l) (define (loop xs acc) (if (null? xs) acc (loop (cdr xs) (insert-sorted (car xs) acc)))) (loop l '())) (define (merge xs ys) (cond ((null? xs) ys) ((null? ys) xs) ((< (car xs) (car ys)) (cons (car xs) (merge (cdr xs) ys))) (else (cons (car ys) (merge xs (cdr ys)))))) (define (split l) (define (loop xs n ys zs) (cond ((null? xs) (cons (reverse ys) (reverse zs))) ((= n 0) (loop (cdr xs) 0 ys (cons (car xs) zs))) (else (loop (cdr xs) (- n 1) (cons (car xs) ys) zs)))) (loop l (quotient (length l) 2) '() '())) (define (merge-sort l) (cond ((null? l) '()) ((null? (cdr l)) l) (else (let* ((splitted (split l)) (left (car splitted)) (right (cdr splitted))) (merge (merge-sort left) (merge-sort right)))))) (define (quick-sort l) (if (or (null? l) (null? (cdr l))) l (let* ((pivot (car l)) (tail (cdr l)) (left (filter (lambda(x) (< x pivot)) tail)) (right (filter (lambda(x) (>= x pivot)) tail))) (append (quick-sort left) (list pivot) (quick-sort right))))) (define (test s l) (if (null? (s l)) 0 1)) ;За 10 000 произволни елемента merge-sort и quick-sort са видимо по-бързи от останалите.(очаквано) ;При 10 000 и 20 000 изгледжа, че insertion-sort е по-бърз от selection-sort ;За 500 000 и 1 000 000 : quick-sort е по-бърз от merge-sort ;Извод от наблюденията: quick-sort > merge-sort > insertion-sort > selection-sort
false
66c47379ae4a80a73c6c36052c08f18e05bc1fff
427586e066e5d7d146d3b24c1400781a91011a94
/code/include/memoization.sld
09e17563c4efba085d4f0f1955fe39b2c985ebe2
[ "LicenseRef-scancode-public-domain" ]
permissive
cslarsen/scheme-presentation
07cb3d5d7850cc6e7616dad43718c139178cbd7c
7b66aef60041f95358f0eab72c58ac400e1f902f
refs/heads/master
2016-08-11T14:50:33.517262
2016-01-28T07:25:06
2016-01-28T07:25:06
50,564,125
0
0
null
null
null
null
UTF-8
Scheme
false
false
828
sld
memoization.sld
(define-library (memoization) (import (scheme base) (scheme write) (srfi 69)) (export define-memoize lambda-memoize) (begin (define-syntax lambda-memoize (syntax-rules () ((_ (arg ...) body ...) (let ((table (make-hash-table equal?))) (lambda (arg ...) (let ((key (list arg ...))) (if (hash-table-exists? table key) (hash-table-ref table key) (let ((value (begin body ...))) (hash-table-set! table key value) value)))))))) (define-syntax define-memoize (syntax-rules () ((_ (name arg ...) body ...) (define name (lambda-memoize (arg ...) (begin body ...)))))) ))
true
18bd79b68e00c1437c739a24dee72664ab5c700b
4f91474d728deb305748dcb7550b6b7f1990e81e
/utils/ch1/3-bigger-and-smaller.scm
314fd75f8b44a38fa7f6b2a3d9dab3eb809619dd
[]
no_license
CanftIn/sicp
e686c2c87647c372d7a6a0418a5cdb89e19a75aa
92cbd363c143dc0fbf52a90135218f9c2bf3602d
refs/heads/master
2021-06-08T22:29:40.683514
2020-04-20T13:23:59
2020-04-20T13:23:59
85,084,486
2
0
null
null
null
null
UTF-8
Scheme
false
false
108
scm
3-bigger-and-smaller.scm
(define (bigger x y) (if (> x y) x y)) (define (smaller x y) (if (> x y) y x))
false