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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
97eadd2cccba2b277e86914e02012cf375920c4f | 951b7005abfe3026bf5b3bd755501443bddaae61 | /astonish/stream/函数式程序的模块化和对象的模块化.scm | 85f13ef100c6bd820ac45a9905c7c6131050691b | []
| 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 | 1,625 | scm | 函数式程序的模块化和对象的模块化.scm | (define random-init 1)
(define (rand-update x)
(remainder (+ (* 13 x) 5) 24))
(define (random-numbers op-stream)
(define (numbers last-value op-stream)
(let ((op (stream-car op-stream)))
(cond ((pair? op)
(cons-stream (cadr op)
(numbers (cadr op)
(stream-cdr op-stream))))
(else (let ((next-value (rand-update last-value)))
(cons-stream next-value
(numbers next-value
(stream-cdr op-stream))))))))
(numbers random-init op-stream))
(define the-op-stream (list->stream '(generate (reset 9))))
(define the-random-numbers (random-numbers the-op-stream))
;要查看流中的全部元素,不能用“流.scm”里定义的show-n,因为最后只有一个元素的时候,op-stream是空,但还会调用numbers过程,所以需要利用延时求值
(define (show-n-2 s n)
(if (= n 0)
'()
(let ((the-s (force s)))
(cons (stream-car the-s)
(show-n-2 (delay (stream-cdr the-s)) (- n 1))))))
(show-n-2 (delay the-random-numbers) 2)
;参考sicp-solution隐式定义的版本:
(define (random-numbers op-stream)
(define numbers
(cons-stream random-init
(stream-map
(lambda (num op)
(if (pair? op)
(cadr op)
(rand-update num)))
numbers op-stream)))
(stream-cdr numbers))
(define the-random-numbers (random-numbers the-op-stream))
(show-n-2 (delay the-random-numbers) 2)
| false |
9a082a1d9ff03557a09ba73ef358a7a1188bb6d9 | bb65446a9debece8580bf0a20a229055038a5f6b | /examples/base/databind-1.scm | 4e096079a0ff6ccc3e1e87ae5f86ab084e38886d | []
| no_license | arvyy/DataDrivenScreenshots | f4ee1171c03a4a51cd96a3dd26b7205335445080 | bd96d5bf22fdd449d681eaa509807108f72be442 | refs/heads/master | 2020-11-24T13:47:33.153065 | 2019-12-15T12:10:37 | 2019-12-15T12:10:37 | 228,175,925 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 356 | scm | databind-1.scm | ; simple data binding. Data is bound to single item, and used to define single property.
(define r (rect #:x 100
#:y (calc (data) data)
#:width 100
#:height 100))
(define (item-getter t)
(apply-data r (+ 100 (* 50 t))))
(define get-dds-gif
(dds-gif #:duration 4
#:item-getter item-getter))
| false |
64a3ac6ff0232a0cc28fca2936a86ff4baeb6c87 | 657a95c82617af612da2a5fa410ac44a67a39feb | /sicp/02/2.60.ss | 4c9ca0b9b6abce08ce87a134d0bf054c9ff1e7b0 | []
| no_license | wangjiezhe/sicp | ed16395576ac163f000b6dc59ef4928bfab3013f | 635dad3bc6dacd07665c17eba2bbe4fcdbbb530f | refs/heads/master | 2020-04-06T07:02:32.281885 | 2016-08-20T08:10:24 | 2016-08-20T08:10:24 | 57,348,685 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 92 | ss | 2.60.ss | (define (adjoin x set)
(cons x set))
(define (union-set set1 set2)
(append set1 set2))
| false |
c93c9b3ef68f06fcc86c128f09f2be98ae0612bf | b0c1935baa1e3a0b29d1ff52a4676cda482d790e | /misc/issues/162.scm | ffdec6ca81b03808aaf6784c99ae046b707ccac6 | [
"MIT"
]
| permissive | justinethier/husk-scheme | 35ceb8f763a10fbf986340cb9b641cfb7c110509 | 1bf5880b2686731e0870e82eb60529a8dadfead1 | refs/heads/master | 2023-08-23T14:45:42.338605 | 2023-05-17T00:30:56 | 2023-05-17T00:30:56 | 687,620 | 239 | 28 | MIT | 2023-05-17T00:30:07 | 2010-05-26T17:02:56 | Haskell | UTF-8 | Scheme | false | false | 69 | scm | 162.scm | (import (lib))
(foo)
; Think this should be 'baz instead of an error
| false |
0b555ddf89e3a6f25a46f3d0b370967c2825bc0a | 018a7ce673c5be3cf3df61bd5c5036581d6646a7 | /examples/MultiProject/entrypoint.scm | a6abcf5fa4a1cfe5e195c68eda5f283620d66836 | [
"MIT"
]
| permissive | iwillspeak/feersum | e857deec2b8683960f9ac6d1f395fb5f625204a8 | 1602e8333aa11c0335c9775c0ab49bf01389ba98 | refs/heads/main | 2023-08-07T17:15:19.843607 | 2023-06-20T06:28:28 | 2023-06-20T06:28:28 | 223,348,583 | 31 | 2 | MIT | 2023-06-10T21:29:11 | 2019-11-22T07:33:04 | F# | UTF-8 | Scheme | false | false | 51 | scm | entrypoint.scm | (import (multifile test))
(greet "Second Project")
| false |
f67f9454f4e7926b4cf34f4f49f1aad3df261432 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /System/system/component-model/type-info.sls | a474f772baeea0112b42485f557bbc36181710fb | []
| 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 | 847 | sls | type-info.sls | (library (system component-model type-info)
(export new is? type-info? get-properties get-attributes get-events)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new System.ComponentModel.TypeInfo a ...)))))
(define (is? a) (clr-is System.ComponentModel.TypeInfo a))
(define (type-info? a) (clr-is System.ComponentModel.TypeInfo a))
(define-method-port
get-properties
System.ComponentModel.TypeInfo
GetProperties
(System.ComponentModel.PropertyDescriptorCollection))
(define-method-port
get-attributes
System.ComponentModel.TypeInfo
GetAttributes
(System.ComponentModel.AttributeCollection))
(define-method-port
get-events
System.ComponentModel.TypeInfo
GetEvents
(System.ComponentModel.EventDescriptorCollection)))
| true |
e497597baec50915891ba742d55d01dbff80b17d | e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6 | /ch2/2.36.scm | dfca18326b34006c66ea2b84a5ede6fd4e45adff | []
| no_license | lythesia/sicp-sol | e30918e1ebd799e479bae7e2a9bd4b4ed32ac075 | 169394cf3c3996d1865242a2a2773682f6f00a14 | refs/heads/master | 2021-01-18T14:31:34.469130 | 2019-10-08T03:34:36 | 2019-10-08T03:34:36 | 27,224,763 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 326 | scm | 2.36.scm | (load "2.2.3.scm")
; zip-like
(define (accumulate-n op null-var seqs)
(if (null? (car seqs)) ; shortest
'()
(cons
(accumulate op null-var (map car seqs))
(accumulate-n op null-var (map cdr seqs))
)
)
)
; test
; (display (accumulate-n + 0 (list '(1 2 3) '(4 5 6) '(7 8 9) '(10 11 12))))(newline)
| false |
2e07b3658227e389d1c0d74fb4a58b18a0f3ea12 | 8febfb80e03d741b7ba996b75596e13ddaf6f58c | /stock-green.scm | 241cab276cfa4d9cf9186af6a47d4ecdbbfad897 | []
| no_license | ThomasHintz/stock-green | 9684570b24a30c7e21437a87c8dad6018d2a12e7 | c9e3e48819cd171d48789b9d0e67ad1291b04440 | refs/heads/master | 2021-01-01T06:10:45.538608 | 2012-11-28T20:28:23 | 2012-11-28T20:28:23 | 6,726,377 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 7,301 | scm | stock-green.scm | (import chicken scheme data-structures)
(use numbers fox srfi-1)
;;;;;;;;;;;;;;;; generic ;;;;;;;;;;;;;;
(define (store? test)
(assert (list? test))
(not (null? test)))
(define-syntax mapm
(syntax-rules ()
((_ mac ls)
(let ((mac-list (map (lambda (lst) (cons 'mac lst)) ls)))
(eval
`(begin
,@mac-list)
(interaction-environment))))))
(define-syntax accessor
(syntax-rules ()
((_ name key)
(define (name alist . val)
(assert (list? alist))
(if (store? val)
(alist-update key (car val) alist)
(alist-ref key alist))))))
(define (combine-percents l)
(fold + 0 (map (lambda (e) (* (car e) (cadr e))) l)))
;;;;;;;;;;;;;;;; equations ;;;;;;;;;;;;;
(define (cumulative-avg k new-value average)
(/ (+ new-value (* k average)) (+ k 1)))
(define (random-percent)
(* 0.000001 (random 1000000)))
(define (random-pos-or-neg)
(expt -1 (random 100)))
(define (projected-value stock)
(+ (stock-value stock)
(* (combine-percents
`((,(- (stock-avg-value stock) 1) 0.7)
(,(stock-recent-avg stock) 0.3)))
(stock-value stock))))
(define (volatile-change stock-value volatility)
(if (< (random-percent) volatility)
(* stock-value (* (random-percent) (random-pos-or-neg)))
0))
(define (generate-value stock random-change volatility-change)
(+ (stock-value stock)
(* (combine-percents
`((,(- (stock-avg-value stock) 1) 0.6)
(,(stock-recent-avg stock) 0.3)
(,random-change 0.1)))
(stock-value stock))
volatility-change))
;;;;;;;;;;;;;; utilities ;;;;;;;;;;;;;;
(define (->pct num) (* 100 num))
(define (->pct-string num)
(fox (->pct num) 0 #f '(2) "%"))
(define (->$ num)
(string-append "$"
(fox num '(2) '#("," 3))))
;;;;;;;;;;;;;;; stocks ;;;;;;;;;;;;;;;;
(define (make-stock #!key (name "") (price 0) (projected 0) (last 0)
(avg '((samples . 0) (value . 0))) (recent-avg 0) (volatility 0)
(value 0))
`((name . ,name) (price . ,price) (projected . ,projected)
(last . ,last) (avg . ,avg)
(recent-avg . ,recent-avg) (volatility . ,volatility)
(value . ,value)))
(mapm accessor
'((stock-name 'name)
(stock-price 'price)
(stock-projected 'projected)
(stock-last 'last)
(stock-avg 'avg)
(stock-samples 'samples)
(stock-recent-avg 'recent-avg)
(stock-volatility 'volatility)
(stock-value 'value)))
(define (stock-price stock)
(alist-ref 'value stock))
(define (stock-avg-samples stock . val)
(if (store? val)
(stock-avg stock (stock-samples (stock-avg stock) (car val)))
(stock-samples (stock-avg stock))))
(define (stock-avg-value stock . val)
(if (store? val)
(stock-avg stock (stock-value (stock-avg stock) (car val)))
(stock-value (stock-avg stock))))
(define (stock-cumulative-avg stock new-value)
(cumulative-avg (stock-avg-samples stock)
(/ new-value (stock-value stock))
(stock-avg-value stock)))
(define (display-stock stock)
(let ((padding 18))
(print "")
(fox (stock-name stock) (+ padding (string-length (stock-name stock))) #t "\n")
(fox "price: " padding #t)
(fox (->$ (stock-price stock)) 0 #t '(2) "\n")
(fox "projected: " padding #t)
(fox (->pct-string (stock-projected stock)) #t "\n")
(fox "last: " padding #t)
(fox (->pct-string (stock-last stock)) #t "\n")
(fox "average: " padding #t)
(fox (->pct-string (- (stock-avg-value stock) 1)) #t "\n")
(fox "recent average: " padding #t)
(fox (->pct-string (stock-recent-avg stock)) #t "\n")
(fox "volatility: " padding #t)
(fox (->pct-string (stock-volatility stock)) #t "\n")
(fox "value: " padding #t)
(print (stock-value stock))))
(define (make-test-stock)
(make-stock name: "Google" price: 10 projected: 0 last: 0
avg: '((samples . 0) (value . 0)) recent-avg: 0 volatility: 0.1 value: 30))
(define (make-test-stock-apple)
(make-stock name: "Apple" price: 20 projected: 0 last: 0
avg: '((samples . 0) (value . 0)) recent-avg: 0 volatility: 0.05 value: 40))
;;;;;;;;;;;;;; players ;;;;;;;;;;;;;;;;;
(define (make-player #!key (name "") (cash 0) (stocks '()))
`((name . ,name) (cash . ,cash) (stocks . ,stocks)))
(mapm accessor
'((player-name 'name)
(player-cash 'cash)
(player-stocks 'stocks)))
(define (player-stock-shares player stock-name . val)
(alist-ref stock-name (player-stocks player) string=?))
(define (player-has-stock-in? player name)
(not (null? (filter (lambda (stock)
(string=? (car stock) name))
(player-stocks player)))))
(define (player-stock-value player stock)
(* (player-stock-shares player (stock-name stock))
(stock-price stock)))
(define (player-net-worth player stocks)
(+ (fold (lambda (stock worth)
(+ (player-stock-value player stock) worth))
0
stocks)
(player-cash player)))
(define (make-test-player)
(make-player name: "food good" cash: 10000
stocks: '(("Google" . 100) ("Apple" . 200))))
(define (display-player-stock player stock)
(let ((padding 26))
(fox (stock-name stock) (- padding 1) #t "\n")
(fox "value: " padding #t)
(fox (->$ (player-stock-value player stock)) 0 #t '(2) "\n")
(fox "shares: " padding #t)
(fox (player-stock-shares player (stock-name stock)) 0 #t "\n")))
(define (display-player-stocks player stocks)
(map (lambda (stock)
(display-player-stock player stock))
(filter (lambda (stock) (player-has-stock-in? player (stock-name stock))) stocks)))
(define (display-player player stocks)
(let ((padding 18))
(print "")
(fox (player-name player) (+ padding (string-length (player-name player))) #t "\n")
(fox "net worth: " padding #t)
(fox (->$ (player-net-worth player stocks)) 0 #t '(2) "\n")
(fox "cash: " padding #t)
(fox (->$ (player-cash player)) 0 #t '(2) "\n")
(fox "stocks:" (- padding 1) #t)
(print "")
(display-player-stocks player stocks)))
(display-player (make-test-player) `(,(make-test-stock) ,(make-test-stock-apple)))
;;;;;;;;;;;;; game play ;;;;;;;;;;;;;;;;
(define (generate-stock-new-value stock)
(generate-value stock
(* (random-percent) (random-pos-or-neg))
(volatile-change (stock-value stock) (stock-volatility stock))))
(define (update-stock stock new-value)
(let ((stock (list-copy stock)))
(set! stock (stock-avg-value stock (stock-cumulative-avg stock new-value)))
(set! stock (stock-avg-samples stock (+ 1 (stock-avg-samples stock))))
(set! stock (stock-value stock new-value))
stock))
;; (stock-avg-value (make-test-stock) 1)
;; (stock-avg (make-test-stock))
(let ((stock (make-test-stock)))
(set! stock (update-stock stock 30))
(set! stock (update-stock stock (generate-stock-new-value stock)))
(display-stock stock))
(define google (make-test-stock))
(set! google (update-stock google 30))
(begin (set! google (update-stock google (generate-stock-new-value google)))
(display-stock google)
(display-player (make-test-player) `(,google)))
| true |
f6357be142e5691bdd0682ae120d7d1d4cf5fa6f | 923209816d56305004079b706d042d2fe5636b5a | /sitelib/http/header-field/content-md5.scm | a2a4de95d11f0ed9eff90fa61af54800657593a4 | [
"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 | 355 | scm | content-md5.scm | (library (http header-field content-md5)
(export Content-MD5)
(import (rnrs (6))
(http abnf))
;;; 14.15 Content-MD5
;; md5-digest = <base64 of 128 bit MD5 digest as per RFC 1864>
(define md5-digest (rep+ (bar ALPHA DIGIT))) ; FIXME
(define Content-MD5
(seq (string->rule "Content-MD5") (char->rule #\:) *LWS md5-digest))
)
| false |
be2f84dc7d775e7a6932106410a5e7372c05157f | 4a01cc0d02f7bc90a2fad16a3784faf0cdfedaba | /sicp-streams-core.scm | 3f434cbb5acc5b09c1c62e8cb2decffa0ada231d | []
| no_license | lbeckman314/sicp-chicken | cdc04046632a783e4df6875f11e81f58d8136162 | 0f65de82acb06ae6abcff655dc1aea115cfdc142 | refs/heads/master | 2020-09-01T21:19:52.593955 | 2016-08-30T20:28:37 | 2016-08-30T20:28:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 6,488 | scm | sicp-streams-core.scm | (define stream-null
@("The empty stream")
'())
(define the-empty-stream
@("A synonym for {{stream-null}}")
stream-null)
(define stream-null?
@("Is this stream null?"
(stream "The stream to test")
(@to "boolean"))
null?)
(define-syntax cons-stream
@("Constructs a stream; returns a stream whose {{stream-car}} is {{a}}
and whose {{stream-cdr}} is a delayed {{d}}."
(a "The address part")
(d "The decrement part")
(@to "stream"))
(ir-macro-transformer
(lambda (expression rename inject)
(match expression
((_ a b) `(cons ,a (delay ,b)))))))
(define (stream-ref s n)
@("Returns the nth element of the stream, consuming any non-memoized
elements."
(s "The stream to consume")
(n "The nth element")
(@to "object"))
(if (= n 0)
(stream-car s)
(stream-ref (stream-cdr s) (- n 1))))
(define (stream-map proc s)
@("Constructs a stream which is a {{proc}}-mapped {{s}}."
(proc "The procedure to apply")
(s "The stream to apply to")
(@to "stream"))
(if (stream-null? s)
stream-null
(cons-stream (proc (stream-car s))
(stream-map proc (stream-cdr s)))))
(define (stream-for-each proc s)
@("Applies {{proc}} to every element of {{s}}, consuming it."
(proc "The procedure to apply")
(s "The stream to apply to"))
(if (stream-null? s)
'done
(begin (proc (stream-car s))
(stream-for-each proc (stream-cdr s)))))
(define (display-stream s)
@("Displays every element of the stream."
(s "The stream to display"))
(stream-for-each display-line s))
(define (display-line x) (newline) (display x))
(define (stream-car stream)
@("Takes the first element of the stream."
(stream "The stream to take")
(@to "object"))
(car stream))
(define (stream-cdr stream)
@("Forces and returns the cdr of the stream."
(stream "The stream whose cdr to force")
(@to "stream"))
(force (cdr stream)))
(define (stream-enumerate-interval low high)
@("Enumerates the interval between {{low}} and {{high}} streamingly."
(low "The lower bound")
(high "The upper bound")
(@to "stream"))
(if (> low high)
stream-null
(cons-stream
low
(stream-enumerate-interval (+ low 1) high))))
(define (stream-filter pred stream)
@("Filters a stream, applying {{pred}}."
(pred "The predicate upon which to filter.")
(stream "The stream to filter")
(@to "stream"))
(cond ((stream-null? stream) stream-null)
((pred (stream-car stream))
(cons-stream (stream-car stream)
(stream-filter
pred
(stream-cdr stream))))
(else (stream-filter pred (stream-cdr stream)))))
(define stream->list
@("Converts a stream to a list, consuming it (or up to n elements)."
(stream "The stream to convert to a list")
(n "Optionally, the maximum number of elements to consume; otherwise: all elements")
(@to "stream"))
(case-lambda
((stream) (stream->list stream +inf.0))
((stream n)
(if (or (stream-null? stream) (zero? n))
'()
(cons (stream-car stream) (stream->list (stream-cdr stream) (- n 1)))))))
(define (scale-stream stream factor)
@("Scales the stream by a constant factor."
(stream "The stream to scale")
(factor "The factor by which to scale it")
(@to "stream"))
(stream-map (lambda (x) (* x factor)) stream))
(define (euler-transform s)
@("Applies [[http://en.wikipedia.org/wiki/Series_acceleration#Euler.27s_transform|Euler's
transform]], i.e. a linear sequence transformation for improved
convergence, to a stream."
(s "The stream to which to apply Euler's transform")
(@to "stream"))
(let ((s0 (stream-ref s 0))
(s1 (stream-ref s 1))
(s2 (stream-ref s 2)))
(cons-stream (- s2 (/ (square (- s2 s1))
(+ s0 (* -2 s1) s2)))
(euler-transform (stream-cdr s)))))
(define (make-tableau transform s)
@("Makes a tableau (i.e., a stream of streams) compounded from some
transformation."
(transform "The compounding transformation")
(s "The stream to transformatively compound")
(@to "stream"))
(cons-stream s (make-tableau transform (transform s))))
(define (accelerated-sequence transform s)
@("Accelerates some converging sequence."
(transform "The transformation to apply")
(s "The sequence to accelerate, e.g. [[euler-transform]]")
(@to "stream"))
(stream-map stream-car (make-tableau transform s)))
(define (integers-starting-from n)
@("Enumerates the integers starting from n streamingly."
(n "The number to start from")
(@to "stream"))
(cons-stream n (integers-starting-from (+ n 1))))
(define integers
@("Enumerates the positive integers streamingly.")
(integers-starting-from 1))
(define (interleave s1 s2)
@("Interleaves two streams."
(s1 "The interleavened stream")
(s1 "The interleaving stream")
(@to "stream"))
(if (stream-null? s1)
s2
(cons-stream (stream-car s1)
(interleave s2 (stream-cdr s1)))))
(define (pairs s t)
@("Generates the stream of pairs (S_i, T_j), where i <= j."
(s "The first stream to pair")
(t "The second stream to pair")
(@to "stream"))
(cons-stream
(list (stream-car s) (stream-car t))
(interleave
(stream-map (lambda (x) (list (stream-car s) x))
(stream-cdr t))
(pairs (stream-cdr s) (stream-cdr t)))))
(define (merge s1 s2)
@("Merges two ordered streams into one ordered result stream,
eliminating repetitions."
(s1 "Mergend")
(s2 "Merger")
(@to "stream"))
(cond ((stream-null? s1) s2)
((stream-null? s2) s1)
(else
(let ((s1car (stream-car s1))
(s2car (stream-car s2)))
(cond ((< s1car s2car)
(cons-stream
s1car
(merge (stream-cdr s1) s2)))
((> s1car s2car)
(cons-stream
s2car
(merge s1 (stream-cdr s2))))
(else
(cons-stream
s1car
(merge (stream-cdr s1)
(stream-cdr s2)))))))))
(define (list->stream list)
@("Takes a list and streamifies it."
(list "The list to streamify")
(@to "stream"))
(if (null? list) stream-null
(cons-stream (car list) (list->stream (cdr list)))))
| true |
e31a0354a2b226b00654e2f1a70d0e426ac0274b | 5a68949704e96b638ca3afe335edcfb65790ca20 | /cps-interpreter/tests/apply-map-list.scm | 406e3d1e8bd5749f05997b88d0c68d09721f5fb9 | []
| no_license | terryc321/lisp | 2194f011f577d6b941a0f59d3c9152d24db167b2 | 36ca95c957eb598facc5fb4f94a79ff63757c9e5 | refs/heads/master | 2021-01-19T04:43:29.122838 | 2017-05-24T11:53:06 | 2017-05-24T11:53:06 | 84,439,281 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 157 | scm | apply-map-list.scm |
(apply map list '((1 2 3)(10 20 30)))
;;
;; expect '((1 10)(2 20)(3 30))
;; some classic definition of transpose
(apply map + '((1 2 3)(10 20 30)))
;;
| false |
dc9862233fccb8c76829c2ef9910223566c6ccfd | fba55a7038615b7967256306ee800f2a055df92f | /vvalkyrie/2.3/ex-2-55.scm | 84400f57b00760b7a09ee0a2d6dda25623adbede | []
| no_license | lisp-korea/sicp2014 | 7e8ccc17fc85b64a1c66154b440acd133544c0dc | 9e60f70cb84ad2ad5987a71aebe1069db288b680 | refs/heads/master | 2016-09-07T19:09:28.818346 | 2015-10-17T01:41:13 | 2015-10-17T01:41:13 | 26,661,049 | 2 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 75 | scm | ex-2-55.scm | ;; ex 2.54
(car ''abracadabra)
;;=> (car (quote 'abracadabra))
;;=> quote
| false |
987ef201548fc12646f158e858090767bb068b34 | f1dda554fd9bf0dc7de60c84d9c87edf0e416ef8 | /TSPL/3.6.1.ss | 48281c955c1ba1eaae39194d538cd3140ff91340 | [
"MIT"
]
| permissive | shenxs/about-scheme | 3381680b6b685dc19df20c0a253eb9fd7530d663 | 7260128257b5b99fd516116de0387df92e2027e2 | refs/heads/master | 2021-11-23T11:15:36.994915 | 2021-10-24T02:39:29 | 2021-10-24T02:39:29 | 40,663,316 | 20 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 1,458 | ss | 3.6.1.ss | ;;修改gpa 使其可以处理x成绩,x不计入成绩
(library (grades)
(export gpa->grade gpa)
(import (rnrs))
(define in-range?
(lambda (x n y)
(and (>= n x) (< n y))))
(define-syntax range-case
(syntax-rules (- else)
[(_ expr ((x - y) e1 e2 ...) ... [else ee1 ee2 ...])
(let ([tmp expr])
(cond
[(in-range? x tmp y) e1 e2 ...]
...
[else ee1 ee2 ...]))]
[(_ expr ((x - y) e1 e2 ...) ...)
(let ([tmp expr])
(cond
[(in-range? x tmp y) e1 e2 ...]
...))]))
(define letter->number
(lambda (x)
(case x
[(a) 4.0]
[(b) 3.0]
[(c) 2.0]
[(d) 1.0]
[(f) 0.0]
[else (assertion-violation 'grade "invalid letter grade" x)])))
(define gpa->grade
(lambda (x)
(range-case x
[(0.0 - 0.5) 'f]
[(0.5 - 1.5) 'd]
[(1.5 - 2.5) 'c]
[(2.5 - 3.5) 'b]
[else 'a])))
(define-syntax gpa
(syntax-rules ()
[(_ g1 g2 ...)
(letrec ([f (lambda (l) (cond
[(null? l) '()]
[(eqv? 'x (car l)) (f (cdr l))]
[else (cons (letter->number (car l)) (f (cdr l)))]))])
(let ([ls (f '(g1 g2 ...))])
(if (= (length ls) 0)
0
(/ (apply + ls) (length ls)))))]))
)
| true |
7f3637eb2fcb2b9a0b7b6b377125cf083c286a88 | 3629e5c33ebbc3acbaa660fb324c26357098147c | /examples/glbook/example6-1.scm | 5e0d167e4a62e5219074cceacab96312aba6254e | [
"LicenseRef-scancode-x11-sg",
"MIT"
]
| permissive | shirok/Gauche-gl | f31a62ce4c2d91795f972b668861a77626b02cb5 | a569e3009314f81bc513827064e05869220c6a9d | refs/heads/master | 2023-06-07T15:56:17.514969 | 2023-06-01T06:56:48 | 2023-06-01T06:56:48 | 9,487,174 | 4 | 5 | MIT | 2018-09-24T21:39:18 | 2013-04-17T02:13:32 | C | UTF-8 | Scheme | false | false | 1,623 | scm | example6-1.scm | ;; Example 6-1 Blending Example
(use gl)
(use gl.glut)
(define *left-first* #t)
(define (init)
(gl-enable GL_BLEND)
(gl-blend-func GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA)
(gl-shade-model GL_FLAT)
(gl-clear-color 0.0 0.0 0.0 0.0)
)
(define (draw-left-triangle)
(gl-begin GL_TRIANGLES)
(gl-color '#f32(1.0 1.0 0.0 0.75))
(gl-vertex '#f32(0.1 0.9 0.0))
(gl-vertex '#f32(0.1 0.1 0.0))
(gl-vertex '#f32(0.7 0.5 0.0))
(gl-end))
(define (draw-right-triangle)
(gl-begin GL_TRIANGLES)
(gl-color '#f32(0.0 1.0 1.0 0.75))
(gl-vertex '#f32(0.9 0.9 0.0))
(gl-vertex '#f32(0.3 0.5 0.0))
(gl-vertex '#f32(0.9 0.1 0.0))
(gl-end))
(define (disp)
(gl-clear GL_COLOR_BUFFER_BIT)
(if *left-first*
(begin (draw-left-triangle)
(draw-right-triangle))
(begin (draw-right-triangle)
(draw-left-triangle)))
(gl-flush)
)
(define (reshape w h)
(gl-viewport 0 0 w h)
(gl-matrix-mode GL_PROJECTION)
(gl-load-identity)
(if (<= w h)
(glu-ortho-2d 0.0 1.0 0.0 (* 1.0 (/ h w)))
(glu-ortho-2d 0.0 (* 1.0 (/ w h)) 0.0 1.0))
)
(define (keyboard key x y)
(cond
((or (= key (char->integer #\t))
(= key (char->integer #\T)))
(set! *left-first* (not *left-first*))
(glut-post-redisplay))
((= key (char->integer #\escape))
(exit 0))
))
(define (main args)
(glut-init args)
(glut-init-display-mode (logior GLUT_SINGLE GLUT_RGB))
(glut-init-window-size 200 200)
(glut-create-window *program-name*)
(init)
(glut-reshape-func reshape)
(glut-keyboard-func keyboard)
(glut-display-func disp)
(glut-main-loop)
0)
| false |
a0ace3aa7478f190989f33fcf5166224be0a808f | 58381f6c0b3def1720ca7a14a7c6f0f350f89537 | /Chapter 2/2.1/Ex2.11.scm | 595daece386ba5d84c0eff9d66241c4181cc7084 | []
| 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 | 2,269 | scm | Ex2.11.scm | #lang planet neil/sicp
;;helpers
(define (make-interval a b) (cons a b))
(define (lower-bound interval) (car interval))
(define (upper-bound interval) (cdr interval))
(define (mul-interval x y)
(let ((x1 (lower-bound x))
(x2 (upper-bound x))
(y1 (lower-bound y))
(y2 (upper-bound y)))
(cond ((and (positive? x1) (positive? x2)
(positive? y1) (positive? y2))
;[+ +] * [+ +]
(make-interval (* x1 y1) (* x2 y2)))
((and (positive? x1) (positive? x2)
(negative? y1) (positive? y2))
;[+ +] * [- +]
(make-interval (* x2 y1) (* x2 y2)))
((and (positive? x1) (positive? x2)
(negative? y1) (negative? y2))
;[+ +] * [- -]
(make-interval (* x2 y1) (* x1 y2)))
((and (negative? x1) (positive? x2)
(positive? y1) (positive? y2))
;[- +] * [+ +]
(make-interval (* x1 y2) (* x2 y2)))
((and (negative? x1) (positive? x2)
(negative? y1) (positive? y2))
;[- +] * [- +]
(make-interval (min (* x2 y1) (* x1 y2))
(max (* x2 y2) (* x1 y1))))
((and (negative? x1) (positive? x2)
(negative? y1) (negative? y2))
;[- +] * [- -]
(make-interval (* x2 y1) (* x1 y1)))
((and (negative? x1) (negative? x2)
(positive? y1) (positive? y2))
;[- -] * [+ +]
(make-interval (* x1 y2) (* x2 y1)))
((and (negative? x1) (negative? x2)
(negative? y1) (positive? y2))
;[- -] * [- +]
(make-interval (* x1 y2) (* x1 y1)))
((and (negative? x1) (negative? x2)
(negative? y1) (negative? y2))
;[- -] * [- -]
(make-interval (* x2 y2) (* x1 y1))))))
(define a (make-interval 1 2))
(define b (make-interval -2 2))
(define c (make-interval -4 -1))
(mul-interval a a) ;; (1 4)
(mul-interval a b) ;; (-4 4)
(mul-interval a c) ;; (-8 -1)
(mul-interval b a) ;; (-4 4)
(mul-interval b b) ;; (-4 4)
(mul-interval b c) ;; (-8 8)
(mul-interval c a) ;; (-8 -1)
(mul-interval c b) ;; (-8 8)
(mul-interval c c) ;; (1 16)
| false |
55dfe5ff75e19ccd4553a68ddcd3ecf8625e900e | 557c51d080c302a65e6ef37beae7d9b2262d7f53 | /workspace/scheme-tester/notes/pl-12.scm | 4f3d35826ea03a3b1dba2d3583dc4fcf15fd6d21 | []
| no_license | esaliya/SchemeStack | 286a18a39d589773d33e628f81a23bcdd0fc667b | dcfa1bbfa63b928a7ea3fc244f305369763678ad | refs/heads/master | 2020-12-24T16:24:08.591437 | 2016-03-08T15:30:37 | 2016-03-08T15:30:37 | 28,023,003 | 3 | 4 | null | null | null | null | UTF-8 | Scheme | false | false | 5,407 | scm | pl-12.scm | ;-----------------------------------------------------------------------------------------
; Multiplying elements of a vector
;-----------------------------------------------------------------------------------------
; a simple implementation with letrec
(define product
(lambda (v)
(letrec ([loop (lambda (v init-acc)
(cond
[(null? v) init-acc]
[else (loop (cdr v) (* (car v) init-acc))]))])
(loop v 1))))
; now let's trace how many times we invoke the multiplication
; to do this let's define a function to do the multiplication
(define asterisk
(trace-lambda * (x y)
(* x y)))
; now change the original definition to use asterisk instead of built-in *
(define product2
(lambda (v)
(letrec ([loop (lambda (v init-acc)
(cond
[(null? v) init-acc]
[else (loop (cdr v) (asterisk (car v) init-acc))]))])
(loop v 1))))
; great! we saw that multiplication is wasted 6 times when our vector is (1 2 3 4 0 5)
; let's see if we can improve this by adding a zero check for the (car v)
(define product3
(lambda (v)
(letrec ([loop (lambda (v init-acc)
(cond
[(null? v) init-acc]
[(zero? (car v)) 0]
[else (loop (cdr v) (asterisk (car v) init-acc))]))])
(loop v 1))))
; nice, we reduced the number calls to asterisk to 4
; what would happen if we forget all the crap and use the direct style to implement this?
(define product4
(lambda (v)
(cond
[(null? v) 1]
[else (asterisk (car v) (product4 (cdr v)))])))
; same story as in product2, i.e. wasted 6 asterisk calls
; let's see the effect or zero check for (car v)
(define product5
(lambda (v)
(cond
[(null? v) 1]
[(zero? (car v)) 0]
[else (asterisk (car v) (product5 (cdr v)))])))
; again the same story as in product3, i.e. wasted 4 asterisk calls
; also the calculation happened in the reverse order w.r.t that of product3
; now, let's try to CPS this and see
(define product6-cps
(lambda (v k)
(cond
[(null? v) (k 1)]
[(zero? (car v)) (k 0)]
[else (product6-cps (cdr v) (lambda (w) (asterisk-cps (car v) w k)))])))
(define asterisk-cps
(trace-lambda * (m n k)
(k (* m n))))
; okay, this style cps simply wasted 4 asterisk calls
; the order was reverse as same as in product5
; let's try to write a cps version where we remember the initial continuation
; to be used for our zero case and a use a growing continuation for other work
; but I want to first check k-grow for the zero case as well
(define product7-cps
(lambda (v k-init)
(letrec ([loop (lambda (v k-grow)
(cond
[(null? v) (k-grow 1)]
[(zero? (car v)) (k-grow 0)]
[else (loop (cdr v) (lambda (w) (asterisk-cps (car v) w k-grow)))]))])
(loop v k-init))))
; aha! as I expected it too wasted 4 asterisk calls :)
; it's time to use k-init to avoid this in zero check
(define product8-cps
(lambda (v k-init)
(letrec ([loop (trace-lambda cps-loop (v k-grow)
(cond
[(null? v) (k-grow 1)]
[(zero? (car v)) (k-init 0)]
[else (loop (cdr v) (lambda (w) (asterisk-cps (car v) w k-grow)))]))])
(loop v k-init))))
; wonderful! as expected this time it didn't call the asterisk
; it's now time to play with call/cc
; I will use the good-old direct style with call/cc
; hmm I think i know the reason for this thing below, i.e. everytime we call the product9 a completely new thing
; pops up
(define product9
(lambda (v)
(call/cc
(lambda (k-init)
(cond
[(null? v) 1]
[(zero? (car v)) (k-init 0)]
[else (asterisk (car v) (product9 (cdr v)))])))))
; let's see if what I am thinking is correct, i.e. this should show some fat stack
(define product10
(lambda (v)
(call/cc
(lambda (k-init)
(letrec ([loop (trace-lambda loop (v)
(cond
[(null? v) 1]
[(zero? (car v)) (k-init 0)]
[else (asterisk (car v) (loop (cdr v)))]))])
(loop v))))))
; yep, it showed a fat stack
; let's dig down deep into the following usual cps version
(define product11
(lambda (v)
(call/cc
(lambda (k-init)
(letrec ([loop (trace-lambda loop (v k-grow)
(cond
[(null? v) (k-grow 1)]
[(zero? (car v)) (k-init 0)]
[else (loop (cdr v) (lambda (w) (k-grow (* (car v) w))))]))])
(loop v k-init))))))
; yea, this is a flat stack
; let's see if we can get the same out of product10 with another call/cc
; this seems to have some weirdness
(define product12
(lambda (v)
(call/cc
(lambda (k-init)
(letrec ([loop (trace-lambda loop (v k)
(cond
[(null? v) (k 1)]
[(zero? (car v)) (k-init 0)]
[else (asterisk (car v) (call/cc (lambda (t) (loop (cdr v) t))))]))])
(loop v k-init))))))
| false |
9cefdb9ab0c6106c333572f3b250450161b5e20c | e7d3de04e42b598d01b85327c3b8a1947f0347c9 | /belang_v3.scm | 3160f9e071fa8cb2d418ca847c091d7d105dc81b | []
| no_license | beoliver/belang | b8a73d9a7ebda15cab803e7d03a0fe6833005041 | 9a17d1ffa312b73dc3052657a1b710047c08de8a | refs/heads/master | 2020-05-16T21:32:51.724350 | 2015-06-02T08:59:13 | 2015-06-02T08:59:13 | 35,674,665 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 6,941 | scm | belang_v3.scm |
;; belang v3
;; To Do ::
;;; add self refernecing guards
;;; there is a problem with matching against the passed value...
;;; will add if conditional for testing
;; ((lambda* (n)
;; (if (= 0 n)
;; "finished"
;; (this (- n 1))))
;; 10)
(define primitives
;; loaded as the first frame of the environment
`((eq? . ,eq?) (= . ,=) (+ . ,+) (- . ,-) (* . ,*) (/ . ,/) (nil . nil) (newline . ,newline) (display . ,display) (id . ,(lambda (x) x))))
(define (lookup k env)
(if (null? env)
#f
(or (assoc k (car env))
(lookup k (cdr env)))))
(define (define-var! k v env)
(let ((kv (assoc k (car env))))
(if kv
(set-cdr! kv v)
(set-car! env (cons (cons k v) (car env))))))
;; predicates
(define (tagged? tag xs)
(and (list? xs)
(eq? tag (car xs))))
(define (self-evaluating? x)
(or (number? x) (boolean? x) (string? x) (char? x) (tagged? 'quote x)))
(define (primitive-procedure? x)
(procedure? x))
(define (compound-procedure? x)
;; internal representation of lambdas
(tagged? 'procedure x))
(define (guarded-procedures? x)
;; many internal lambdas under one definition
(tagged? 'guarded x))
(define (special-form? x)
;; (display "special-form?")(newline)
(and (list? x) (assoc (car x) special-forms)))
;; special forms -- only for parsing
(define (sf-if exp env)
(let ((evaluated-predicate (meta-eval (cadr exp) env))
(then-branch (caddr exp))
(else-branch (cadddr exp))) ;; will fail on (if #f 1)
(if evaluated-predicate
(meta-eval then-branch env)
(meta-eval else-branch env))))
(define (sf-define sf env)
(let ((var (cadr sf))
(val (caddr sf)))
(define-var! var (meta-eval val env) env)))
(define (sf-lambda sf env)
(let ((params (cadr sf))
(body (cddr sf)))
`(procedure ,params ,body ,env)))
(define (sf-lambda* sf env)
;; uses 'this as a reference back to it's definition in it's own scoped environment
(let* ((params (cadr sf))
(body (cddr sf))
(this-env (cons '() env))
(this-lambda `(procedure ,params ,body ,this-env)))
(set-car! this-env (cons (cons 'this this-lambda) (car this-env)))
this-lambda))
(define (sf-guard sf env)
(let* ((untagged-lambdas (cdr sf))
(tagged-lambdas
(map (lambda (x)
(let* ((params (car x))
(body (cdr x)))
`(procedure ,params ,body ,env))) untagged-lambdas)))
(cons 'guarded tagged-lambdas)))
(define (sf-guard* sf env)
(let* ((untagged-lambdas (cdr sf))
(tagged-lambdas
(map (lambda (x)
(let* ((params (car x))
(body (cdr x))
(this-env (cons '() env))
(this-lambda `(procedure ,params ,body ,this-env)))
(set-car! this-env (cons (cons 'this this-lambda) (car this-env)))
this-lambda)) untagged-lambdas)))
(cons 'guarded tagged-lambdas)))
(define (sf-fun sf env)
(let* ((clauses (cdr sf))
(parsed-clauses
(map (lambda (clause) (parse-fun-clause (list) clause)) clauses)))
(sf-guard (cons 'guard parsed-clauses) env))) ;; now eval and convert to lambdas
(define (parse-fun-clause head body)
(if (eq? (car body) '->)
(cons (reverse head) (cdr body))
(parse-fun-clause (cons (car body) head) (cdr body))))
(define special-forms
`((define . ,sf-define)
(lambda . ,sf-lambda)
(lambda* . ,sf-lambda*)
(fun . ,sf-fun)
(guard . ,sf-guard)
(guard* . ,sf-guard*)
(if . ,sf-if)
))
(define (eval-special-form sf env)
;; (display "eval-special-form") (newline)
(let ((special-form (cdr (assoc (car sf) special-forms))))
(special-form sf env)))
;; accessors
(define procedure-params cadr)
(define procedure-body caddr)
(define procedure-env cadddr)
;; eval
(define (meta-eval x env)
;; (display "meta-eval")(newline)
(cond ((self-evaluating? x) x)
((symbol? x) (cdr (lookup x env)))
((special-form? x) (eval-special-form x env))
(else ; application
(let ((evaluated-head (meta-eval (car x) env))
(evaluated-body (map (lambda (arg) (meta-eval arg env)) (cdr x))))
(meta-apply evaluated-head evaluated-body)))))
(define (meta-eval-sequence xs env)
;; (display "meta-eval-sequence")(newline)
(if (null? (cdr xs))
(meta-eval (car xs) env)
(begin (meta-eval (car xs) env)
(meta-eval-sequence (cdr xs) env))))
;; apply
(define (meta-apply x args)
;; (display "meta-apply")(newline)
(cond ((primitive-procedure? x) (apply x args))
((compound-procedure? x)
(if (null? (procedure-params x))
(meta-eval-sequence (procedure-body x) (procedure-env x))
(let ((y (curry-procedure x args)))
(if (null? (procedure-params y))
(meta-eval-sequence (procedure-body y) (procedure-env y))
y))))
((guarded-procedures? x)
(let ((y (curry-guarded-procedures x args)))
(if (compound-procedure? y) ; we found a match
(meta-eval-sequence (procedure-body y) (procedure-env y))
y)))))
;; handling partial application (the meat of it)
;; curry procedure seems to work for normal lambdas
(define (curry-procedure proc args)
(let ((params (procedure-params proc))
(body (procedure-body proc))
(env (procedure-env proc))
(new-frame (list)))
(call-with-current-continuation
(lambda (return)
(for-each (lambda (param arg)
(cond ((and (self-evaluating? param) ; param is num,bool,char etc
(not (equal? param arg))); arg is NOT identical!
(return 'curry-pattern-err)); return error
((and (self-evaluating? param) ; param is num,bool,char etc
(equal? param arg)) ; arg is identical
(set! params (cdr params))) ; remove param as it matched
(else
(set! params (cdr params)) ; remove param as it matched
(set! new-frame ; add binding to new-frame
(cons (cons param arg)
new-frame)))))
params args)
(if (null? new-frame) ; empty is all params were self evaluating
`(procedure ,params ,body ,env)
`(procedure ,params ,body ,(cons new-frame env)))))))
(define (curry-guarded-procedures proc args)
(let ((procedures (cdr proc))
(matching-procedures (list)))
(call-with-current-continuation
(lambda (return)
(for-each (lambda (proc)
(let ((new-proc (curry-procedure proc args)))
(cond ((eq? new-proc 'curry-pattern-err) 'do-nothing)
((null? (procedure-params new-proc))
(return new-proc)) ; return IMMEDIATELY as we are good
(else (set! matching-procedures
(cons new-proc matching-procedures))))))
procedures)
(if (null? matching-procedures)
(display "NO PATTERN FOUND FOR GUARD")
(cons 'guarded (reverse matching-procedures)))))))
;; repl (avoid infinite loops)
(define (repl)
(display "\n ?> ")
(let ((x (meta-eval (read) global-env)))
(cond ((compound-procedure? x) (display '<compound-procedure>))
((guarded-procedures? x) (display '<guarded-procedures>))
(else (display x)))
(repl)))
;; global state
(define global-env (list '() primitives))
| false |
72146a2af467b6a35bcb3591ea350d7cd9eb84a8 | d63c4c79d0bf83ae646d0ac023ee0528a0f4a879 | /cs444/do.scm | ee0d279cc223dd26ac3c9b9b889c775e9ad87605 | []
| no_license | stratigoster/UW | 4dc31f08f7f1c9a958301105dcad481c39c5361f | 7a4bff4f1476607c43278c488f70d01077b1566b | refs/heads/master | 2021-07-07T04:52:01.543221 | 2011-08-15T05:08:48 | 2011-08-15T05:08:48 | 10,858,995 | 1 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 62,763 | scm | do.scm | (require (lib "match.ss"))
(require (lib "trace.ss"))
(require (lib "pretty.ss"))
(load "types.scm")
(load "macro.scm")
(define 1- (lambda (n) (- n 1)))
(define myapply (lambda (x) (apply x ())))
(define pkg-name #f)
(define do-record? #f)
(define rangeT #f)
(define infun? #f)
(define find-ref
(lambda (lst)
(- (length lst) (length (member #t (map (match-lambda (#f #f) (_ #t)) lst))))))
(define ty-error-expr
(lambda s
(eval `(ty-error ,line ,column '(error alpha) ,@s))))
(define ty-error-stmt
(lambda s
(eval `(ty-error ,line ,column '(void) ,@s))))
(define except-list '("numeric_error" "constraint_error"))
(define default-except '(("numeric_error" "ZeroDivisionError") ("constraint_error" "TypeError")))
(define uses '())
(define classs '())
(define prev-class #f)
(define main-defined #f)
(define freeInt 0)
(define getFreeInt
(lambda (b)
(set! freeInt (+ 1 freeInt))
(if (and b (not (member freeInt except-list)))
(set! except-list (cons freeInt except-list)))
freeInt))
(define resolve-enum
(lambda (expr type)
(match expr
(('VAR x) (if (assoc x type)
(list (cadr (assoc x type)) 0)
(list 'VAR x)))
(x x))))
(define Union
(lambda (e1 e2)
(without #f (map (lambda (s) (member s (cdr e2))) (cdr e1)))))
(define matcht (make-hash-table 'equal))
(define mama
(lambda (params defn)
(let ((ret
(cond
((equal? 'void defn) (or (equal? 'void params) (equal? 'alpha params)))
((or (equal? 'alpha defn) (equal? 'alpha params)) #t)
((list? defn) (begin
(call/cc
(lambda (k)
(for-each
(lambda (x)
(match x
((x M T e) (hash-table-put! matcht x (list #f T e)))
(_ (k #f))))
defn)))
(let ((ret (m2 params defn)))
(if (not ret) ;; no match
#f
(let ((blah (map
(lambda (x)
(list (car x)
(cadr x)
(caddr x)
(list (car (hash-table-get matcht (car x) #f))
(cadr (hash-table-get matcht (car x) #f)))))
defn)))
(let ((retval (set-defaults blah defn)))
(if (checkcheck retval)
retval
#f)))))))
(else #f))))
(begin
(set! matcht (make-hash-table 'equal))
ret))))
(define set-defaults
(lambda (params defn)
(if (null? params)
'()
(begin
(cons (match (car params)
((pname pinout pT (#f pTT)) (list pname pinout pT (list (match (car defn) ((_ _ _ (v _)) v)) pTT)))
(x x))
(set-defaults (cdr params) (cdr defn)))))))
;; ( ("x" 5 'int #f) ("y" 10 'int #f) ...)
(define checkcheck
(lambda (L)
(not (in-list? #f (map (lambda (x) (car (cadddr x))) L)))))
(define m2
(lambda (params defn)
(if (null? params)
#t
(if (list? params)
(match (car params)
((x as (v T)) (let ((ret (hash-table-get matcht x #f)))
(if ret
(if (not (car ret)) ;; not defined yet
(if (equal? T (lookup 'TYPE (cadr ret)))
(begin
(hash-table-put! matcht x (list v T (caddr ret)))
(m2 (cdr params) (if (list? defn)
(match (car defn)
((a val typ exp) (let ((blah (hash-table-get matcht a #f)))
(if (car blah) ;; already defined
(cdr defn)
defn)))
(_ #f))
#f)))
#f)
#f)
#f)))
((v T) (if (not (null? defn))
(match (car defn)
((x M TT e) (let ((ret (hash-table-get matcht x #f)))
(if ret
(if (not (car ret)) ;; not defined yet
(if (equal? T (lookup 'TYPE TT))
(begin
(hash-table-put! matcht x (list v T e))
(m2 (cdr params) (cdr defn)))
#f)
#f)
#f)))
(_ #f))
#f))
(_ #f))
(equal? 'void defn)))))
; ((x 'as (v T)) (v T) ... )
; ((x MODE T #f) (y MODE T e)...)
; :
; ((x v) (y v)...)
(define Match
(lambda (params defn)
(cond
((and (eq? 'void params) (eq 'void params)) '())
((eq? 'void params) #f)
((eq? 'void params) #f)
(else
(call/cc
(lambda (koo)
(let aloop ((top params)
(bot defn)
(vis '()))
(cond
((and (null? top) (null? bot) (null? vis)) '())
((and (null? top) (null? bot)) (koo #f))
((and (null? top) (null? vis)) (koo #f))
((null? bot) (koo #f))
((null? top)
(cond
((assoc (caar bot) vis)
(cons (assoc (car bot) vis)
(aloop top trest
(car brest) (cdr brest)
(without (assoc (car bot) vis)
vis))))
((list-ref (car bot) 3)
(cons (list (list-ref bot 3) (list-ref bot 2))
(aloop top trest
(car brest) (cdr brest)
vis)))
(else (koo #f))))
(else
((match (list (car top) (car bot))
(((v T) (x mode U w))
(cond
((equal? T U)
(cons (list x mode U v)
(aloop (cdr top) (cdr bot) vis)))
((assoc x vis)
(koo #f))))
(((x 'as (v T)) (y mode U w))
(if (and (equal? x y) (equal? T U))
(cons (list y mode U v)
(aloop (cdr top (cdr bot) vis)))
(aloop (cdr top) bot (cons (list x 'as (v T)) vis))))
(_ (koo #f)))))
))))))))
(define do-scope '())
;------------
(define do-start
(match-lambda
((p ps eof)
(let* ((p (p))
(ps (ps))
(eof (eof)))
(cons p ps)))))
(define do-package
(match-lambda
((gen pkg p-rest)
(let* ((gen (gen)) (pkg (pkg)) (p-rest (p-rest)))
(unless (null? gen)
(begin
(ty-error line column p-rest "Generics aren't supported")
(exit))
p-rest)))))
(define do-package-rest
(lambda (pkg) (car (map myapply pkg))))
(define do-package-decl
(match-lambda
((i is head private body beginn except end j semi)
(set! do-scope '(PacDecl))
(let* ((i (match (i) (("Id" l id) id) (_ 'error)))
(line line)
(column (- column (caddr next-token)))
(t0 (if *scope* (mdisplay "- Package name is: " i)))
(t1 (set! pkg-name i))
(t2 (create-scope!))
(is (is))
(head (apply append (head)))
(private (private))
(t3 (set! do-scope '(PacBody)))
(body (body))
(beginn (beginn))
(except (except))
(end (end))
(j (match (j) ((("Id" l id)) id) (() i) (_ 'error)))
(semi (semi))
(pkg (if (not (and (null? body) (null? beginn) (null? except)))
'PKG 'PKG-DECL))
(t4 (if (equal? pkg-name "main")
(if main-defined
(ty-error-stmt "Main package has already been defined"))
(if (member pkg-name classs)
(ty-error-stmt "Package `" pkg-name "' has already been defined"))))
)
(set! do-scope '())
(if (and (equal? pkg-name "main") (eq? pkg 'PKG)) (set! main-defined #t))
(if prev-class (ty-error-stmt "A package declaration must be followed by its body"))
(if (eq? pkg 'PKG-DECL) (set! prev-class pkg-name) (set! prev-class #f))
(set! classs (cons pkg-name classs))
(cond
((or (symbol? i) (symbol? j)) '(error))
((not (equal? i j))
(ty-error line column '(error)
"Package name declaration and closure are not the same"))
(else
(list pkg
i
(list 'USE (let ((u uses)) (set! uses '()) u))
(list 'HEAD (without 'void head))
(list 'PRIVATE (match private
((("private") private) (apply append (apply append private)))
(_ '())))
(list 'BODY (match body
((("body") body) (without 'void (apply append (apply append body))))
(_ '())))
(list 'BEGIN (match beginn
((("begin") beginn) (apply append beginn))
(_ '())))
(list 'EXCEPT (match except
((("exception") except) (apply append except))
(_ '())))
)))))
(_ 'void)))
(define do-package-body
(lambda (lst)
(match (cons ((car lst)) (cons ((cadr lst)) (cddr lst)))
((("body")("Id" l i) is ds beginn except end j semi)
(let* ((line line)
(column (- column (caddr next-token)))
(is (is))
(t0 (set! pkg-name i))
(t1 (if *scope* (mdisplay "- Package body is: " i)))
(t2 (set! do-scope '(PacBody)))
(t3 (if (not (member pkg-name classs))
(ty-error-stmt "Package `" pkg-name "' must be first defined")))
(ds (ds))
(beginn (beginn))
(except (except))
(end (end))
(j (match (j) ((("Id" l id)) id) (() i) (_ 'error)))
(semi (semi)))
(if (equal? pkg-name "main") (set! main-defined #t))
(if (not (equal? pkg-name prev-class)) (ty-error-stmt "Package body must follow head of the same package"))
(set! prev-class #f)
(set! do-scope '())
(set! classs (cons pkg-name classs))
(cond
((or (symbol? i) (symbol? j)) '(error))
((not (equal? i j))
(ty-error line column '(error)
"Package name declaration and closure are not the same"))
(else
(list 'PKG-BODY
i
(list 'USE (let ((u uses)) (set! uses '()) u))
(list 'DEF (apply append (apply append ds)))
(list 'BEGIN (match beginn
((("begin") beginn) (apply append beginn))
(_ '())))
(list 'EXCEPT (match except
((("exception") except) (apply append except))
(_ '())))
)))))
(_ 'void)
)))
(define do-head
(lambda (lst)
((car lst))))
(define do-decl (lambda (lst) (map myapply lst)))
(define do-except
(lambda (lst)
(match (map myapply lst)
((("when") rest)
rest)
(_ '(void)))))
(define do-except-tail
(lambda (lst)
(match (map myapply lst)
((("others") ("=>") stmt)
(list (list 'EELSE (apply append stmt))))
((id ids ("=>") stmt)
(map (match-lambda
(("Id" lin id)
(if (or (lookup 'EXCEPT id) (assoc id default-except))
(list 'EIF id (apply append stmt))
(ty-error line column '(void) "Unknown exception handled: " id)))
(_ '(void)))
(cons id (let aloop ((lst ids))
(if (null? lst) '()
(cons (cadr lst) (aloop (cddr lst))))))))
(_ '(void)))))
(define do-use
(lambda (lst)
(match (map myapply lst)
((("use") ("Id" lin id) ids (";"))
(if (equal? id pkg-name)
(ty-error line column '(void) "Can't USE same package")
(unless (member id classs)
(ty-error line column '(void) "Unknown class: " id)
(begin
(set! uses (cons id uses))
(let aloop ((lst ids))
(if (or (null? lst) (< (length lst) 2))
'(void)
(match (cadr lst)
(("Id" lin id)
(if (equal? id pkg-name)
(ty-error line column '(void) "Can't USE same package")
(unless (member id classs)
(ty-error line column '(void) "Unknown class: " id)
(if (member id uses)
(ty-error line column '(void) "Class is already being used: " id)
(begin
(set! uses (cons id uses))
(aloop (cddr lst)))))))
(_ '(void)))))))))
(_ '(void)))))
(define do-var-decl
(match-lambda
((id ids col constant T assign semi)
(let* ((id (caddr (id)))
(ids (call/cc
(lambda (k)
(let aloop ((ids (ids)))
(cond
((null? ids) '())
(else (match (car ids)
((",") (aloop (cdr ids)))
(("Id" l id) (cons id (aloop (cdr ids))))
(else (k '())))))))))
(ids (cons id ids))
(col (col))
(line line)
(column (1- column))
(constant (match (constant) ((("contant")) #t) (_ #f)))
(T (T))
(assign (assign))
(e (if (or (null? assign) (eq? 'alpha (type-of assign)) (eq? T 'except)) #f (cadr assign)))
(e (if e (let aloop ((TT (lookup 'TYPE T))
(t (type-of e))
(ret (val-of e))
(vis '()))
(let ((tt (lookup 'TYPE t)))
(if (or (equal? T t) (not (access? tt)))
(list ret t)
(if (member (cadr tt) vis)
(ty-error line column #f
"Circular accessor types")
(aloop TT (cadr tt) (list 'DEREF ret) (cons (cadr tt) vis))))))
#f))
(semi (semi)))
(if (eq? T 'except)
(if (or constant e)
(ty-error line column '(void) "Invalid exception declaration")
(begin (map (lambda (id)
(insert-info! 'EXCEPT id 'exception)
(if (not (member id except-list))
(set! except-list (cons id except-list))))
ids)
'(void)))
(cond
((and (list? T) (alpha? (type-of T))) '(void))
((and e (enum? (type-of e)) (list? (type-of e)) (> (length (type-of e)) 2) (not (member T (cdr (type-of e)))))
(ty-error line column 'void "Ambiguous enumerator type"))
((and e (enum? (type-of e)) (list? (type-of e)) (member T (cdr (type-of e))))
(map (lambda (id)
(if (insert-info! 'VAR id T)
(if (and e (not (alpha? (type-of e))))
(if (lookup 'TYPE T)
; (list 'STORE id (list (cadr (assoc (cadr (val-of e)) (cadr (lookup 'TYPE T)))) 0))
(list 'INIT id (if (enum? T)
(resolve-enum (val-of e) (cadr (lookup 'TYPE T)))
(val-of e)))
'void)
'void)
'void))
ids))
((and e (eq? 'typ (type-of e)))
(ty-error line column '(void) "Expression contains type name, needed variable name"))
((and e (not (U T (type-of e))))
(ty-error line column (if do-record? (list (list id 'alpha)) '(void))
"Incompatible types in assignment of `" (printt (type-of e)) "' to `" (printt T) "'"))
(else (if do-record?
(map (lambda (id)
(list id T e))
ids)
(apply append (map (lambda (id)
(begin (if (insert-info! 'VAR id T)
(if (and e (not (alpha? (type-of e))))
(list (list 'INIT id (val-of e)))
(list (list 'INIT id (default-value (lookup 'TYPE T)))))
'(void))))
ids))))))))
(_ 'VAROR)))
(define default-value
(match-lambda
(('record rest) (list 'Record (map (match-lambda ((name type id) (list name (if id (val-of id) (default-value (lookup 'TYPE type))))) (_ 'void)) rest)))
(('access T) (list 'Access))
(_ '(0 0))))
(define do-var-type
(match-lambda
((T Ts) (let* ((T (T))(Ts (Ts)))
(match (list T Ts)
((("Id" l T) ())
(let ((t (lookup 'TYPE T)))
(cond
((void? t)
(ty-error line column 'alpha
"Missing full type declaration for `" T "' before use"))
((or (int? t) (bool? t) (astring? t) (float? t)) t)
(t (if (and (array? t)
(match (cadr t)
((('UNCONST i)) #t)
(_ #f)
))
(ty-error
line column 'alpha
"Unconstrained array needs its dimensions specified")
T))
(else
(ty-error line column 'alpha
"Uninitialized type `" T "'")))))
(_ 'VERR))))
((except) (let* ((except (except)))
'except))))
(define do-var-type2 (lambda (lst) (map myapply lst))) ;!!!!!!!!!!!!!!!!!!!!!!!!!!
(define do-type-decl
(match-lambda
((type id rest)
(let* ((type (type))
(id (id))
(rest (rest)))
(match id
(("Id" l id)
(if (and (list? rest) (alpha? (type-of rest)))
'(void)
(begin (insert-info! 'TYPE id rest)
'(void))))
(_ '(void)))))
((sub id is T semi)
(let* ((sub (sub))
(id (id))
(is (is))
(T (T))
(semi (semi)))
(match id
(("Id" l id)
(if (and (list? T) (alpha? (type-of T)))
'void
(begin (insert-info! 'TYPE id T)
'(void))))
(_ '(void)))))
(_ 'TERRO)))
(define do-type-decl2
(match-lambda
((semi) (let* ((semi (semi)))
'void))
((is rest) (let* ((is (is))
(rest (rest)))
rest))
(_ 'T2ERRO)))
(define do-type-decl3
(match-lambda
((decl) (decl))
((private semi) (let* ((private (private))
(semi (semi)))
'void))
(_ 'T3ERRO)))
(define do-enum-decl
(match-lambda
((open id ids close semi)
(let* ((open (open))
(id (id))
(ids (ids))
(close (close))
(semi (semi)))
(match id
(("Id" l id)
(list 'enum (cons (list id 0)
(let aloop ((ids ids) (num 1))
(cond
((null? ids) '())
(else (match (car ids)
(("Id" l id) (cons (list id num)
(aloop (cdr ids) (+ num 1))))
((",") (aloop (cdr ids) num))
(_ '()))))))))
(_ 'alpha))))
(_ 'ENUMERR)))
(define do-array-decl
(lambda (lst)
(match (map myapply lst)
((array open bound bound2 close of ("Id" l type) semi)
(unless (lookup 'TYPE type)
(ty-error-expr "Undefined type `" type "'")
(list 'array
(cons bound
(let aloop ((c1 (match bound (('UNCONST i) #t) (_ #f)))
(lst bound2))
(cond
((null? lst) '())
((eq? 'alpha (car lst)) (aloop c1 (cdr lst)))
(else (let* ((comma (car lst))
(bound (cadr lst))
(c2 (match bound (('UNCONST i) #t) (_ #f))))
(if (eq? c1 c2)
(cons bound (aloop c2 (cddr lst)))
(ty-error line column '()
"Mixing unconstrained and constrained array definitions")))))))
type)))
(_ '(void)))))
(define do-bound
(match-lambda
((a b)
(match (list (a) b)
((("range") range) (range))
(((id 'typ) r)
(set! rangeT id)
(let ((r (r)))
(if (match r ((('expr e)) #t) (_ #f))
(ty-error line column 'alpha "Invalid range: type..expression")
(let* ((T (lookup 'TYPE id)))
(cond
((not (or (enum? T) (int? T) (bool? T)))
(ty-error line column 'alpha
"Array indices must all be of enumeratable type, given `" id "'"))
(else
(match r
(('unconst) (list 'UNCONST id))
((('RANGE a b t)) (list 'RANGE a b t))
(() (cond
((int? T) (list 'RANGE '(FIRST int) '(LAST int) 'int))
((bool? T) (list 'RANGE '(0 0) '(1 1) 'bool))
(else (list 'RANGE '(0 0) (list (1- (length (cadr T))) 0) id))))
(_ 'alpha))))))))
((e1 e2)
(let ((e2 (e2)))
(match e2
((('to e2))
(if (and (or (int? (type-of e1)) (bool? (type-of e1)))
(equal? (type-of e1) (type-of e2)))
(list 'RANGE (val-of e1) (val-of e2) (type-of e1))
(let ((t1 (if (string? (type-of e1)) (list 'enum (type-of e1)) (type-of e1)))
(t2 (if (string? (type-of e2)) (list 'enum (type-of e2)) (type-of e2))))
(if (and (enum? t1) (enum? t2))
(let ((union (Union t1 t2)))
(cond
((null? union)
(ty-error line column 'alpha "Not compatible enumerator instances"))
((> (length union) 1)
(ty-error line column 'alpha "Ambiguous enumarator range"))
(else
(let ((v1 (if (string? (type-of e1))
(val-of e1)
(list (cadr (assoc (cadr (val-of e1))
(cadr (lookup 'TYPE (caar union)))))
0)))
(v2 (if (string? (type-of e2))
(val-of e2)
(list (cadr (assoc (cadr (val-of e2))
(cadr (lookup 'TYPE (caar union)))))
0))))
(list 'RANGE v1 v2 (caar union))))))
(ty-error line column 'alpha "Incompatible range types")))))
(_ (ty-error line column 'alpha
"Expression must be followed by .. and expression")))))
;(_ 'alpha)
))))
(define do-bound2
(lambda (lst)
(match (map myapply lst)
((("..") e) (list 'to e))
((("range") r) r)
(_ 'alpha))))
(define do-bound3
(lambda (lst)
(match (map myapply lst)
((("<>")) 'unconst)
((t) t))))
(define do-range
(lambda (lst)
(match (map myapply lst)
((e1 ("..") e2)
(cond
((or (alpha? (type-of e1))
(alpha? (type-of e2))) 'alpha)
((and (or (int? (type-of e1))
(bool? (type-of e1)))
(equal? (type-of e1) (type-of e2))
(if rangeT
(or (eq? (lookup 'TYPE rangeT) (type-of e1))
(eq? (lookup 'TYPE rangeT) (type-of e2)))
#t))
(list 'RANGE (val-of e1) (val-of e2) (type-of e1)))
(else
(let ((t1 (if (string? (type-of e1)) (list 'enum (type-of e1)) (type-of e1)))
(t2 (if (string? (type-of e2)) (list 'enum (type-of e2)) (type-of e2))))
(if (and (enum? t1) (enum? t2))
(let* ((union (Union t1 t2))
(union (if rangeT (if (assoc rangeT union) (list (assoc rangeT union)) '()) union)))
(set! rangeT #f)
(cond
((null? union)
(ty-error line column 'alphga "Not compatible enumerator instances"))
((> (length union) 1)
(ty-error line column 'alpha "Ambiguous enumarator range"))
(else
(let ((v1 (if (string? (type-of e1))
(val-of e1)
(list (cadr (assoc (cadr (val-of e1))
(cadr (lookup 'TYPE (caar union)))))
0)))
(v2 (if (string? (type-of e2))
(val-of e2)
(list (cadr (assoc (cadr (val-of e2))
(cadr (lookup 'TYPE (caar union)))))
0))))
(list 'RANGE v1 v2 (caar union))))))
(ty-error line column 'alpha "Incompatible range types"))))))
(_ 'alpha)
)))
(define do-record-decl
(match-lambda
((rec1 component end rec2 semi)
(let* ((rec1 (rec1))
(enable (set! do-record? #t))
(component (component))
(disable (set! do-record? #f))
(end (end))
(rec2 (rec2))
(semi (semi)))
component))
(_ 'RERROR)))
(define do-component
(lambda (lst)
(match (map myapply lst)
((("null") (";")) '(record (("" void))))
((var vars)
(let* ((vars
(match var
(v
(list 'record
(append v
(let aloop ((vars (apply append vars)))
(if (null? vars)
'()
(match (car vars)
((id T e) (cons (list id T e)
(aloop (cdr vars))))
(x '())))))))))
(ht (make-hash-table 'equal))
(vs (begin (for-each (lambda (var)
(hash-table-put!
ht
(car var)
(+ 1
(hash-table-get
ht
(car var)
(lambda () 0)))))
(cadr vars))
(hash-table-for-each
ht
(lambda (v n)
(if (> n 1)
(ty-error line column vars
"conflicting declarations of variable " v)))))))
vars))
(_ 'CERROR))))
(define do-access-decl
(lambda (lst)
(match (cadr (map myapply lst))
(("Id" l id) (if (lookup 'TYPE id)
(list 'access id)
(ty-error line column 'alpha
"`" id "' is undefined")))
(_ '(void)))))
(define do-fun-sig
(lambda (lst)
(set! infun? #t)
(match (map myapply lst)
((function (and name (? string?)) () return ("Id" l T))
(set! infun? #f)
(if (lookup 'TYPE T)
(list name (list '-> 'void (if (symbol? (lookup 'TYPE T)) (lookup 'TYPE T) T)))
(ty-error line column '()
"Undefined return type")))
((function (and name (? string?)) (params) return ("Id" l T))
(set! infun? #f)
(if (lookup 'TYPE T)
(list name (list '-> params (if (symbol? (lookup 'TYPE T)) (lookup 'TYPE T) T)))
(ty-error line column '()
"Undefined return type")))
(_ 'alpha))))
(define do-fun-name
(lambda (lst)
(match (map myapply lst)
((("Id" l name)) name)
((("Str" s)) (if (member s '("and" "or"
"=" "/=" "<" "<=" ">" ">="
"+" "-" "&"
"*" "/" "mod"
"**" "abs" "not"))
s
(ty-error line column 'error
"Invalid overloading of a built-in function: `" s "' doesn't exist")))
(_ 'error))))
(define do-fun-decl
(lambda (lst)
(match (map myapply lst)
((((and name (? string?)) rest) semi)
(let ((N (getFreeInt #f)))
(insert-info! 'FUN-DECL name (cons N rest))
'(void)))
(_ '(void)))))
(define do-fun-body
(match-lambda
((sig mid semi)
(let ((sig (sig))
(NUMBER 0))
(match (list (peek-token) sig)
(("is" ((and name (? string?)) rest))
(let ((N (without #f
(map (lambda (x)
(if (equal? (cdr x) (cadr sig))
(car x) #f))
(or (lookup 'FUN name) '())))))
(if (null? N)
(begin
(set! NUMBER (getFreeInt #f))
(insert-info! 'FUN-BODY name (cons NUMBER rest)))
(set! NUMBER (car N)))))
(_ (set! NUMBER (getFreeInt #f))
(insert-info! 'FUN-DECL (car sig) (cons NUMBER (cadr sig)))))
(append-scope!)
(if *scope* (mdisplay "-- Scope start of function:" (car sig)))
(set! do-scope
(cons 'FunBody
(cons (match sig
(((? string?) ('-> para ret)) ret)
(_ 'alpha))
do-scope)))
(if (list? (cadadr sig))
(for-each (lambda (lst)
(match lst
((name mode T e) (insert-info! 'VAR name (lookup 'TYPE T)))
(_ '())))
(cadadr sig)))
(match (cons sig (map myapply (list mid semi)))
((((and name (? string?)) rest) () semi)
(delete-scope!)
(if *scope* (mdisplay "-- Scope end of function:" (car sig)))
(set! do-scope (cddr do-scope))
(list (list 'SIG (string-append "_" (number->string NUMBER) "_" (car sig)))))
((((and name (? string?)) rest) (is ds beginn except end id) semi)
(delete-scope!)
(if *scope* (mdisplay "-- Scope end of function:" (car sig)))
(set! do-scope (cddr do-scope))
(if (or (null? id) (match id ((("Id" l id)) (equal? id name)) ((id) (equal? id name))))
(list (list 'FUN
(string-append "_" (number->string NUMBER) "_" name)
(match sig
((name para) (match para
(('-> 'void T) '())
(('-> (and para (? list-of-lists?)) T) (map car para))
(_ '())))
(_ '()))
(list 'DEF (apply append (apply append ds)))
(list 'BEGIN (match beginn
((b beginn) (apply append beginn))
(_ '())))
(list 'EXCEPT (match except
((e except) (apply append except))
(_ '())))
))
(ty-error-stmt "Function's names don't correspond")))
(_ (delete-scope!)
(if *scope* (mdisplay "-- Scope end of function:" (car sig)))
(set! do-scope (cddr do-scope))
'(void)))))
(_ '(void))))
(define do-proc-sig
(lambda (lst)
(match (map myapply lst)
((function ("Id" l name) ())
(list name (list '-> 'void 'void)))
((function ("Id" l name) (params))
(list name (list '-> params 'void)))
(_ 'alpha))))
(define do-proc-decl
(lambda (lst)
(match (map myapply lst)
((((and name (? string?)) rest) semi)
(let ((N (getFreeInt #f)))
(insert-info! 'FUN-DECL name (cons N rest))
'(void)))
(_ '(void)))))
(define do-proc-body
(match-lambda
((sig mid semi)
(let ((sig (sig))
(NUMBER #f))
(match (list (peek-token) sig)
(("is" ((and name (? string?)) rest))
(let ((N (without #f
(map (lambda (x)
(if (equal? (cdr x) (cadr sig))
(car x) #f))
(or (lookup 'FUN name) '())))))
(if (null? N)
(begin
(set! NUMBER (getFreeInt #f))
(insert-info! 'FUN-BODY name (cons NUMBER rest)))
(set! NUMBER (car N)))))
(_ (set! NUMBER (getFreeInt #f))
(insert-info! 'FUN-DECL (car sig) (cons NUMBER (cadr sig)))))
(append-scope!)
(if *scope* (mdisplay "-- Scope start of procedure:" (car sig)))
(set! do-scope (cons 'ProcBody do-scope))
(if (list? (cadadr sig))
(for-each (lambda (lst)
(match lst
((name mode T e) (insert-info! 'VAR name (lookup 'TYPE T)))
(_ '())))
(cadadr sig)))
(match (cons sig (map myapply (list mid semi)))
((((and name (? string?)) rest) () semi)
(delete-scope!)
(if *scope* (mdisplay "-- Scope end of procedure:" (car sig)))
(set! do-scope (cdr do-scope))
(list (list 'SIG (string-append "_" (number->string NUMBER) "_" (car sig)))))
((((and name (? string?)) rest) (is ds beginn except end id) semi)
(delete-scope!)
(if *scope* (mdisplay "-- Scope end of procedure:" (car sig)))
(set! do-scope (cdr do-scope))
(if (or (null? id) (match id ((("Id" l id)) (equal? id name)) (_ #f)))
(list (list 'FUN
(string-append "_" (number->string NUMBER) "_" name)
(match sig
((name para) (match para
(('-> 'void 'void) '())
(('-> (and para (? list-of-lists?)) 'void) (map car para))
(_ '())))
(_ '()))
(list 'DEF (apply append (apply append ds)))
(list 'BEGIN (match beginn
((b beginn) (apply append beginn))
(_ '())))
(list 'EXCEPT (match except
((e except) (apply append except))
(_ '())))
))
(ty-error-stmt "Procedure's names don't correspond")))
(_ (delete-scope!)
(if *scope* (mdisplay "-- Scope end of procedure:" (car sig)))
(set! do-scope (cdr do-scope))
'(void)))))
(_ '(void))))
(define do-param-list
(lambda (lst)
(match (map myapply lst)
((open (and param (? list?)) () close) param)
((open (and param (? list?)) params close)
(let ((params (append param
(let aloop ((lst params)
(vis (without #f (map (lambda(x) (if(alpha? x)#f
(car x)))param))))
(if (null? lst)
'()
(let* ((semi (car lst))
(param (if (list? (cadr lst)) (cadr lst) '(alpha)))
(vars (without #f (map(lambda(x)(if(alpha? x)#f(car x)))param))))
(if (null? (without #f (map (lambda (id)
(if(alpha? id)#f
(member id vis)))
vars)))
(append param
(aloop (cddr lst) (append vars vis)))
(ty-error line column '(alpha)
"Erroneous repetition of parameters"))))))))
params))
(_ 'void)
)))
(define do-param
(lambda (lst)
(match (map myapply lst)
((("Id" l id) ids col in out ("Id" l T) e)
(cond
((not (lookup 'TYPE T)) (ty-error line column '(alpha) "Unknown type `" T "'"))
((and infun? (not (null? out)))
(ty-error line column '(alpha)
"Function arguments can't have mode OUT"))
((and (= (length e) 2) (list? (cadr e))
(and (not (equal? (lookup 'TYPE T) (type-of (cadr e))))
(and (enum? (type-of (cadr e)))
(not (member T (type-of (cadr e)))))))
(ty-error line column '(alpha)
"Parameter type doesn't match with expression's"))
(else
(map
(lambda (id)
(list id
(cond
((and (null? in) (null? out)) 'IN)
((null? in) 'OUT)
((null? out) 'IN)
(else 'IN-OUT))
T (match e (((":=") e) e) (_ #f))))
(cons id
(let aloop ((lst ids) (vis (list id)))
(if (null? lst) '()
(let ((comma (car lst))
(id (match (cadr lst) (("Id" l id) id) (_ 'alpha))))
(unless (member id vis)
(cons id (aloop (cddr lst) (cons id vis)))
(ty-error
line column '(alpha)
"Erroneous repetition of parameter `" id "'"))))))))))
(_ 'alpha))))
(define (do-statement lst)
(match
(peek-token)
("Id" (set! do-scope (cons (token-name) do-scope)))
(_ '()))
(match
(map myapply lst)
((("null") semi) '(void))
((("if") e1 then s1 elif els end iff semi)
(unless (or (alpha? (type-of e1)) (bool? (type-of e1)))
(ty-error-stmt "IF conditional should be of boolean type")
(let* ((elif (let aloop ((lst elif))
(if (null? lst)
lst
(let* ((elsif (car lst))
(e (cadr lst))
(then (caddr lst))
(s (apply append (cadddr lst))))
(unless (or (alpha? (type-of e)) (bool? (type-of e)))
(begin
(ty-error-stmt "ELSIF conditional should be of boolean type")
'())
(cons (list 'ELSIF (val-of e) s)
(aloop (cddddr lst))))))))
(els (match els
(() els)
((("else") s) (list 'ELSE (apply append s))))))
(list (list 'IF (val-of e1) (apply append s1) elif els)))))
((("exit") id when semi) (list
(list 'EXIT
(match id
((("Id" l id))
(if (member id do-scope)
id
(ty-error line column 'error
"Unknown loop name: `" id "'")))
(() (if (memq 'Loop do-scope)
(cadr (memq 'Loop do-scope))
(ty-error line column 'error
"Exit statement must be within a loop")))
(_ '())
)
(match when
((("when") e)
(if (or (alpha? (type-of e))
(bool? (type-of e)))
(val-of e)
(ty-error line column 'error
"Expression in when clause must be of boolean type")))
(_ '(1 0))
))))
; need to do much more work of typechecking
((("return") e semi)
(unless (null? e)
(if (memq 'FunBody do-scope)
(if (equal? (cadr (memq 'FunBody do-scope)) (type-of (car e)))
(list (list 'RETURN (val-of (car e))))
(ty-error-stmt "Return type of the current function doesn't match"))
(ty-error-stmt "Not in a function to be able to return from"))
(if (or #f ;(memq 'PacBody do-scope)
(memq 'ProcBody do-scope))
'((RETURN))
(ty-error-stmt "Not in a procedure to be able to return from"))))
((("raise") x semi)
(if (null? x)
'((RAISE))
(match x
((("Id" l id)) (list (list 'RAISE id)))
(_ '(void)))))
((("Id" l id) rest)
(match rest
('semi (let* ((f (lookup 'FUN id)) ; parameterless proc called
(fs (unless f '()
(without #f
(map (lambda (f)
(match f
((num '-> 'void 'void) num)
(_ #f)))
f)))))
(if (= (length (without #f fs)) 1)
(list (list 'PCALL (string-append "_" (number->string (car (without #f fs))) "_" id) '()))
(ty-error-stmt "No compatible procedure found")
)))
(('label rest) rest)
(('lookup lst e) (if (lookup 'VAR id)
(if (member (lookup 'VAR id) '(enum int string float bool))
(if (equal? (lookup 'VAR id)
(type-of e))
(list (list 'STORE (list 'VAR id) (val-of e)))
(ty-error-stmt "Can't assign a value to a variable of inferior type"))
(let aloop ((left (list (list 'VAR id) (lookup 'VAR id)))
(lst lst))
(if (null? lst)
(let ((T (lookup 'TYPE (type-of left))))
(if (access? T)
(aloop (list (list 'DEREF (val-of left)) (cadr T))
lst)
(list (list 'STORE (val-of left) (val-of e)))))
(let ((id (cadar lst))) ; [ ('FIELD id) .... ]
(let* ((v (type-of left)) ; v = "k"
(T (lookup 'TYPE v))) ; T = '(record (("Data" 'int) ...))
(cond
((access? T)
(aloop (list (list 'DEREF (val-of left))
(cadr T))
(if (eq? id 'all)
(cdr lst)
lst)))
((record? T)
(let ((r (assoc id (cadr T))))
(if (not r)
(ty-error-expr "Record `" v "' doesn't contain field `" id "'")
(aloop (list (list 'LOOKUP-FIELD (val-of left) v id) (cadr r)) (cdr lst)))))
(else
(ty-error-expr "To use `.' (dot) left hand side must be a record"))))))))
(ty-error-stmt "No such variable to assign a value to: `" id "'")))
(('para arg) (if (or (lookup 'FUN id) (member id '("write" "read"))) ; procedure?
(let* ((sig (or (lookup 'FUN id) '()))
(sig (without #f (map (match-lambda ((NUM '-> from 'void) (list NUM '-> from 'void)) (_ #f)) sig)))
(arg (map (match-lambda (((v 'agr) 'as T) (list v 'as T))
((v T) (list v T))
(_ 'error))
arg))
(fun (map (lambda (f) (mama arg (cadr f))) (map cdr sig))))
(case (length (without #f fun))
((0) (match id
("write" (match arg
(((v T)) (list (list 'PRINT v)))
(_ (ty-error-stmt "No compatible procedure found"))))
("read" (match arg
((((and ('VAR _) v) T)) (match T
('int (list (list 'STORE v (list 'TOINT (list 'READ-NUM)))))
('float (list (list 'STORE v (list 'TOFLOAT (list 'READ-NUM)))))
('string (list (list 'STORE v (list 'READ-STR))))
(_ (ty-error-stmt "No_compatible procedure found"))))
(_ (ty-error-stmt "No compatible procedure found"))))
(_ (ty-error-stmt "No compatible procedure found"))))
((1) (list (list 'PCALL (string-append "_" (number->string (car (list-ref sig (find-ref fun)))) "_" id) (car (without #f fun)))))
(else (ty-error-stmt "Ambiguous procedure call"))))
(ty-error-stmt "No procedure found with the name: " id)))
(lst lst)
))
(('CASE e when) (list 'CASE e when))
(('FOR a b c d) (list 'FOR a b c d))
((block) (list block))
(_ '(void))
))
(define do-cas
(lambda (lst)
(let* ((ca ((car lst)))
(expr ((cadr lst)))
(val (val-of expr))
(type (if (and (list? (type-of expr))
(not (null? (type-of expr)))
(eq? 'enum (car (type-of expr))))
(if (> (length (type-of expr)) 2)
(ty-error line column 'alpha "Ambiguous enumerable expression")
(begin
(set! val (resolve-enum val (cadr (lookup 'TYPE (cadr (type-of expr))))))
(cadr (type-of expr))))
(type-of expr)))
(type (if (or (enum? type) (int? type) (bool? type) (alpha? type))
type
(ty-error line column 'alpha "Case works only on integer, boolean, or enumerator types")))
)
(set! do-scope (cons 'Case (cons type do-scope)))
(match (cons ca (cons (list val type) (map myapply (cddr lst))))
((("case") e is when end cas semi)
(set! do-scope (cddr do-scope))
(list 'CASE (val-of e) (let aloop ((when when))
(if (or (void? when) (null? when))
when
(cons (cadr when)
(aloop (cddr when)))))))
(_ 'crap)
))))
(define do-id-rest
(lambda (lst)
(if (not (equal? (peek-token) ":"))
(set! do-scope (cdr do-scope)))
(match (map myapply lst)
(((";")) 'semi)
(((":") rest2) (if (not (member (car do-scope) except-list))
(set! except-list (cons (car do-scope) except-list)))
(set! do-scope (cdr do-scope))
(list 'label rest2))
(((arg) () () (";")) (list 'para arg))
((() lst ((":=") e) (";")) (list 'lookup lst e))
(_ '(error))
)))
(define do-subname
(lambda (lst)
(match (map myapply lst)
(((".") name) (list 'FIELD (match name
(('Id id) id)
(('Str id) id)
('all 'all))))
(lst lst))))
(define do-id-rest2 (lambda (lst) (map myapply lst)))
(define do-block
(lambda (lst)
(append-scope!)
(if *scope* (mdisplay "--- Entering block " (if (string? (car do-scope)) (car do-scope) "")))
(if (not (string? (car do-scope))) (set! do-scope (cons (number->string (getFreeInt #f)) do-scope)))
(set! do-scope (cons 'Block do-scope))
(let ((k (string->number (cadr do-scope))))
(match (map myapply lst)
((declare beginn s except end id semi)
(delete-scope!)
(set! do-scope (cdr do-scope)) ;deleting 'Block
(if *scope* (mdisplay "--- Leaving block"))
(cond
((and (null? id) (not k))
(ty-error line column '(void) "Named block must be ended with name"))
((match id
((("Id" l id)) (not (or k (equal? id (car do-scope)))))
(_ #f))
(ty-error line column '(void) "Block's names don't match"))
(else
(list 'BLOCK (number->string k)
(list 'DEF (match declare
((d ds) (apply append (apply append ds)))
(_ '())))
(list 'BEGIN (apply append s))
(list 'EXCEPT (match except
((e es) (apply append (apply append es)))
(_ '())))))))
(_ (delete-scope!)
(if *scope* (mdisplay "--- Leaving block"))
'(void))))))
(define do-loop
(lambda (lst)
(if (not (string? (car do-scope))) (set! do-scope (cons (number->string (getFreeInt #t)) do-scope)))
(set! do-scope (cons 'Loop do-scope))
;check if label name already exists:
(let ((k (if (string? (cadr do-scope)) (string->number (cadr do-scope)) #f)))
(match (map myapply lst)
((l1 s end l2 (("Id" l id)) semi) ;Named loop
(set! do-scope (cdr do-scope))
(if (eq? 'Loop (car do-scope)) (set! do-scope (cdr do-scope)))
(cond
((and (string? (car do-scope)) (equal? id (car do-scope)))
(list 'LOOP id (apply append s)))
(k
(list 'LOOP (number->string k) (apply append s)))
((and (not k) (string? (car do-scope)))
(ty-error line column '(void) "Loop names don't match"))
(else
(ty-error line column '(void) "Named loop needs a label before it"))))
((l1 s end l2 () semi) ;Nameless loop
(set! do-scope (cddr do-scope))
(if (not k)
(ty-error line column '(void) "Named loop needs to be named in the end")
(list 'LOOP (number->string k) (apply append s))))
(_ (set! do-scope (cdr do-scope))
(if (number? (car do-scope))
(set! do-scope (cdr do-scope)))
'(void))
))))
(define do-while
(lambda (lst)
(match (map myapply lst)
((while e loop)
(match e
((e 'bool) (match loop
(('LOOP name rest) (list 'WHILE e name rest))
(_ '(void))))
((_ 'alpha) '(void))
((_ T) (ty-error line column '(void) "While expression must be of type Boolean"))
(_ '(void))))
(_ '(void)))))
(define do-for
(lambda (lst)
(append-scope!)
(match lst
((for id in rev range loop)
(let* ((for (for))
(id (match (id) (("Id" l id) id) (_ 'error)))
(in (in))
(rev (rev))
(range (range))
(tmp (insert-info! 'VAR id (cadddr range)))
(loop (loop)))
(delete-scope!)
(list 'FOR id rev range loop)))
(_ (delete-scope!)
'(void)))))
(define do-when-list
(lambda (lst)
(let ((type (cadr do-scope))) ; type :: string
(match (map myapply lst)
((("others") ("=>") stmt)
(list 'ELSE (without 'void (apply append stmt))))
(((e T) range ors ("=>") stmt)
(call/cc
(lambda (bk)
(if (alpha? T) (bk 'void))
(let* ((e e)
(T (if (and (list? T)
(not (null? T))
(eq? 'enum (car T)))
(if (member type T)
(begin
(set! e (resolve-enum e (cadr (lookup 'TYPE type))))
type)
(begin
(ty-error line column 'alpha "Ambiguous enumerable expression")
(bk 'void)))
(if (equal? type T)
type
(begin
(ty-error line column 'alpha "WHEN expression must be of type `" type "'")
(bk 'void)))))
)
(list 'WHEN
(let ((first (match range
((("..") (f S))
(let* ((f f)
(T S)
(T (if (and (list? T)
(not (null? T))
(eq? 'enum (car T)))
(if (member type T)
(begin
(set! f (resolve-enum f (cadr (lookup 'TYPE type))))
type)
(begin
(ty-error line column 'alpha "Ambiguous enumerable expression")
(bk 'void)))
(if (equal? type T)
type
(begin
(ty-error line column 'alpha "WHEN expression must be of type `" type "'")
(bk 'void)))))
)
(list 'RANGE e f)))
(_ e)))
(rest (let aloop ((lst ors))
(if (null? lst)
'()
(let ((x (car lst))
(y (cadr lst))
(z (caddr lst)))
(match (list y z)
(((e T) (("..") (f S)))
(let* ((e e)
(f f)
(T T)
(T (if (and (list? T)
(not (null? T))
(eq? 'enum (car T)))
(if (member type T)
(begin
(set! e (resolve-enum e (cadr (lookup 'TYPE type))))
type)
(begin
(ty-error line column 'alpha "Ambiguous enumerable expression")
(bk 'void)))
(if (equal? type T)
type
(begin
(ty-error line column 'alpha "WHEN expression must be of type `" type "'")
(bk 'void)))))
(T S)
(T (if (and (list? T)
(not (null? T))
(eq? 'enum (car T)))
(if (member type T)
(begin
(set! f (resolve-enum f (cadr (lookup 'TYPE type))))
type)
(begin
(ty-error line column 'alpha "Ambiguous enumerable expression")
(bk 'void)))
(if (equal? type T)
type
(begin
(ty-error line column 'alpha "WHEN expression must be of type `" type "'")
(bk 'void)))))
)
(cons (list 'RANGE e f) (aloop (cdddr lst)))))
(((e T) ())
(let* ((e e)
(T T)
(T (if (and (list? T)
(not (null? T))
(eq? 'enum (car T)))
(if (member type T)
(begin
(set! e (resolve-enum e (cadr (lookup 'TYPE type))))
type)
(begin
(ty-error line column 'alpha "Ambiguous enumerable expression")
(bk 'void)))
(if (equal? type T)
type
(begin
(ty-error line column 'alpha "WHEN expression must be of type `" type "'")
(bk 'void)))))
)
(cons e (aloop (cdddr lst)))))
(_ (bk 'void))
))))))
(unless (null? rest)
(cons 'COR (cons first rest))
(list first)))
(without 'void (apply append stmt)))))))
(_ 'vOId)))))
(define do-expr
(match-lambda
((re lst)
(let* ((re (re)) (lst (lst)))
(let aloop ((re re)(lst lst))
(if (null? lst)
re
(aloop (let* ((w1 re)
(w2 (cadr lst))
(op (car lst)))
(cond
((alpha? (type-of w1)) (list 'error 'alpha))
((alpha? (type-of w2)) (list 'error 'alpha))
((and (bool? (type-of w1)) (bool? (type-of w2)))
(list (list (car op) (val-of w1) (val-of w2))
'bool
))
(else
(ty-error (cadr op) (caddr op) (list 'error 'alpha)
(car op) " works on boolean values"))))
(cddr lst))))))
(_ 'EXOR)))
(define do-expr2
(match-lambda
((re lst)
(let* ((re (re)) (lst (lst)))
(let aloop ((re re)(lst lst))
(if (null? lst)
re
(aloop (let* ((w1 re)
(w2 (cadr lst))
(op (car lst)))
(cond
((alpha? (type-of w1)) (list 'error 'alpha))
((alpha? (type-of w2)) (list 'error 'alpha))
((and (bool? (type-of w1)) (bool? (type-of w2)))
(list (list (car op) (val-of w1) (val-of w2))
'bool
))
(else
(ty-error (cadr op) (caddr op) (list 'error 'alpha)
(car op) " works on boolean values"))))
(cddr lst))))))
(_ 'EXOR2)))
(define do-orelse
(lambda (lst)
(let* ((op ((car lst)))
(line line) (column column)
(ap ((cadr lst))))
(list (if (null? ap) 'OR 'OR-ELSE) line (- column 2)))))
(define do-andthen
(lambda (lst)
(let* ((op ((car lst)))
(line line) (column column)
(ap ((cadr lst))))
(list (if (null? ap) 'AND 'AND-THEN) line (- column 3)))))
(define do-relation
(match-lambda
((si lst)
(let* ((si (si))(lst (lst)))
(if (or (null? lst) (= 1 (length lst)))
si
(let* ((w1 si)
(w2 (cadr lst))
(op (car lst))
(t1 (type-of w1))
(t1 (if (string? t1) (list 'enum t1) t1))
(t2 (type-of w2))
(t2 (if (string? t2) (list 'enum t2) t2)))
(cond
((or (and (int? (type-of w1))
(int? (type-of w2)))
(and (float? (type-of w1))
(float? (type-of w2))))
(list (list (car op) (val-of w1) (val-of w2)) 'bool))
((and (astring? (type-of w1))
(astring? (type-of w2)))
(list (list (car op) (val-of w1) (val-of w2)) 'bool))
((and (enum? t1)
(enum? t2))
(let ((union (Union t1 t2)))
(cond
((null? union) (ty-error (cadr op) (caddr op) '(error alpha)
"Not compatible enumerator type instances"))
((> (length union) 1)
(cond
((equal? (cadr (val-of w1)) (cadr (val-of w2)))
(if (memq (car op) '(EQ LEQ GEQ))
'((1 0) bool)
'((0 0) bool)))
(else (ty-error (cadr op) (caddr op) '(error alpha)
"Ambiguous operands for comparison"))))
(else
(list (list (car op)
(let ((ke (assoc (cadr (val-of w1))
(cadr (lookup 'TYPE (caar union))))))
(if ke (list (cadr ke) 0) (val-of w1)))
(let ((ke (assoc (cadr (val-of w2))
(cadr (lookup 'TYPE (caar union))))))
(if ke (list (cadr ke) 0) (val-of w2))))
'bool)))))
(else
(ty-error (cadr op) (caddr op) '(error alpha)
(symbol->string (car op))
" works on string, enumerator and numeric values of the same type"))))
)))
(_ 'RERROR)))
(define do-relat_op
(lambda (op) (let* ((op ((car op))))
(list (match op
(("=") 'EQ)
(("/=") 'NEQ)
(("<") 'LT)
(("<=") 'LEQ)
((">") 'GT)
((">=") 'GEQ)
(_ 'ERR)
) line (- column (string-length (car op)))))))
(define do-simp_expr
(match-lambda
((un te lst)
(let* ((un (un))
(te (te))
(lst (lst))
(te (cond
((alpha? (type-of te)) te)
((and (not (null? un))
(eq? (caar un) 'MINUS))
(if (or (int? (type-of te))
(float? (type-of te)))
(list (list 'NEG (val-of te)) (type-of te))
(ty-error (cadar un) (caddar un) (list 'error 'alpha)
"Unary operations only work on numeric types")))
(else te))))
(let aloop ((te te)(lst lst))
(if (or (null? lst) (alpha? (type-of te)))
te
(aloop (let ((w1 te)
(w2 (cadr lst))
(op (car lst)))
(cond
((alpha? (type-of w1)) w1)
((alpha? (type-of w2)) w1)
((eq? (car op) 'AMP)
(if (and (astring? (type-of w1))
(astring? (type-of w2)))
(list (list 'CONCAT (val-of w1) (val-of w2)) 'string)
(ty-error (cadr op) (caddr op) (list 'error 'alpha)
"Can only concatenate strings")))
((or (and (int? (type-of w1)) (int? (type-of w2)))
(and (float? (type-of w1)) (float? (type-of w2))))
(list (list (car op) (val-of w1) (val-of w2))
(type-of w1) ;or w2
))
(else
(ty-error (cadr op) (caddr op) (list 'error 'alpha)
(car op) " works on numeric values of the same type"))))
(cddr lst))))))
(_ 'SERROR)))
(define do-unary_op
(lambda (op) (let* ((op ((car op))))
(match op
(("+") (list 'PLUS line (1- column)))
(("-") (list 'MINUS line (1- column)))
(_ 'ERR)
))))
(define do-adding_op
(lambda (op) (let* ((op ((car op))))
(match op
(("&") (list 'AMP line (1- column)))
(un un)
))))
(define do-term
(match-lambda
((fac lst)
(let aloop ((fac (fac))(lst (lst)))
(if (null? lst)
fac
(aloop (let ((w1 fac)
(w2 (cadr lst))
(op (car lst)))
(if (or (and (int? (type-of w1))
(int? (type-of w2)))
(and (float? (type-of w1))
(float? (type-of w2))))
(list (list (car op) (val-of w1) (val-of w2))
(type-of w1) ;or w2
)
(ty-error (cadr op) (caddr op) (list 'error 'alpha)
(symbol->string (car op))
" works on numeric values of the same type")))
(cddr lst)))))
(_ 'TERROR)))
(define do-mult_op
(lambda (op) (let* ((op ((car op))))
(list (match op
(("/") 'DIV)
(("*") 'MUL)
(("mod") 'MOD)
(_ 'MERR)
) line (- column (string-length (car op)))))))
(define do-factor
(lambda (lst)
(let* ((a ((car lst)))
(line line)
(column (1- column))
(b ((cadr lst))))
(match (list a b)
((("not") pri) (cond
((alpha? (type-of pri)) pri)
((bool? (type-of pri))
(list (list 'NOT (val-of pri)) 'bool))
(else (ty-error line column (list 'error 'alpha)
"NOT takes a boolean type"))))
((("abs") pri) (cond
((alpha? (type-of pri)) pri)
((or (int? (type-of pri))
(float? (type-of pri)))
(list (list 'ABS (val-of pri)) (type-of pri)))
(else (ty-error line column (list 'error 'alpha)
"ABS takes a numeric type"))))
((pri ()) pri)
((pri (("**") pro)) (cond
((or (alpha? (type-of pri))
(alpha? (type-of pro))) '(error alpha))
((and (or (int? (type-of pri))
(float? (type-of pri)))
(int? (type-of pro)))
(list (list 'POW (val-of pri) (val-of pro))
(type-of pri)))
(else
(ty-error line column (list 'error 'alpha)
"Power function can only raise numeric types to the power of a positive integer"))))
(_ 'ERACTOR)))))
;(no functions, records, arrays, aggregates!)
(define (do-primary e)
(let* ((e (map myapply e)))
(match e
((("Id" l var) lst)
(if (and (equal? (peek-token) "=>") (not (eq? 'Case (car do-scope))))
(list var 'agr) ; part of aggregate, ie. =>
(if (lookup 'FUN var) ; Function?
(if (null? lst)
(let ((ret (unless (lookup 'FUN var) '() ; No params
(map (lambda (f)
(match f
((NUM '-> 'void ret) (list NUM ret))
(_ #f)))
(lookup 'FUN var)))))
(case (length (without #f ret))
((0) (ty-error-expr "No compatible function found"))
((1) (list (list 'CALL (string-append "_" (number->string (caar (without #f ret))) "_" var) '()) (cadar (without #f ret))))
(else (ty-error-expr "Ambiguous function call"))))
(let ((fun (map (lambda (f) (mama (car lst) (caddr f))) (lookup 'FUN var))))
(case (length (without #f fun))
((0) (ty-error-expr "No compatible function found"))
((1) (let* ((n (find-ref fun))
(NUM (car (list-ref (lookup 'FUN var) n)))
(T (cadddr (list-ref (lookup 'FUN var) n))))
(list (list 'CALL (string-append "_" (number->string NUM) "_" var)
(map (match-lambda
((a inout b (v T)) (list a inout b v))
(x x))
(car (without #f fun)))) T)))
(else (ty-error-expr "Ambiguous function call"))))
)
(let* ((v (lookup 'VAR var)) ; Non-function
(T (lookup 'TYPE v)))
(if (or (and (not v) (not (lookup 'TYPE var))) (void? T))
(if (void? T)
(ty-error-expr "Trying to use a variable of a not fully defined type")
(ty-error-expr "Undeclared variable `" var"'"))
(let aloop ((left (if (lookup 'TYPE var)
(list var 'typ)
(list (list 'VAR var) v)))
(lst lst))
(if (null? lst)
left
(match (car lst)
(('dot ('Id id))
(let* ((v (type-of left)) ; v = "k"
(T (lookup 'TYPE v))) ; T = '(record (("Data" 'int) ...))
(cond
((access? T)
(aloop (list (list 'DEREF (val-of left))
(cadr T))
lst))
((record? T)
(let ((r (assoc id (cadr T))))
(if (not r)
(ty-error-expr "Record `" v "' doesn't contain field `" id "'")
(aloop (list (list 'LOOKUP-FIELD (val-of left) v id) (cadr r))
(cdr lst)))))
(else
(ty-error-expr "To use `.' (dot) left hand side must be a record")))))
(('dot 'all)
(let* ((v (type-of left))
(T (lookup 'TYPE v)))
(unless (access? T)
(ty-error-expr "`.all' dereferences accessor types")
(aloop (list (list 'DEREF (val-of left))
(cadr T))
(cdr lst)))))
(('apo agg)
(match agg
("succ" (if (or (enum? (type-of left))
(enum? (lookup 'TYPE (type-of left)))
(int? (lookup 'TYPE (type-of left)))
(int? (type-of left))
)
(aloop (list (list 'PLUS (val-of left) '(1 0))
(type-of left))
(cdr lst))
(ty-error-expr
"Attribute Succ works on numerical and enumerator values only")))
("pred" (if (or (enum? (type-of left))
(enum? (lookup 'TYPE (type-of left)))
(int? (lookup 'TYPE (type-of left)))
(int? (type-of left))
)
(aloop (list (list 'MINUS (val-of left) '(1 0))
(type-of left))
(cdr lst))
(ty-error-expr
"Attribute Pred works on numerical and enumerator values only")))
("ceiling" (if (or (float? (lookup 'TYPE (type-of left)))
(float? (type-of left)))
(aloop (list (list 'TOINT (list 'CEILING (val-of left))) 'int)
(cdr lst))
(ty-error-expr
"Attribute Ceiling works on float values only")))
("floor" (if (or (float? (lookup 'TYPE (type-of left)))
(float? (type-of left)))
(aloop (list (list 'TOINT (list 'FLOOR (val-of left))) 'int)
(cdr lst))
(ty-error-expr
"Attribute Floor works on float values only")))
("float" (if (or (int? (lookup 'TYPE (type-of left)))
(int? (type-of left)))
(aloop (list (list 'TOFLOAT (val-of left)) 'float)
(cdr lst))
(ty-error-expr
"Attribute Float works on integer values only")))
("pos" (if (or (enum? (type-of left))
(enum? (lookup 'TYPE (type-of left)))
(int? (lookup 'TYPE (type-of left)))
(int? (type-of left))
(bool? (lookup 'TYPE (type-of left)))
(bool? (type-of left)))
(aloop (list (list 'POS (val-of left)) 'int)
(cdr lst))
(ty-error-expr
"Attribute Pos works on numeric and enumerator values only")))
("size" (match left
((var 'typ)
(aloop (list (list 'SIZE var) 'int)
(cdr lst)))
(_ (ty-error-expr
"Attribute Size works only on Types"))))
("last" (match left
((var 'typ)
(if (or (int? (lookup 'TYPE var))
(bool? (lookup 'TYPE var))
(float? (lookup 'TYPE var))
(enum? (lookup 'TYPE var)))
(aloop (list (list 'LAST var) var)
(cdr lst))))
(_ (ty-error-expr
"Attribute Last works only on Types"))))
("first" (match left
((var 'typ)
(if (or (int? (lookup 'TYPE var))
(bool? (lookup 'TYPE var))
(float? (lookup 'TYPE var))
(enum? (lookup 'TYPE var)))
(aloop (list (list 'FIRST var) var)
(cdr lst))))
(_ (ty-error-expr
"Attribute First works only on Types"))))
("length" (match left
((var 'typ)
(if (array? (lookup 'TYPE var))
(aloop (list (list 'LENGTH var) 'int)
(cdr lst))
(ty-error-expr
"Attribute Length only works with array types")))
(_ (ty-error-expr
"Attribute Length only works with array types"))))
("Char" (if (or (int? (lookup 'TYPE (type-of left)))
(int? (type-of left)))
(aloop (list (list 'CHAR (val-of left)) 'string)
(cdr lst))
(ty-error-expr
"Attribute Char works on integer values only")))
("len" (if (or (astring? (lookup 'TYPE (type-of left)))
(astring? (type-of left)))
(aloop (list (list 'LEN (val-of left)) 'int)
(cdr lst))
(ty-error-expr
"Attribute Len works on string values only")))
(_ (ty-error-expr "Invalid Attribute usage"))))
;(())
(_ '(error alpha))))))))))
((("(") e (")")) e)
((lit) lit)
(_ (list 'error 'alpha))
)))
;done
(define do-literal
(lambda (e)
(let* ((e ((car e))))
(match e
(("Int" j e) (list (list j e) 'int))
(("Float" i d e) (list (list i d e) 'float))
(("true") (list '(1 0) 'bool))
(("false") (list '(0 0) 'bool))
(("Str" s) (list s 'string))
(_ (list 'error 'alpha))
))))
(define do-name-part
(lambda (lst)
(match (map myapply lst)
(((".") rest) (list 'dot rest))
((("'") agg) (list 'apo agg))
((lst) lst)
)))
(define do-agg
(lambda (lst)
(match (map myapply lst)
((("Id" l id)) id)
(lst lst)
)))
(define do-agg-list
(lambda (lst)
(match (map myapply lst)
((("(") name to rest (")"))
(let* ((name (match name
(((and x (? string?))) x)
(x x)))
(v (match to ; handle range
((("=>") expr) (list name 'as expr))
(_ name))))
(cons v
(let aloop ((lst rest))
(if (null? lst)
'()
(let* ((a (car lst))
(b (cadr lst))
(c (caddr lst)))
(match (list a b c)
(((",") name (("=>") name2))
(cons (list name 'as name2)
(aloop (cdddr lst))))
(((",") name ())
(cons name
(aloop (cdddr lst))))
(_ '()))))))))
(_ 'void))))
(define do-name-list
(lambda (lst)
(match (map myapply lst)
((("others")) 'others)
(((v T) range rest)
(let ((v (match range ; handle range
((("..") (w S)) (list 'RANGE v w)) ;check type compatibility
(_ (list v T)))))
(let aloop ((v v)
(lst rest))
(if (null? lst)
v
(let* ((e
(match
(car lst)
((("|") (u T) (("..") (w S))) (list 'RANGE u w)) ;check type compatibility
((("|") (u T) ()) (list u T)) ;check type compatibility
(_ '(void)))))
(aloop (list 'OR v e) (cdr lst)))))))
(_ '(void)))))
(define do-name-rest
(lambda (lst)
(match ((car lst))
(("Id" l id) (list 'Id id))
(("Str" s) (list 'Str s))
(("all") 'all)
(_ 'void))))
| false |
3ed8889e25b972ed0811a6b82ee4d3de1cd02394 | bcfa2397f02d5afa93f4f53c0b0a98c204caafc1 | /scheme/chapter2/ex2_08_test.scm | d3c8a36adc702528b2f6498e3252c49d61a58144 | []
| no_license | rahulkumar96/sicp-study | ec4aa6e1076b46c47dbc7a678ac88e757191c209 | 4dcd1e1eb607aa1e32277e1c232a321c5de9c0f0 | refs/heads/master | 2020-12-03T00:37:39.576611 | 2017-07-05T12:58:48 | 2017-07-05T12:58:48 | 96,050,670 | 0 | 0 | null | 2017-07-02T21:46:09 | 2017-07-02T21:46:09 | null | UTF-8 | Scheme | false | false | 267 | scm | ex2_08_test.scm | ;; SICP 1.8
(test-case "Ex 1.8 Interval Subtraction"
(let ((a (make-interval 10 12))
(b (make-interval 4 6)))
(assert-equal 4 (lower-bound (sub-interval a b)))
(assert-equal 8 (upper-bound (sub-interval a b)))))
| false |
1f128644017b8d9520705dfa767851fe708328bd | 74d2f4ec77852839450ab8563971a5e0f615c019 | /chapter_02/exercise_2_34.scm | 8ee7b37a75c1ef640cb7b21b8ada297075cf27b7 | []
| no_license | wangoasis/sicp | b56960a0c3202ce987f176507b1043ed632ed6b3 | 07eaf8d46f7b8eae5a46d338a4608d8e993d4568 | refs/heads/master | 2021-01-21T13:03:11.520829 | 2016-04-22T13:52:15 | 2016-04-22T13:52:15 | 53,835,426 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 344 | scm | exercise_2_34.scm | ( define ( accumulate op initial sequence )
( if ( null? sequence ) initial
( op ( car sequence )
( accumulate op initial ( cdr sequence ) ) ) ) )
( define ( horner-eval x coefficient-sequence )
( accumulate
( lambda ( this-coeff higher-terms ) ( + this-coeff ( * x higher-terms ) ) )
0
coefficient-sequence ) )
| false |
ac65f92ba7af1fb9d66f373ea6079ce31f1d9a9e | ab05b79ab17619f548d9762a46199dc9eed6b3e9 | /sitelib/ypsilon/gtk/menu.scm | ea2ea3444357f21f9c4608c3cc30fc629aa8246b | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | lambdaconservatory/ypsilon | 2dce9ff4b5a50453937340bc757697b9b4839dee | f154436db2b3c0629623eb2a53154ad3c50270a1 | refs/heads/master | 2021-02-28T17:44:05.571304 | 2017-12-17T12:29:00 | 2020-03-08T12:57:52 | 245,719,032 | 1 | 0 | NOASSERTION | 2020-03-07T23:08:26 | 2020-03-07T23:08:25 | null | UTF-8 | Scheme | false | false | 12,991 | scm | menu.scm | #!nobacktrace
;;; Ypsilon Scheme System
;;; Copyright (c) 2004-2009 Y.FUJITA / LittleWing Company Limited.
;;; See license.txt for terms and conditions of use.
(library (ypsilon gtk menu)
(export gtk_menu_attach
gtk_menu_attach_to_widget
gtk_menu_bar_get_child_pack_direction
gtk_menu_bar_get_pack_direction
gtk_menu_bar_get_type
gtk_menu_bar_new
gtk_menu_bar_set_child_pack_direction
gtk_menu_bar_set_pack_direction
gtk_menu_detach
gtk_menu_direction_type_get_type
gtk_menu_get_accel_group
gtk_menu_get_accel_path
gtk_menu_get_active
gtk_menu_get_attach_widget
gtk_menu_get_for_attach_widget
gtk_menu_get_monitor
gtk_menu_get_tearoff_state
gtk_menu_get_title
gtk_menu_get_type
gtk_menu_item_activate
gtk_menu_item_deselect
gtk_menu_item_get_accel_path
gtk_menu_item_get_label
gtk_menu_item_get_right_justified
gtk_menu_item_get_submenu
gtk_menu_item_get_type
gtk_menu_item_get_use_underline
gtk_menu_item_new
gtk_menu_item_new_with_label
gtk_menu_item_new_with_mnemonic
gtk_menu_item_select
gtk_menu_item_set_accel_path
gtk_menu_item_set_label
gtk_menu_item_set_right_justified
gtk_menu_item_set_submenu
gtk_menu_item_set_use_underline
gtk_menu_item_toggle_size_allocate
gtk_menu_item_toggle_size_request
gtk_menu_new
gtk_menu_popdown
gtk_menu_popup
gtk_menu_reorder_child
gtk_menu_reposition
gtk_menu_set_accel_group
gtk_menu_set_accel_path
gtk_menu_set_active
gtk_menu_set_monitor
gtk_menu_set_screen
gtk_menu_set_tearoff_state
gtk_menu_set_title
gtk_menu_shell_activate_item
gtk_menu_shell_append
gtk_menu_shell_cancel
gtk_menu_shell_deactivate
gtk_menu_shell_deselect
gtk_menu_shell_get_take_focus
gtk_menu_shell_get_type
gtk_menu_shell_insert
gtk_menu_shell_prepend
gtk_menu_shell_select_first
gtk_menu_shell_select_item
gtk_menu_shell_set_take_focus
gtk_menu_tool_button_get_menu
gtk_menu_tool_button_get_type
gtk_menu_tool_button_new
gtk_menu_tool_button_new_from_stock
gtk_menu_tool_button_set_arrow_tooltip_markup
gtk_menu_tool_button_set_arrow_tooltip_text
gtk_menu_tool_button_set_menu)
(import (rnrs) (ypsilon ffi))
(define lib-name
(cond (on-linux "libgtk-x11-2.0.so.0")
(on-sunos "libgtk-x11-2.0.so.0")
(on-freebsd "libgtk-x11-2.0.so.0")
(on-openbsd "libgtk-x11-2.0.so.0")
(on-darwin "Gtk.framework/Gtk")
(on-windows "libgtk-win32-2.0-0.dll")
(else
(assertion-violation #f "can not locate GTK 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 name args)))))
(define-syntax define-function/va_list
(syntax-rules ()
((_ ret name args)
(define name (lambda x (assertion-violation 'name "va_list argument not supported"))))))
;; void gtk_menu_attach (GtkMenu* menu, GtkWidget* child, guint left_attach, guint right_attach, guint top_attach, guint bottom_attach)
(define-function void gtk_menu_attach (void* void* unsigned-int unsigned-int unsigned-int unsigned-int))
;; void gtk_menu_attach_to_widget (GtkMenu* menu, GtkWidget* attach_widget, GtkMenuDetachFunc detacher)
(define-function void gtk_menu_attach_to_widget (void* void* (c-callback void (void* void*))))
;; GtkPackDirection gtk_menu_bar_get_child_pack_direction (GtkMenuBar* menubar)
(define-function int gtk_menu_bar_get_child_pack_direction (void*))
;; GtkPackDirection gtk_menu_bar_get_pack_direction (GtkMenuBar* menubar)
(define-function int gtk_menu_bar_get_pack_direction (void*))
;; GType gtk_menu_bar_get_type (void)
(define-function unsigned-long gtk_menu_bar_get_type ())
;; GtkWidget* gtk_menu_bar_new (void)
(define-function void* gtk_menu_bar_new ())
;; void gtk_menu_bar_set_child_pack_direction (GtkMenuBar* menubar, GtkPackDirection child_pack_dir)
(define-function void gtk_menu_bar_set_child_pack_direction (void* int))
;; void gtk_menu_bar_set_pack_direction (GtkMenuBar* menubar, GtkPackDirection pack_dir)
(define-function void gtk_menu_bar_set_pack_direction (void* int))
;; void gtk_menu_detach (GtkMenu* menu)
(define-function void gtk_menu_detach (void*))
;; GType gtk_menu_direction_type_get_type (void)
(define-function unsigned-long gtk_menu_direction_type_get_type ())
;; GtkAccelGroup* gtk_menu_get_accel_group (GtkMenu* menu)
(define-function void* gtk_menu_get_accel_group (void*))
;; const gchar* gtk_menu_get_accel_path (GtkMenu* menu)
(define-function char* gtk_menu_get_accel_path (void*))
;; GtkWidget* gtk_menu_get_active (GtkMenu* menu)
(define-function void* gtk_menu_get_active (void*))
;; GtkWidget* gtk_menu_get_attach_widget (GtkMenu* menu)
(define-function void* gtk_menu_get_attach_widget (void*))
;; GList* gtk_menu_get_for_attach_widget (GtkWidget* widget)
(define-function void* gtk_menu_get_for_attach_widget (void*))
;; gint gtk_menu_get_monitor (GtkMenu* menu)
(define-function int gtk_menu_get_monitor (void*))
;; gboolean gtk_menu_get_tearoff_state (GtkMenu* menu)
(define-function int gtk_menu_get_tearoff_state (void*))
;; const gchar* gtk_menu_get_title (GtkMenu* menu)
(define-function char* gtk_menu_get_title (void*))
;; GType gtk_menu_get_type (void)
(define-function unsigned-long gtk_menu_get_type ())
;; void gtk_menu_item_activate (GtkMenuItem* menu_item)
(define-function void gtk_menu_item_activate (void*))
;; void gtk_menu_item_deselect (GtkMenuItem* menu_item)
(define-function void gtk_menu_item_deselect (void*))
;; const gchar* gtk_menu_item_get_accel_path (GtkMenuItem* menu_item)
(define-function char* gtk_menu_item_get_accel_path (void*))
;; const gchar* gtk_menu_item_get_label (GtkMenuItem* menu_item)
(define-function char* gtk_menu_item_get_label (void*))
;; gboolean gtk_menu_item_get_right_justified (GtkMenuItem* menu_item)
(define-function int gtk_menu_item_get_right_justified (void*))
;; GtkWidget* gtk_menu_item_get_submenu (GtkMenuItem* menu_item)
(define-function void* gtk_menu_item_get_submenu (void*))
;; GType gtk_menu_item_get_type (void)
(define-function unsigned-long gtk_menu_item_get_type ())
;; gboolean gtk_menu_item_get_use_underline (GtkMenuItem* menu_item)
(define-function int gtk_menu_item_get_use_underline (void*))
;; GtkWidget* gtk_menu_item_new (void)
(define-function void* gtk_menu_item_new ())
;; GtkWidget* gtk_menu_item_new_with_label (const gchar* label)
(define-function void* gtk_menu_item_new_with_label (char*))
;; GtkWidget* gtk_menu_item_new_with_mnemonic (const gchar* label)
(define-function void* gtk_menu_item_new_with_mnemonic (char*))
;; void gtk_menu_item_select (GtkMenuItem* menu_item)
(define-function void gtk_menu_item_select (void*))
;; void gtk_menu_item_set_accel_path (GtkMenuItem* menu_item, const gchar* accel_path)
(define-function void gtk_menu_item_set_accel_path (void* char*))
;; void gtk_menu_item_set_label (GtkMenuItem* menu_item, const gchar* label)
(define-function void gtk_menu_item_set_label (void* char*))
;; void gtk_menu_item_set_right_justified (GtkMenuItem* menu_item, gboolean right_justified)
(define-function void gtk_menu_item_set_right_justified (void* int))
;; void gtk_menu_item_set_submenu (GtkMenuItem* menu_item, GtkWidget* submenu)
(define-function void gtk_menu_item_set_submenu (void* void*))
;; void gtk_menu_item_set_use_underline (GtkMenuItem* menu_item, gboolean setting)
(define-function void gtk_menu_item_set_use_underline (void* int))
;; void gtk_menu_item_toggle_size_allocate (GtkMenuItem* menu_item, gint allocation)
(define-function void gtk_menu_item_toggle_size_allocate (void* int))
;; void gtk_menu_item_toggle_size_request (GtkMenuItem* menu_item, gint* requisition)
(define-function void gtk_menu_item_toggle_size_request (void* void*))
;; GtkWidget* gtk_menu_new (void)
(define-function void* gtk_menu_new ())
;; void gtk_menu_popdown (GtkMenu* menu)
(define-function void gtk_menu_popdown (void*))
;; void gtk_menu_popup (GtkMenu* menu, GtkWidget* parent_menu_shell, GtkWidget* parent_menu_item, GtkMenuPositionFunc func, gpointer data, guint button, guint32 activate_time)
(define-function void gtk_menu_popup (void* void* void* (c-callback void (void* void* void* void* void*)) void* unsigned-int uint32_t))
;; void gtk_menu_reorder_child (GtkMenu* menu, GtkWidget* child, gint position)
(define-function void gtk_menu_reorder_child (void* void* int))
;; void gtk_menu_reposition (GtkMenu* menu)
(define-function void gtk_menu_reposition (void*))
;; void gtk_menu_set_accel_group (GtkMenu* menu, GtkAccelGroup* accel_group)
(define-function void gtk_menu_set_accel_group (void* void*))
;; void gtk_menu_set_accel_path (GtkMenu* menu, const gchar* accel_path)
(define-function void gtk_menu_set_accel_path (void* char*))
;; void gtk_menu_set_active (GtkMenu* menu, guint index_)
(define-function void gtk_menu_set_active (void* unsigned-int))
;; void gtk_menu_set_monitor (GtkMenu* menu, gint monitor_num)
(define-function void gtk_menu_set_monitor (void* int))
;; void gtk_menu_set_screen (GtkMenu* menu, GdkScreen* screen)
(define-function void gtk_menu_set_screen (void* void*))
;; void gtk_menu_set_tearoff_state (GtkMenu* menu, gboolean torn_off)
(define-function void gtk_menu_set_tearoff_state (void* int))
;; void gtk_menu_set_title (GtkMenu* menu, const gchar* title)
(define-function void gtk_menu_set_title (void* char*))
;; void gtk_menu_shell_activate_item (GtkMenuShell* menu_shell, GtkWidget* menu_item, gboolean force_deactivate)
(define-function void gtk_menu_shell_activate_item (void* void* int))
;; void gtk_menu_shell_append (GtkMenuShell* menu_shell, GtkWidget* child)
(define-function void gtk_menu_shell_append (void* void*))
;; void gtk_menu_shell_cancel (GtkMenuShell* menu_shell)
(define-function void gtk_menu_shell_cancel (void*))
;; void gtk_menu_shell_deactivate (GtkMenuShell* menu_shell)
(define-function void gtk_menu_shell_deactivate (void*))
;; void gtk_menu_shell_deselect (GtkMenuShell* menu_shell)
(define-function void gtk_menu_shell_deselect (void*))
;; gboolean gtk_menu_shell_get_take_focus (GtkMenuShell* menu_shell)
(define-function int gtk_menu_shell_get_take_focus (void*))
;; GType gtk_menu_shell_get_type (void)
(define-function unsigned-long gtk_menu_shell_get_type ())
;; void gtk_menu_shell_insert (GtkMenuShell* menu_shell, GtkWidget* child, gint position)
(define-function void gtk_menu_shell_insert (void* void* int))
;; void gtk_menu_shell_prepend (GtkMenuShell* menu_shell, GtkWidget* child)
(define-function void gtk_menu_shell_prepend (void* void*))
;; void gtk_menu_shell_select_first (GtkMenuShell* menu_shell, gboolean search_sensitive)
(define-function void gtk_menu_shell_select_first (void* int))
;; void gtk_menu_shell_select_item (GtkMenuShell* menu_shell, GtkWidget* menu_item)
(define-function void gtk_menu_shell_select_item (void* void*))
;; void gtk_menu_shell_set_take_focus (GtkMenuShell* menu_shell, gboolean take_focus)
(define-function void gtk_menu_shell_set_take_focus (void* int))
;; GtkWidget* gtk_menu_tool_button_get_menu (GtkMenuToolButton* button)
(define-function void* gtk_menu_tool_button_get_menu (void*))
;; GType gtk_menu_tool_button_get_type (void)
(define-function unsigned-long gtk_menu_tool_button_get_type ())
;; GtkToolItem* gtk_menu_tool_button_new (GtkWidget* icon_widget, const gchar* label)
(define-function void* gtk_menu_tool_button_new (void* char*))
;; GtkToolItem* gtk_menu_tool_button_new_from_stock (const gchar* stock_id)
(define-function void* gtk_menu_tool_button_new_from_stock (char*))
;; void gtk_menu_tool_button_set_arrow_tooltip_markup (GtkMenuToolButton* button, const gchar* markup)
(define-function void gtk_menu_tool_button_set_arrow_tooltip_markup (void* char*))
;; void gtk_menu_tool_button_set_arrow_tooltip_text (GtkMenuToolButton* button, const gchar* text)
(define-function void gtk_menu_tool_button_set_arrow_tooltip_text (void* char*))
;; void gtk_menu_tool_button_set_menu (GtkMenuToolButton* button, GtkWidget* menu)
(define-function void gtk_menu_tool_button_set_menu (void* void*))
) ;[end]
| true |
093e14e7b315c5a508a243df9159f3dd5e616da4 | a5cff5beae635b13a1d67cb707856212fbbe32a5 | /chapter8.scm | 035c6a72d4e6ba0cac5311f78aaf9b5368285109 | []
| no_license | abelard2008/plai | f6c1b2fa17d224579e8ec6e08d74e5f6fa80d5ed | b7de61a647a555f0355fc1d9617e80d6af27907d | refs/heads/master | 2020-12-10T21:26:24.032181 | 2020-01-16T10:47:20 | 2020-01-16T10:47:20 | 233,715,673 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,315 | scm | chapter8.scm | #lang plai
(define-type CFAE/L
[num (n number?)]
[add (lhs CFAE/L?)(rhs CFAE/L?)]
[id (name symbol?)]
[fun (param symbol?)(body CFAE/L?)]
[app (fun-expr CFAE/L?)(arg-expr CFAE/L?)])
(define-type CFAE/L-Value
[numV (n number?)]
[closureV (param symbol?)
(body CFAE/L?)
(env Env?)]
[exprV (expr CFAE/L?)
(env Env?)])
(define-type Env
[mtSub]
[aSub (name symbol?)(value CFAE/L-Value?)(env Env?)])
(define (num+ x y) ;; need this because we can't just use Scheme + to add FAE-values
(numV (+ (numV-n x) (numV-n y))))
(define (parse sexp)
(cond [(number? sexp) (num sexp)]
[(symbol? sexp) (id sexp)]
[(list? sexp)
(case (first sexp)
((+)
(add (parse (second sexp))
(parse (third sexp))))
((with) ; Notice how we parse with!!!!
(app (fun (first (second sexp)) ;
(parse (third sexp))) ; Solves exercise 6.3.1
(parse (second (second sexp))))) ;
((fun)
(fun (first (second sexp))
(parse (third sexp))))
(else
(app (parse (first sexp))
(parse (second sexp)))))]))
(define (lookup name env)
(type-case Env env
[mtSub() (error 'lookup "no binding for identifier")]
[aSub (bound-name bound-value rest-ds)
(if (symbol=? bound-name name)
bound-value
(lookup name rest-ds))]))
(define (interp expr env)
(type-case CFAE/L expr
[num (n) (numV n)]
[add (l r)(num+ (interp l env)(interp r env))]
[id (v) (lookup v env)]
[fun (bound-id bound-body)
(closureV bound-id bound-body env)]
[app (fun-expr arg-expr)
(local ([define fun-val (interp fun-expr env)]
[define arg-val (exprV arg-expr env)])
(interp (closureV-body fun-val)
(aSub (closureV-param fun-val)
arg-val
(closureV-env fun-val))))]))
;(interp (parse '{with {x 3} x}) {mtSub})
;(interp {parse '(with (x 3) (+ x x))} (mtSub))
;{parse '(with (x 3) (+ x x))}
;(interp {parse '(with (x 3) (+ x x))} (mtSub)) | false |
e8cb483bf442cf15dc8e05ee3540d43245a2b4d8 | 7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107 | /ex-4.24.scm | 84e02b373de6660cc22be77bd994761886b34489 | []
| 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,173 | scm | ex-4.24.scm | ;;; Exercise 4.24. Design and carry out some experiments to compare the speed
;;; of the original metacircular evaluator with the version in this section.
;;; Use your results to estimate the fraction of time that is spent in analysis
;;; versus execution for various procedures.
(load "./sec-4.1.1.scm")
(load "./sec-4.1.2.scm")
(load "./sec-4.1.3.scm")
(load "./sec-4.1.4.scm")
(define eval-original eval)
(load "./sec-4.1.7.scm")
(define eval-analyzed eval)
(define sample-codes
'((begin (define (fib n)
(cond ((= n 1) 1)
((= n 2) 1)
(else (+ (fib (- n 1)) (fib (- n 2))))))
(print (fib 26)))
(begin (define (loop n)
(if (= n 0)
'done
(begin (+ 1 1)
(loop (- n 1)))))
(loop 100000))
))
(for-each (lambda (code)
(print "================================")
(print "Code: " code)
(print "Original:")
(time (eval-original code the-global-environment))
(print "Analyzed:")
(time (eval-analyzed code the-global-environment)))
sample-codes)
| false |
eac85dad697555635c3e9d4fd1da7830986135ff | 53b12a47b6a5329efff3f674c5df5f92d2cbb09f | /math/fibonacci/gcc-tcc-scheme-fib.ss | f3f46a271e8c9876cd69d0158f3f78c5d49e894a | []
| no_license | absop/SchemeMathBench | 11aac8b1d552107f0e9812d61f37b3657442daee | 64a01c6c81b659f43e210162eb36af27ad9105fd | refs/heads/master | 2021-09-01T19:57:27.603056 | 2021-08-22T12:44:10 | 2021-08-22T12:44:10 | 227,276,292 | 3 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,227 | ss | gcc-tcc-scheme-fib.ss | (time (system "gcc -o gfib.so gfib.c -O2 -s -fPIC -shared"))
(time (system "tcc -o tfib.so tfib.c -s -fPIC -shared"))
(load-shared-object "gfib.so")
(load-shared-object "tfib.so")
; gfib is exactly the same as tfib
(define gfib (foreign-procedure "gfib" (int) int))
(define tfib (foreign-procedure "tfib" (int) int))
(define sfib
(lambda (n)
(if (< n 2)
n
(+ (sfib (- n 1))
(sfib (- n 2))))))
(time (gfib 40))
(time (tfib 40))
(time (sfib 40))
#!eof
(time (system "gcc -o gfib.so gfib.c -O2 -s -fPIC -shared"))
no collections
0.000000000s elapsed cpu time
0.259551000s elapsed real time
64 bytes allocated
(time (system "tcc -o tfib.so tfib.c -s -fPIC -shared"))
no collections
0.000000000s elapsed cpu time
0.065528500s elapsed real time
48 bytes allocated
(time (gfib 40))
no collections
0.671875000s elapsed cpu time
0.664039700s elapsed real time
0 bytes allocated
(time (tfib 40))
no collections
1.328125000s elapsed cpu time
1.339470400s elapsed real time
0 bytes allocated
(time (sfib 40))
no collections
1.406250000s elapsed cpu time
1.412271600s elapsed real time
0 bytes allocated
[Finished in 4.0s]
| false |
22c528fcf48651eb1e920f157ffd4bd5d2d52ace | bdeb8973603dd2ce97faaf59164f45fd322234c8 | /exercise-1-5-mini-project/grouping.scm | 6d3f22736d075f13d8e2df12500bdc3f07db69ad | []
| no_license | emilbaekdahl/pp-exercises | 782e080c5ab0a96210cec765699f0071a4ab558b | ce9e93d03357f2aec46f648b33d18205529f775d | refs/heads/master | 2020-07-28T00:50:05.001308 | 2019-11-13T21:44:15 | 2019-11-13T21:46:00 | 209,260,169 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 9,007 | scm | grouping.scm | ; Emil Bækdahl <[email protected]> (20165378)
; The first section of this file defines a number of functions for helping with
; the construction and inspection of groupings. The second section defines
; functions for the actual grouping tasks to be carried out in the project.
; These are random-grouping, grouping-by-counting, balanced-grouping-by-counting
; and random-grouping-predicate.
(load "group.scm")
(load "helpers.scm")
(load "random.scm")
; Grouping constructor. A grouping represents the relationship between multiple
; students and groups as a list of pairs on the form (group-id . student-id).
; This function returns a grouping based on a list of groups.
;
; Examples:
; >>> (grouping groups)
; >>> '((1 . "123") (1 . "234") (2 . "345") (2 . "345") ...)
(define (grouping groups)
(reduce append
(map (lambda (group)
(map (lambda (student-id)
(cons (group-id group) student-id))
(group-student-ids group)))
groups)
'()))
; Determines if a subject is a grouping.
(define (grouping? g)
(cond ((null? g) #t)
(else (and (pair? (car g))
(grouping? (cdr g))))))
; Returns all group ids in a grouping.
(define (grouping-group-ids grouping)
(unique (grouping-group-ids-helper grouping)))
; Helper function for grouping-group-ids
(define (grouping-group-ids-helper grouping)
(cond ((null? grouping) '())
(else (cons (caar grouping)
(grouping-group-ids-helper (cdr grouping))))))
; Get the ids of the students in a group in a grouping with a given id.
;
; Parameters:
; grouping (list): The grouping at interest.
; group-id (number): The id of the group we want the student ids from.
(define (grouping-group-student-ids grouping group-id)
(let ((pairs (filter grouping
(lambda (pair)
(= (car pair)
group-id)))))
(map (lambda (pair)
(cdr pair))
pairs)))
; Get a list of groups in a grouping based on a list of students. This extracts
; the group ids and their corresponding student ids from a grouping and creates
; groups with the group function.
;
; Parameters:
; grouping (list): The grouping at interest.
; students (list): A list of students which will be used to map the student
; ids in the grouping to an actual student association list.
(define (grouping-groups grouping students)
(let ((group-ids (grouping-group-ids grouping)))
(map (lambda (group-id)
(let* ((student-ids (grouping-group-student-ids grouping
group-id))
(students (map (lambda (student-id)
(student-find students student-id))
student-ids)))
(group group-id students)))
group-ids)))
; Get a single group by id from a grouping. Works by calling grouping-groups
; followed by a group-find with the passed id.
;
; Parameters:
; grouping (list): The grouping to find the group in.
; group-id (number): The id og the group to find.
; students (list): A list of students. This is needed since a grouping only
; contains the ids of the students and not all their information.
(define (grouping-group grouping group-id students)
(let ((groups (grouping-groups grouping students)))
(group-find groups group-id)))
; Return the number of groups in a grouping
(define (grouping-number-of-groups grouping)
(length (grouping-group-ids grouping)))
; Returns a list of group sizes in a grouping
(define (grouping-group-sizes grouping)
(let ((group-ids (grouping-group-ids grouping)))
(map (lambda (id)
(length (grouping-group-student-ids grouping id)))
group-ids)))
; Returns the size of the largest group in a grouping.
(define (grouping-max-group-size grouping)
(apply max (grouping-group-sizes grouping)))
; Returns the size of the smallest group in a grouping.
(define (grouping-min-group-size grouping)
(apply min (grouping-group-sizes grouping)))
; Pretty printer for a grouping
(define (print-grouping grouping students)
(let ((groups (grouping-groups grouping students)))
(for-each (lambda (group)
(begin (print-group group)
(newline)
(newline)))
groups)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Grouping formation functions ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Grouping by counting. Generates a grouping of students into k groups. This
; works by creating a list of same length as students that contains a repeating
; pattern of the numbers 1 to k in ascending order. This list is then zipped
; with a list of student ids, using pair-zip, and the result is returned.
;
; Parameters:
; students (list): A list of students created with the student function.
; k (number): The number of groups to create.
;
; Examples:
; >>> (grouping-by-counting students 3)
; >>> '((1 . "0001") (2 . "0002") (3 . "0003") (1 . "0004"))
(define (grouping-by-counting students k)
(let ((numbering (repeat (range 1 k) (length students)))
(student-ids (student-id-mapper students)))
(pair-zip numbering student-ids)))
; Balanced grouping by counting. This function works in the same way as
; grouping-by-counting but the list of students is first sorted by one or more
; keys. In this way we ensure that students with different values for the
; passed keys are distributed between the groups.
;
; Parameters:
; students (list): A list of students.
; k (number): The number of groups to form.
; key (symbol): The key to balance the students in the groups by. This has
; to correspond to a key in a student association list.
(define (balanced-grouping-by-counting students k . keys)
(let ((sorted (reduce (lambda (key lst)
(sort-by lst key))
keys
students)))
(grouping-by-counting sorted k)))
; This is a helper function for the last two grouping functions,
; random-grouping and random-grouping-predicate, that generate a list of groups
; from a list of students based on a list of group sizes. This works by, in
; each iteration, shuffling the list of students and creating a group from the
; first n students in that list (n being the current group size). The function
; returns #f if the list of groups sizes does not match the number of students.
;
; Parameters:
; students (list): A list of students.
; group-sizes (list): A list of group sizes to be created.
(define (random-groups students group-sizes)
(if (= (sum group-sizes)
(length students))
(cond ((null? students) '())
(else (let* ((shuffled (shuffle students))
(current-size (car group-sizes))
(remaining-sizes (cdr group-sizes))
(selected-students (take current-size students))
(remaining-students (drop current-size students)))
(cons (group (length group-sizes)
selected-students)
(random-groups remaining-students
remaining-sizes)))))
#f))
; Generate a random grouping of students based on a list of group sizes. This
; works by generating a random list of groups using the random-groups function
; and converting the result to a grouping.
;
; Parameters:
; students (list): A list of students.
; group-sizes (list): A list of group sizes to form.
(define (random-grouping students group-sizes)
(grouping (random-groups students group-sizes)))
; Generates a random grouping where each group should fulfil a predicate. If a
; result does not fulfil the predicate, the function is retried - up to 100
; times.
;
; Parameters:
; students (list): A list of students.
; group-sizes (list): A list of group sizes to form.
; predicate (procedure): A boolean predicate function that takes a group as
; parameter. We try to get all groups to fulfill this predicate.
(define (random-grouping-predicate students group-sizes predicate)
(grouping (random-grouping-predicate-helper students group-sizes predicate 1000)))
; Helper function for random-grouping-predicate which uses a limimt parameter
; to determine how many retries we allow at maximum. If this limit is hit, we
; return the latest grouping.
(define (random-grouping-predicate-helper students group-sizes predicate limit)
(let ((groups (random-groups students group-sizes)))
(cond ((or (= limit 0)
(all? groups predicate)) groups)
(else (random-grouping-predicate-helper (shuffle students)
group-sizes
predicate
(- limit 1))))))
| false |
74d94cad33d2192bf0346e107d9b9525e6a1b654 | 378e5f5664461f1cc3031c54d243576300925b40 | /rsauex/packages/devilutionx.scm | 2650ec0098aa3cfffbba3ea384e9dc1de292019b | []
| 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,436 | scm | devilutionx.scm | (define-module (rsauex packages devilutionx)
#:use-module ((gnu packages crypto) #:prefix crypto:)
#:use-module ((gnu packages sdl) #:prefix sdl:)
#:use-module ((guix build-system cmake) #:prefix cmake-build-system:)
#:use-module ((guix gexp))
#:use-module ((guix git-download) #:prefix git-download:)
#:use-module ((guix licenses) #:prefix licenses:)
#:use-module ((guix packages)))
(define-public devilutionx
(package
(name "devilution")
(version "1.1.0")
(source
(origin
(method git-download:git-fetch)
(uri (git-download:git-reference
(url "https://github.com/diasurgical/devilutionX")
(commit version)))
(file-name (git-download:git-file-name name version))
(sha256
(base32
"18kidqcdl7ny51hx7kpcw0nm5s77ns02xnspm80dqd12simgzbfx"))))
(build-system cmake-build-system:cmake-build-system)
(arguments
'(#:tests? #f
#:configure-flags
(list (string-append "-DTTF_FONT_DIR=\"" (assoc-ref %outputs "out") "/share/fonts/truetype/\""))))
(inputs
`(("libsodium" ,crypto:libsodium)
("sdl2-mixer" ,sdl:sdl2-mixer)
("sdl2-ttf" ,sdl:sdl2-ttf)))
(home-page "https://github.com/diasurgical/devilutionX")
(synopsis "Diablo build for modern operating systems.")
(description "Diablo build for modern operating systems.")
(license licenses:unlicense)))
| false |
33ef7427028e5885d0d2227d70919915e673d95e | c74dcb1facbd920d762017345171f47f8e41d0c5 | /chapter_1/1.3.scm | ef39d2cc8df9dbd38b8829098f14713cabdebbea | []
| no_license | akash-akya/sicp-exercises | 5125c1118c7f0e4400cb823508797fb67c745592 | c28f73719740c2c495b7bc38ee8b790219482b67 | refs/heads/master | 2021-06-15T19:12:47.679967 | 2019-08-03T14:03:20 | 2019-08-03T14:03:20 | 136,158,517 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 291 | scm | 1.3.scm | #lang sicp
(define (large-two a b c)
(if (or (> a b) (> a c))
(if (> b c)
(cons a b)
(cons a c))
(cons b c)))
(define (square a) (* a a))
(define (sum-of-square a b c)
(define pair (large-two a b c))
(+ (square (car pair))
(square (cdr pair))))
| false |
e27fb7cef5070313e417d429204afd7b20280d34 | ffb2e7c6951bb43c61fb5142c94f95f8b2ed5ffa | /Assignment 12/environment.ss | 0a8ea631ac9baab2aee5418edbeee3b6c246e5a0 | []
| no_license | shahdk/SchemeInterpreter | 6dd97d9ddf085947876eb569aab953c0dc1fef50 | 8a2035e658e862ab3c185fe362c2dd62ca46950a | refs/heads/master | 2021-01-10T19:51:02.159237 | 2014-06-12T01:04:44 | 2014-06-12T01:04:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,163 | ss | environment.ss | (define empty-env
(lambda ()
'()))
(define extend-env
(lambda (syms vals env)
(cons (cons syms (list->vector vals)) env)))
(define apply-env
(lambda (env sym)
(if (or (null? env) (null? (car env)))
(apply-global-env sym)
(let* ([syms (if (= (length (caar env)) 2)
(cond [(equal? (caaar env) 'variable) (cdaar env)]
[(equal? (caaar env) 'improper) (car (cdaar env))]
[(equal? (caaar env) 'sys-var) (list (caar env))]
[else (car (car env))])
(car (car env)))]
[vals (if (= (length (caar env)) 2)
(cond [(equal? (caaar env) 'variable) (vector (cdar env))]
[(equal? (caaar env) 'improper) (list->vector (apply-env-improper (length syms) (vector->list (cdar env))))]
[else (cdr (car env))])
(cdr (car env)))]
[env (cdr env)])
(let ([pos (find-position sym syms)])
(if (number? pos)
(if (vector? vals)
(let ([temp (vector-ref vals pos)])
(if (vector? temp)
(vector->list temp)
temp))
(let ([temp (list-ref vals pos)])
(if (vector? temp)
(vector->list temp)
temp)))
(apply-env env sym)))))))
(define add-to-env
(lambda (symbols values env)
(set-cdr! (car env) (list->vector (cons values (vector->list (cdar env)))))
(set-car! (car env) (cons symbols (caar env)))))
(define apply-env-improper
(lambda (len vals)
(cond
[(= len 1) (list vals)]
[else (append (list (car vals)) (apply-env-improper (- len 1) (cdr vals)))])))
(define find-position
(lambda (sym ls)
(cond [(null? ls) #f]
[(equal? sym (car ls)) 0]
[else (let ([index (find-position sym (cdr ls))])
(if (number? index)
(+ index 1)
#f))])))
(define environment?
(lambda (env)
(cond
[(or (null? env) (null? (car env))) #t]
[else (and (or ((list-of null?) (caar env)) ((list-of symbol?) (caar env))) (vector? (cdar env)) (environment? (cdr env)))])))
(define improper->proper
(lambda (p)
(if (not (pair? p))
(cons p '())
(cons (car p) (improper->proper (cdr p))))))
(define change-env
(lambda (env sym val)
(if (or (null? env) (null? (car env)))
(extend-global-env sym val)
(let ([syms (caar env)]
[vals (cdar env)]
[env (cdr env)])
(let ((pos (find-position sym syms)))
(if (number? pos)
(vector-set! vals pos val)
(change-env env sym val)))))))
(define make-indices
(lambda (n accu)
(if (= n 0)
(cons 0 accu)
(make-indices (- n 1) (cons n accu)))))
(define extend-global-env
(lambda (sym val)
(if (assq sym global-env)
(set-cdr! (assq sym global-env) (list val))
(set! global-env (cons (cons sym (list val)) global-env)))))
(define apply-global-env
(lambda (sym)
(let ([ele (assq sym global-env)])
(if ele
(cadr ele)
(begin (display sym) (read))))))
| false |
dc90bbe9f6bb797f32593b879746b33cad16f031 | 38bf86e526c4d667225531bb817237304f5339e6 | /lib/gr2e.scm | 710b7add042c53381b905c0f099f475f524fba56 | []
| no_license | SumiTomohiko/gauche-rss2email | c5aff808ca7cf9ece960d9cdf4030678f7307a4d | bec7faf44fcf81b13272ebdd768146fe32c17d23 | refs/heads/master | 2020-04-06T21:32:17.468515 | 2009-07-31T13:19:25 | 2009-07-31T13:19:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 28,830 | scm | gr2e.scm | ;; -*- coding: utf-8 -*-
(define-module gr2e
(export gr2e-main <gr2e-plugin>)
(use file.util)
(use gauche.charconv)
(use gauche.fcntl)
(use gauche.interactive)
(use gauche.parseopt)
(use rfc.base64)
(use rfc.http)
(use rfc.mime)
(use rfc.uri)
(use util.list)
(use util.match)
(use srfi-13)
(use sxml.ssax)
(use sxml.sxpath)
(use gr2e.gsmtp)
(use html2text)
(use html2text.htmlprag)
(use magic))
(select-module gr2e)
(define-class <gr2e-plugin> () (
(patterns :init-keyword :patterns :init-form '())
(get-body :init-keyword :get-body :init-value #f)))
(define-class <gr2e> () (
(verbose :init-keyword :verbose :init-value #f)
(name :init-keyword :name :init-value "")
(plugins :init-keyword :plugins :init-form '())
(config-dir
:init-keyword :config-dir
:init-value (build-path (home-directory) ".gr2e"))
(plugins-module :init-keyword :plugins-module :init-value "gr2e.plugins")))
(define-class <smtp> () (
(host :init-keyword :host :init-value "localhost")
(port :init-keyword :port :init-value 25)))
(define-class <settings> () (
(next-id :init-keyword :next-id :init-value 0)
(from :init-keyword :from :init-value "")
(to :init-keyword :to :init-value "")
(entries :init-keyword :entries :init-form (make-hash-table 'string=?))
(smtp :init-keyword :smtp :init-value (make <smtp>))))
(define-class <entry> () (
(id :init-keyword :id :init-value 0)
(tags :init-keyword :tags :init-value '())
(url :init-keyword :url :init-value "")
(last-entry :init-keyword :last-entry :init-value "")))
(define-class <rss-proc> () (
(rss->items :init-keyword :rss->items :init-value #f)
(item->link :init-keyword :item->link :init-value #f)
(item->body :init-keyword :item->body :init-value #f)
(item->title :init-keyword :item->title :init-value #f)))
(define (alist->smtp l)
(let ((smtp (make <smtp>)))
(for-each
(lambda (elem)
(case (car elem)
('host (set! (ref smtp 'host) (car (cdr elem))))
('port (set! (ref smtp 'port) (car (cdr elem))))))
l)
smtp))
(define (get-entry-attr ht attr)
(case attr
((id url) (car (hash-table-get ht attr)))
((tags) (hash-table-get ht attr))))
(define (list->entry l)
(let ((ht (alist->hash-table l)) (entry (make <entry>)))
(for-each
(lambda (attr) (set! (ref entry attr) (get-entry-attr ht attr)))
'(tags url id))
entry))
(define (hash->settings l)
(let ((settings (make <settings>)))
(hash-table-map (alist->hash-table l)
(lambda (key value)
(case key
((next-id from to) (set! (ref settings key) (car value)))
('entries
(for-each
(lambda (l)
(let ((entry (list->entry l)))
(hash-table-put!
(ref settings 'entries) (ref entry 'url) entry)))
value))
('smtp (set! (ref settings 'smtp) (alist->smtp value))))))
settings))
(define (get-settings-path config-dir) (build-path config-dir "settings"))
(define (load-settings config-dir)
(let (
(lock (make <sys-flock>)))
(if (not (file-is-directory? config-dir))
(make-directory* config-dir))
(let ((url-file (get-settings-path config-dir)))
(if (file-exists? url-file)
(let ((input-port (open-input-file url-file)))
(sys-fcntl input-port F_SETLKW lock)
(let ((l (read input-port)))
(close-input-port input-port)
(hash->settings l)))
(make <settings>)))))
(define (get-sxml-element path sxml)
(define (get-first-body elements)
(if (pair? elements)
(let ((element (car elements)))
(if (and (pair? element) (equal? (car element) '@))
(get-first-body (cdr elements))
element))
""))
(let1 elem ((sxpath path) sxml)
(if (pair? elem)
(get-first-body (cdar elem))
"")))
(define (multipart? mime)
(let ((type (ref mime 'type)))
(or (string=? type "multipart") (string=? type "message"))))
(define (mime->header-data mime)
(let (
(data "")
(transfer-encoding
(if (slot-bound? mime 'transfer-encoding)
(ref mime 'transfer-encoding)
"base64")))
(define (data-append s)
(set! data (string-append data s)))
(define (data-append-empty-line)
(data-append "\r\n"))
;; example; Content-Type: text/plain; charset=utf-8
(data-append
(format #f "Content-Type: ~a/~a" (ref mime 'type) (ref mime 'subtype)))
(if (ref mime 'parameters)
(begin
(let append-parameters ((parameters (ref mime 'parameters)))
(if (null? parameters)
#t
(begin
(data-append
(format
#f
"; ~a=\"~a\""
(car (car parameters)) (car (cdr (car parameters)))))
(append-parameters (cdr parameters)))))
(data-append "\r\n"))
#t)
(data-append
(if (multipart? mime)
""
(format #f "Content-Transfer-Encoding: ~a\r\n" transfer-encoding)))
(let data-append-headers ((headers (ref mime 'headers)))
(if (null? headers)
#t
(begin
(data-append
(format
#f
"~a: ~a\r\n"
(car (car headers))
(mime-encode-word (car (cdr (car headers))))))
(data-append-headers (cdr headers)))))
(data-append-empty-line)
(data-append
(if (multipart? mime)
"This is a multi-part message in MIME format.\r\n\r\n"
""))
data))
(define (mime-boundary mime)
(let find-boundary ((parameters (ref mime 'parameters)))
(cond
((null? parameters) "")
((equal? (car (car parameters)) "boundary") (car (cdr (car parameters))))
(else (cdr parameters)))))
(define (mime->data mime)
(let (
(transfer-encoding
(if (slot-bound? mime 'transfer-encoding)
(ref mime 'transfer-encoding)
"base64"))
(data (mime->header-data mime)))
(if (multipart? mime)
(begin
(let append-contents ((contents (ref mime 'content)))
(if (null? contents)
#t
(begin
(set! data (string-append data "--" (mime-boundary mime) "\r\n"))
(set! data (string-append data (mime->data (car contents))))
(append-contents (cdr contents)))))
(set! data (string-append data "--" (mime-boundary mime) "--\r\n")))
(cond
((equal? transfer-encoding "base64")
(set!
data
(string-append
data (base64-encode-string (ref mime 'content)) "\r\n")))
(else (error (format #f "Unknown encoding: ~a" transfer-encoding)))))
data))
(define (send-mail gr2e settings from to mime)
(let ((data (mime->data mime)) (smtp (ref settings 'smtp)))
(gsmtp-sendmail
(ref smtp 'host) (ref smtp 'port) from to data (ref gr2e 'verbose))))
(define (gr2e-http-get gr2e host port path query fragment)
(let (
(url (format #f "~a~a" host (if port (format #f ":~a" port) "")))
(path
(format
#f
"~a~a~a"
path
(if query (format #f "?~a" query) "")
(if fragment (format #f "#~a" fragment) ""))))
(when (ref gr2e 'verbose) (format #t "HTTP GET http://~a~a\n" url path))
(http-get url path)))
(define (send-rss-mail url rss-proc gr2e settings entry items)
(define (apply-plugin gr2e rss-proc item)
(define (apply-plugin-internal plugins rss-proc item link content)
(if (null? plugins)
(values link content)
(let1 plugin (car plugins)
(define (apply-patterns patterns link content)
(if (null? patterns)
(values link content)
(if ((car patterns) link)
(receive (link content)
((ref plugin 'get-body) link rss-proc item)
(apply-patterns (cdr patterns) link content))
(apply-patterns (cdr patterns) link content))))
(apply-patterns (ref plugin 'patterns) link content))))
(apply-plugin-internal
(ref gr2e 'plugins)
rss-proc
item
((ref rss-proc 'item->link) item)
((ref rss-proc 'item->body) item)))
(define (extract-images html)
(define (extract-images-internal sxml images)
(if (null? sxml)
images
(let1 elem (car sxml)
(if (pair? elem)
(if (equal? (car elem) 'img)
(extract-images-internal (cdr sxml) (append images (list elem)))
(extract-images-internal
(cdr sxml) (append (extract-images-internal elem '()) images)))
(extract-images-internal (cdr sxml) images)))))
(extract-images-internal (html->sxml html) '()))
(define (fetch-images url tags)
(fold
(lambda (tag seed)
(define (join-url url1 url2)
(cond
((#/^[A-Z]+:\/\//i url2) url2)
((string-prefix? url2 "/")
(receive
(scheme user host port path query fragment) (uri-parse url1)
(uri-compose
:scheme scheme
:userinfo user
:host host
:port port
:path url2)))
(else
(receive
(scheme user host port path query fragment) (uri-parse url1)
(let1 dir (sys-dirname path)
(uri-compose
:scheme scheme
:userinfo user
:host host
:port port
:path
(simplify-path
(string-join
(list dir url2)
(if (string-suffix? "/" dir) "" "/")))))))))
(receive
(scheme user host port path query fragment)
(uri-parse (join-url url (cadar ((sxpath '(@ src)) tag))))
(receive
(status headers body)
(gr2e-http-get gr2e host port path query fragment)
(append seed (if (string=? status "200") (list body) '())))))
'()
tags))
(if (null? items)
#t
(let* (
(item (car items))
(link ((ref rss-proc 'item->link) item)))
(if (string=? (ref entry 'last-entry) link)
#t
(receive (link content) (apply-plugin gr2e rss-proc item)
(let (
(boundary "----=_NextPart_34204_8606_01C88AB5.532EF880")
(from (ref settings 'from))
(to (ref settings 'to))
(body (make <mime-part>))
(mail (make <mime-part>)))
(set! (ref body 'type) "text")
(set! (ref body 'subtype) "plain")
(set! (ref body 'parameters) '(("charset" "utf-8")))
(set! (ref body 'transfer-encoding) "base64")
(set! (ref body 'headers) '())
(set! (ref body 'parent) mail)
(set! (ref body 'index) 0)
(set! (ref body 'content)
(string-append
(format #f "URL: ~a\n\n" link)
(html2text link content)
(format #f "\n\nURL: ~a" link)))
(set! (ref mail 'type) "multipart")
(set! (ref mail 'subtype) "alternative")
(set! (ref mail 'parameters) (list (list "boundary" boundary)))
(set! (ref mail 'headers)
(list
(list "From" from)
(list "To" to)
(list
"Subject"
(format
#f
"{gr2e}~a~a"
(string-join
(map
(cut format #f "{~a}" <>)
(sort (ref entry 'tags) (cut string<? <> <>)))
"")
(string-trim-both ((ref rss-proc 'item->title) item))))))
(set! (ref mail 'parent) #f)
(set! (ref mail 'content) (cons body '()))
(let1 images (extract-images content)
(when (pair? images)
(let1 cookie (magic-open MAGIC_MIME)
(magic-load cookie "")
(fold
(lambda (image seed)
(let* (
(type-subtype
(string-split
(magic-buffer cookie image (string-size image))
"/"))
(type (car type-subtype))
(subtype (cadr type-subtype)))
(if (string=? type "image")
(begin
(let1 mime (make <mime-part>)
(set! (ref mime 'type) type)
(set! (ref mime 'subtype) subtype)
(set! (ref mime 'parameters) '())
(set! (ref mime 'transfer-encoding) "base64")
(set! (ref mime 'headers) '())
(set! (ref mime 'parent) mail)
(set! (ref mime 'index) seed)
(set! (ref mime 'content) image)
(set!
(ref mail 'content)
(append (ref mail 'content) (list mime))))
(+ seed 1))
seed)))
2
(fetch-images url images))
(magic-close cookie))))
(send-mail gr2e settings from to mail)
(send-rss-mail url rss-proc gr2e settings entry (cdr items))))))))
(define (type-of-rss rss)
(define (skip-processing-instruction rss)
(let loop ((rss rss))
(let1 elem (car rss)
(if (pair? elem)
(if (#/^\*[A-Z]+\*$/ (symbol->string (car elem)))
(loop (cdr rss))
rss)
(loop (cdr rss))))))
(let1 tag (caar (skip-processing-instruction rss))
(case tag
((rdf RDF) 'rss1.0)
((rss RSS) 'rss2.0)
((feed FEED) 'atom)
(else
(let1 tag (car (reverse (string-split (symbol->string tag) ":")))
(cond
((string-ci=? tag "rdf") 'rss1.0)
((string-ci=? tag "rss") 'rss2.0)
((string-ci=? tag "feed") 'atom)
(else #f)))))))
(define (extract-namespace s)
(let1 splitter ":"
(string-join (reverse (cdr (reverse (string-split s splitter)))) splitter)))
(define (tag->symbol namespace tag)
(string->symbol (string-join (list namespace tag) ":")))
(define (make-atom-proc rss)
(let1 namespace (extract-namespace (symbol->string (caaddr rss)))
(let (
(feed-tag (tag->symbol namespace "feed"))
(entry-tag (tag->symbol namespace "entry"))
(link-tag (tag->symbol namespace "link"))
(content-tag (tag->symbol namespace "content"))
(title-tag (tag->symbol namespace "title")))
(make <rss-proc>
:rss->items (lambda (rss) ((sxpath (list feed-tag entry-tag)) rss))
:item->link
(lambda (item) (get-sxml-element (list link-tag '@ 'href) item))
:item->body (lambda (item) (get-sxml-element (list content-tag) item))
:item->title
(lambda (item) (get-sxml-element (list title-tag) item))))))
(define rss2.0-proc
(make <rss-proc>
:rss->items (lambda (rss) ((sxpath '(rss channel item)) rss))
:item->link (lambda (item) (get-sxml-element '(link) item))
:item->body (lambda (item) (get-sxml-element '(description) item))
:item->title (lambda (item) (get-sxml-element '(title) item))))
(define (make-rss1.0-proc rss)
(let* (
(tag-namespace "http://purl.org/rss/1.0/")
(attr-namespace "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
(rdf-tag (tag->symbol attr-namespace "RDF"))
(item-tag (tag->symbol tag-namespace "item"))
(about-tag (tag->symbol attr-namespace "about"))
(description-tag (tag->symbol tag-namespace "description"))
(title-tag (tag->symbol tag-namespace "title")))
(make <rss-proc>
:rss->items (lambda (rss) ((sxpath (list rdf-tag item-tag)) rss))
:item->link (lambda (item) (cadar ((sxpath (list '@ about-tag)) item)))
:item->body (lambda (item) (get-sxml-element (list description-tag) item))
:item->title (lambda (item) (get-sxml-element (list title-tag) item)))))
(define (make-rss-proc rss)
(let ((type (type-of-rss rss)))
(case type
((atom) (make-atom-proc rss))
((rss2.0) rss2.0-proc)
((rss1.0) (make-rss1.0-proc rss))
(else (error (format #f "Unknown RSS type: ~a" type))))))
(define (replace-env s)
(regexp-replace-all
#/(?:^|[^$])${(?<name>[A-Z]+)}/
s
(lambda (m)
(let* (
(name (rxmatch-substring m 'name))
(value (if (string=? name "HOME") (sys-getenv name) #f)))
(if value value (format #f "${~a}" name))))))
(define (get-rss-body gr2e entry)
(let1 entry-url (ref entry 'url)
(if (string-prefix? "http://" entry-url)
(receive (scheme user-info host port path query fragment)
(uri-parse entry-url)
(receive (status header body)
(gr2e-http-get gr2e host port path query fragment)
(if (equal? status "200") (ces-convert body "*JP") #f)))
(call-with-input-file (replace-env entry-url) (cut port->string <>)))))
(define (get-rss gr2e settings entry)
(guard (e
(else (format #t "ERROR: ~a\n~a\n" (ref entry 'url) (ref e 'message))))
(let1 body (get-rss-body gr2e entry)
(when body
(let* (
(rss (ssax:xml->sxml (open-input-string body) '()))
(rss-proc (make-rss-proc rss))
(items ((ref rss-proc 'rss->items) rss)))
(when (pair? items)
(send-rss-mail (ref entry 'url) rss-proc gr2e settings entry items)
(set!
(ref entry 'last-entry)
((ref rss-proc 'item->link) (car items)))))))))
(define (load-last-entry settings config-dir)
(guard (e (<error> (print "INFO: " (ref e 'message))))
(let* (
(path (build-path config-dir "last-entry"))
(port (open-input-file path))
(ht (alist->hash-table (read port))))
(close-input-port port)
(hash-table-map ht
(lambda (key value)
(guard (e (<error> (print (ref e 'message))))
(let* (
(entries (ref settings 'entries))
(entry (hash-table-get entries key)))
(set! (ref entry 'last-entry) (car value)))))))))
(define (call-with-locking path operation proc)
(let ((lock (make <sys-flock> :type F_WRLCK)))
(call-with-output-file
path
(lambda (port) (when (sys-fcntl port operation lock) (proc))))))
(define (call-with-locking-settings config-dir proc)
(call-with-locking (build-path config-dir ".lock.settings") F_SETLKW proc))
(define (call-with-locking-run config-dir proc)
(call-with-locking (build-path config-dir ".lock.run") F_SETLK proc))
(define (make-common-description settings)
(let ((smtp (ref settings 'smtp)))
(format #f "From: ~a
To: ~a
SMTP host: ~a
SMTP port: ~a
" (ref settings 'from) (ref settings 'to) (ref smtp 'host) (ref smtp 'port))))
(define (make-entry-description entry)
(format #f "id: ~a
url: ~a
tags: ~a
" (ref entry 'id) (ref entry 'url) (string-join (sort (ref entry 'tags)) " ")))
(define (execute-show gr2e args)
(define (usage gr2e)
(format #t "Usage: ~a show [ID]\n" (ref gr2e 'name))
(exit 0))
(let* (
(args (parse-options args (("h|help" => (cut usage gr2e)))))
(id (if (pair? args) (car args) #f))
(config-dir (ref gr2e 'config-dir))
(settings #f))
(call-with-locking-settings
config-dir
(lambda () (set! settings (load-settings config-dir))))
(display
(if id
(make-entry-description
(find
(lambda (entry) (= (ref entry 'id) (string->number id)))
(hash-table-values (ref settings 'entries))))
(string-join
(append
(list (make-common-description settings))
(map
(cut make-entry-description <>)
(sort
(hash-table-values (ref settings 'entries))
(lambda (entry-a entry-b)
(< (ref entry-a 'id) (ref entry-b 'id))))))
""))))
0)
(define (update-last-entry config-dir entries)
(call-with-output-file
(build-path config-dir "last-entry")
(lambda (port)
(write
(fold
(lambda (entry init)
(cons (list (ref entry 'url) (ref entry 'last-entry)) init))
'()
(hash-table-values entries))
port))))
(define (load-plugins gr2e)
(define (symbol->module-name module)
(regexp-replace-all #/\./ (symbol->string module) "/"))
(define (get-plugin-name plugin) (car (reverse (string-split plugin "/"))))
(for-each
(lambda (module)
(load module)
(set!
(ref gr2e 'plugins)
(append
(ref gr2e 'plugins)
(list
((eval
(string->symbol
(format #f "get-~a-plugin" (get-plugin-name module)))
(interaction-environment)))))))
(library-fold
(regexp-replace-all
#/\./ (format #f "~a.*" (ref gr2e 'plugins-module)) "/")
(lambda (name path seed) (cons name seed))
'())))
(define (execute-run gr2e args)
(define (usage gr2e)
(format #t "Usage: ~a run\n" (ref gr2e 'name))
(exit 0))
(let1 args (parse-options args (("h|help" => (cut usage gr2e))))
(load-plugins gr2e)
(let ((config-dir (ref gr2e 'config-dir)))
(call-with-locking-run
config-dir
(lambda ()
(let ((settings #f))
(call-with-locking-settings
config-dir
(lambda () (set! settings (load-settings config-dir))))
(load-last-entry settings config-dir)
(let ((entries (ref settings 'entries)))
(hash-table-map
entries
(lambda (key value) (get-rss gr2e settings value)))
(update-last-entry config-dir entries)))))))
0)
(define (execute-init gr2e args)
(define (usage gr2e)
(format #t "Usage: ~a init\n" (ref gr2e 'name))
(exit 0))
(let (
(args (parse-options args (("h|help" => (cut usage gr2e)))))
(config-dir (ref gr2e 'config-dir)))
(make-directory* config-dir)
(call-with-output-file
(get-settings-path config-dir)
(lambda (port)
(write
(list
(list 'from "")
(list 'to "")
(list 'next-id 0)
(list 'entries)
(list 'smtp (list 'host "127.0.0.1") (list 'port 25)))
port))))
0)
(define (save-settings config-dir settings)
(call-with-output-file
(get-settings-path config-dir)
(lambda (port)
(let ((entries (ref settings 'entries)) (smtp (ref settings 'smtp)))
(write
(list
(list 'next-id (ref settings 'next-id))
(list 'from (ref settings 'from))
(list 'to (ref settings 'to))
(append
'(entries)
(map
(lambda (entry)
(list
(list 'id (ref entry 'id))
(list 'url (ref entry 'url))
(append '(tags) (ref entry 'tags))))
(hash-table-values entries)))
(list
'smtp
(list 'host (ref smtp 'host))
(list 'port (ref smtp 'port))))
port)))))
(define (call-with-read-write-settings config-dir proc)
(call-with-locking-settings
config-dir
(lambda ()
(let ((settings (load-settings config-dir)))
(let ((status (proc settings)))
(save-settings config-dir settings)
status)))))
(define (execute-edit gr2e args)
(define (usage gr2e)
(let1 name (ref gr2e 'name)
(format #t "Usage: ~a edit from <From>\n" name)
(format #t " ~a edit to <To>\n" name)
(format #t " ~a edit tag <ID> [TAGS...]\n" name)
(format #t " ~a edit smtp host <Host>\n" name)
(format #t " ~a edit smtp port <Port>\n" name))
(exit 0))
(let (
(args (parse-options args (("h|help" => (cut usage gr2e)))))
(config-dir (ref gr2e 'config-dir)))
(call-with-read-write-settings
config-dir
(lambda (settings)
(let ((entries (ref settings 'entries)) (smtp (ref settings 'smtp)))
(match args
(("from" from) (set! (ref settings 'from) from))
(("to" to) (set! (ref settings 'to) to))
(("tag" id . tags)
(let* (
(id (string->number id))
(entry
(find
(lambda (entry) (= (ref entry 'id) id))
(hash-table-values entries))))
(set! (ref entry 'tags) tags)))
(("smtp" "host" host) (set! (ref smtp 'host) host))
(("smtp" "port" port) (set! (ref smtp 'port) (string->number port)))
(else (usage gr2e)))))))
0)
(define (execute-add gr2e args)
(define (usage gr2e)
(format #t "Usage: ~a add <URL> [TAGS...]\n" (ref gr2e 'name))
(exit 0))
(let1 args (parse-options args (("h|help" => (cut usage gr2e))))
(when (null? args) (usage gr2e))
(let (
(url (car args)) (tags (cdr args)) (config-dir (ref gr2e 'config-dir)))
(call-with-read-write-settings
config-dir
(lambda (settings)
(hash-table-put!
(ref settings 'entries)
url
(make <entry> :url url :id (ref settings 'next-id) :tags (sort tags)))
(set! (ref settings 'next-id) (+ (ref settings 'next-id) 1))))))
0)
(define (execute-remove gr2e args)
(define (usage gr2e)
(format #t "Usage: ~a remove <ID>\n" (ref gr2e 'name))
(exit 0))
(let1 args (parse-options args (("h|help" => (cut usage gr2e))))
(when (null? args) (usage gr2e))
(let ((id (car args)) (config-dir (ref gr2e 'config-dir)))
(call-with-read-write-settings
config-dir
(lambda (settings)
(let (
(url
(ref
(find
(lambda (entry) (= (ref entry 'id) (string->number id)))
(hash-table-values (ref settings 'entries)))
'url)))
(hash-table-delete! (ref settings 'entries) url))))))
0)
(define (gr2e-main args)
(define (usage gr2e)
(format #t "Usage: ~a [OPTIONS...] SUBCOMMAND [OPTIONS...]
OPTIONS
-p: plugins module name
-I: load-path
-c --config: configure directory
-h --help: show this message
SUBCOMMAND
add: add new RSS entry.
edit: edit RSS entry.
remove: remove RSS entry.
run: fetch RSS.
show: show entry infomation.
For detail, use --help option for each subcommand.
" (ref gr2e 'name))
(exit 0))
(debug-print-width 1024)
(let ((gr2e (make <gr2e> :name (car args))))
(let (
(args
(parse-options (cdr args) (
("v|verbose" => (lambda () (set! (ref gr2e 'verbose) #t)))
("h|help" => (cut usage gr2e))
("p=s" =>
(lambda (plugins-module)
(set! (ref gr2e 'plugins-module) plugins-module)))
("I=s" => (lambda (path) (append! *load-path* (list path))))
("c|config=s" =>
(lambda (dir) (set! (ref gr2e 'config-dir) dir)))))))
(if (pair? args)
(let ((subcommand (string->symbol (car args))) (subargs (cdr args)))
(case subcommand
((run) (execute-run gr2e subargs))
((show) (execute-show gr2e subargs))
((init) (execute-init gr2e subargs))
((edit) (execute-edit gr2e subargs))
((add) (execute-add gr2e subargs))
((remove) (execute-remove gr2e subargs))
(else
(format #t "Unknown subcommand: ~a\n" subcommand)
(usage gr2e))))
(usage gr2e)))))
(provide "gr2e")
;; vim: tabstop=2 shiftwidth=2 expandtab softtabstop=2 filetype=scheme
| false |
82a8a2a87dbb2a614e6e3fe388e701bb743c0270 | 801a158ca6e2ba7651907c347fefc2930f327141 | /tests/test-define.ss | aed47375b14087489bc2d739d276f0f1f60e8503 | [
"MIT"
]
| permissive | evilbinary/duck-compiler | 8782cc049b9175902bdb482ba4aff5107aace193 | 8c64a521f012aa6b2b7b9385f11976b216cc07e0 | refs/heads/master | 2021-07-06T07:44:33.933316 | 2020-10-25T04:02:36 | 2020-10-25T04:02:36 | 195,368,722 | 29 | 4 | null | null | null | null | UTF-8 | Scheme | false | false | 1,557 | ss | test-define.ss | ;; test
(import (scheme) (test) (duck) )
(add-test "test define"
; [(define a 100) ""]
; [(define square
; (lambda (x)
; (* x x)))
; ""
; ]
; [(define (square x b)
; (* x x))
; ""
; ]
[(begin
(define a 100)
(define (test x) x)
)
""
]
; [(begin
; (define hello (lambda (n)
; (printc "hello")
; ))
; (hello)
; )
; "hello"
; ]
; [(begin
; (define fib (lambda (n)
; (printc "fib(%d)" n)
; (fib (- n 1))
; ))
; (fib 10)
; )
; '()
; ]
;;no pass
; [(begin
; (define fib (lambda (n)
; ;;(printc "fib[%d] \\n" n)
; (if (= n 0)
; (begin
; (printc "1 ")
; 0
; )
; (if (= n 1)
; (begin
; (printc "2 ")
; 1
; )
; (begin
; (printc "f2[%d] " n)
; (+ (fib (- n 1)) (fib (- n 2)))
; )
; )
; )
; ))
; (printc "test=%d" (fib 10))
; ) '()]
)
; (add-test "test combine"
; [(set! square (lambda (x) (* x x))) '()]
; [(define a (lambda () (a))) '()]
; [(begin
; (define (factorial n)
; (define (iter product counter)
; (if (> counter n)
; product
; (iter (* counter product)
; (+ counter 1))))
; (iter 1 1))
; (printc "ret=%d" (factorial 30)) )
; '()]
; )
(test-all)
| false |
aa73e57ec373f7e5ac8b069e787055f884623631 | d57239c14ab14ee3a119ba3f1091d0016f46b7e5 | /submission/icfp08/src/scheme/remember.scm | bcc0587a5ec04e7123ca0d7310b2fdb1329a2a58 | []
| no_license | magnusjonsson/tidder-icfpc-2008 | c09b0684825375180ca7216fb30c3420af68d153 | 84d68fd9ac358c38e7eff99117d9cdfa86c1864a | refs/heads/master | 2021-05-16T02:58:02.169244 | 2020-10-03T06:54:11 | 2020-10-03T06:54:11 | 25,338 | 3 | 1 | null | 2020-10-03T06:54:12 | 2008-06-14T20:05:00 | Scheme | UTF-8 | Scheme | false | false | 11,425 | scm | remember.scm | #lang scheme
(require "messages.scm")
(require "vec2.scm")
(require "intersect.scm")
(require "tangent.scm")
(require "misc-syntax.ss")
(require (only-in rnrs/base-6 assert))
(require (prefix-in gfx- "graphics.scm"))
(provide remember-objects remember-object
print-remembered clear-remembered
first-hit-obj first-hit-time
first-curve-hit-angle first-curve-hit-obj
line-obstructed?
unobstructed-point-obj-tangents
unobstructed-obj-obj-tangents
remembered-dirty?
clear-remembered-dirty
draw-remembered
)
; We store all objects seen.
; The value corresponding to each object is a parent object as in the Union-Find algorithm.
;
(define-struct versioned-tangents (version tangents) #:mutable)
(define-struct info (parent ; used for union-find to group connected objects
; add more here as needed
ccw ; versioned-tangents
cw ; versioned-tangents
neighbours
) #:mutable)
(define obj-count 0)
(define group-count 0)
(define remembered (make-hash)) ; obj -> info
; new objects are pushed here in the order they arrive
(define history '())
(define (objects-added-since version)
(let ((h history)
(r '()))
(while (not (eq? h version))
(push! r (pop! h)))
r))
(define (clear-remembered)
(set! remembered (make-hash))
(set! history '())
(set! obj-count 0)
(set! group-count 0)
(set! dirty #t))
(define dirty #t)
(define (remembered-dirty?)
dirty)
(define (clear-remembered-dirty)
(set! dirty #f))
(define (remember-object o)
(remember-objects (list o)))
; more efficient than remember-object
(define (remember-objects objects)
(let ((new-objects (filter (lambda (o)
(and (obj? o)
(not (equal? 'home-base (obj-kind o)))
(not (hash-ref remembered o #f))))
objects)))
;(printf "received new objects: ~a~n" new-objects)
;(printf "checking old tangents~n")
(for-each (lambda (o)
(assert (obj? o))
(let ()
(hash-set! remembered o
(make-info o ; parent
(make-versioned-tangents '() '())
(make-versioned-tangents '() '())
'() ; neighbours
))
; pushing to history
(push! history o)
(inc! obj-count)
(inc! group-count)
;(printf "merging obj to groups~n")
(merge-new-obj o)
;(printf "done merging~n")
(set! dirty #t)))
new-objects)))
(define (test-remember-objects)
(clear-remembered)
(remember-objects
(list (make-obj 'crater (make-vec2 50.0 -5.0) 5.0) (make-obj 'crater (make-vec2 50.0 5.0) 5.0))))
(define (add-neighbor a b)
(define (add-single-neighbor a b)
(let ((info (hash-ref remembered a)))
(set-info-neighbours! info (cons b (info-neighbours info)))))
(add-single-neighbor a b)
(add-single-neighbor b a))
(define (merge-new-obj o)
(hash-for-each remembered
(lambda (obj parent)
(when (and (not (eq? o obj)) (objects-overlap? o obj))
(merge o obj)
(add-neighbor o obj)))))
; the Union part of Union-Find
(define (merge a b)
(let ((a (find a))
(b (find b)))
(when (not (equal? a b))
(when (< (random) 0.5)
(swap! a b))
(set-info-parent! (hash-ref remembered a) b)
(dec! group-count)
;(printf "~a objs in ~a groups~n" obj-count group-count)
(assert (> obj-count group-count 0))
)))
; the Find part of Union-Find
(define (find o)
(let* ((o-info (hash-ref remembered o #f))
(p (info-parent o-info)))
(if (equal? p o)
o
(let ((g (find p)))
(set-info-parent! o-info g)
g))))
(define (same-group? a b)
(eq? (find a) (find b)))
(define (print-remembered)
(printf "remembered objects:")
(hash-for-each remembered
(lambda (key value)
(printf " ~a" key)))
(printf "~n"))
(define (line-obstructed? p0 p1 (tabu-obj-list '()))
(let ((t (first-hit-time p0 (vec2- p1 p0) tabu-obj-list)))
(and t (< t 1))))
(define (first-hit-time origin ray (tabu-obj-list '()))
(let ((b (first-hit-obj origin ray tabu-obj-list)))
(and b (ray-circle-intersection-first-time origin ray (obj-pos b) (obj-radius b)))))
(define (first-hit-obj origin ray (tabu-obj-list '()))
(let ((best-time #f)
(best-obj #f))
(hash-for-each remembered
(lambda (obj parent)
; if there's an intersection that happens before
; target-distance, (return obj)
(when (not (member obj tabu-obj-list))
(let ((t (ray-circle-intersection-first-time
origin ray (obj-pos obj) (obj-radius obj))))
(when t
(unless (and best-time (< best-time t))
(set! best-obj obj)
(set! best-time t)))))))
best-obj))
(define (first-curve-hit-angle curve-start curve-center direction)
(let ((best-angle #f))
; possible optimization: only check adjacent obstacles
(hash-for-each remembered
(lambda (obj _)
(let ((t (curve-circle-intersection-angle
curve-start curve-center direction
(obj-pos obj) (obj-radius obj))))
(when t
(unless (and best-angle (< best-angle t))
(set! best-angle t))))))
best-angle))
(define (first-curve-hit-obj obj curve-start curve-center direction)
(let ((best-angle #f)
(best-obj #f))
; only check neighbors
(for-each (lambda (o)
(let ((t (curve-circle-intersection-angle2
curve-start curve-center (obj-radius obj) direction
(obj-pos o) (obj-radius o))))
(when t
(unless (and best-angle (< best-angle t))
(set! best-angle t)
(set! best-obj o)))))
(info-neighbours (hash-ref remembered obj)))
best-obj))
(define (objects-overlap? o1 o2)
(<= (vec2-distance (obj-pos o1) (obj-pos o2))
(+ (obj-radius o1) (obj-radius o2))))
(define (unobstructed-point-obj-tangents point)
(let ((result '()))
(define (consider obj dir)
(let ((tangent-point (tangent point (obj-pos obj) (obj-radius obj) (- dir))))
(unless (line-obstructed? point tangent-point (list obj))
(push! result (list obj dir tangent-point)))))
(hash-for-each remembered
(lambda (obj _)
(consider obj -1)
(consider obj 1)))
result))
(define (unobstructed-obj-obj-tangents obj1 dir1)
(let* ((info (hash-ref remembered obj1))
(versioned-tangents (match dir1
(1 (info-ccw info))
(-1 (info-cw info)))))
(bring-tangents-up-to-date versioned-tangents obj1 dir1)
(versioned-tangents-tangents versioned-tangents)))
(define (bring-tangents-up-to-date vt obj1 dir1)
(let ((new-objs (objects-added-since (versioned-tangents-version vt))))
(set-versioned-tangents-tangents!
vt
(append (discover-new-tangents obj1 dir1 new-objs)
(filter-old-tangents (versioned-tangents-tangents vt) new-objs)))
(set-versioned-tangents-version! vt history)))
(define (discover-new-tangents obj1 dir1 new-objs)
(let ((result '()))
(define (consider obj2 dir2)
(let ((tangent-points (circle-circle-tangent (obj-pos obj1) (obj-radius obj1) dir1
(obj-pos obj2) (obj-radius obj2) dir2)))
(unless (line-obstructed? (car tangent-points) (cdr tangent-points) (list obj1 obj2))
(push! result (list (car tangent-points)
obj2 dir2 (cdr tangent-points))))))
(for-each (lambda (obj2)
(when (not (equal? obj1 obj2))
; straight loop
(consider obj2 dir1)
(unless (objects-overlap? obj1 obj2)
; zig-zagging between overlapping objects doesn't
; make sense
(consider obj2 (- dir1)))))
new-objs)
result))
(define (filter-old-tangents tangents new-objs)
(define (clear? tangent)
(match tangent
((list point1 obj2 dir2 point2)
(not (ormap (lambda (o)
(line-intersects-circle? point1 point2 (obj-pos o) (obj-radius o)))
new-objs)))))
(filter clear? tangents))
(define (test)
(test1)
(test2)
(test3)
(test-remember-objects))
(define (test1)
(clear-remembered)
(remember-objects (list (make-obj 'crater (make-vec2 10 0) 1)))
(printf "~a~n~n" (unobstructed-point-obj-tangents (make-vec2 0 0)))
(remember-objects (list (make-obj 'crater (make-vec2 5 1) 1)))
(printf "~a~n~n" (unobstructed-point-obj-tangents (make-vec2 0 0))))
(define (test2)
(clear-remembered)
(let ((o1 (make-obj 'crater (make-vec2 10 0) 1))
(o2 (make-obj 'crater (make-vec2 5 0) 2))
(o3 (make-obj 'crater (make-vec2 0 0) 1)))
(remember-objects (list o1 o2 o3))
(assert (line-obstructed? (make-vec2 2 0) (make-vec2 8 0) (list)))
(assert (line-obstructed? (make-vec2 2 0) (make-vec2 8 0) (list o1 o3)))
(assert (not (line-obstructed? (make-vec2 2 0) (make-vec2 8 0) (list o1 o2 o3))))
))
(define (test3)
(define (pretty-list-of-length correct-length list)
(printf "list:~n")
(dolist (i list)
(printf "--> ~a~n" i))
(assert (= (length list) correct-length)))
(clear-remembered)
(let ((o1 (make-obj 'crater (make-vec2 10 0) 1))
(o2 (make-obj 'crater (make-vec2 0 0) 1)))
(remember-objects (list o1 o2))
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o1 -1))
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o1 1))
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o2 -1))
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o2 1))
; put something between them
(let ((o3 (make-obj 'crater (make-vec2 5 0) 2)))
(remember-object o3)
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o1 -1))
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o1 1))
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o2 -1))
(pretty-list-of-length 2 (unobstructed-obj-obj-tangents o2 1))
(pretty-list-of-length 4 (unobstructed-obj-obj-tangents o3 -1))
(pretty-list-of-length 4 (unobstructed-obj-obj-tangents o3 1))
)))
(define (draw-remembered)
(when (gfx-on?)
(hash-for-each remembered
(lambda (obj _)
(let ((p (obj-pos obj)))
(gfx-circle (vec2-x p) (vec2-y p) (obj-radius obj)))))))
| false |
cbb2770b3295f169e550b1d9c27ccd8c2cb0b5f2 | 29fdc68ecadc6665684dc478fc0b6637c1293ae2 | /package.scm | 0d36140876858d23bb0a4012414fb36d82698d5c | [
"MIT"
]
| permissive | shirok/WiLiKi | 5f99f74551b2755cb4b8deb4f41a2a770138e9dc | f0c3169aabd2d8d410a90033d44acae548c65cae | refs/heads/master | 2023-05-11T06:20:48.006068 | 2023-05-05T18:29:48 | 2023-05-05T18:30:12 | 9,766,292 | 20 | 6 | MIT | 2018-10-07T19:15:09 | 2013-04-30T07:40:21 | Scheme | UTF-8 | Scheme | false | false | 345 | scm | package.scm | (define-gauche-package "WiLiKi"
:version "0.8.2"
:description "WikiClone written in Scheme."
:require (("Gauche" (>= "0.9.10")))
:maintainers ("[email protected]")
:authors ("Shiro Kawai <[email protected]>")
:homepage "https://practical-scheme.net/wiliki/wiliki.cgi"
:repository "https://github.com/shirok/WiLiKi"
:licenses ("BSD")
)
| false |
e8f96a920ed1c3b0a44338b34c5f771fef899827 | 46244bb6af145cb393846505f37bf576a8396aa0 | /eopl/ch2/2.19.scm | 87f308b57e660b0de2297948342dddcc6790b55f | []
| no_license | aoeuidht/homework | c4fabfb5f45dbef0874e9732c7d026a7f00e13dc | 49fb2a2f8a78227589da3e5ec82ea7844b36e0e7 | refs/heads/master | 2022-10-28T06:42:04.343618 | 2022-10-15T15:52:06 | 2022-10-15T15:52:06 | 18,726,877 | 4 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 1,075 | scm | 2.19.scm | #lang racket
(define (action-fail action reason)
(error action reason))
(define (number->bintree n) `(,n () ()))
(define current-element car)
(define at-leaf? null?)
(define (move-to-left t)
(if (at-leaf? t)
(action-fail 'move-to-left 'met-leaf)
(cadr t)))
(define (move-to-right t)
(if (at-leaf? t)
(action-fail 'move-to-right 'met-leaf)
(caddr t)))
(define (insert-to-left n t)
(list (current-element t)
(if (at-leaf? (move-to-left t))
(number->bintree n)
(list n (move-to-left t) '()))
(move-to-right t)))
(define (insert-to-right n t)
(list (current-element t)
(move-to-left t)
(if (at-leaf? (move-to-right t))
(number->bintree n)
(list n '() (move-to-right t)))
))
(number->bintree 13)
(define t1 (insert-to-right
14
(insert-to-left
12
(number->bintree 13))))
t1
(move-to-left t1)
(current-element (move-to-left t1))
(at-leaf? (move-to-right (move-to-left t1)))
(insert-to-left 15 t1) | false |
eed1c0e363b8cb39d3db081e178c2f544ff7b29f | b14c18fa7a4067706bd19df10f846fce5a24c169 | /Chapter2/2.20.scm | f72d1dcc9f644a1f413a5f5d798bf87d8341add0 | []
| no_license | silvesthu/LearningSICP | eceed6267c349ff143506b28cf27c8be07e28ee9 | b5738f7a22c9e7967a1c8f0b1b9a180210051397 | refs/heads/master | 2021-01-17T00:30:29.035210 | 2016-11-29T17:57:16 | 2016-11-29T17:57:16 | 19,287,764 | 3 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 323 | scm | 2.20.scm | #lang scheme
(include "map.scm")
(filter (lambda (x) (= (remainder x 2) 0)) (list 1 2 3 4 5))
(filter (lambda (x) (= (remainder x 2) 1)) (list 1 2 3 4 5))
(define (same-parity x . y)
(filter
(lambda (i) (= (remainder i 2) (remainder x 2)))
(cons x y)
)
)
(same-parity 1 2 3 4 5 6 7)
(same-parity 0 1 2 3 4 5 6 7) | false |
d33a4b8acc2d759f3a612e3ac681a672a3ccf3bf | b14c18fa7a4067706bd19df10f846fce5a24c169 | /Chapter1/1.22.scm | 8082fcda2cb42b0317daa44704d138713f78cc66 | []
| no_license | silvesthu/LearningSICP | eceed6267c349ff143506b28cf27c8be07e28ee9 | b5738f7a22c9e7967a1c8f0b1b9a180210051397 | refs/heads/master | 2021-01-17T00:30:29.035210 | 2016-11-29T17:57:16 | 2016-11-29T17:57:16 | 19,287,764 | 3 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,688 | scm | 1.22.scm | #lang scheme
(define (square x) (* x x))
(define (divides? a b)
(= (remainder b a) 0))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (smallest-divisor n)
(find-divisor n 2))
; above from 1.21
(define (prime? n)
(= n (smallest-divisor n)))
(define (timed-prime-test n)
(newline)
(display "Begin Test on ")
(display n)
(start-prime-test n (current-milliseconds)))
(define (start-prime-test n start-time)
(let ((r (prime? n)))
;(report-prime (- (current-milliseconds) start-time))
(if r
(report-prime (- (current-milliseconds) start-time))
#f
)
)
)
(define (report-prime elapsed-time)
(newline)
(display "End Test")
(newline)
(display " *** ")
(display elapsed-time)
(newline)
#t)
; found large prime here http://www.arachnoid.com/prime_numbers/
;(timed-prime-test 9007199254740881)
;(timed-prime-test 11)
; profiling function "time"
;(time (prime? 9007199254740881))
(define (search-for-prime n)
(if (= (remainder n 2) 0)
(search-for-prime (+ n 1))
(unless (timed-prime-test n) ; use when as "if only", use unless as "else only"
(search-for-prime (+ n 2))
)
)
)
;(search-for-prime 1000)
;(search-for-prime 10000)
;(search-for-prime 100000)
;(search-for-prime 1000000)
;(search-for-prime 10000000)
; Can not take reasonable time on small number
(search-for-prime 1000000000000000) ; 1000000000000037 : 577
(search-for-prime 10000000000000000) ; 10000000000000061 : 1916
(search-for-prime 100000000000000000) ; 100000000000000003 : 5975
(search-for-prime 1000000000000000000) ; 1000000000000000003 : 20424
| false |
dba4643c1090055cc430b5ec99f147803627a216 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /mscorlib/system/security/policy/strong-name.sls | 963aaa71551dc85d10559839f61244a5cde11253 | []
| 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,643 | sls | strong-name.sls | (library (system security policy strong-name)
(export new
is?
strong-name?
get-hash-code
to-string
create-identity-permission
copy
equals?
name
public-key
version)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.Security.Policy.StrongName a ...)))))
(define (is? a) (clr-is System.Security.Policy.StrongName a))
(define (strong-name? a) (clr-is System.Security.Policy.StrongName a))
(define-method-port
get-hash-code
System.Security.Policy.StrongName
GetHashCode
(System.Int32))
(define-method-port
to-string
System.Security.Policy.StrongName
ToString
(System.String))
(define-method-port
create-identity-permission
System.Security.Policy.StrongName
CreateIdentityPermission
(System.Security.IPermission System.Security.Policy.Evidence))
(define-method-port
copy
System.Security.Policy.StrongName
Copy
(System.Object))
(define-method-port
equals?
System.Security.Policy.StrongName
Equals
(System.Boolean System.Object))
(define-field-port
name
#f
#f
(property:)
System.Security.Policy.StrongName
Name
System.String)
(define-field-port
public-key
#f
#f
(property:)
System.Security.Policy.StrongName
PublicKey
System.Security.Permissions.StrongNamePublicKeyBlob)
(define-field-port
version
#f
#f
(property:)
System.Security.Policy.StrongName
Version
System.Version))
| true |
7253aed4bb07a8a79b19af01385fe5ab525a1add | 3b3a00b8f68d2032dcdca64e5dbeefdcf37c06a5 | /Compiler/optimize-jumps.ss | 1c77c72b423813088c1d78845cccaac2c24b71ab | []
| no_license | iomeone/p423-compiler | 1615b9bd3b8ef910a7217244924b8c8d283f7eca | 5efe33f128d6d4b3decb818f315d9f14781cc241 | refs/heads/master | 2020-12-09T03:10:46.831308 | 2015-05-04T03:36:37 | 2015-05-04T03:36:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 4,475 | ss | optimize-jumps.ss | #|
A11 - Apr 03, 2015
pass: optimize-jumps
This pass removes redundant jumps (function calls) from the code.
how it works:
1. find all redundant stuffs (`[label (lambda () (jump))]`), then add relations (label -> jump) to a graph
2. remove all the bindings as above; for circular (mutual) references, add a dummy binding to the program (e.g., `[f$1 (lambda () (f$1))]`)
3. replace all old labels in the body with the new labels (meaningful ones)
Input & Output:
Program ::= (letrec ((Label (lambda () Tail)) *) Tail) ;;
Tail ::= (if (Relop Triv Triv) (Label) (Label)) ;;
| (begin Effect * Tail)
| (Triv)
Effect ::= (set! Loc Triv) ;;
| (set! Loc (Binop Triv Triv)) ;;
Triv ::= Loc ;;
| Integer | Label
Loc ::= Reg | Disp | Ind ;;
|#
(library (Compiler optimize-jumps)
(export optimize-jumps)
(import
(chezscheme)
(Framework helpers)
(Framework match)
(Compiler common)
(Compiler utils))
(define-who optimize-jumps
(define (get-new-def*-and-jump-table defs*)
(let loop ([defs* defs*] [jump-table '()] [acc '()])
(cond
[(null? defs*) (values (reverse acc) (reverse jump-table))]
[(null? (car defs*)) (loop (cdr defs*) jump-table acc)]
[(label? (caar (cddadr (car defs*)))) ;; i know, i know... but it works.
(loop (cdr defs*)
(graphq-add (caar defs*) `(,(caar (cddadr (car defs*)))) jump-table)
acc)]
[else (loop (cdr defs*) jump-table (cons (car defs*) acc))])))
(define (resolve-jt-and-new-defs old-labels jump-table)
(let loop ([labels old-labels] [acc '()] [optional-new-defs '()])
(cond
[(null? labels) (values (reverse acc) (reverse optional-new-defs))]
[(null? (graphq-dfs (car labels) jump-table)) ;; oops, circular references
(loop (cdr labels)
acc
(cons `[,(car labels) (lambda () (,(car labels)))] optional-new-defs))]
[else (loop (cdr labels)
(cons `(,(car labels) . ,(car (graphq-dfs (car labels) jump-table))) acc)
optional-new-defs)])))
(define replace-label
(lambda (j-pairs)
(lambda (label)
(cond
[(assq label j-pairs) => cdr]
[else label]))))
(define Tail
(lambda (j-pairs)
(lambda (tail)
(match tail
[(if (,relop ,[(Triv j-pairs) -> triv1] ,[(Triv j-pairs) -> triv2])
(,label1) (,label2))
`(if (,relop ,triv1 ,triv2)
(,((replace-label j-pairs) label1))
(,((replace-label j-pairs) label2)))]
[(begin ,[(Effect j-pairs) -> ef*] ... ,[tail])
`(begin ,ef* ... ,tail)]
[(,[(Triv j-pairs) -> triv]) `(,triv)]
[,el (errorf who "Invalid Tail ~s" el)]))))
(define Effect
(lambda (j-pairs)
(lambda (effect)
(match effect
[(set! ,loc (,binop ,[(Triv j-pairs) -> triv1] ,[(Triv j-pairs) -> triv2]))
`(set! ,loc (,binop ,triv1 ,triv2))]
[(set! ,loc ,[(Triv j-pairs) -> triv])
`(set! ,loc ,triv)]
[,el (errorf who "Invalid Effect ~s" el)]))))
(define Triv
(lambda (j-pairs)
(lambda (triv)
(match triv
[,int (guard (integer? int)) int]
[,lab (guard (label? lab)) ((replace-label j-pairs) lab)]
[,el el])))) ;; loc
(lambda (prog)
(match prog
[(letrec (,def* ...) ,tail) ;; def: [,label* (lambda () ,tail*)]
(let-values ([(new-def jump-table) (get-new-def*-and-jump-table def*)]) ;; generate new defs (without redundant jumps), and a graph for relations
(let-values ([(j-pairs new-defs-for-circular) ;; reduce the graph to an easy assoc. list, also gets dummy defs for mutual references
(resolve-jt-and-new-defs (map car jump-table) jump-table)])
(match `(letrec ,(append new-def new-defs-for-circular) ,tail)
[(letrec ([,f-label* (lambda () ,[(Tail j-pairs) -> f-tail*])] ...)
,[(Tail j-pairs) -> f-tail])
`(letrec ([,f-label* (lambda () ,f-tail*)] ...) ,f-tail)])))])))
)
| false |
ed386997a108d5326f3936e9081b3045cb6b60b7 | 0011048749c119b688ec878ec47dad7cd8dd00ec | /src/spoilers/808/solution.scm | 5a9f8f95397c43844c582540981da26ca781c54a | [
"0BSD"
]
| permissive | turquoise-hexagon/euler | e1fb355a44d9d5f9aef168afdf6d7cd72bd5bfa5 | 852ae494770d1c70cd2621d51d6f1b8bd249413c | refs/heads/master | 2023-08-08T21:01:01.408876 | 2023-07-28T21:30:54 | 2023-07-28T21:30:54 | 240,263,031 | 8 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 821 | scm | solution.scm | (import
(chicken fixnum)
(euler))
(define (reverse-number n)
(let loop ((n n) (acc 0))
(if (fx= n 0)
acc
(loop (fx/ n 10) (fx+ (fx* acc 10) (fxmod n 10))))))
(define (square-root n)
(let loop ((i n))
(let ((_ (fx/ (fx+ i (fx/ n i)) 2)))
(if (fx< _ i)
(loop _)
i))))
(define (solve n)
(let loop ((i 1) (cnt 0) (acc 0))
(if (fx= cnt n)
acc
(let* ((s (fx* i i)) (r (reverse-number s)))
(if (fx= s r)
(loop (fx+ i 2) cnt acc)
(let ((_ (square-root r)))
(if (and (fx= (fx* _ _) r)
(prime? i)
(prime? _))
(loop (fx+ i 2) (fx+ cnt 1) (fx+ acc s))
(loop (fx+ i 2) cnt acc))))))))
(let ((_ (solve 50)))
(print _) (assert (= _ 3807504276997394)))
| false |
e18a19e98f2e8b83c27a8bb27d79ea08af911871 | f08220a13ec5095557a3132d563a152e718c412f | /logrotate/skel/usr/share/guile/2.0/ice-9/occam-channel.scm | ea1154b52d89f9af91ebd0783e17314814df76ac | [
"Apache-2.0"
]
| permissive | sroettger/35c3ctf_chals | f9808c060da8bf2731e98b559babd4bf698244ac | 3d64486e6adddb3a3f3d2c041242b88b50abdb8d | refs/heads/master | 2020-04-16T07:02:50.739155 | 2020-01-15T13:50:29 | 2020-01-15T13:50:29 | 165,371,623 | 15 | 5 | Apache-2.0 | 2020-01-18T11:19:05 | 2019-01-12T09:47:33 | Python | UTF-8 | Scheme | false | false | 7,436 | scm | occam-channel.scm | ;;;; Occam-like channels
;;; Copyright (C) 2003, 2006 Free Software Foundation, Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 occam-channel)
#:use-module (oop goops)
#:use-module (ice-9 threads)
#:export-syntax (alt
;; macro use:
oc:lock oc:unlock oc:consequence
oc:immediate-dispatch oc:late-dispatch oc:first-channel
oc:set-handshake-channel oc:unset-handshake-channel)
#:export (make-channel
?
!
make-timer
;; macro use:
handshake-channel mutex
sender-waiting?
immediate-receive late-receive
)
)
(define no-data '(no-data))
(define receiver-waiting '(receiver-waiting))
(define-class <channel> ())
(define-class <data-channel> (<channel>)
(handshake-channel #:accessor handshake-channel)
(data #:accessor data #:init-value no-data)
(cv #:accessor cv #:init-form (make-condition-variable))
(mutex #:accessor mutex #:init-form (make-mutex)))
(define-method (initialize (ch <data-channel>) initargs)
(next-method)
(set! (handshake-channel ch) ch))
(define-method (make-channel)
(make <data-channel>))
(define-method (sender-waiting? (ch <data-channel>))
(not (eq? (data ch) no-data)))
(define-method (receiver-waiting? (ch <data-channel>))
(eq? (data ch) receiver-waiting))
(define-method (immediate-receive (ch <data-channel>))
(signal-condition-variable (cv ch))
(let ((res (data ch)))
(set! (data ch) no-data)
res))
(define-method (late-receive (ch <data-channel>))
(let ((res (data ch)))
(set! (data ch) no-data)
res))
(define-method (? (ch <data-channel>))
(lock-mutex (mutex ch))
(let ((res (cond ((receiver-waiting? ch)
(unlock-mutex (mutex ch))
(scm-error 'misc-error '?
"another process is already receiving on ~A"
(list ch) #f))
((sender-waiting? ch)
(immediate-receive ch))
(else
(set! (data ch) receiver-waiting)
(wait-condition-variable (cv ch) (mutex ch))
(late-receive ch)))))
(unlock-mutex (mutex ch))
res))
(define-method (! (ch <data-channel>))
(! ch *unspecified*))
(define-method (! (ch <data-channel>) (x <top>))
(lock-mutex (mutex (handshake-channel ch)))
(cond ((receiver-waiting? ch)
(set! (data ch) x)
(signal-condition-variable (cv (handshake-channel ch))))
((sender-waiting? ch)
(unlock-mutex (mutex (handshake-channel ch)))
(scm-error 'misc-error '! "another process is already sending on ~A"
(list ch) #f))
(else
(set! (data ch) x)
(wait-condition-variable (cv ch) (mutex ch))))
(unlock-mutex (mutex (handshake-channel ch))))
;;; Add protocols?
(define-class <port-channel> (<channel>)
(port #:accessor port #:init-keyword #:port))
(define-method (make-channel (port <port>))
(make <port-channel> #:port port))
(define-method (? (ch <port-channel>))
(read (port ch)))
(define-method (! (ch <port-channel>))
(write (port ch)))
(define-class <timer-channel> (<channel>))
(define the-timer (make <timer-channel>))
(define timer-cv (make-condition-variable))
(define timer-mutex (make-mutex))
(define (make-timer)
the-timer)
(define (timeofday->us t)
(+ (* 1000000 (car t)) (cdr t)))
(define (us->timeofday n)
(cons (quotient n 1000000)
(remainder n 1000000)))
(define-method (? (ch <timer-channel>))
(timeofday->us (gettimeofday)))
(define-method (? (ch <timer-channel>) (t <integer>))
(lock-mutex timer-mutex)
(wait-condition-variable timer-cv timer-mutex (us->timeofday t))
(unlock-mutex timer-mutex))
;;; (alt CLAUSE ...)
;;;
;;; CLAUSE ::= ((? CH) FORM ...)
;;; | (EXP (? CH) FORM ...)
;;; | (EXP FORM ...)
;;;
;;; where FORM ... can be => (lambda (x) ...)
;;;
;;; *fixme* Currently only handles <data-channel>:s
;;;
(define-syntax oc:lock
(syntax-rules (?)
((_ ((? ch) form ...)) (lock-mutex (mutex ch)))
((_ (exp (? ch) form ...)) (lock-mutex (mutex ch)))
((_ (exp form ...)) #f)))
(define-syntax oc:unlock
(syntax-rules (?)
((_ ((? ch) form ...)) (unlock-mutex (mutex ch)))
((_ (exp (? ch) form ...)) (unlock-mutex (mutex ch)))
((_ (exp form ...)) #f)))
(define-syntax oc:consequence
(syntax-rules (=>)
((_ data) data)
((_ data => (lambda (x) e1 e2 ...))
(let ((x data)) e1 e2 ...))
((_ data e1 e2 ...)
(begin data e1 e2 ...))))
(define-syntax oc:immediate-dispatch
(syntax-rules (?)
((_ ((? ch) e1 ...))
((sender-waiting? ch)
(oc:consequence (immediate-receive ch) e1 ...)))
((_ (exp (? ch) e1 ...))
((and exp (sender-waiting? ch))
(oc:consequence (immediate-receive ch) e1 ...)))
((_ (exp e1 ...))
(exp e1 ...))))
(define-syntax oc:late-dispatch
(syntax-rules (?)
((_ ((? ch) e1 ...))
((sender-waiting? ch)
(oc:consequence (late-receive ch) e1 ...)))
((_ (exp (? ch) e1 ...))
((and exp (sender-waiting? ch))
(oc:consequence (late-receive ch) e1 ...)))
((_ (exp e1 ...))
(#f))))
(define-syntax oc:first-channel
(syntax-rules (?)
((_ ((? ch) e1 ...) c2 ...)
ch)
((_ (exp (? ch) e1 ...) c2 ...)
ch)
((_ c1 c2 ...)
(first-channel c2 ...))))
(define-syntax oc:set-handshake-channel
(syntax-rules (?)
((_ ((? ch) e1 ...) handshake)
(set! (handshake-channel ch) handshake))
((_ (exp (? ch) e1 ...) handshake)
(and exp (set! (handshake-channel ch) handshake)))
((_ (exp e1 ...) handshake)
#f)))
(define-syntax oc:unset-handshake-channel
(syntax-rules (?)
((_ ((? ch) e1 ...))
(set! (handshake-channel ch) ch))
((_ (exp (? ch) e1 ...))
(and exp (set! (handshake-channel ch) ch)))
((_ (exp e1 ...))
#f)))
(define-syntax alt
(lambda (x)
(define (else-clause? x)
(syntax-case x (else)
((_) #f)
((_ (else e1 e2 ...)) #t)
((_ c1 c2 ...) (else-clause? (syntax (_ c2 ...))))))
(syntax-case x (else)
((_ c1 c2 ...)
(else-clause? x)
(syntax (begin
(oc:lock c1)
(oc:lock c2) ...
(let ((res (cond (oc:immediate-dispatch c1)
(oc:immediate-dispatch c2) ...)))
(oc:unlock c1)
(oc:unlock c2) ...
res))))
((_ c1 c2 ...)
(syntax (begin
(oc:lock c1)
(oc:lock c2) ...
(let ((res (cond (oc:immediate-dispatch c1)
(oc:immediate-dispatch c2) ...
(else (let ((ch (oc:first-channel c1 c2 ...)))
(oc:set-handshake-channel c1 ch)
(oc:set-handshake-channel c2 ch) ...
(wait-condition-variable (cv ch)
(mutex ch))
(oc:unset-handshake-channel c1)
(oc:unset-handshake-channel c2) ...
(cond (oc:late-dispatch c1)
(oc:late-dispatch c2) ...))))))
(oc:unlock c1)
(oc:unlock c2) ...
res)))))))
| true |
06ed19637b4ebdad90c5b2f68be0f6b3a6bb6143 | 8eb21733f83949941fadcb268dd4f0efab594b7f | /000/srfi-4/contrib/cowan/r6rs/chicken-tests.scm | c8e87e5575426a190a4e9a4347fd8fd4134f264c | []
| no_license | srfi-explorations/final-srfis | d0994d215490333062a43241c57d0c2391224527 | bc8e7251d5b52bf7b11d9e8ed8b6544a5d973690 | refs/heads/master | 2020-05-02T07:29:24.865266 | 2019-03-26T19:02:18 | 2019-03-26T19:02:18 | 177,819,656 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 117 | scm | chicken-tests.scm | ;;;; Basic tests of (r6rs bytevectors).
(import (r6rs bytevectors))
(import utf8)
(include "r6rs/shared-tests.scm")
| false |
ebdab915e9db89079990bb961bb67ef394fa9d3a | 12fc725f8273ebfd9ece9ec19af748036823f495 | /tools/schemelib/wg/pass-leaving.scm | 4701a1d06921c4492466171a6392cc37909bef72 | []
| 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 | 14,907 | scm | pass-leaving.scm | ;;
;; pass-leaving.scm
;;
;; Copyright 2007 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.
;;
(module
pass-leaving
mzscheme
(require (lib "usual.scm" "wg"))
(require (lib "ast-util.scm" "wg"))
(require (lib "ast-spec.scm" "wg"))
(require (lib "tables.scm" "wg"))
(require (lib "declarations.scm" "wg"))
(require (lib "mop.scm" "wg"))
(require (lib "match.scm" "wg"))
(require (lib "settings.scm" "wg"))
(require (prefix h. (lib "hash.scm" "wg")))
;; Returns a list of function declarations in the given AST.
(define (build-func-list ast)
(cond
((any-pred cxx-oper? cxx-conv? ast)
'()) ;; xxx not yet supported
((func-like-decl? ast)
(list ast))
((named-list? ast)
(apply append (map build-func-list (cdr ast))))
(else
'())))
;; A record of information regarding the leave status of a function.
;; "s" is the leave status, which is one of: 'yes (is leaving), 'no
;; (not leaving), 'unknown (whether leaving), 'impossible (to
;; resolve). "d" is the declaration (its AST).
(define-struct lstat (s d))
(define (infer-stat lmap root-ast)
(define (stat-sum xs)
(cond
((memq 'yes xs)
'yes)
((list-membs-all-match? xs (fix eq? 'no))
'no)
((list-membs-all-match? xs (fix include-eq? '(no impossible)))
'impossible)
(else
'unknown)))
(define (infer-stmtlist xs)
(stat-sum (map infer-stmt xs)))
(define (infer-exprlist xs)
(stat-sum (map infer-expr xs)))
(define/kw (infer-expr-attr ast #:optional (name 'expr))
(alet expr (fget-reqd-nlist-elem-1 ast name)
(infer-expr expr)))
(define/kw (infer-opt-expr-attr ast #:optional (name 'expr))
(aif expr (fget-opt-nlist-elem-1 ast name)
(infer-expr expr)
'no))
(define (infer-exprs-attr ast)
(alet exprs (fget-reqd-nlist-elem ast 'exprs)
(infer-exprlist (cdr exprs))))
;; Uses "lmap", but does not modify it. Returns the inferred leave
;; status; the possible values are the same as for "lstat-s".
(define (infer-stmt ast)
;;(write-nl (list 'inferring ast))
(or (any-leaving-annot ast)
(cond
((block? ast)
(alet stmts (fget-reqd-nlist-elem ast 'stmts)
(infer-stmtlist (cdr stmts))))
((local-var? ast)
(aif init (fget-opt-nlist-elem-1 ast 'init)
(infer-expr init) 'no))
((any-pred trap-block? expr-stmt? ast)
(alet expr (fget-reqd-nlist-elem-1 ast 'expr)
(infer-expr expr)))
((return-stmt? ast)
(aif expr (fget-opt-nlist-elem-1 ast 'expr)
(infer-expr expr) 'no))
((if-stmt? ast)
(let ((expr (fget-reqd-nlist-elem-1 ast 'cond-expr))
(stmt1 (fget-reqd-nlist-elem-1 ast 'then-stmt))
(stmt2 (fget-opt-nlist-elem-1 ast 'else-stmt)))
(stat-sum (list (infer-expr expr)
(infer-stmt stmt1)
(if stmt2 (infer-stmt stmt2) 'no)))))
((any-pred while-stmt? do-while-stmt? ast)
(let ((expr (fget-reqd-nlist-elem-1 ast 'cond-expr))
(stmt (fget-reqd-nlist-elem-1 ast 'stmt)))
(stat-sum (list (infer-expr expr)
(infer-stmt stmt)))))
((for-stmt? ast)
(let ((expr1 (fget-opt-nlist-elem-1 ast 'init-expr))
(expr2 (fget-opt-nlist-elem-1 ast 'cond-expr))
(expr3 (fget-opt-nlist-elem-1 ast 'step-expr))
(stmt (fget-reqd-nlist-elem-1 ast 'stmt)))
(stat-sum (list (if expr1 (infer-expr expr1) 'no)
(if expr2 (infer-expr expr2) 'no)
(if expr3 (infer-expr expr3) 'no)
(infer-stmt stmt)))))
((switch-stmt? ast)
(let ((expr (fget-reqd-nlist-elem-1 ast 'switch-expr))
(stmts (fget-reqd-nlist-elem ast 'stmts)))
(stat-sum (list (infer-expr expr)
(infer-stmtlist (cdr stmts))))))
((list-named-one-of? ast '(switch-case switch-default))
;; These are labels only, and can only contain constant integer
;; values at most, nothing leaving.
'no)
((any-pred goto-stmt? break-stmt? continue-stmt? ast)
'no)
((list-named? ast 'cxx-chunk)
'impossible)
((statement? ast)
;; xxx this kind of strict checking causes extensibility
;; problems; suppose someone extends the language with a new
;; statement type, as we actually have already done...
(error "unsupported statement" ast))
(else
(error "expected statement" ast)))))
;; Checks if the passed AST node has a "leaving" annotation. If so,
;; returns either 'yes or 'no as the leaving status (as
;; appropriate). Otherwise returns #f.
(define (any-leaving-annot ast)
(aif leaving (fget-opt-nlist-elem ast 'leaving)
(alet stat (second leaving)
(if stat 'yes 'no))
#f))
;; Most expressions as such do not leave, but many expressions may
;; contain subexpressions (such as those of type call-expr) that
;; may leave.
;;
;; Constructors may not leave, according to Symbian conventions,
;; and we assume these conventions are followed, and hence that new
;; and new[] do not cause a leave due to the constructor. If the
;; "new" operator might leave, we assume it is of the ELeave
;; overload variant, and has the appropriate "leaving" annotation.
;; Overloaded new and new[] operators themselves might cause a
;; leave for cases other than new (ELeave) also; see the notes
;; regarding our operator support below.
;;
;; If the Symbian conventions allowed for leaving destructors,
;; delete and delete[] operations might leave; we assume the
;; conventions are followed. Overloaded delete and delete[]
;; operators themselves might cause a leave; see the notes
;; regarding our operator support below.
;;
;; If Symbian conventions allowed for leaving constructors, the
;; constructor invocations resulting from ctor-call-expr and
;; super-call-expr and ctor-super initializer expressions should
;; also be considered, but we assume that the conventions are
;; followed.
;;
;; xxx currently not resolving leave status for operator
;; invocations -- just assuming the status as 'no (unless there is
;; an explicit annotation, as there should be with new (ELeave), at
;; least), which is dangerous; but certainly Symbian OS has APIs
;; such that say operator<< is leaving
;;
;; xxx do not know whether cxx-conv special functions may leave
;;
;; xxx invocations via member function pointers are not supported
;; at all
(define (infer-expr ast)
(define (g ast)
(if ast (infer-expr ast) 'no))
(or (any-leaving-annot ast)
(cond
((call-expr? ast)
;; Resolving this is not too straightforward. Arguments are
;; trivial; if any may leave, then the overall call
;; expression may. If the target expression may leave, then
;; its leave status is 'yes. Otherwise, if the target
;; expression resolves to a function reference, then the
;; leave status is that indicated by func-t type; if it
;; indicates nothing, then the status is 'impossible.
;; Otherwise the target expression must resolve to a
;; function; if the function is known, the leave status is
;; that declared or inferred for that function (possibly
;; still 'unknown); if the function is unknown (undefined),
;; the leave status is 'impossible.
(let* ((arglist (fget-opt-nlist-elem-1up-e ast 'exprs))
(argstat (infer-exprlist arglist))
(fid (fget-opt-nlist-elem-1 ast 'decl-id-ref))
(target (fget-reqd-nlist-elem-1 ast 'target))
(tstat (infer-expr target))
(cstat
(if (expr-get-name-ref target)
(if fid
(alet entry (h.fetch-reqd lmap fid)
(lstat-s entry))
'impossible)
(or
(let* ((ttype (strip-any-ref-to (get-texpr-or-tvar target))))
(and (func-t? ttype)
(any-leaving-annot ttype)))
'impossible))))
(stat-sum (list tstat argstat cstat))))
((any-pred unary-op-expr? cast-expr?
delete-expr? delete-array-expr? ast)
(infer-expr-attr ast))
((any-pred dot-expr? arrow-expr? binary-op-expr? ast)
(stat-sum (list (infer-expr-attr ast 'expr1)
(infer-expr-attr ast 'expr2))))
((any-pred new-expr? ctor-call-expr? multi-op-expr? ast)
(infer-exprs-attr ast))
((new-array-expr? ast)
(error "unsupported" ast))
((index-expr? ast)
(stat-sum (list (infer-expr-attr ast 'expr)
(infer-expr-attr ast 'index))))
((if-expr? ast)
(stat-sum (list (infer-expr-attr ast 'cond-expr)
(infer-expr-attr ast 'then-expr)
(infer-expr-attr ast 'else-expr))))
((lift-stmt-expr? ast)
(error "should have been lifted already" ast))
((any-pred name-ref? literal? texpr-expr? sizeof-expr? ast)
'no)
((expression? ast)
(error "unsupported expression" ast))
(else
(error "expected expression" ast)))))
(define (infer-any ast)
(cond
((expression? ast)
(infer-expr ast))
(else
(infer-stmt ast))))
(infer-any root-ast))
(define* (pass-leave-infer ast tables)
(define func-list (build-func-list ast))
(define lmap (h.new))
(define (to-stat leaving? known? inferable?)
(if known?
(if leaving? 'yes 'no)
(if inferable? 'unknown 'impossible)))
;; Build an initial version of the map.
(for-each
(lambda (ast)
(let* ((decl-id (fget-reqd-nlist-elem-1 ast 'decl-id))
(type (func-get-func-t ast))
(leaving (fget-opt-nlist-elem type 'leaving))
(known? (true? leaving))
(leaving? (and leaving (cadr leaving)))
(body (fget-opt-nlist-elem ast 'block))
(inferable? (true? body))
(status (to-stat leaving? known? inferable?))
(entry (make-lstat status ast)))
(h.store-set! lmap decl-id entry)))
func-list)
;; Infer until can infer no more. We know that a TRAP cannot leave,
;; and hence any calls within the body of a TRAP need not be
;; inspected. Any non-trapped call to a leaving function will
;; result in (leaving #t) status. If nothing is known to be
;; leaving, and only calls to unknown functions remain, then the
;; leave status is unresolvable. Otherwise it may become resolvable
;; if we can infer the leave status of the remaining calls. If
;; there is a "leaving" annotation within a call, then that
;; information will be taken for a fact.
;;
;; xxx for functions that are virtual, we should probably adopt the
;; leave status of any overridden method whose leave status is
;; known; this is because when calling a virtual, we do not know
;; (based on the static receiver type) which exact method we are
;; calling; we should actually add a pass that adds annotations
;; indicating the parent method of an overriding virtual method, to
;; make the required information available
(let loop ()
(alet found #f
(for-each
(lambda (entry)
(when (eq? (lstat-s entry) 'unknown)
(let* ((decl (lstat-d entry))
(body (fget-reqd-nlist-elem decl 'block))
(new-stat (infer-stat lmap body)))
(when (not (eq? new-stat 'unknown))
(if (gop-true? 'show-leave-infer) (write-nl (list 'inferred 'leave 'status (to-string new-stat) 'for (get-decl-name decl))))
(set-lstat-s! entry new-stat)
(set! found #t)))))
(h.all-values lmap))
(when found (loop))))
(list ast (tables-set tables 'l-table lmap)))
;; A pass for checking that if a function has been declared as
;; (leaving #f) and it has a body, then there is nothing that we know
;; might leave in the body of the function; essentially we just
;; re-resolve the leaving status of the function from its body, using
;; one pass of the routine we already have.
(define* (pass-leave-check ast tables)
(define lmap (tables-get-reqd tables 'l-table))
(define func-list (build-func-list ast))
(define (check-func ast)
(let* ((decl-id (fget-reqd-nlist-elem-1 ast 'decl-id))
(body (fget-opt-nlist-elem ast 'block))
(entry (h.fetch-reqd lmap decl-id))
(claimed-stat (lstat-s entry)))
(when (and body (eq? claimed-stat 'no))
(alet actual-stat (infer-stat lmap body)
(when (eq? actual-stat 'yes)
;; If there had not been a declaration, then
;; the status should agree with the inferred
;; status.
(error "function declared as non-leaving, but its body has potentially leaving expressions" ast))))))
(for-each check-func func-list)
(list ast tables))
;; Inspects all elements in "ast". For any elements that have an
;; "assume-leaving" attribute, we check that our idea of the leave
;; status for that AST node is consistent with the assumption.
(define* (pass-leave-assumption ast tables)
(define lmap (tables-get-reqd tables 'l-table))
(define (check ast)
(when (named-list? ast)
(when (any-pred statement? expression? ast)
(awhen assume-elem (fget-opt-nlist-elem ast 'assume-leaving)
(let* ((assume-value (second assume-elem))
(assume-stat (if assume-value 'yes 'no))
(actual-stat (infer-stat lmap ast)))
(when (memq actual-stat '(yes no))
(alet actual-value (case-eq actual-stat
('yes #t)
('no #f)
(else (assert-fail)))
(unless (eq? assume-value actual-value)
(error-f "incorrect assumption in ~s: leaving status assumed as ~s, but is ~s" ast assume-value actual-value)))))))
(for-each check ast)))
;; Only checks blocks. We do not support anything else anyway, so
;; this will save us some time.
(define (trav ast)
(cond
((block? ast)
(check ast))
((named-list? ast)
(for-each trav ast))))
(trav ast)
(list ast tables)) ;; end assumption checking pass
) ; end module
| false |
784c1507b9690b5c3d1328aabb69e05243c42657 | b3f1b85ae1ce3bc09332b2a2c4f79b10aff2f82b | /C311GitTest/mk.scm | 0dab095c4887355d3619a69187ba6c110f315ed4 | []
| no_license | KingLeper/PlayingWithGit | 54a7d9a3abcc0c1fe51a07818f06ffec27213320 | 629f17bf4d9dba0b9ee707c22d54a47f02b2b324 | refs/heads/master | 2020-05-17T13:54:12.305323 | 2011-11-22T18:58:47 | 2011-11-22T18:58:47 | 2,829,761 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 9,521 | scm | mk.scm | ;;; This file was generated by writeminikanren.pl
;;; Generated at 2006-11-07 00:11:44
(define-syntax lambdag@
(syntax-rules ()
((_ (p) e) (lambda (p) e))))
(define-syntax lambdaf@
(syntax-rules ()
((_ () e) (lambda () e))))
(define-syntax run*
(syntax-rules ()
((_ (x) g ...) (run #f (x) g ...))))
(define-syntax rhs
(syntax-rules ()
((_ x) (cdr x))))
(define-syntax lhs
(syntax-rules ()
((_ x) (car x))))
(define-syntax size-s
(syntax-rules ()
((_ x) (length x))))
(define-syntax var
(syntax-rules ()
((_ x) (vector x))))
(define-syntax var?
(syntax-rules ()
((_ x) (vector? x))))
(define-syntax pkg
(syntax-rules ()
((_ s c*) (cons s c*))))
(define-syntax sof
(syntax-rules ()
((_ p) (car p))))
(define-syntax cof
(syntax-rules ()
((_ p) (cdr p))))
(define empty-s '())
(define empty-c '())
(define empty-p (pkg empty-s empty-c))
(define walk
(lambda (v s)
(cond
((var? v)
(let ((a (assq v s)))
(cond
(a (walk (rhs a) s))
(else v))))
(else v))))
(define ext-s
(lambda (x v s)
(cons `(,x . ,v) s)))
(define unify*
(lambda (u v p)
(let ((s (sof p)) (c* (cof p)))
(let ((s^ (unify u v s)))
(cond
(s^ (cond
((eq? s^ s) p)
((ormap
(lambda (c)
(constraint? c s^))
c*)
#f)
(else (pkg s^ c*))))
(else #f))))))
(define constraint?
(lambda (c s)
(case (car c)
((never-pair)
(pair? (walk (cadr c) s)))
((never-equal)
(let ((u (cadr c))
(v (caddr c)))
(term-equal?
(walk* u s)
(walk* v s)))))))
(define unify
(lambda (u v s)
(let ((u (walk u s))
(v (walk v s)))
(cond
((eq? u v) s)
((var? u) (ext-s-check u v s))
((var? v) (ext-s-check v u s))
((and (pair? u) (pair? v))
(let ((s (unify (car u) (car v) s)))
(and s
(unify (cdr u) (cdr v) s))))
((equal? u v) s)
(else #f)))))
(define ext-s-check
(lambda (x v s)
(cond
((occurs-check x v s) #f)
(else (ext-s x v s)))))
(define occurs-check
(lambda (x v s)
(let ((v (walk v s)))
(cond
((var? v) (eq? v x))
((pair? v)
(or
(occurs-check x (car v) s)
(occurs-check x (cdr v) s)))
(else #f)))))
(define never-pair*
(lambda (c p)
(let ((c (walk c (sof p))))
(cond
((var? c) (pkg/c `(never-pair ,c) p))
((pair? c) #f)
(else p)))))
(define pkg/c
(lambda (c p)
(pkg (sof p) (ext-c c (cof p)))))
(define ext-c
(lambda (c c*)
(cons c c*)))
(define never-equal*
(lambda (u v p)
(let ((s (unify u v (sof p))))
(cond
((not s) p)
(else
(let ((u (walk* u (sof p)))
(v (walk* v (sof p))))
(cond
((term-equal? u v) #f)
(else
(pkg/c
`(never-equal ,u ,v)
p)))))))))
(define term-equal?
(lambda (u v)
(cond
((eq? u v) #t)
((or (var? u) (var? v)) #f)
((and (pair? u) (pair? v))
(and (term-equal? (car u) (car v))
(term-equal? (cdr u) (cdr v))))
(else (equal? u v)))))
(define walk*
(lambda (w s)
(let ((v (walk w s)))
(cond
((var? v) v)
((pair? v)
(cons
(walk* (car v) s)
(walk* (cdr v) s)))
(else v)))))
(define reify-s
(lambda (v s)
(let ((v (walk v s)))
(cond
((var? v)
(ext-s v (reify-name (size-s s)) s))
((pair? v) (reify-s (cdr v)
(reify-s (car v) s)))
(else s)))))
(define reify-name
(lambda (n)
(string->symbol
(string-append "_" "." (number->string n)))))
(define reify
(lambda (v p)
(let ((s (sof p)) (c* (cof p)))
(let ((v (walk* v s))
(wc* (walk* c* s)))
(let ((s (reify-s v empty-s)))
(let ((c* (get-c* wc* s)))
(cond
((null? c*) (walk* v s))
(else
(let ((s^ (reify-s c* s))
(c^ (walk* c* s)))
(let ((d (clean c^)))
(let ((v (walk* v s))
(r (walk* d s^)))
`(,v : ,r))))))))))))
(define clean
(lambda (c*)
(let loop ((c (car c*)) (c* (cdr c*)))
(cond
((null? c*) (cons c '()))
((ormap
(lambda (c^) (compare? c c^))
c*)
(loop (car c*) (cdr c*)))
(else
(cons c
(loop (car c*) (cdr c*))))))))
(define compare?
(lambda (c c^)
(cond
((term-equal? c c^) #t)
(else
(and
(eq? (car c) 'never-equal)
(eq? (car c^) 'never-equal)
(term-equal?
(reverse (cdr c))
(cdr c^)))))))
(define get-c*
(lambda (wc* s)
(cond
((null? wc*) '())
((okay-c (car wc*) s)
=>
(lambda (c)
(cons c
(get-c* (cdr wc*) s))))
(else
(get-c* (cdr wc*) s)))))
(define okay-c
(lambda (wc s)
(case (car wc)
((never-pair)
(let ((v (cadr wc)))
(and
(var? v)
(not (var? (walk v s)))
wc)))
((never-equal)
(let ((u (cadr wc))
(v (caddr wc)))
(and
(unify u v empty-s)
(or (anyvar? u s)
(anyvar? v s))
wc))))))
(define anyvar?
(lambda (v s)
(cond
((var? v) (not (var? (walk v s))))
((pair? v) (or (anyvar? (car v) s)
(anyvar? (cdr v) s)))
(else #f))))
(define ==-unchecked
(lambda (v w)
(lambdag@ (p)
(unify*-unchecked v w p))))
(define mzero (lambda () #f))
(define unit (lambda (a) a))
(define choice (lambda (a f) (cons a f)))
(define-syntax inc
(syntax-rules ()
((_ e) (lambdaf@ () e))))
(define-syntax case-inf
(syntax-rules ()
((_ e =0 ((a^) =1) ((a f) >=1) ((f^) ?))
(let ((a-inf e))
(cond
((not a-inf) =0)
((procedure? a-inf)
(let ((f^ a-inf)) ?))
((and (pair? a-inf)
(procedure? (cdr a-inf)))
(let ((a (car a-inf)) (f (cdr a-inf)))
>=1))
(else (let ((a^ a-inf)) =1)))))))
(define-syntax run
(syntax-rules ()
((_ n (x) g0 g^ ...)
(take n (lambdaf@ ()
((fresh (x)
(lambdag@ (p)
(bind* (g0 p) g^ ...
(lambdag@ (p)
(cons (reify x p) '())))))
empty-p))))))
(define take
(lambda (n f)
(if (and n (zero? n))
'()
(case-inf (f)
'()
((a) a)
((a f)
(cons (car a) (take (and n (- n 1)) f)))
((f) (take n f))))))
(define ==
(lambda (u v)
(lambdag@ (p)
(unify* u v p))))
(define never-equalo
(lambda (u v)
(lambdag@ (p)
(never-equal* u v p))))
(define never-pairo
(lambda (u)
(lambdag@ (p)
(never-pair* u p))))
(define-syntax fresh
(syntax-rules ()
((_ (x ...) g0 g ...)
(lambdag@ (p)
(let ((x (var 'x)) ...)
(bind* (g0 p) g ...))))))
(define-syntax bind*
(syntax-rules ()
((_ e) e)
((_ e g0 g ...)
(let ((a-inf e))
(and a-inf (bind* (bind a-inf g0) g ...))))))
(define bind
(lambda (a-inf g)
(case-inf a-inf
(mzero)
((a) (g a))
((a f) (mplus (g a) (lambdaf@ () (bind (f) g))))
((f) (inc (bind (f) g))))))
(define-syntax conde
(syntax-rules (else)
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (p)
(inc
(mplus*
(bind* (g0 p) g ...)
(bind* (g1 p) g^ ...) ...))))))
(define-syntax mplus*
(syntax-rules ()
((_ e) e)
((_ e0 e ...)
(mplus e0 (lambdaf@ () (mplus* e ...))))))
(define mplus
(lambda (a-inf f)
(case-inf a-inf
(f)
((a) (choice a f))
((a f^) (choice a (lambdaf@ () (mplus (f) f^))))
((f^) (inc (mplus (f) f^))))))
(define-syntax conda
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (p)
(ifa ((g0 p) g ...)
((g1 p) g^ ...) ...)))))
(define-syntax ifa
(syntax-rules ()
((_) (mzero))
((_ (e g ...) b ...)
(let loop ((a-inf e))
(case-inf a-inf
(ifa b ...)
((a) (bind* a-inf g ...))
((a f) (bind* a-inf g ...))
((f) (inc (loop (f)))))))))
(define-syntax condu
(syntax-rules ()
((_ (g0 g ...) (g1 g^ ...) ...)
(lambdag@ (p)
(ifu ((g0 p) g ...)
((g1 p) g^ ...) ...)))))
(define-syntax ifu
(syntax-rules ()
((_) (mzero))
((_ (e g ...) b ...)
(let loop ((a-inf e))
(case-inf a-inf
(ifu b ...)
((a) (bind* a-inf g ...))
((a f) (bind* (unit a) g ...))
((f) (inc (loop (f)))))))))
(define-syntax project
(syntax-rules ()
((_ (x ...) g g* ...)
(lambdag@ (p)
(let ((s (sof p)))
(let ((x (walk* x s)) ...)
((fresh () g g* ...) p)))))))
(define succeed (== #f #f))
(define fail (== #f #t))
(define onceo
(lambda (g)
(condu
(g succeed)
(else fail))))
| true |
4131c0d253475ca7819b53f0d0c1770adb9f5ca0 | df0ba5a0dea3929f29358805fe8dcf4f97d89969 | /exercises/informatics-2/02-linear-iterative-process/reverse-digits.scm | d1fc94732ae75f62a8f611f78a759195a04bd2b1 | [
"MIT"
]
| permissive | triffon/fp-2019-20 | 1c397e4f0bf521bf5397f465bd1cc532011e8cf1 | a74dcde683538be031186cf18367993e70dc1a1c | refs/heads/master | 2021-12-15T00:32:28.583751 | 2021-12-03T13:57:04 | 2021-12-03T13:57:04 | 210,043,805 | 14 | 31 | MIT | 2019-12-23T23:39:09 | 2019-09-21T19:41:41 | Racket | UTF-8 | Scheme | false | false | 966 | scm | reverse-digits.scm | (require rackunit rackunit/text-ui)
; Докато изчерпваме цифрите от number, ги слагаме в reversed
(define (reverse-digits n)
(define (helper number reversed)
(if (= number 0) ; Изчерпали сме напълно number
reversed ; Съответно reversed e напълнен и готов
(helper (quotient number 10)
(+ (* reversed 10)
(remainder number 10)))))
(helper n 0))
(define reverse-digits-tests
(test-suite
"Tests for reverse-digits"
(check = (reverse-digits 3) 3)
(check = (reverse-digits 12) 21)
(check = (reverse-digits 42) 24)
(check = (reverse-digits 666) 666)
(check = (reverse-digits 1337) 7331)
(check = (reverse-digits 65510) 1556)
(check = (reverse-digits 1234567) 7654321)
(check = (reverse-digits 8833443388) 8833443388)
(check = (reverse-digits 100000000000) 1)))
(run-tests reverse-digits-tests)
| false |
a2cf013b93515195e89ee9025eccafedb26c5d9a | defeada37d39bca09ef76f66f38683754c0a6aa0 | /System.Xml.Linq/system/xml/linq/xname.sls | 8e6dbb6bb82b7cb3dd3c03a9034937049b038595 | []
| 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,227 | sls | xname.sls | (library (system xml linq xname)
(export is?
xname?
get-hash-code
get
to-string
equals?
local-name
namespace
namespace-name)
(import (ironscheme-clr-port))
(define (is? a) (clr-is System.Xml.Linq.XName a))
(define (xname? a) (clr-is System.Xml.Linq.XName a))
(define-method-port
get-hash-code
System.Xml.Linq.XName
GetHashCode
(System.Int32))
(define-method-port
get
System.Xml.Linq.XName
Get
(static: System.Xml.Linq.XName System.String System.String)
(static: System.Xml.Linq.XName System.String))
(define-method-port
to-string
System.Xml.Linq.XName
ToString
(System.String))
(define-method-port
equals?
System.Xml.Linq.XName
Equals
(System.Boolean System.Object))
(define-field-port
local-name
#f
#f
(property:)
System.Xml.Linq.XName
LocalName
System.String)
(define-field-port
namespace
#f
#f
(property:)
System.Xml.Linq.XName
Namespace
System.Xml.Linq.XNamespace)
(define-field-port
namespace-name
#f
#f
(property:)
System.Xml.Linq.XName
NamespaceName
System.String))
| false |
6bc8b1226557bf85182bf7aad62a36f53beac8e5 | f4aeaa0812ac15d5a8d2cb6da75ac335c3cf5cf4 | /miruKanren/run.scm | 3f564a89e7a749123dd8506df4996553b5c3502b | [
"MIT"
]
| permissive | orchid-hybrid/microKanren-sagittarius | 13f7916f8ef7c946cefeb87e9e52d6d4a5dfe6c9 | 9e740bbf94ed2930f88bbcf32636d3480934cfbb | refs/heads/master | 2021-01-13T01:54:20.589391 | 2015-06-13T12:40:14 | 2015-06-13T12:40:14 | 29,868,626 | 12 | 4 | null | 2015-02-12T07:11:25 | 2015-01-26T16:01:10 | Scheme | UTF-8 | Scheme | false | false | 759 | scm | run.scm | (define (print s) (display s) (newline))
(define (run^ n g)
;; Compute up to a set limit of results
(map reify-kanren (take n ((call/fresh g) initial-kanren))))
(define (run* g)
;; Compute every result
(map reify-kanren (take-all ((call/fresh g) initial-kanren))))
(define (runi g)
;; This version of run returns one result from the
;; stream at a time interactively asking if you
;; want more or not
(let (($ ((call/fresh g) initial-kanren)))
(let loop (($ (pull $)))
(if (null? $)
(print 'thats-all!)
(begin (print (reify-kanren (car $)))
(print '(another? y/n))
(case (read)
((y yes) (loop (pull (cdr $))))
(else (print 'bye!))))))))
| false |
cbf886a6d40f64d80036bebf20174ce50c048e23 | d8bdd07d7fff442a028ca9edbb4d66660621442d | /scam/tests/20-scam/unify/unifyunderscore.scm | c6571ff4c0e82ba16cbeb90af9e6039084042202 | []
| no_license | xprime480/scam | 0257dc2eae4aede8594b3a3adf0a109e230aae7d | a567d7a3a981979d929be53fce0a5fb5669ab294 | refs/heads/master | 2020-03-31T23:03:19.143250 | 2020-02-10T20:58:59 | 2020-02-10T20:58:59 | 152,641,151 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 198 | scm | unifyunderscore.scm | (import (only (scam unify) unify)
(test narc))
(narc-label "Unify Underscore")
(narc-expect
({ :Y 3 } (unify #(:: 3)
#('(this is :to :be :ignored) :Y))))
(narc-report)
| false |
78169adcb13c1173d00fbdd6bdd139d2c84cc9ee | eef5f68873f7d5658c7c500846ce7752a6f45f69 | /test/termite/test/test_node2.scm | 963fda671749f96fd26ebc2454b19b325b2ed85d | [
"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 | 154 | scm | test_node2.scm | (%load-library '(spheres/concurrency termite))
(define node1 (make-node "localhost" 3001))
(define node2 (make-node "localhost" 3002))
(node-init node2)
| false |
166480e542b29edf0485ff1896784f19d0b9fc77 | fca62d08480d0db43627f51449b9caea48295601 | /sources/units/http-server-intern.scm | 78f95acd8be34e686edf0e61071def5ed9487fa9 | [
"MIT"
]
| permissive | alxbnct/Schemings | aa4783cca04b4a393972ead754cd3e2ce89bf193 | a7c322ee37bf9f43b696c52fc290488aa2dcc238 | refs/heads/master | 2023-06-01T02:06:38.441543 | 2021-06-12T15:27:28 | 2021-06-12T15:27:28 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,024 | scm | http-server-intern.scm | (import srfi-1)
(import (chicken condition))
(declare (unit http-server-intern))
(declare (uses exceptions))
(declare (uses fastcgi))
(declare (uses json))
(declare (uses regex))
(declare (uses validation))
;; invokes a procedure with compiled http binding regexes
(: with-compiled-http-binding-regexes
(forall (r) (
(list-of (struct http-binding)) ((list-of (struct regex)) -> r) -> r)))
(define (with-compiled-http-binding-regexes http-bindings procedure)
(with-guaranteed-release
(lambda ()
(map
(lambda (http-binding)
(regex-compile (http-binding-route-regex http-binding)))
http-bindings))
(lambda (http-binding-regexes)
(procedure http-binding-regexes))
(lambda (http-binding-regexes)
(for-each
(lambda (http-binding-regex)
(regex-free http-binding-regex))
http-binding-regexes))))
;; searches for a http binding matching a request
(: find-http-binding-match (
(list-of (struct http-binding)) (list-of (struct regex)) string string ->
(or (pair (struct http-binding) (list-of string)) false)))
(define (find-http-binding-match http-bindings http-binding-regexes method uri)
(letrec* ((find-http-binding-match-iter
(lambda (zipped)
(if (not (null? zipped))
(let* ((http-binding (caar zipped))
(http-binding-method (http-binding-method http-binding))
(http-binding-regex (cadar zipped)))
(if (equal? http-binding-method method)
(let ((regex-captures
(regex-execute-compiled
http-binding-regex
uri)))
(if (not (null? regex-captures))
(cons http-binding regex-captures)
(find-http-binding-match-iter (cdr zipped))))
(find-http-binding-match-iter (cdr zipped))))
#f))))
(find-http-binding-match-iter
(zip http-bindings http-binding-regexes))))
;; invokes a procedure with validation errors exception handling
(: http-with-validation-errors-exception-handling
(forall (r) ((-> r) ((list-of symbol) -> *) -> r)))
(define (http-with-validation-errors-exception-handling procedure exception-procedure)
(handle-exceptions
exception
(if (validation-errors-exception? exception)
(let ((validation-errors (validation-errors-exception-validation-errors exception)))
(exception-procedure validation-errors))
(abort exception))
(procedure)))
;; formats a list of validation errors
(: http-format-validation-errors ((list-of symbol) -> string))
(define (http-format-validation-errors validation-errors)
(with-json-array
(lambda (json-node)
(for-each
(lambda (validation-error)
(json-array-add-value json-node (symbol->string validation-error)))
validation-errors)
(json->string json-node))))
| false |
5c87ad828c1427f39142ffb5182d6d5d46c6dc72 | b946259dec865fd015e98ad09212692dcd0ee073 | /interpreter/bool.scm | fb50616732fe86706f30de2de5345bff7cb06452 | [
"MIT"
]
| permissive | TurtleKitty/Vaquero | 5e5ce1419bcd0fe841d8cd3d791d1a9174bac022 | d4c3823f7f7a88a67679ee774532d499ef1ac982 | refs/heads/master | 2021-06-09T14:45:54.658784 | 2021-05-28T04:31:09 | 2021-05-28T04:31:09 | 81,528,904 | 22 | 2 | MIT | 2020-02-06T01:50:16 | 2017-02-10T05:08:28 | Scheme | UTF-8 | Scheme | false | false | 997 | scm | bool.scm |
(define vaquero-send-bool-vtable
(let ()
(method answers?
(cont (lambda (msg) (hte? vaquero-send-bool-vtable msg))))
(method autos
(cont '(autos messages not to-bool to-text type view)))
(method messages
(cont (htks vaquero-send-bool-vtable)))
(method bool-not
(cont (not obj)))
(method to-bool
(cont obj))
(method view
(cont
(if (or (eq? obj 'false) (not obj))
'false
'true)))
(method to-text
(cont (if obj "true" "false")))
(method type
(cont '(bool)))
(alist->hash-table
`((answers? . ,answers?)
(autos . ,autos)
(messages . ,messages)
(not . ,bool-not)
(to-bool . ,to-bool)
(to-symbol . ,view)
(to-text . ,to-text)
(type . ,type)
(view . ,view)
(default . ,idk)))))
| false |
138c3ef3906fa37f2d8644a39bbe12e0ed7886b8 | 46244bb6af145cb393846505f37bf576a8396aa0 | /sicp/2_78.scm | 2b1ec54e03393aa1b7722bfd2db0d381e09a34d3 | []
| no_license | aoeuidht/homework | c4fabfb5f45dbef0874e9732c7d026a7f00e13dc | 49fb2a2f8a78227589da3e5ec82ea7844b36e0e7 | refs/heads/master | 2022-10-28T06:42:04.343618 | 2022-10-15T15:52:06 | 2022-10-15T15:52:06 | 18,726,877 | 4 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 1,436 | scm | 2_78.scm | #lang racket
(define (attach-tag type-tag contents)
(if (or (symbol? contents)
(number? contents))
contents
(cons type-tag contents)))
(define (type-tag datum)
(if (pair? datum)
(car datum)
(cond ((symbol? datum) 'symbol)
((number? datum) 'scheme-number)
(else (error "Bad tagged datum -- TYPE-TAG" datum)))))
(define (contents datum)
(if (pair? datum)
(cdr datum)
(cond ((symbol? datum) datum)
((number? datum) datum)
(else (error "Bad tagged datum -- TYPE-TAG" datum)))))
; Exercise 2.78. The internal procedures in the scheme-number package are essentially nothing more
;than calls to the primitive procedures +, -, etc. It was not possible to use the primitives of the language
;directly because our type-tag system requires that each data object have a type attached to it. In fact,
;however, all Lisp implementations do have a type system, which they use internally. Primitive predicates
;such as symbol? and number? determine whether data objects have particular types. Modify the
;definitions of type-tag, contents, and attach-tag from section 2.4.2 so that our generic system
;takes advantage of Scheme's internal type system. That is to say, the system should work as before except
;that ordinary numbers should be represented simply as Scheme numbers rather than as pairs whose car is
;the symbol scheme-number.
| false |
897d67709d71b273e8655b0f501ca3f41f7b2703 | 12fc725f8273ebfd9ece9ec19af748036823f495 | /tools/schemelib/wg/mop.scm | 4930c205bf2714525dbe91f57b3323a8e16d4f3b | []
| 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 | 9,823 | scm | mop.scm | ;;
;; mop.scm
;;
;; Copyright 2007 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.
;;
;; Defines a meta-object protocol (MOP) for querying the model of an
;; analyzed program. In our case, what we are querying is an AST and
;; some additional information. This structure makes pretty printing
;; easy, but is not necessarily optimal for queries like this. Still,
;; it's not that bad, and when these queries are sufficient, the user
;; does not really have to care about the queried structure.
(module
mop
mzscheme
(require (lib "ast-spec.scm" "wg"))
(require (lib "ast-util.scm" "wg"))
(require (lib "prop-util.scm" "wg"))
(require (lib "tables.scm" "wg"))
(require (lib "declarations.scm" "wg"))
(require (lib "usual.scm" "wg"))
(require (lib "graph.scm" "wg"))
(require (prefix h. (lib "hash.scm" "wg")))
(require (prefix e. (lib "environment.scm" "wg")))
(define* (make-qname names)
(symbol-join names "::"))
;; If the passed expression names a value, this function returns
;; the relevant name-ref (sub)expression; #f is returned otherwise.
(define* (expr-get-name-ref ast)
(cond
((name-ref? ast)
ast)
((any-pred dot-expr? arrow-expr? ast)
(expr-get-name-ref (get-expr ast 'expr2)))
(else
#f)))
(define/kw* (get-expr ast #:optional (name 'expr))
(fget-reqd-nlist-elem-1 ast name))
(define* (get-texpr-or-tvar ast)
(or (fget-opt-nlist-elem-1 ast 'type)
'(tvar)))
(define* (get-texpr ast)
(or (fget-opt-nlist-elem-1 ast 'type)
(error "expression has no type" ast)))
(define* (strip-any-ref-to texpr)
(if (ref-to? texpr)
(get-texpr texpr)
texpr))
(define* (global-decl-and-cont? ast)
(and (global-decl? ast)
(global-decl-cont? ast)))
(define* (function-decl? ast)
(list-named-one-of? ast '(global-func inst-meth class-meth cxx-ctor cxx-dtor cxx-oper cxx-conv)))
(define* (global-decl? ast)
(or (function-decl? ast)
(list-named-one-of? ast '(cxx-class cxx-struct cxx-union cxx-typedef global-var class-var inst-var))))
(define* (global-decl-cont? ast)
(list-named-one-of? ast '(cxx-unit cxx-namespace body cxx-class cxx-struct cxx-union)))
(define* (texpr-check-func-t texpr)
(unless (list-named? texpr 'func-t)
(error "not a function type" texpr))
texpr)
(define* (func-get-func-t ast)
(texpr-check-func-t (fget-reqd-nlist-elem-1 ast 'type)))
(define (nlist-get-reqd-type ast)
(fget-reqd-nlist-elem ast 'type))
(define* (func-modify-arg ast f)
(nlist-modify-by-path ast '(type func-t args arg) f))
(define* (func-modify-returns ast f)
(nlist-modify-by-path ast '(type func-t returns) f))
;; Returns #f for an unresolved base type.
(define (get-base-type-id ast)
(unless (list-named? ast 'base)
(error "argument" ast))
(let ((type (fget-reqd-nlist-elem-1 ast 'type)))
(unless (list-named? type 'tname-ref)
(error (format "bases of type ~s unsupported" type)))
(let ((id-ref (fget-opt-nlist-elem-1 type 'decl-id-ref)))
;;(write-nl (list "ref" id-ref))
id-ref)))
;; Gets the decl IDs for all immediate bases of "ast". Unresolved
;; bases are excluded. The order is the same as in the declaration.
;;
;; XXX We only support "public" inheritance at present, and treat all
;; inheritance as public inheritance. Anything else is quite rare
;; anyway.
(define (get-base-refs d-table ast)
(let* ((elem-list (get-opt-nlist-elem-1up-e ast 'bases))
(ref-list (map get-base-type-id elem-list)))
;;(write-nl (list "reflist" (compact ref-list)))
(compact ref-list)))
;; Gets the decl IDs recursively for all bases of "ast". Implemented
;; so that inheritance loops will not cause non-termination. Left
;; bases are favored over right ones; the leftmost base is fully
;; recursed before any others.
(define* (get-base-refs-r d-table ast)
(define result '())
(define (trav ast)
(for-each
(lambda (id-ref)
(unless (include-eq? result id-ref)
(push-set! result id-ref)
(trav (get-decl-by-id d-table id-ref))))
(get-base-refs d-table ast)))
(trav ast)
result)
;; Checks for cycles in "bases" of the given element. Inheritance
;; cycles are not allowed. "decl-id-ref" attributes should already be
;; present as appropriate. Unknown bases are ignored.
;;
;; Note that in C++ it may be okay to inherit from the same base more
;; than once via other bases. We just want to make sure that no base
;; inherits from itself, as that is not legal in C++, and we might
;; want to let the user know about such problems.
(define (bases-cyclic? ast tables)
#f) ;; xxx may not use get-base-refs-r here
;; Determines whether all of the bases of the given record are known.
;; Not just the immediate children, but the whole ancestor hierarchy.
;; In practice, if bases-known? is not true for a record, then we may
;; not know all of the methods it has, and this may lead to incorrect
;; name resolution (in the C++ sense).
(define* (bases-known? ast tables)
(define d-table (get-d-table tables))
;; Used to keep track of bases already examined. We do not want to
;; examine any branch more than once.
(define id-list '())
(define (seen? id)
(if (include-eq? id-list id)
#t
(begin
(push-set! id-list id)
#f)))
(define (do-decl ast)
;;(write-nl (list "decl" ast))
(let ((id (fget-reqd-nlist-elem-1 ast 'decl-id)))
(if (seen? id)
#t
(aif bases (fget-opt-nlist-elem ast 'bases)
(do-bases bases)
#t))))
(define (do-bases ast)
;;(write-nl (list "bases" ast))
(let ((bases (cdr ast)))
(list-membs-all-match? bases do-base)))
(define (do-base ast)
;;(write-nl (list "base" ast))
(let* ((type (fget-reqd-nlist-elem-1 ast 'type)))
(unless (list-named? type 'tname-ref)
(error (format "bases of type ~s unsupported" type)))
(let* ((id-ref (fget-opt-nlist-elem-1 type 'decl-id-ref)))
;;(write-nl (list "id" id-ref))
(if (not id-ref)
#f
(let* ((base-decl (get-decl-by-id d-table id-ref)))
(do-decl base-decl))))))
(do-decl ast))
(define* (get-decl-name ast)
(fget-reqd-nlist-elem-1 ast 'name))
(define (get-member-from-list-by-name mlist name)
(find-first
mlist
(lambda (ast)
(let ((mname (get-decl-name ast)))
(eq? name mname)))))
(define* (get-member-by-name ast name)
(get-member-from-list-by-name
(get-members-list ast)
name))
;; Currently compares by name only. This is not good enough for
;; overloads. xxx
(define (members-include? mlist melem)
(true? (get-member-from-list-by-name
mlist
(get-decl-name melem))))
;; Gets all members of the specified declaration.
(define* (get-members-list ast)
(let* ((members (get-opt-nlist-elem-1up-e ast 'body)))
members))
;; Excludes private members, ctors, and dtors.
(define (get-inherited-members-list ast)
(let* ((members (get-opt-nlist-elem-1up-e ast 'body)))
(filter
(lambda (ast)
(and (not (list-named-one-of? ast '(cxx-ctor cxx-dtor)))
(let ((access (get-reqd-nlist-elem-1 ast 'access)))
(not (eq? access 'private)))))
members)))
;; This function builds a full members list for the container
;; specified by "ast", excluding private ones in ancestors. Full in
;; terms of all known members. To determine whether the list is
;; really complete, call the bases-known? function also.
(define* (build-full-members-list ast tables)
;; We are not quite sure about the order in which we should examine
;; the bases, but if we have two parents that both either directly
;; or indirectly provide a method, then we shall favor the one
;; listed first in the list of bases. Indirectly inheriting the
;; same member more than once via different parents does not really
;; cause a conflict here.
(define result (get-members-list ast))
(define d-table (get-d-table tables))
(define base-refs (get-base-refs-r d-table ast))
(write-nl (list "bases" base-refs))
(for-each
(lambda (ast)
(define mlist (get-inherited-members-list ast))
(for-each
(lambda (melem)
(unless (members-include? result melem)
(push-set! result melem)))
mlist))
(map (fix get-decl-by-id d-table) base-refs))
result)
;; Looks to see whether the passed members list contains any abstract
;; (pure virtual) members. This can be useful in determining which
;; classes can be instantiated, and which cannot.
(define* (has-abstract-members? mlist)
(find-first
(lambda (mb)
(has-true-bool-prop-memb? mb 'pure))
mlist))
) ; end module
| false |
cc5aa9f03d27c3f4a0b91c378b3f307e3d78b0a4 | 4f97d3c6dfa30d6a4212165a320c301597a48d6d | /cocoa/Barliman/mk-and-rel-interp/cbv-lc.scm | ed0bc8aae27bf6fd1293ab1e4cd5f6abc029c878 | [
"MIT",
"LicenseRef-scancode-free-unknown"
]
| permissive | michaelballantyne/Barliman | 8c0b1ccbe5141347a304fe57dc9f85085aae9228 | 7a58671a85b82c05b364b60aa3a372313d71f8ca | refs/heads/master | 2022-09-24T05:59:45.760663 | 2019-11-25T10:32:26 | 2019-11-25T10:32:26 | 268,399,942 | 0 | 0 | MIT | 2020-06-01T01:48:21 | 2020-06-01T01:48:20 | null | UTF-8 | Scheme | false | false | 59 | scm | cbv-lc.scm | ;; Call-by-value Lambda Calculus
;; TODO -- implement! :) | false |
111189f4ee5ac1ded7283099adb6fe9a0bca8192 | 84d08da008fb9828d754375ee94e0b97e859c301 | /lib/gram/lib/zipper.scm | 8a373ed07833090964b15ace099bb0c93cb4e371 | [
"BSD-3-Clause"
]
| permissive | emallson/gram | 4263c9edf1edda40eb5904591b98736749741fe4 | 1023a0ab2998fb27e7f71aeada11acbae91d4a23 | refs/heads/master | 2021-01-21T04:40:50.085623 | 2020-12-19T17:40:33 | 2020-12-19T17:40:33 | 50,430,299 | 21 | 2 | null | 2016-04-07T17:41:06 | 2016-01-26T13:29:06 | C | UTF-8 | Scheme | false | false | 6,303 | scm | zipper.scm | (define-module (gram lib zipper)
#:use-module (srfi srfi-9 gnu)
#:use-module (ice-9 match)
#:use-module (oop goops)
#:export (zipper? mkzip unzip set swap del
zipper zipper-node
insert go rotate
extract children
top find path replay transform z-> zmap zfilter
contains?))
(define-immutable-record-type zipper
(make-zipper node left up right)
zipper?
(node zipper-node)
(left zipper-left)
(up zipper-up)
(right zipper-right))
(define (go-left z)
(match z
(($ zipper node (next rest ...) up right)
(make-zipper next rest up (cons node right)))
(_ #f)))
(define (go-right z)
(match z
(($ zipper node left up (next rest ...))
(make-zipper next (cons node left) up rest))
(_ #f)))
(define-generic extract)
(define-method (extract (kids <list>) (old-parent <list>))
kids)
(define (go-up z)
(match z
(($ zipper #nil '() ($ zipper old left up right) '())
(make-zipper (extract '() old)
left up right))
(($ zipper node left ($ zipper old uleft uup uright) right)
(make-zipper (extract (append (reverse left) (list node) right) old)
uleft uup uright))
(_ #f)))
(define-generic children)
(define-method (children (lst <list>)) lst)
(define-method (children atom) #f)
(define (leaf? z)
(eq? #f (children z)))
(define (go-down z)
(match z
(($ zipper node _ _ _)
(let ((kids (children node)))
(cond
((eq? #f kids) #f)
((null? kids) (make-zipper #nil '() z '()))
(#t (make-zipper (car kids) '() z (cdr kids))))))
(_ #f)))
(define (insert-right z new)
(match z
(($ zipper #nil '() _ '())
(set z new))
(($ zipper node left up right)
(make-zipper node left up (cons new right)))
(_ #f)))
(define (insert-left z new)
(match z
(($ zipper #nil '() _ '())
(set z new))
(($ zipper node left up right)
(make-zipper node (cons new left) up right))
(_ #f)))
(define (rotate-left z)
(match z
[($ zipper node (left rest ...) up right)
(make-zipper left (cons node rest) up right)]
[_ #f]))
(define (rotate-right z)
(match z
[($ zipper node left up (right rest ...))
(make-zipper right left up (cons node rest))]
[_ #f]))
(define (go z dir)
(case dir
((left) (go-left z))
((right) (go-right z))
((up) (go-up z))
((down) (go-down z))
(else #f)))
(define (rotate z dir)
(case dir
((left) (rotate-left z))
((right) (rotate-right z))
(else #f)))
(define (insert z new dir)
(case dir
((left) (insert-left z new))
((right) (insert-right z new))
(else #f)))
(define (set z new)
(match z
(($ zipper _ left up right)
(make-zipper new left up right))
(_ #f)))
(define (swap z f . args)
(set z (apply f (zipper-node z) args)))
(define (del z)
(match z
(($ zipper node left up (next rest ...))
(make-zipper next left up rest))
(($ zipper node (next rest ...) up '())
(make-zipper next rest up '()))
(($ zipper node '() up '())
(make-zipper #nil '() up '()))
(($ zipper _ #f #f #f)
(make-zipper #nil #f #f #f))
(_ #f)))
(define (unzip z)
(match z
(($ zipper node #f #f #f)
node)
(($ zipper _ _ _ _)
(unzip (go-up z)))
(_ #f)))
(define (mkzip l)
(make-zipper l #f #f #f))
(define (top z)
(mkzip (unzip z)))
(define (find-dfs p? z)
(if (or (not (zipper? z)) (p? (zipper-node z)))
z
(let ((down (find-dfs p? (go z 'down))))
(if down
down
(find-dfs p? (go z 'right))))))
(define (find z p?)
(find-dfs p? (top z)))
(define (path z)
(match z
(($ zipper node #f #f #f)
'())
(($ zipper _ '() _ _)
(append (path (go z 'up)) (list 'down)))
(($ zipper _ (a b ...) _ _)
(append (path (go z 'left)) (list 'right)))
(_ #f)))
(define (replay z path)
(if (null? path)
z
(or (replay (go z (car path)) (cdr path)) z)))
(define (transform z p? f . rest)
"Transforms the given zipper by finding the first element `dst`
satisfying predicate `p?', calling `(apply f dst rest)`, and then
returning to the original position.
If `p?' does not satisfy `procedure?' then it is instead compared with
`equal?'."
(let ((track (path z))
(dst (find z (if (procedure? p?)
p?
(lambda (x) (equal? p? x))))))
(if dst
(replay (top (apply f dst rest)) track)
z)))
(define (find-dfs p? z)
(if (or (not (zipper? z)) (p? (zipper-node z)))
z
(let ((down (find-dfs p? (go z 'down))))
(if down
down
(find-dfs p? (go z 'right))))))
(define-syntax z->
(syntax-rules ()
[(z-> z (xform args ...))
(or (xform z args ...) z)]
[(z-> z (xform args ...) xforms ...)
(let [(zp (xform z args ...))]
(if zp
(z-> zp xforms ...)
z))]))
(define (-zmap z f)
(if (zipper? z)
(let* ((down (z-> z
(swap f)
(go 'down)
(-zmap f)
(go 'up))))
(z-> down
(go 'right)
(-zmap f)))
#f))
(define (zmap z f . rest)
"Applies f x rest to each leaf node of zipper `z' in depth-first
order."
(let ((track (path z))
(result (-zmap (top z) (lambda (x) (if (leaf? x) (apply f x rest) x)))))
(replay (top result) track)))
(define (-zfilter z p?)
(if (zipper? z)
(let ((zp (if (p? (zipper-node z)) z (del z))))
(let* ((next* (z-> zp (go 'down) (-zfilter p?) (go 'up)))
(next (if (null? (zipper-node next*))
(del next*)
next*)))
(z-> next (go 'right) (-zfilter p?))))
#f))
(define (zfilter z p? . rest)
"Returns the zipper containing the leaf elements of `z' which
satisfy (apply p? x rest)."
(let ((track (path z))
(result (-zfilter (top z) (lambda (x)
(or (not (leaf? x))
(apply p? x rest))))))
(replay (top result) track)))
(define (contains? z x)
(not (eq? #f (find z (lambda (y) (equal? x y))))))
| true |
ac18163c8071cfd52f22c4a2fb04315e18c6f3d4 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /System.Xml/system/xml/xsl/xsl-compiled-transform.sls | ca1b9879c6b18bc6ca06b2c8bedb8dc550b88328 | []
| no_license | futsuki/ironscheme-port | 2dbac82c0bda4f4ff509208f7f00a5211d1f7cd5 | 4e7a81b0fbeac9a47440464988e53fb118286c54 | refs/heads/master | 2016-09-06T17:13:11.462593 | 2015-09-26T18:20:40 | 2015-09-26T18:20:40 | 42,757,369 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,864 | sls | xsl-compiled-transform.sls | (library (system xml xsl xsl-compiled-transform)
(export new
is?
xsl-compiled-transform?
transform
load
output-settings
temporary-files)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.Xml.Xsl.XslCompiledTransform a ...)))))
(define (is? a) (clr-is System.Xml.Xsl.XslCompiledTransform a))
(define (xsl-compiled-transform? a)
(clr-is System.Xml.Xsl.XslCompiledTransform a))
(define-method-port
transform
System.Xml.Xsl.XslCompiledTransform
Transform
(System.Void
System.Xml.XmlReader
System.Xml.Xsl.XsltArgumentList
System.Xml.XmlWriter
System.Xml.XmlResolver)
(System.Void
System.Xml.XPath.IXPathNavigable
System.Xml.Xsl.XsltArgumentList
System.Xml.XmlWriter)
(System.Void System.Xml.XPath.IXPathNavigable System.Xml.XmlWriter)
(System.Void
System.Xml.XPath.IXPathNavigable
System.Xml.Xsl.XsltArgumentList
System.IO.Stream)
(System.Void
System.Xml.XPath.IXPathNavigable
System.Xml.Xsl.XsltArgumentList
System.IO.TextWriter)
(System.Void
System.Xml.XmlReader
System.Xml.Xsl.XsltArgumentList
System.Xml.XmlWriter)
(System.Void
System.Xml.XmlReader
System.Xml.Xsl.XsltArgumentList
System.IO.TextWriter)
(System.Void
System.Xml.XmlReader
System.Xml.Xsl.XsltArgumentList
System.IO.Stream)
(System.Void System.Xml.XmlReader System.Xml.XmlWriter)
(System.Void
System.String
System.Xml.Xsl.XsltArgumentList
System.Xml.XmlWriter)
(System.Void
System.String
System.Xml.Xsl.XsltArgumentList
System.IO.TextWriter)
(System.Void
System.String
System.Xml.Xsl.XsltArgumentList
System.IO.Stream)
(System.Void System.String System.Xml.XmlWriter)
(System.Void System.String System.String))
(define-method-port
load
System.Xml.Xsl.XslCompiledTransform
Load
(System.Void
System.String
System.Xml.Xsl.XsltSettings
System.Xml.XmlResolver)
(System.Void
System.Xml.XmlReader
System.Xml.Xsl.XsltSettings
System.Xml.XmlResolver)
(System.Void
System.Xml.XPath.IXPathNavigable
System.Xml.Xsl.XsltSettings
System.Xml.XmlResolver)
(System.Void System.Xml.XPath.IXPathNavigable)
(System.Void System.Xml.XmlReader)
(System.Void System.String))
(define-field-port
output-settings
#f
#f
(property:)
System.Xml.Xsl.XslCompiledTransform
OutputSettings
System.Xml.XmlWriterSettings)
(define-field-port
temporary-files
#f
#f
(property:)
System.Xml.Xsl.XslCompiledTransform
TemporaryFiles
System.CodeDom.Compiler.TempFileCollection))
| true |
357841f84562fb46fec0c4e9c875dd29a09bf225 | ece1c4300b543df96cd22f63f55c09143989549c | /Chapter1/Exercise 1.43.scm | eebdf27301570740dc0fcdc812aa66a76435d14a | []
| no_license | candlc/SICP | e23a38359bdb9f43d30715345fca4cb83a545267 | 1c6cbf5ecf6397eaeb990738a938d48c193af1bb | refs/heads/master | 2022-03-04T02:55:33.594888 | 2019-11-04T09:11:34 | 2019-11-04T09:11:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,600 | scm | Exercise 1.43.scm | ; Exercise 1.43: If ff is a numerical function and nn is a positive integer, then we can form the nthnth repeated application of ff, which is defined to be the function whose value at xx is f(f(...(f(x))...))f(f(...(f(x))...)). For example, if ff is the function x↦x+1x↦x+1, then the nthnth repeated application of ff is the function x↦x+nx↦x+n. If ff is the operation of squaring a number, then the nthnth repeated application of ff is the function that raises its argument to the 2n-th2n-th power. Write a procedure that takes as inputs a procedure that computes ff and a positive integer nn and returns the procedure that computes the nthnth repeated application of ff. Your procedure should be able to be used as follows:
; ((repeated square 2) 5)
; 625
; Hint: You may find it convenient to use compose from Exercise 1.42.
#lang planet neil/sicp
(define (square x)
(* x x)
)
(define (repeated_recursive f k)
(define (compose f g)
(lambda (x) (f (g x)))
)
(if (= 0 k)
(lambda (x) x)
(compose f (repeated_recursive f (- k 1)))
)
)
(define (repeated f k)
(define (compose f g)
(lambda (x) (f (g x)))
)
(define (next g)
(compose f g)
)
(define (iter n result)
(if (= k n)
result
(iter (+ n 1) (next result))
)
)
(iter 1 f)
)
((repeated_recursive square 2) 5)
((repeated square 2) 5)
````````````````````````````````````````````````````````````
Welcome to DrRacket, version 6.6 [3m].
Language: planet neil/sicp, with debugging; memory limit: 128 MB.
625
625
> | false |
23eb298bef0546b3fdc0b52c0c92910ec88305ea | 3122ce5556fe991665e2436e8d4950019deab43c | /test.ss | 79e742f084a2c87dd70e58075b94432ef3dbed31 | [
"MIT"
]
| permissive | guenchi/Schemacs | 555d2cb8522844f3e4dc0180a91ee0867c998748 | d23d507eeb1b2b58fb99cb04ca5acb59c0a3c496 | refs/heads/master | 2020-06-17T10:14:33.799200 | 2020-03-24T23:56:10 | 2020-03-24T23:56:10 | 195,893,099 | 45 | 4 | null | null | null | null | UTF-8 | Scheme | false | false | 730 | ss | test.ss |
(raw-off)
(clean-screem)
(init-mouse)
(define restart
(lambda ()
(raw-on)
(init)
(welcome)
(message)
(move-to (row-size) 0)
(start)))
(define write-act
(lambda (x)
(if (not (null? x))
(begin
(display (car (loc-info x)))
(display " , ")
(display (cdr (loc-info x)))
(if (car (acts-info x)) (display-with 'white " insert ") (display-with 'red " delete "))
(write (cdr (acts-info x)))
(newline)
(write-act (cdr x))))))
(display "text actual:")
(newline)
(write-out *text*)
(newline)
(display "action chain:")
(newline)
(write-act (cdr *acts*))
(newline)
(display "(exit) to exit, (restart) to restart.")
| false |
9a18a1c35a86b33da246fcac248866be525627f9 | 958488bc7f3c2044206e0358e56d7690b6ae696c | /scheme/guile/eval.scm | a0bef481a64e5b3c857458fe5ae09b6ab75a0c19 | []
| no_license | possientis/Prog | a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4 | d4b3debc37610a88e0dac3ac5914903604fd1d1f | refs/heads/master | 2023-08-17T09:15:17.723600 | 2023-08-11T12:32:59 | 2023-08-11T12:32:59 | 40,361,602 | 3 | 0 | null | 2023-03-27T05:53:58 | 2015-08-07T13:24:19 | Coq | UTF-8 | Scheme | false | false | 456 | scm | eval.scm | (define env (interaction-environment))
(display (eval '(+ 1 2) env))(newline)
(display (primitive-eval '(+ 1 2)))(newline)
(set! env (current-module))
(display (eval '(+ 1 2) env))(newline)
(display (module-variable env '+))(newline) ; #<variable 561fcc267640 value: #<procedure + (#:optional _ _ . _)>>
(module-add! env 'x (make-variable 5))
(display "x = ")(display x)(newline)
(display "x = ")(display (module-ref env 'x))(newline)
(exit 0)
| false |
1c1fcd9b9020c8e95475b890f854f7ad29cf5e21 | 648776d3a0d9a8ca036acaf6f2f7a60dcdb45877 | /queries/ron/folds.scm | ae79583ea85377be07ce12fc6c67eb2132f902c8 | [
"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 | 67 | scm | folds.scm | [
(array)
(map)
(tuple)
(struct)
(block_comment)
] @fold
| false |
2ab8bf064c2eba3fe1dc73ae98c64154a98871a9 | e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6 | /ch3/3.53.scm | 10b2ab62328bce5ffd7b69749042bed280fdbeaf | []
| no_license | lythesia/sicp-sol | e30918e1ebd799e479bae7e2a9bd4b4ed32ac075 | 169394cf3c3996d1865242a2a2773682f6f00a14 | refs/heads/master | 2021-01-18T14:31:34.469130 | 2019-10-08T03:34:36 | 2019-10-08T03:34:36 | 27,224,763 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 15 | scm | 3.53.scm | ; 1 2 4 .. 2^n
| false |
3a8a8f49f87e11764f01ebdb6b70cd826bd47fa6 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /UnityEngine/unity-engine/physics2-d.sls | 76c88a77a04ef507ac774723e42ce06f6bd3003f | []
| 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 | 24,847 | sls | physics2-d.sls | (library (unity-engine physics2-d)
(export new
is?
physics2-d?
ignore-collision
get-ignore-collision?
get-ray-intersection-all
overlap-circle-non-alloc
overlap-point-non-alloc
linecast-all
get-ray-intersection
get-ray-intersection-non-alloc
overlap-area-non-alloc
box-cast-all
ignore-layer-collision
box-cast
linecast
get-ignore-layer-collision?
circle-cast
raycast
overlap-circle-all
raycast-non-alloc
circle-cast-non-alloc
is-touching?
overlap-point-all
linecast-non-alloc
overlap-area-all
overlap-area
raycast-all
circle-cast-all
box-cast-non-alloc
is-touching-layers?
overlap-circle
overlap-point
ignore-raycast-layer
default-raycast-layers
all-layers
velocity-iterations-get
velocity-iterations-set!
velocity-iterations-update!
position-iterations-get
position-iterations-set!
position-iterations-update!
gravity-get
gravity-set!
gravity-update!
raycasts-hit-triggers?-get
raycasts-hit-triggers?-set!
raycasts-hit-triggers?-update!
raycasts-start-in-colliders?-get
raycasts-start-in-colliders?-set!
raycasts-start-in-colliders?-update!
delete-stops-callbacks?-get
delete-stops-callbacks?-set!
delete-stops-callbacks?-update!
change-stops-callbacks?-get
change-stops-callbacks?-set!
change-stops-callbacks?-update!
velocity-threshold-get
velocity-threshold-set!
velocity-threshold-update!
max-linear-correction-get
max-linear-correction-set!
max-linear-correction-update!
max-angular-correction-get
max-angular-correction-set!
max-angular-correction-update!
max-translation-speed-get
max-translation-speed-set!
max-translation-speed-update!
max-rotation-speed-get
max-rotation-speed-set!
max-rotation-speed-update!
min-penetration-for-penalty-get
min-penetration-for-penalty-set!
min-penetration-for-penalty-update!
baumgarte-scale-get
baumgarte-scale-set!
baumgarte-scale-update!
baumgarte-toiscale-get
baumgarte-toiscale-set!
baumgarte-toiscale-update!
time-to-sleep-get
time-to-sleep-set!
time-to-sleep-update!
linear-sleep-tolerance-get
linear-sleep-tolerance-set!
linear-sleep-tolerance-update!
angular-sleep-tolerance-get
angular-sleep-tolerance-set!
angular-sleep-tolerance-update!)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new UnityEngine.Physics2D a ...)))))
(define (is? a) (clr-is UnityEngine.Physics2D a))
(define (physics2-d? a) (clr-is UnityEngine.Physics2D a))
(define-method-port
ignore-collision
UnityEngine.Physics2D
IgnoreCollision
(static: System.Void UnityEngine.Collider2D UnityEngine.Collider2D)
(static:
System.Void
UnityEngine.Collider2D
UnityEngine.Collider2D
System.Boolean))
(define-method-port
get-ignore-collision?
UnityEngine.Physics2D
GetIgnoreCollision
(static:
System.Boolean
UnityEngine.Collider2D
UnityEngine.Collider2D))
(define-method-port
get-ray-intersection-all
UnityEngine.Physics2D
GetRayIntersectionAll
(static: UnityEngine.RaycastHit2D[] UnityEngine.Ray)
(static: UnityEngine.RaycastHit2D[] UnityEngine.Ray System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Ray
System.Single
System.Int32))
(define-method-port
overlap-circle-non-alloc
UnityEngine.Physics2D
OverlapCircleNonAlloc
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Collider2D[])
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Collider2D[]
System.Int32)
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Collider2D[]
System.Int32
System.Single)
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Collider2D[]
System.Int32
System.Single
System.Single))
(define-method-port
overlap-point-non-alloc
UnityEngine.Physics2D
OverlapPointNonAlloc
(static: System.Int32 UnityEngine.Vector2 UnityEngine.Collider2D[])
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Collider2D[]
System.Int32)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Collider2D[]
System.Int32
System.Single)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Collider2D[]
System.Int32
System.Single
System.Single))
(define-method-port
linecast-all
UnityEngine.Physics2D
LinecastAll
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single
System.Single))
(define-method-port
get-ray-intersection
UnityEngine.Physics2D
GetRayIntersection
(static:
UnityEngine.RaycastHit2D
UnityEngine.Ray
System.Single
System.Int32)
(static: UnityEngine.RaycastHit2D UnityEngine.Ray)
(static: UnityEngine.RaycastHit2D UnityEngine.Ray System.Single))
(define-method-port
get-ray-intersection-non-alloc
UnityEngine.Physics2D
GetRayIntersectionNonAlloc
(static: System.Int32 UnityEngine.Ray UnityEngine.RaycastHit2D[])
(static:
System.Int32
UnityEngine.Ray
UnityEngine.RaycastHit2D[]
System.Single)
(static:
System.Int32
UnityEngine.Ray
UnityEngine.RaycastHit2D[]
System.Single
System.Int32))
(define-method-port
overlap-area-non-alloc
UnityEngine.Physics2D
OverlapAreaNonAlloc
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.Collider2D[])
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.Collider2D[]
System.Int32)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.Collider2D[]
System.Int32
System.Single)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.Collider2D[]
System.Int32
System.Single
System.Single))
(define-method-port
box-cast-all
UnityEngine.Physics2D
BoxCastAll
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
ignore-layer-collision
UnityEngine.Physics2D
IgnoreLayerCollision
(static: System.Void System.Int32 System.Int32)
(static: System.Void System.Int32 System.Int32 System.Boolean))
(define-method-port
box-cast
UnityEngine.Physics2D
BoxCast
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single))
(define-method-port
linecast
UnityEngine.Physics2D
Linecast
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single
System.Single)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single))
(define-method-port
get-ignore-layer-collision?
UnityEngine.Physics2D
GetIgnoreLayerCollision
(static: System.Boolean System.Int32 System.Int32))
(define-method-port
circle-cast
UnityEngine.Physics2D
CircleCast
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
System.Single
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single))
(define-method-port
raycast
UnityEngine.Physics2D
Raycast
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.RaycastHit2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
System.Int32
System.Single))
(define-method-port
overlap-circle-all
UnityEngine.Physics2D
OverlapCircleAll
(static: UnityEngine.Collider2D[] UnityEngine.Vector2 System.Single)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
System.Single
System.Int32
System.Single)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
raycast-non-alloc
UnityEngine.Physics2D
RaycastNonAlloc
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[])
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32
System.Single)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
circle-cast-non-alloc
UnityEngine.Physics2D
CircleCastNonAlloc
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[])
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single)
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32)
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32
System.Single)
(static:
System.Int32
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
is-touching?
UnityEngine.Physics2D
IsTouching
(static:
System.Boolean
UnityEngine.Collider2D
UnityEngine.Collider2D))
(define-method-port
overlap-point-all
UnityEngine.Physics2D
OverlapPointAll
(static: UnityEngine.Collider2D[] UnityEngine.Vector2)
(static: UnityEngine.Collider2D[] UnityEngine.Vector2 System.Int32)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
System.Int32
System.Single)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
System.Int32
System.Single
System.Single))
(define-method-port
linecast-non-alloc
UnityEngine.Physics2D
LinecastNonAlloc
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[])
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Int32)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Int32
System.Single)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Int32
System.Single
System.Single))
(define-method-port
overlap-area-all
UnityEngine.Physics2D
OverlapAreaAll
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
UnityEngine.Vector2)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single)
(static:
UnityEngine.Collider2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single
System.Single))
(define-method-port
overlap-area
UnityEngine.Physics2D
OverlapArea
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
UnityEngine.Vector2)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
UnityEngine.Vector2
System.Int32
System.Single
System.Single))
(define-method-port
raycast-all
UnityEngine.Physics2D
RaycastAll
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
System.Int32
System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
circle-cast-all
UnityEngine.Physics2D
CircleCastAll
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
System.Single
UnityEngine.Vector2)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single)
(static:
UnityEngine.RaycastHit2D[]
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
box-cast-non-alloc
UnityEngine.Physics2D
BoxCastNonAlloc
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[])
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32
System.Single)
(static:
System.Int32
UnityEngine.Vector2
UnityEngine.Vector2
System.Single
UnityEngine.Vector2
UnityEngine.RaycastHit2D[]
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
is-touching-layers?
UnityEngine.Physics2D
IsTouchingLayers
(static: System.Boolean UnityEngine.Collider2D)
(static: System.Boolean UnityEngine.Collider2D System.Int32))
(define-method-port
overlap-circle
UnityEngine.Physics2D
OverlapCircle
(static: UnityEngine.Collider2D UnityEngine.Vector2 System.Single)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
System.Single
System.Int32)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
System.Single
System.Int32
System.Single)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
System.Single
System.Int32
System.Single
System.Single))
(define-method-port
overlap-point
UnityEngine.Physics2D
OverlapPoint
(static: UnityEngine.Collider2D UnityEngine.Vector2)
(static: UnityEngine.Collider2D UnityEngine.Vector2 System.Int32)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
System.Int32
System.Single)
(static:
UnityEngine.Collider2D
UnityEngine.Vector2
System.Int32
System.Single
System.Single))
(define-field-port
ignore-raycast-layer
#f
#f
(static:)
UnityEngine.Physics2D
IgnoreRaycastLayer
System.Int32)
(define-field-port
default-raycast-layers
#f
#f
(static:)
UnityEngine.Physics2D
DefaultRaycastLayers
System.Int32)
(define-field-port
all-layers
#f
#f
(static:)
UnityEngine.Physics2D
AllLayers
System.Int32)
(define-field-port
velocity-iterations-get
velocity-iterations-set!
velocity-iterations-update!
(static: property:)
UnityEngine.Physics2D
velocityIterations
System.Int32)
(define-field-port
position-iterations-get
position-iterations-set!
position-iterations-update!
(static: property:)
UnityEngine.Physics2D
positionIterations
System.Int32)
(define-field-port
gravity-get
gravity-set!
gravity-update!
(static: property:)
UnityEngine.Physics2D
gravity
UnityEngine.Vector2)
(define-field-port
raycasts-hit-triggers?-get
raycasts-hit-triggers?-set!
raycasts-hit-triggers?-update!
(static: property:)
UnityEngine.Physics2D
raycastsHitTriggers
System.Boolean)
(define-field-port
raycasts-start-in-colliders?-get
raycasts-start-in-colliders?-set!
raycasts-start-in-colliders?-update!
(static: property:)
UnityEngine.Physics2D
raycastsStartInColliders
System.Boolean)
(define-field-port
delete-stops-callbacks?-get
delete-stops-callbacks?-set!
delete-stops-callbacks?-update!
(static: property:)
UnityEngine.Physics2D
deleteStopsCallbacks
System.Boolean)
(define-field-port
change-stops-callbacks?-get
change-stops-callbacks?-set!
change-stops-callbacks?-update!
(static: property:)
UnityEngine.Physics2D
changeStopsCallbacks
System.Boolean)
(define-field-port
velocity-threshold-get
velocity-threshold-set!
velocity-threshold-update!
(static: property:)
UnityEngine.Physics2D
velocityThreshold
System.Single)
(define-field-port
max-linear-correction-get
max-linear-correction-set!
max-linear-correction-update!
(static: property:)
UnityEngine.Physics2D
maxLinearCorrection
System.Single)
(define-field-port
max-angular-correction-get
max-angular-correction-set!
max-angular-correction-update!
(static: property:)
UnityEngine.Physics2D
maxAngularCorrection
System.Single)
(define-field-port
max-translation-speed-get
max-translation-speed-set!
max-translation-speed-update!
(static: property:)
UnityEngine.Physics2D
maxTranslationSpeed
System.Single)
(define-field-port
max-rotation-speed-get
max-rotation-speed-set!
max-rotation-speed-update!
(static: property:)
UnityEngine.Physics2D
maxRotationSpeed
System.Single)
(define-field-port
min-penetration-for-penalty-get
min-penetration-for-penalty-set!
min-penetration-for-penalty-update!
(static: property:)
UnityEngine.Physics2D
minPenetrationForPenalty
System.Single)
(define-field-port
baumgarte-scale-get
baumgarte-scale-set!
baumgarte-scale-update!
(static: property:)
UnityEngine.Physics2D
baumgarteScale
System.Single)
(define-field-port
baumgarte-toiscale-get
baumgarte-toiscale-set!
baumgarte-toiscale-update!
(static: property:)
UnityEngine.Physics2D
baumgarteTOIScale
System.Single)
(define-field-port
time-to-sleep-get
time-to-sleep-set!
time-to-sleep-update!
(static: property:)
UnityEngine.Physics2D
timeToSleep
System.Single)
(define-field-port
linear-sleep-tolerance-get
linear-sleep-tolerance-set!
linear-sleep-tolerance-update!
(static: property:)
UnityEngine.Physics2D
linearSleepTolerance
System.Single)
(define-field-port
angular-sleep-tolerance-get
angular-sleep-tolerance-set!
angular-sleep-tolerance-update!
(static: property:)
UnityEngine.Physics2D
angularSleepTolerance
System.Single))
| true |
0f301009c967f15f3b99bac240fc1b123b4f1d97 | f03b4ca9cfcdbd0817ec90869b2dba46cedd0937 | /lib/multimin.scm | 63acc3fef391186a88071440d363366e44b5f496 | []
| no_license | lrsjohnson/upptackt | d696059263d18cd7390eb7c3d3650954f0b5f732 | 9bfd2ec70b82116701e791620ab342f3e7d9750e | refs/heads/master | 2021-01-19T00:08:06.163617 | 2015-06-24T14:01:03 | 2015-06-24T14:01:03 | 31,883,429 | 2 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 14,447 | scm | multimin.scm | ;;;; MULTIMIN.SCM -- n-dimensional minimization routines
;;; 9/22/89 (gjs) reduce->a-reduce
(declare (usual-integrations = + - * /
zero? 1+ -1+
;; truncate round floor ceiling
sqrt exp log sin cos))
;;; Nelder-Mead downhill simplex algorithm.
;;; We have a function, f, defined on points in n-space.
;;; We are looking for a local minimum of f.
;;; The central idea -- We have a simplex of n+1 vertices where f is
;;; known. We want to deform the simplex until it sits on the minimum.
;;; A simplex is represented as a list of entries, each of which is a
;;; pair consisting of a vertex and the value of f at that vertex.
(define simplex-size length)
(define simplex-vertex car)
(define simplex-value cdr)
(define simplex-entry cons)
;;; Simplices are stored in sorted order
(define simplex-highest car)
(define simplex-but-highest cdr)
(define simplex-next-highest cadr)
(define (simplex-lowest s) (car (last-pair s)))
(define (simplex-add-entry entry s)
(let ((fv (simplex-value entry)))
(let loop ((s s))
(cond ((null? s) (list entry))
((> fv (simplex-value (car s))) (cons entry s))
(else (cons (car s) (loop (cdr s))))))))
(define (simplex-adjoin v fv s)
(simplex-add-entry (simplex-entry v fv) s))
(define (simplex-sort s)
(let lp ((s s) (ans '()))
(if (null? s)
ans
(lp (cdr s) (simplex-add-entry (car s) ans)))))
(define simplex-centroid
(lambda (simplex)
(scalar*vector (/ 1 (simplex-size simplex))
(a-reduce vector+vector
(map simplex-vertex simplex)))))
(define extender
(lambda (p1 p2)
(let ((dp (vector-vector p2 p1)))
(lambda (k)
(vector+vector p1 (scalar*vector k dp))))))
(define (make-simplex point step f)
(simplex-sort
(map (lambda (vertex) (simplex-entry vertex (f vertex)))
(cons point
(let ((n (vector-length point)))
(generate-list n
(lambda (i)
(vector+vector point
(scalar*vector step
(v:make-basis-unit n i))))))))))
(define (stationary? simplex epsilon)
(close-enuf? (simplex-value (simplex-highest simplex))
(simplex-value (simplex-lowest simplex))
epsilon))
(define nelder-wallp? false)
;;; Example:
#|
(define (f vec)
(let ((x (vector-ref vec 0)) (y (vector-ref vec 1)))
(+ (square (- x 3)) (square (- y 2)))))
(nelder-mead f #(0.1 0.1) 1 0.000001 100)
|#
(define (nelder-mead f start-pt start-step epsilon maxiter)
(define shrink-coef 0.5)
(define reflection-coef 2.0)
(define expansion-coef 3.0)
(define contraction-coef-1 1.5)
(define contraction-coef-2 (- 2 contraction-coef-1))
(define (simplex-shrink point simplex)
(let ((pv (simplex-vertex point)))
(simplex-sort
(map (lambda (sp)
(if (eq? point sp)
sp
(let ((vertex ((extender pv (simplex-vertex sp))
shrink-coef)))
(simplex-entry vertex (f vertex)))))
simplex))))
(define (nm-step simplex)
(let ((g (simplex-highest simplex))
(h (simplex-next-highest simplex))
(s (simplex-lowest simplex))
(s-h (simplex-but-highest simplex)))
(let* ((vg (simplex-vertex g)) (fg (simplex-value g))
(fh (simplex-value h)) (fs (simplex-value s))
(extend (extender vg (simplex-centroid s-h))))
(let* ((vr (extend reflection-coef))
(fr (f vr))) ;try reflection
(if (< fr fh) ;reflection successful
(if (< fr fs) ;new minimum
(let* ((ve (extend expansion-coef))
(fe (f ve))) ;try expansion
(if (< fe fs) ;expansion successful
(simplex-adjoin ve fe s-h)
(simplex-adjoin vr fr s-h)))
(simplex-adjoin vr fr s-h))
(let* ((vc (extend (if (< fr fg)
contraction-coef-1
contraction-coef-2)))
(fc (f vc))) ;try contraction
(if (< fc fg) ;contraction successful
(simplex-adjoin vc fc s-h)
(simplex-shrink s simplex))))))))
(define (limit simplex count)
(if nelder-wallp? (write-line (simplex-lowest simplex)))
(if (stationary? simplex epsilon)
(list 'ok (simplex-lowest simplex) count)
(if (fix:= count maxiter)
(list 'maxcount (simplex-lowest simplex) count)
(limit (nm-step simplex) (fix:+ count 1)))))
(limit (make-simplex start-pt start-step f) 0))
;;;(define (stationary? simplex epsilon)
;;; (let ((np1 (length simplex)))
;;; (let* ((mean (/ (a-reduce + (map simplex-value simplex)) np1))
;;; (variance (/ (a-reduce +
;;; (map (lambda (e)
;;; (square (- (simplex-value e) mean)))
;;; simplex))
;;; np1)))
;;; (< variance epsilon))))
;;; Variable Metric Methods:
;;; Fletcher-Powell (choice of line search)
;;; Broyden-Fletcher-Goldfarb-Shanno (Davidon's line search)
;;; The following utility procedure returns a gradient function given a
;;; differentiable function f of a vector of length n. In general, a gradient
;;; function accepts an n-vector and returns a vector of derivatives. In this
;;; case, the derivatives are estimated by richardson-extrapolation of a
;;; central difference quotient, with the convergence tolerance being a
;;; specified parameter.
(define (generate-gradient-procedure f n tol)
(lambda (x)
(generate-vector
n
(lambda (i)
(richardson-limit
(let ((fi (lambda (t)
(f (vector+vector x
(scalar*vector t
(v:make-basis-unit n i)))))))
(lambda (h) (/ (- (fi h) (fi (- h))) 2 h)))
(max 0.1 (* 0.1 (abs (vector-ref x i)))) ;starting h
2 ;ord -- see doc for RE.SCM
2 ;inc
tol)))))
;;; The following line-minimization procedure is Davidon's original
;;; recommendation. It does a bracketing search using gradients, and
;;; then interpolates the straddled minimum with a cubic.
(define (line-min-davidon f g x v est)
(define (t->x t) (vector+vector x (scalar*vector t v)))
(define (linef t) (f (t->x t)))
(define (lineg t) (g (t->x t)))
(define f0 (linef 0))
(define g0 (lineg 0))
(define s0 (/ (- f0 est) -.5 (v:dot-product g0 v)))
(let loop ((t (if (and (positive? s0) (< s0 1)) s0 1))
(iter 0))
(if (> iter 100)
(list 'no-min)
(let ((ft (linef t))
(gt (lineg t)))
(if (or (>= ft f0)
(>= (v:dot-product v gt) 0))
(let* ((vg0 (v:dot-product v g0))
(vgt (v:dot-product v gt))
(z (+ (* 3 (- f0 ft) (/ 1 t)) vg0 vgt))
(w (sqrt (- (* z z) (* vg0 vgt))))
(tstar (* t (- 1 (/ (+ vgt w (- z))
(+ vgt (- vg0) (* 2 w))))))
(fstar (linef tstar)))
(if (< fstar f0)
(list 'ok (t->x tstar) fstar)
(loop tstar (+ iter 1))))
(loop (* t 2) (+ iter 1)))))))
;;; The following line-minimization procedure is based on Brent's
;;; algorithm.
(define (line-min-brent f g x v est)
(define (t->x t) (vector+vector x (scalar*vector t v)))
(define (linef t) (f (t->x t)))
(define (lineg t) (g (t->x t)))
(define f0 (linef 0))
(define g0 (lineg 0))
(define s0 (/ (- f0 est) -.5 (v:dot-product g0 v)))
(let loop ((t (if (and (positive? s0) (< s0 1)) s0 1))
(iter 0))
(if (> iter 100)
(list 'no-min)
(let ((ft (linef t))
(gt (lineg t)))
(if (or (>= ft f0)
(>= (v:dot-product v gt) 0))
(let* ((result (brent-min linef 0 t *sqrt-machine-epsilon*))
(tstar (car result))
(fstar (cadr result)))
(list 'ok (t->x tstar) fstar))
(loop (* t 2) (+ iter 1)))))))
;;; In the following implementation of the Davidon-Fletcher-Powell
;;; algorithm, f is a function of a single vector argument that returns
;;; a real value to be minimized, g is the vector-valued gradient and
;;; x is a (vector) starting point, and est is an estimate of the minimum
;;; function value. If g is '(), then a numerical approximation is
;;; substituted using GENERATE-GRADIENT-PROCEDURE. ftol is the convergence
;;; criterion: the search is stopped when the relative change in f falls
;;; below ftol.
(define fletcher-powell-wallp? false)
(define (fletcher-powell line-search f g x est ftol maxiter)
(let ((n (vector-length x)))
(if (null? g) (set! g (generate-gradient-procedure
f n (* 1000 *machine-epsilon*))))
(let loop ((H (m:make-identity n))
(x x)
(fx (f x))
(gx (g x))
(count 0))
(if fletcher-powell-wallp? (print (list x fx gx)))
(let ((v (matrix*vector H (scalar*vector -1 gx))))
(if (positive? (v:dot-product v gx))
(begin
(if fletcher-powell-wallp?
(display (list "H reset to Identity at iteration" count)))
(loop (m:make-identity n) x fx gx count))
(let ((r (line-search f g x v est)))
(if (eq? (car r) 'no-min)
(list 'no-min (cons x fx) count)
(let ((newx (cadr r))
(newfx (caddr r)))
(if (close-enuf? newfx fx ftol) ;convergence criterion
(list 'ok (cons newx newfx) count)
(if (fix:= count maxiter)
(list 'maxcount (cons newx newfx) count)
(let* ((newgx (g newx))
(dx (vector-vector newx x))
(dg (vector-vector newgx gx))
(Hdg (matrix*vector H dg))
(A (matrix*scalar
(m:outer-product (vector->column-matrix dx)
(vector->row-matrix dx))
(/ 1 (v:dot-product dx dg))))
(B (matrix*scalar
(m:outer-product (vector->column-matrix Hdg)
(vector->row-matrix Hdg))
(/ -1 (v:dot-product dg Hdg))))
(newH (matrix+matrix H (matrix+matrix A B))))
(loop newH newx newfx newgx (fix:+ count 1)))))))))))))
;;; The following procedures, DFP and DFP-BRENT, call directly upon
;;; FLETCHER-POWELL. The first uses Davidon's line search which is
;;; efficient, and would be the normal choice. The second uses Brent's
;;; line search, which is less efficient but more reliable.
(define (dfp f g x est ftol maxiter)
(fletcher-powell line-min-davidon f g x est ftol maxiter))
(define (dfp-brent f g x est ftol maxiter)
(fletcher-powell line-min-brent f g x est ftol maxiter))
;;; The following is a variation on DFP, due (independently, we are told)
;;; to Broyden, Fletcher, Goldfarb, and Shanno. It differs in the formula
;;; used to update H, and is said to be more immune than DFP to imprecise
;;; line-search. Consequently, it is offered with Davidon's line search
;;; wired in.
(define bfgs-wallp? false)
(define (bfgs f g x est ftol maxiter)
(let ((n (vector-length x)))
(if (null? g) (set! g (generate-gradient-procedure
f n (* 1000 *machine-epsilon*))))
(let loop ((H (m:make-identity n))
(x x)
(fx (f x))
(gx (g x))
(count 0))
(if bfgs-wallp? (print (list x fx gx)))
(let ((v (matrix*vector H (scalar*vector -1 gx))))
(if (positive? (v:dot-product v gx))
(begin
(if bfgs-wallp?
(display (list "H reset to Identity at iteration" count)))
(loop (m:make-identity n) x fx gx count))
(let ((r (line-min-davidon f g x v est)))
(if (eq? (car r) 'no-min)
(list 'no-min (cons x fx) count)
(let ((newx (cadr r))
(newfx (caddr r)))
(if (close-enuf? newfx fx ftol) ;convergence criterion
(list 'ok (cons newx newfx) count)
(if (fix:= count maxiter)
(list 'maxcount (cons newx newfx) count)
(let* ((newgx (g newx))
(dx (vector-vector newx x))
(dg (vector-vector newgx gx))
(Hdg (matrix*vector H dg))
(dxdg (v:dot-product dx dg))
(dgHdg (v:dot-product dg Hdg))
(u (vector-vector (scalar*vector (/ 1 dxdg) dx)
(scalar*vector (/ 1 dgHdg) Hdg)))
(A (matrix*scalar
(m:outer-product (vector->column-matrix dx)
(vector->row-matrix dx))
(/ 1 dxdg)))
(B (matrix*scalar
(m:outer-product (vector->column-matrix Hdg)
(vector->row-matrix Hdg))
(/ -1 dgHdg)))
(C (matrix*scalar
(m:outer-product (vector->column-matrix u)
(vector->row-matrix u))
dgHdg))
(newH
(matrix+matrix (matrix+matrix H A)
(matrix+matrix B C))))
(loop newH newx newfx newgx (fix:+ count 1)))))))))))))
| false |
ce2279be08ff3a8870d0db8f4f10234ca02cd1f4 | fae4190f90ada065bc9e5fe64aab0549d4d4638a | /pre-effect/private/infer.ss | 494a123cdc9ddd9f06c02231b5da0d3460ff0397 | []
| 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 | 145 | ss | infer.ss | (module infer mzscheme
(require (all-except (lib "unit.ss") rename) "big-unit.ss" "signatures.ss")
(provide-signature-elements infer^)
) | false |
b19246203f2006803760a91741abc346540baa20 | d074b9a2169d667227f0642c76d332c6d517f1ba | /sicp/ch_2/exercise.2.35.scm | 76a25662d7c9e552b80224cae4912fe5f482c911 | []
| no_license | zenspider/schemers | 4d0390553dda5f46bd486d146ad5eac0ba74cbb4 | 2939ca553ac79013a4c3aaaec812c1bad3933b16 | refs/heads/master | 2020-12-02T18:27:37.261206 | 2019-07-14T15:27:42 | 2019-07-14T15:27:42 | 26,163,837 | 7 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 905 | scm | exercise.2.35.scm | #lang racket/base
(require "../lib/test.rkt")
(require "../lib/myutils.scm")
;; Exercise 2.35
;; Redefine `count-leaves' from section *Note 2-2-2:: as an
;; accumulation:
;;
;; (define (count-leaves t)
;; (accumulate <??> <??> (map <??> <??>)))
(define (count-leaves x)
(cond ((null? x) 0)
((not (pair? x)) 1)
(else (+ (count-leaves (car x))
(count-leaves (cdr x))))))
(define (count-leaves2 t)
(accumulate + 0 (map (lambda (l) (if (list? l) (count-leaves2 l) 1)) t)))
(define x (cons '(1 2) '(3 4)))
(assert-equal 3 (length x))
(assert-equal 2 (length (list x x)))
(assert-many (lambda (fut)
(assert-equal 0 (fut '()))
(assert-equal 1 (fut '(a)))
(assert-equal 4 (fut x))
(assert-equal 8 (fut (list x x))))
count-leaves
count-leaves2)
(assert-equal 0 0)
(done)
| false |
4dd36e779f1b2679f2ef720fb1b309abdcd374eb | 984c1388350023db96bde3ba12dbfdd5bdf3bdeb | /acquire/board.rkt | e268d1a94b97a8d6ef62c027609da774035aa56b | []
| no_license | LeifAndersen/backend-coach | e5f11e4fd640be79d59c9e81a53c56c7aff47d0b | c788ac6865d7a46aebc4e2e43ff7ef524f523527 | refs/heads/master | 2021-01-20T01:31:38.258489 | 2017-05-18T21:25:38 | 2017-05-18T21:25:38 | 89,289,714 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 22,576 | rkt | board.rkt | #!r6rs
;; ---------------------------------------------------------------------------------------------------
;; a data representation for the board with operations for
;; -- inspecting the board to strategize
;; -- placing tiles on the board to realize a player's action
;; the actions do not enforce the rules of the game only consistent placements
;; also exports tiles+spots: A1 ... I12 via submodule tiles+spots
;; ---------------------------------------------------------------------------------------------------
(library
(board)
(export
tile tile? tile-column tile-row
; tile?
; ;; (-> Any Boolean)
tile<=?
;; (-> Tile Tile Boolean)
tile->string
;; (-> Tile String)
ALL-TILES
;; (Listof Tile)
;; Postcondition: Sorted
STARTER-TILES-n
;; Natural
FOUNDING GROWING MERGING SINGLETON IMPOSSIBLE
;; Symbol
make-board
;; (-> Board)
board-tiles
;; (-> Board (Listof Tile))
(rename-out [ext:what-kind-of-spot what-kind-of-spot])
;; (-> Board Tile SpotType
;; (define-type SpotType (U FOUNDING GROWING MERGING SINGLETON IMPOSSIBLE))
;; Precondition:
;; (free-spot? b t)
;; Postcondition:
;; (U FOUNDING GROWING MERGING SINGLETON IMPOSSIBLE)
(rename-out [ext:growing-which growing-which])
;; (-> Board Tile Hotel)
;; Precondition: (eq? (what-kind-of-spot b t) GROWING)
(rename-out [ext:merging-which merging-which])
;; (-> Board Tile (Values (Pairof Hotel (Listof Hotel)) (Listof Hotel)))
;; Precondition: (eq? (what-kind-of-spot b t) MERGING)
deduplicate/hotel
size-of-hotel
;; (-> Board Hotel Natural)
free-spot?
;; (-> Board Tile Boolean)
(rename-out [ext:merge-hotels merge-hotels])
;; (-> Board Tile Hotel Board)
;; Precondition: (eq? (what-kind-of-spot b t) MERGING)
;; Precondition: (let-values ([(w _) (merging-which b t)]) (member h w))
(rename-out [ext:found-hotel found-hotel])
;; (-> Board Tile Hotel Board)
;; Precondition: (eq? (what-kind-of-spot b t) FOUNDING)
(rename-out [ext:grow-hotel grow-hotel])
;; (-> Board Tile Board)
;; Precondition: (eq? (what-kind-of-spot b t) GROWING)
(rename-out [ext:place-tile place-tile])
;; (-> Board Tile Board)
;; Precondition: (memq (what-kind-of-spot b t) (list SINGLETON GROWING FOUNDING))
(rename-out [ext:set-board set-board])
;; (-> Board Tile (U FOUNDING GROWING MERGING SINGLETON) (Option Hotel) Board)
;; Precondition: (free-spot? b t)
;; Precondition: (==> h (or (eq? FOUNDING a) (eq? MERGING a)))
;; Precondition: (==> (eq? MERGING a) h)
(rename-out [ext:affordable? affordable?])
;; (-> Board Shares-Order Cash Boolean)
(rename-out [ext:*create-board-with-hotels *create-board-with-hotels])
;; (-> (Listof Tile) (Listof (Pairof Hotel (Listof Tile))) Board)
;; Precondition: (distinct t*)
;; Precondition: ((distinct-and-properly-formed t) ht*)
distinct-and-properly-formed
;; (-> (Listof Tile) (-> (Listof (Pairof Hotel (Listof Tile))) Boolean))
)
(import (chezscheme))
;; ---------------------------------------------------------------------------------------------------
;; IMPLEMENTATION: SPOTS
(require (only-in "basics.rkt"
hotel?
SAFE-n
price-per-share
shares-order?
))
(require (only-in "auxiliaries.rkt"
aux:partition
distinct
))
;; =============================================================================
(module tiles racket
(provide (all-defined-out))
(require
"../base/untyped.rkt")
(require (only-in "basics.rkt"
hotel->color
hotel->label))
(require (only-in "auxiliaries.rkt"
randomly-pick))
;; ---------------------------------------------------------------------------------------------------
;; ROWS and COLUMNS
(define COLUMNS
'(1 2 3 4 5 6 7 8 9 10 11 12 13))
(define (column? c)
(if (member c COLUMNS) #t #f))
(define (random-column)
(randomly-pick COLUMNS))
(define (column-> c)
(let loop
([col* COLUMNS])
(cond
[(or (null? col*) (null? (cdr col*)))
#f]
[(eq? c (car col*))
(cadr col*)]
[else
(loop (cdr col*))])))
(define (column-< c)
(let loop
([prev #f]
[col* COLUMNS])
(cond
[(null? col*) #f]
[(eq? c (car col*)) prev]
[else (loop (car col*) (cdr col*))])))
(define column<= <=)
(define (string->column s)
(and (string? s)
(let ([n (string->number s)])
(and n
(member n COLUMNS)
(exact-nonnegative-integer? n)
n))))
(define column->string number->string)
(define ROWS '(A B C D E F G H I))
(define (row? r)
(if (member r ROWS) #t #f))
(define (random-row) (randomly-pick ROWS))
(define (row-v r)
(let loop
([row* ROWS])
(cond
[(or (null? row*) (null? (cdr row*)))
#f]
[(eq? (car row*) r)
(cadr row*)]
[else
(loop (cdr row*))])))
(define (row-^ r)
(let loop
([prev #f]
[row* ROWS])
(cond
[(null? row*) #f]
[(eq? (car row*) r) prev]
[else (loop (car row*) (cdr row*))])))
(define (list-index x y*)
(or
(for/or
([y (in-list y*)]
[i (in-naturals)])
(and (eq? x y) i))
90))
;; ;; Row Row -> Boolean
;; ;; does q appear before r in order?
(define (row<= q r)
(<= (list-index q ROWS)
(list-index r ROWS)))
;; ;; Row Row -> Boolean
;; ;; does q appear strictly before r in order?
(define (row<< q r)
(< (list-index q ROWS)
(list-index r ROWS)))
;; (define (row->text r)
;; (text/font (symbol->string r) 24 "black" #f 'system 'normal 'normal #f))
(define (string->row s)
(and (string? s)
(let ([n (string->symbol s)])
(and n (member n ROWS) n))))
(define row->string symbol->string)
(define CELL-SIZE 66)
;; ---------------------------------------------------------------------------------------------------
(define-record-type tile
(fields column row))
(define tile make-tile
(define TILE-SIZE (assert (- CELL-SIZE 3) exact-nonnegative-integer?))
(define TILE-COLOR 'gray)
(define STARTER-TILES-n 6)
(define-syntax-rule
;; should be an identifier macro but contracts
(ctile letter number) (tile/c number 'letter))
;; (-> column? row? any)
(define (tile/c c r)
(if (and (column? c) (row? r))
(tile c r)
(error 'tile "not (column,row): ~e, ~e" c r)))
(define ALL-TILES
(for*/list
((r ROWS) (c COLUMNS))
(tile c r)))
;; Tile Tile -> Boolean
;; is t1 closer to the top-left corner than t2?
(define (tile<=? t1 t2)
(or (row<< (tile-row t1) (tile-row t2))
(and (row<= (tile-row t1) (tile-row t2))
(column<= (tile-column t1) (tile-column t2)))))
(define (tile<? s t)
(and (tile<=? s t) (not (equal? s t))))
(define (tile>? s t)
(and (tile<=? t s) (not (equal? s t))))
(define (tile->string t)
(format "(~a,~a)" (tile-column t) (tile-row t)))
)
(require 'tiles)
;; ---------------------------------------------------------------------------------------------------
;; data
(define FOUNDING 'FOUNDING)
(define GROWING 'GROWING)
(define MERGING 'MERGING)
(define SINGLETON 'SINGLETON)
(define IMPOSSIBLE 'IMPOSSIBLE)
;; no tile is placed in this cell
(define UNTAKEN 'UNTAKEN)
;; a tile is placed but it does not belong to a hotel
(define TAKEN-NO-HOTEL 'taken-no-hotel)
;; Content = Hotel | UNTAKEN | TAKEN-NO-HOTEL
;; board = [Hashof Tile Content]
;; if a (c,r) key maps to a hotel, it belongs to this hotel; otherwise it is free
(define (board? x)
;;bg; do more?
(and (hash? x)))
(define (board) (make-hashtable))
(define (board-tiles b) (hash-keys b))
;; ---------------------------------------------------------------------------------------------------
;; FUNCTIONS internal
;; Tile *-> Board
;; place tiles; do not found or create hotels
(define (board* . t*)
(for/fold
((b (board)))
((t (in-list t*)))
(place-tile b t)))
(define (ext:*create-board-with-hotels lt lh)
(unless (distinct lt)
(error 'create-board-with-hotels "precondition"))
(unless ((distinct-and-properly-formed lt) lh)
(error 'create-board-with-hotels "precondition"))
(*create-board-with-hotels lt lh))
(define (*create-board-with-hotels lt lh)
(for/fold
((b (apply board* lt)))
((h lh))
(define name (first h))
(define til* (rest h))
(for/fold
((b b))
((t (in-list (rest h))))
(hash-set b t name))))
(define (board-ref b c r)
(hash-ref b (tile c r) (lambda () UNTAKEN)))
;; Board Column Row -> Content
(define (board-set b c r [h TAKEN-NO-HOTEL])
(hash-set b (tile c r) h))
;; Board Column Row [X X X X ->* Y] ->* Y
;; produce neighbors in North East South and West
(define (neighbors b c r f)
(f (north b c r) (east b c r) (south b c r) (west b c r)))
(define (cardinal-direction n-s e-w)
(lambda (b
c
r)
(define north-south (n-s r))
(define east-west (e-w c))
(cond
[(boolean? north-south) UNTAKEN]
[(boolean? east-west) UNTAKEN]
[else (board-ref b east-west north-south)])))
(define north (cardinal-direction row-^ (lambda (x) x)))
(define south (cardinal-direction row-v (lambda (x) x)))
(define east (cardinal-direction (lambda (x) x) column->))
(define west (cardinal-direction (lambda (x) x) column-<))
;; Board Hotel -> [Listof Tile] | sorted * tile<=?
(define (tiles-with-specific-label b h)
(define t* (for/list ([(s label) (in-hash b)] #:when (equal? h label)) s))
(sort t* tile<=?))
;; ---------------------------------------------------------------------------------------------------
;; FUNCTIONS external functions
(define (free-spot? board tile)
(eq? (board-ref board (tile-column tile) (tile-row tile))
UNTAKEN))
(define (ext:what-kind-of-spot board tile)
(unless (free-spot? board tile)
(error 'what-kind-of-spot (format "Precondition: (free-spot ~a ~a)" board tile)))
(what-kind-of-spot board tile))
(define (what-kind-of-spot board tile)
(define column (tile-column tile))
(define row (tile-row tile))
(define surroundings (neighbors board column row list))
(define hotels (deduplicate/hotel
(for/list
([s (in-list surroundings)]
#:when (hotel? s))
(assert s string?))))
(define hotels-n (length hotels))
(define neighbor-taken-no-hotel?
(for/or
([s (in-list surroundings)])
(and (eq? TAKEN-NO-HOTEL s) s)))
(cond
[(= hotels-n 0) (if neighbor-taken-no-hotel? FOUNDING SINGLETON)]
[(= hotels-n 1) (if neighbor-taken-no-hotel? IMPOSSIBLE GROWING)]
[(>= hotels-n 2)
(define any-hotel-safe?
(for/or
((h (in-list hotels)))
(>= (size-of-hotel board h) SAFE-n)))
(if (or neighbor-taken-no-hotel? any-hotel-safe?) IMPOSSIBLE MERGING)]
[else (error 'nope)]))
(define (ext:growing-which board tile)
(unless (eq? (what-kind-of-spot board tile) GROWING)
(error 'growing-which (format "Precondition: expected growing, got ~a" (what-kind-of-spot board tile))))
(growing-which board tile))
(define (growing-which board tile)
;; the 'first' is guranateed by contract
(define n* (neighbors board (tile-column tile) (tile-row tile) list))
(for/or
([c (in-list n*)])
(and (hotel? c) (assert c string?))))
(define (ext:merging-which board tile)
(unless (eq? (what-kind-of-spot board tile) MERGING)
(error 'merging-which (format "Precondition: expected merging, got ~a" (what-kind-of-spot board tile))))
(merging-which board tile))
(define (merging-which board tile)
(define surroundings (neighbors board (tile-column tile) (tile-row tile) list))
(define hotels (deduplicate/hotel
(for/list
([s (in-list surroundings)]
#:when (hotel? s))
(assert s string?))))
(define sorted
(let ([x* (for/list
([h (in-list hotels)])
(list h (size-of-hotel board h)))])
(sort x* (lambda (x y) (> (cadr x) (cadr y))))))
(define partitioned (aux:partition sorted second (lambda (x) (car x))))
(values (assert (first partitioned) pairof-hotel-listof-hotel) (apply append (rest partitioned))))
(define (pairof-hotel-listof-hotel x)
(and (pair? x)
(hotel? (car x))
(list? (cdr x))
(andmap hotel? (cdr x))))
(define (deduplicate/hotel h*)
(let loop ([h* h*])
(cond [(null? h*) '()]
[(member (car h*) (cdr h*)) (loop (cdr h*))]
[else (cons (car h*) (loop (cdr h*)))])))
(define (size-of-hotel board hotel)
(for/fold
((size 0))
([(key value) (in-hash board)])
(if (equal? hotel value) (+ size 1) size)))
(define (ext:grow-hotel board tile)
(unless (eq? (what-kind-of-spot board tile) GROWING)
(error 'grow-hotel (format "Precondition: expected founding, got ~a" (what-kind-of-spot board tile))))
(grow-hotel board tile))
(define (grow-hotel board tile)
(define row (tile-row tile))
(define column (tile-column tile))
(define surroundings (neighbors board column row list))
(define hotel-that-touches (first (filter hotel? surroundings)))
(board-set board column row hotel-that-touches))
(define (ext:merge-hotels board tile hotel)
(unless (eq? (what-kind-of-spot board tile) MERGING)
(error 'merge-hotels (format "Precondition: expected merging, got ~a" (eq? (what-kind-of-spot board tile) MERGING))))
(unless (let-values ([(w _) (merging-which board tile)]) (member hotel w))
(error 'merge-hotels (format "Precondition: hotel ~a is not on a merging spot" hotel)))
(merge-hotels board tile hotel))
(define (merge-hotels board tile hotel)
(define row (tile-row tile))
(define column (tile-column tile))
(define-values (acquirers acquired) (merging-which board tile))
(define acquired-hotels (append (remq hotel acquirers) acquired))
(define relabeled-hotel
(for/hash
(([key current-content] (in-hash board)))
(if (memq current-content acquired-hotels)
(values key hotel)
(values key current-content))))
(board-set relabeled-hotel column row hotel))
(define (ext:found-hotel board tile hotel)
(unless (eq? (what-kind-of-spot board tile) FOUNDING)
(error 'found-hotel (format "Precondition: expected founding, got ~a" (what-kind-of-spot board tile))))
(found-hotel board tile hotel))
(define (found-hotel board tile hotel)
(define row (tile-row tile))
(define column (tile-column tile))
(board-set (hotel-take-over-neighboring-tiles board column row hotel) column row hotel))
;; Board Column Row Hotel -> Board
;; mark all TAKEN-NO-HOTEL tiles on board reachable from (column,row) as belong to hotel
;; Global Invariant: This region does not touch any other hotels
(define (hotel-take-over-neighboring-tiles board column row hotel)
(let loop
((board board)
(to-visit (list (tile column row)))
(visited '()))
(cond
[(empty? to-visit) board]
[(member (first to-visit) visited) (loop board (rest to-visit) visited)]
[else
(define column (tile-column (first to-visit)))
(define row (tile-row (first to-visit)))
(define-values (n e s w)
(let ([r (neighbors board column row list)])
(values (car r) (cadr r) (caddr r) (cadddr r))))
(define no-tiles '())
(loop (board-set board column row hotel)
(append (if (equal? TAKEN-NO-HOTEL n) (list (tile column (or (row-^ row) (error 'badrow)))) no-tiles)
(if (equal? TAKEN-NO-HOTEL e) (list (tile (or (column-> column) (error 'badcol)) row)) no-tiles)
(if (equal? TAKEN-NO-HOTEL s) (list (tile column (or (row-v row) (error 'badrow)))) no-tiles)
(if (equal? TAKEN-NO-HOTEL w) (list (tile (or (column-< column) (error 'badcol)) row)) no-tiles)
(rest to-visit))
(cons (first to-visit) visited))])))
(define (ext:place-tile board tile)
(unless (memq (what-kind-of-spot board tile) (list SINGLETON GROWING FOUNDING))
(error 'place-tile "precondition"))
(place-tile board tile))
(define (place-tile board tile)
(define row (tile-row tile))
(define column (tile-column tile))
(board-set board column row))
(define (ext:set-board board tile kind hotel)
(unless (free-spot? board tile)
(error 'set-board "Precondition"))
(unless (if hotel (or (eq? FOUNDING kind) (eq? MERGING kind)) #t)
(error 'set-board "Precondition"))
(unless (if (eq? MERGING kind) hotel #t)
(error 'set-board "Precondition"))
(set-board board tile kind hotel))
(define (set-board board tile kind hotel)
(cond
[(eq? FOUNDING kind) (if hotel (found-hotel board tile hotel) (place-tile board tile))]
[(and hotel (eq? MERGING kind)) (merge-hotels board tile hotel)]
[(and hotel (eq? SINGLETON kind)) (place-tile board tile)]
[(and hotel (eq? GROWING kind)) (grow-hotel board tile)]
[else (error 'nopers)]))
(define (ext:affordable? board hotels budget)
(unless (shares-order? hotels)
(error 'afoordable "precondigin"))
(affordable? board hotels budget))
(define (affordable? board hotels budget)
(define prices
(for/list
([h (in-list hotels)])
(price-per-share h (size-of-hotel board h))))
(define s
(for/fold
([acc 0])
([c (in-list prices)])
(if c (+ c acc) acc)))
(if (ormap boolean? prices) #f (<= s budget)))
;; ---------------------------------------------------------------------------------------------------
;; notions of contracts for creating a board with hotels specified as lists
;; (1) the hotels have distinct names
;; (2) each hotel comes with at least two tiles
;; (3) the tiles of the hotels and the unassociated tiles are distinct
;; (4) the tiles of each hotel form connected graphs
;; (5) no two hotel chains touch each other directly
(define ((distinct-and-properly-formed free-tiles) hotels-as-lists)
(define hotel-tiles
(for/list
([hl (in-list hotels-as-lists)])
(cdr hl)))
(define first*
(for/list
([hl (in-list hotels-as-lists)])
(car hl)))
(and (or (distinct first*) (tee/-f "hotel names not distinct"))
(or (andmap contains-at-least-two hotel-tiles) (tee/-f "hotels don't have 2 tiles"))
(or (distinct (apply append free-tiles hotel-tiles)) (tee/-f "hotel & free tiles overlap"))
(or (andmap connected-graph hotel-tiles) (tee/-f "hotels not graphs"))
(or (no-two-hotels-touch hotel-tiles) (tee/-f "two hotels touch"))))
(define (tee/-f s)
(error 'distint-and-properly-formed s))
;; ---------------------------------------------------------------------------------------------------
;; auxiliary notiones
;; HT = (cons Tile (cons Tile [Listof Tile])) ;; the tiles of a syntactically well-formed hotel
;; ;; HT -> Boolean
(define (contains-at-least-two ht)
(and (cons? ht) (cons? (rest ht))))
;; ;; HT -> Boolean
;; ;; do the tiles of a hotel form a connected graph?
(define (connected-graph hotel-tiles)
(define start (first hotel-tiles))
(define remaining (rest hotel-tiles))
(define next (connected-to start remaining))
(and (cons? next)
(let loop
((frontier next)
(remaining (remove* next remaining)))
(cond
[(empty? remaining) #t]
[else (define one-step (apply append
(map (λ (f)
(connected-to f remaining))
frontier)))
(and (cons? one-step) (loop one-step (remove* one-step remaining)))]))))
;; ;; [Listof HT] -> Boolean
;; ;; are any pairs of HTs connected? if so, return #f
(define (no-two-hotels-touch hotel-tiles*)
(and-over-pairs-of-distinct-hotels
(lambda (one other)
(not (connected-graph (append one other))))
hotel-tiles*))
;; ;; [HT HT -> Boolean] [Listof HT] -> Boolean
;; ;; apply f to all pairs of distinct HTs on lh
(define (and-over-pairs-of-distinct-hotels f hotel-tiles*)
(or (empty? hotel-tiles*)
(let loop
([preceding '()]
[current (first hotel-tiles*)]
[remaining (rest hotel-tiles*)])
(cond
[(empty? remaining) #t]
[else (and (for/and
((h (append preceding remaining)))
(f current h))
(loop (cons current preceding) (first remaining) (rest remaining)))]))))
;; ;; Tile HT -> [Listof Tile]
;; ;; find all (at most four) tiles in lh that are connected to t
(define (connected-to t hotel-tiles*)
(define r (tile-row t))
(define c (tile-column t))
(define (in r c)
(if (and r c)
(let ([m (member (tile c r) hotel-tiles*)])
(if m
(list (first m))
'()))
'()))
(append (in (or (row-^ r) (error 'badr)) c)
(in (or (row-v r) (error 'badr)) c)
(in r (or (column-> c) (error 'badc)))
(in r (or (column-< c) (error 'badc)))))
) | true |
d924aed8c903187b1245aa7504afd2d9bfc3947f | defeada37d39bca09ef76f66f38683754c0a6aa0 | /System/system/net/sockets/multicast-option.sls | 9856617f8bca08dd149d8a3258fc2e6f16ec6e48 | []
| 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,220 | sls | multicast-option.sls | (library (system net sockets multicast-option)
(export new
is?
multicast-option?
group-get
group-set!
group-update!
local-address-get
local-address-set!
local-address-update!
interface-index-get
interface-index-set!
interface-index-update!)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.Net.Sockets.MulticastOption a ...)))))
(define (is? a) (clr-is System.Net.Sockets.MulticastOption a))
(define (multicast-option? a)
(clr-is System.Net.Sockets.MulticastOption a))
(define-field-port
group-get
group-set!
group-update!
(property:)
System.Net.Sockets.MulticastOption
Group
System.Net.IPAddress)
(define-field-port
local-address-get
local-address-set!
local-address-update!
(property:)
System.Net.Sockets.MulticastOption
LocalAddress
System.Net.IPAddress)
(define-field-port
interface-index-get
interface-index-set!
interface-index-update!
(property:)
System.Net.Sockets.MulticastOption
InterfaceIndex
System.Int32))
| true |
159498055991077acf8492c06b8a2ce915e313cf | 441cc32b0ca50fd0df7f055860cc298f708ca4d2 | /jas-match.scm | 82c07ad78194997b4c967e224e0001c0f5ba8d4e | []
| no_license | soegaard/this-and-that | 3a0e7b55aab6179bfcb5252248efab1347eab9da | 6884ba21b0a9d049716abc0b46cecd7f952c6a68 | refs/heads/master | 2021-08-26T07:39:11.731751 | 2021-08-11T20:23:34 | 2021-08-11T20:23:34 | 4,226,360 | 1 | 2 | null | 2015-07-31T20:28:55 | 2012-05-04T15:34:03 | Racket | UTF-8 | Scheme | false | false | 13,616 | scm | jas-match.scm | ;; jas-match.scm -- Jens Axel Søgaard -- 13/14 dec 2003
;;; PURPOSE
; This is a very naïve implementation of a subset of
; the pattern matcher plt-match.ss, which builds upon
; Wright's pattern matcher, but uses constructor notation
; in the patterns.
; The idea was too see, how far I could get using nothing
; but syntax-rules.
;;; INSTRUCTIONS OF USE
; The user macros are
; (match expr (pattern <guard> expr) ...) , <guard> can be omitted
; (match-lambda (pattern expr ...) ...)
; (match-let ((pattern expr) ...) expr ...)
; (match-let* ((pattern expr) ...) expr ...)
; The syntax of patterns are a subset of the one in:
; <http://download.plt-scheme.org/scheme/plt-clean-cvs/collects/mzlib/plt-match.ss>
; The semantics of the match functions are explained in
; <http://download.plt-scheme.org/scheme/docs/html/mzlib/mzlib-Z-H-22.html#node_chap_22>
; Notably features missing:
; - quasi-patterns
; - set! and get!
; - match-define and match-letrec
; - the ooo and ook extension in list and vector patterns
; - structures (easily added but they are non portable)
;;; IMPLEMENTATION
; The implementation is divided into layers, each layer
; handles one aspect of the pattern matching process.
; The main macro from the user perspective is the match macro.
; (match expr [(pattern expr ...) ...])
; which binds the value to be matched to a variable, and leaves
; the real work to guarded match. Match also handles the case
; of multple patterns.
; The macro guarded-match
; (guarded-match var pattern success failure)
; expands to success if the value bound to var matches the pattern,
; otherwise it expands to failure.
; Guarded-match takes care of guards and then macro calls logical-match.
; The macro logical-match
; (logical-match var pattern success failure)
; expands to success if the value bound to var matches the pattern,
; otherwise it expands to failure.
; Logical-match takes care of patterns of the form
; (and pattern ...)
; (or pattern ...)
; (not pattern pattern ...)
; (? expr pattern ...)
; and then macro calls compound-match.
; The macro compound-match
; (compound-match var pattern success failure)
; expands to success if the value bound to var matches the pattern,
; otherwise it expands to failure.
; Compound-match takes care of patterns of the form
; (cons pattern pattern)
; (list pattern ...)
; (list-rest pattern ... pattern)
; (vector pattern pattern ...)
; (app expr pattern)
; and then macro calls simple-match.
; The macro simple-match
; (simple-match var pattern success failure)
; expands to success if the value bound to var matches the pattern,
; otherwise it expands to failure.
; Simple-match takes care of patterns of the form
; (quote symbol)
; (quote datum)
; pattern-var
; literal
; and possible macro calls literal-match.
; The macro literal-match
; (literal-match var pattern success failure)
; expands to success if the value bound to var matches the pattern,
; otherwise it expands to failure.
; Literal-match takes care of patterns of atoms of the form
; the empty list
; booleans
; strings
; numbers
; characters
; and compound literals.
(define-syntax symbol??
;; From Oleg's "How to write symbol? with syntax-rules.
;; <http://okmij.org/ftp/Scheme/macro-symbol-p.txt>
(syntax-rules ()
((symbol?? (x . y) kt kf) kf) ; It's a pair, not a symbol
((symbol?? #(x ...) kt kf) kf) ; It's a vector, not a symbol
((symbol?? maybe-symbol kt kf)
(let-syntax
((test
(syntax-rules ()
((test maybe-symbol t f) t)
((test x t f) f))))
(test abracadabra kt kf)))))
(define-syntax id-eq??
;; From Oleg's "How to write symbol? with syntax-rules.
;; <http://okmij.org/ftp/Scheme/macro-symbol-p.txt>
(syntax-rules ()
((id-eq?? id b kt kf)
(let-syntax
((id (syntax-rules ()
((id) kf)))
(ok (syntax-rules ()
((ok) kt))))
(let-syntax
((test (syntax-rules ()
((_ b) (id)))))
(test ok))))))
(define (literal? datum)
(or (string? datum)
(number? datum)
(char? datum)
(null? datum)
(boolean? datum)))
(define-syntax literal-match
(syntax-rules ()
[(_ var () success failure) (if (null? var) success failure)]
[(_ var #t success failure) (if (eq? var #t) success failure)]
[(_ var #f success failure) (if (eq? var #f) success failure)]
[(_ var literal success failure) (if (and (literal? var)
(equal? var literal))
success
failure)]))
(define-syntax simple-match
; (simple-match var pattern success failure)
; If the value bound to var matches pattern then the
; expression expands into a let binding the pattern variables
; in the pattern to the matched (sub)values, success becomes the
; body of the let. Otherwise the macro call expands to failure.
(syntax-rules (quote)
[(_ var (quote symbol/datum) success failure) (if ((symbol?? symbol/datum eq? equal?) var 'symbol/datum)
success
failure)]
[(_ var name/literal success failure) (symbol?? name/literal
; pattern variable
(let ([name/literal var])
success)
; literal
(literal-match var name/literal success failure))]))
(define-syntax compound-match
(syntax-rules (cons list list-rest app vector)
[(_ var (cons p1 p2) success failure) (if (pair? var)
(match (car var)
[p1 (match (cdr var)
[p2 success]
[_ failure])]
[_ failure])
failure)]
; Note: Patterns with ooo is handles in super-match
[(_ var (list) success failure) (compound-match var () success failure)]
[(_ var (list p1) success failure) (compound-match var (cons p1 ()) success failure)]
[(_ var (list p1 p2 ...) success failure) (compound-match var (cons p1 (list p2 ...)) success failure)]
[(_ var (vector p1 ...) success failure) (let ([vector-var (vector->list var)])
(compound-match vector-var (list p1 ...) success failure))]
[(_ var (list-rest p1 p2) success failure) (compound-match var (cons p1 p2) success failure)]
[(_ var (list-rest p1 p2 p3 ...) success failure) (compound-match var (cons p1 (list-rest p2 p3 ...)) success failure)]
[(_ var (app expr p1) success failure) (let ([new-var (expr var)])
(match new-var p1 success failure))]
[(_ var pattern success failure) (simple-match var pattern success failure)]))
(define-syntax logical-match
(syntax-rules (and or not ?)
[(_ var (and) success failure) success]
[(_ var (and p1) success failure) (compound-match var p1 success failure)]
[(_ var (and p1 p2 ...) success failure) (compound-match var p1
(logical-match var (and p2 ...) success failure)
failure)]
[(_ var (or p1) success failure) (compound-match var p1 success failure)]
[(_ var (or p1 p2 ...) success failure) (compound-match var p1 success
(logical-match var (or p2 ...) success failure))]
[(_ var (not p) success failure) (logical-match var p failure success)]
[(_ var (not p1 p2 ...) success failure) (logical-match var (and (not p1) (not p2) ...) failure success)]
[(_ var (? expr p ...) success failure) (if expr
(logical-match var (and p ...) success failure)
failure)]
[(_ var pattern success failure) (compound-match var pattern success failure)]))
(define-syntax guarded-match
(syntax-rules ()
[(_ var pattern success failure) (logical-match var pattern success failure)]
[(_ var pattern guard success failure) (guarded-match var pattern (if guard success failure) failure)]))
(define-syntax match
(syntax-rules ()
[(_ expr) (let ([v expr])
'no-match)]
[(_ expr [pattern template]
clauses ...) (let ([v expr])
(guarded-match v pattern
template
(match v clauses ...)))]
[(_ expr [pattern guard template]
clauses ...) (let ([v expr])
(guarded-match v pattern guard
template
(match v clauses ...)))]))
(define-syntax match-lambda
(syntax-rules ()
[(_ (pat expr ...) ...) (lambda (x) (match x (pat expr ...) ...))]))
(define-syntax match-lambda*
(syntax-rules ()
[(_ (pat expr ...) ...) (lambda x (match x (pat expr ...) ...))]))
(define-syntax match-let*
(syntax-rules ()
[(_ () body ...) (begin body ...)]
[(_ ((pat expr)) body ...) ((match-lambda (pat body ...)) expr)]
[(_ ((pat expr) (pat2 expr2) ...) body ...) (match-let* ([pat expr])
(match-let*
((pat2 expr2) ...)
body ...))]))
(define-syntax match-let
(syntax-rules ()
[(_ () body ...) (begin body ...)]
[(_ ((pat expr) ...) body ...) (match-let* ([(list pat ...) (list expr ...)]) body ...)]))
;; Test
(define-syntax test-simple
(syntax-rules ()
[(_ value pattern success failure) (let ([test-simple-var value])
(simple-match test-simple-var pattern success failure))]))
'SIMPLE
(test-simple '() () 'ok 'fail)
(test-simple 1 1 'ok 'fail)
(test-simple 1 2 'fail 'ok)
(test-simple 'foo 'foo 'ok 'fail)
(test-simple 'foo 'bar 'fail 'ok)
(define-syntax test-compound
(syntax-rules ()
[(_ value pattern success failure) (let ([test-compund-var value])
(compound-match test-compund-var pattern success failure))]))
'COMPOUND
(test-compound (cons 1 "foo") (cons 1 "foo") 'ok 'fail)
(test-compound (cons 1 2) (cons a b) (if (= a 1) 'ok 'fail1) 'fail2)
(test-compound (list 1 2 3) (list a b c) (if (= (+ a b c) 6) 'ok 'fail1) 'fail2)
(test-compound (vector 1 2 3) (vector a b c) (if (= (+ a b c) 6) 'ok 'fail1) 'fail2)
(define-syntax test-logical
(syntax-rules ()
[(_ value pattern success failure) (let ([test-logical-var value])
(logical-match test-logical-var pattern success failure))]))
'LOGICAL
(test-logical (cons 1 2)
(and (cons a b) (cons 1 c) (cons d 2))
(if (equal? (list a b c d)
(list 1 2 2 1))
'ok
'fail1)
'fail2)
(test-logical (cons 1 2)
(or 1 "foo" (cons 1 3) (cons 1 2) #\c)
'ok
'fail)
(test-logical (cons 1 2)
(not (cons a b))
'fail
'ok)
(test-logical (cons 1 2)
(not (cons a b))
'fail
'ok)
(test-logical (cons 1 2)
(not 1 2 "foo" (cons 3 4))
'ok
'fail)
'GUARDED
(guarded-match (cons 42 2) (cons a b) (even? a) 'ok 'fail)
(guarded-match (cons 43 2) (cons a b) (even? a) 'fail 'ok)
'FULL
(match (cons 1 2)
[() 'empty]
[(cons 1 b) (if (= b 2) 'ok 'fail)])
(match (cons 1 (cons 2 3))
[() 'empty]
[(cons 1 (cons 2 b)) (if (= b 3) 'ok 'fail)])
(match 'foo
['foo 'ok]
[else 'fail])
(match 'foo
['bar 'fail]
[else 'ok])
'MATCH-LET*
(match-let* ([(list x y z) (list 1 2 3)]
[(vector a b c) (vector 4 5 6)])
(if (= (+ x y z a b c) 21)
'ok
'fail))
(match-let* ([(list x y) (list 1 2)]
[(vector a b) (vector 3 x)])
(if (= (+ x y a b) 7)
'ok
'fail))
'MATCH-LET
(match-let ([(list x y z) (list 1 2 3)]
[(vector a b c) (vector 4 5 6)])
(if (= (+ x y z a b c) 21)
'ok
'fail))
| true |
72d2ca88f5785626fe860d2fb32d90f356ddd3df | 92b8d8f6274941543cf41c19bc40d0a41be44fe6 | /testsuite/libx.scm | b24c9b0ad0d78017d174a9ac3ad69c9f9cabe1a6 | [
"MIT"
]
| permissive | spurious/kawa-mirror | 02a869242ae6a4379a3298f10a7a8e610cf78529 | 6abc1995da0a01f724b823a64c846088059cd82a | refs/heads/master | 2020-04-04T06:23:40.471010 | 2017-01-16T16:54:58 | 2017-01-16T16:54:58 | 51,633,398 | 6 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 161 | scm | libx.scm | ;; test library with same name as module.
(define-library (libx)
(import (scheme base))
(export libx-report)
(begin (define (libx-report) '(ax in libx))))
| false |
149890e7881b98f539f5c1aa5fb85e74914c88a2 | eef5f68873f7d5658c7c500846ce7752a6f45f69 | /spheres/string/unicode.sld | 5d0d6586635810a22980d63a42777ca76b144594 | [
"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 | 777 | sld | unicode.sld | ;;!!! Unicode handling procedures
;; .author Alvaro Castro-Castilla, 2015
;; .author Mikael More, 2010-2012
;; .author Florian Loitsch, 2007-2012
;;
;; Copyright (C) 2007-2012 Florian Loitsch
;; Copyright (C) 2010-2012 Mikael More
(define-library (spheres/string unicode)
(export unicode-char-upper
unicode-char-lower
unicode-string-upper unicode-string-upper! ; "aBc" => "ABC"
unicode-string-lower unicode-string-lower! ; "aBc" => "abc"
unicode-string-capitalize-strict! ; "aBc" => "Abc"
unicode-string-capitalize-strict ;
string-unicode-ci<?
string-unicode-ci<=?
string-unicode-ci=?
string-unicode-ci>?
string-unicode-ci>=?)
(include "unicode.scm"))
| false |
0a8060a913ff69a9b21768f5146efc0360ecef06 | 1384f71796ddb9d11c34c6d988c09a442b2fc8b2 | /tests/payload-float-scm.t | f2ef948c7ed46420e5778402433abbe559671306 | []
| no_license | ft/xmms2-guile | 94c2479eec427a370603425fc9e757611a796254 | 29670e586bf440c20366478462f425d5252b953c | refs/heads/master | 2021-07-08T07:58:15.066996 | 2020-10-12T01:24:04 | 2020-10-12T01:24:04 | 74,858,831 | 1 | 2 | null | null | null | null | UTF-8 | Scheme | false | false | 4,200 | t | payload-float-scm.t | ;; -*- scheme -*-
;; Copyright (c) 2015 xmms2-guile workers, All rights reserved.
;;
;; Terms for redistribution and use can be found in LICENCE.
(use-modules (test tap)
(test payload)
(test setup)
(xmms2 constants)
(xmms2 data-conversion)
(xmms2 payload))
(init-test-tap!)
(define-syntax test-><-float?
(syntax-rules ()
((_ n eps)
(begin (perform-payload-><-test make-float-payload
payload->float
n pass-if-~= eps)
(perform-payload-><-test make-value-payload
payload->float
n pass-if-~= eps)
(perform-payload-><-test make-float-payload
payload->value
n pass-if-~= eps)
(perform-payload-><-test make-value-payload
payload->value
n pass-if-~= eps)))))
(define *tests-per-back-and-forth* 4)
(define (test-float-payload n expected)
(let* ((data (make-float-payload n))
(name (format #f "(make-float-payload ~a)" n))
(type (uint32-ref data 0))
(mantissa-is (int32-ref data 4))
(mantissa-ex (int32-ref expected 4))
(exp-is (int32-ref data 8))
(exp-ex (int32-ref expected 8))
(back-is (payload->float data))
(back-ex (payload->float expected))
(error-is (abs (- n back-is)))
(error-ex (abs (- n back-ex))))
;; The tag should trivially be correct.
(define-test (format #f "~a: Type looks good." name)
(pass-if-= type TYPE-FLOAT))
;; The exponent has to exactly correct.
(define-test (format #f "~a: Exponent looks good." name)
(pass-if-= exp-is exp-ex))
;; The mantissa may be a small bit off, due to rounding.
(define-test (format #f "~a: Mantissa looks good." name)
(pass-if-~= mantissa-is mantissa-ex 65))
;; Check if out if our implementation is at least as near to the original
;; value than the reference implementation.
(define-test (format #f "~a: We are as good as or better than the reference"
name error-is error-ex)
(pass-if-true (<= error-is error-ex)))))
(define *tests-per-payload-test* 4)
(with-fs-test-bundle
(plan (+ (* 18 *tests-per-payload-test*)
(* 5 *tests-per-back-and-forth*)))
;; The expected values come from a reference implementation in C that was
;; taken right out of xmms2's core. The code was compiled on an AMD64 machine
;; running Linux 4.x using frexp(3) from GNU libc 2.24 Compiled by GNU CC
;; version 6.2.0 20160914.
(test-float-payload 0.5 #vu8(0 0 0 9 64 0 0 0 0 0 0 0))
(test-float-payload 1.000000e-01 #vu8(0 0 0 9 102 102 102 128 255 255 255 253))
(test-float-payload 1.000000e-02 #vu8(0 0 0 9 81 235 133 0 255 255 255 250))
(test-float-payload 1.000000e-03 #vu8(0 0 0 9 65 137 55 128 255 255 255 247))
(test-float-payload 9.000000e-01 #vu8(0 0 0 9 115 51 51 0 0 0 0 0))
(test-float-payload 9.000000e-02 #vu8(0 0 0 9 92 40 246 0 255 255 255 253))
(test-float-payload 9.000000e-03 #vu8(0 0 0 9 73 186 94 0 255 255 255 250))
(test-float-payload 1.000000e+01 #vu8(0 0 0 9 80 0 0 0 0 0 0 4))
(test-float-payload 1.000000e+02 #vu8(0 0 0 9 100 0 0 0 0 0 0 7))
(test-float-payload 1.000000e+03 #vu8(0 0 0 9 125 0 0 0 0 0 0 10))
(test-float-payload 9.000000e+06 #vu8(0 0 0 9 68 170 32 0 0 0 0 24))
(test-float-payload 2.000000e+09 #vu8(0 0 0 9 119 53 148 0 0 0 0 31))
(test-float-payload -5.000000e-01 #vu8(0 0 0 9 192 0 0 0 0 0 0 0))
(test-float-payload -1.000000e+03 #vu8(0 0 0 9 131 0 0 0 0 0 0 10))
(test-float-payload -1.000000e+09 #vu8(0 0 0 9 136 202 108 0 0 0 0 30))
(test-float-payload -1.000000e-09 #vu8(0 0 0 9 187 71 208 128 255 255 255 227))
(test-float-payload 1.200000e+22 #vu8(0 0 0 9 81 80 174 128 0 0 0 74))
(test-float-payload -1.200000e-20 #vu8(0 0 0 9 142 169 200 0 255 255 255 190))
(test-><-float? 0.0 1e-6)
(test-><-float? 0.5 1e-6)
(test-><-float? 1.0 1e-6)
(test-><-float? -2e20 1e11)
(test-><-float? 1e-4 1e-10))
| true |
dd29473c28213981d0851dfee34c37356b427853 | 23122d4bae8acdc0c719aa678c47cd346335c02a | /2020/11.scm | 8ea8086407017bdd86cf8a0c4e09066f44107c1e | []
| 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 | 2,772 | scm | 11.scm | #!/usr/bin/env -S scheme --libdirs "../scheme/" --script
(import (chezscheme) (core))
(define seats
(let* ([rows (map (λ row -> (string-append "S" row "S"))
(readlines "11.input"))]
[width (string-length (head rows))]
[sentinel-row (list (make-string width #\S))]
[seats (append sentinel-row rows sentinel-row)])
(list->vector (map (compose list->vector string->list) seats))))
(define directions '((-1 . -1) (0 . -1) (1 . -1)
(-1 . 0) (1 . 0)
(-1 . 1) (0 . 1) (1 . 1)))
(define (peek seats x y) (vector-ref (vector-ref seats y) x))
(define (part-1-rule seats x y)
(define (adjacent-occupied)
(count (λ p -> (eq? #\# (peek seats (+ x (head p)) (+ y (tail p)))))
directions))
(case (peek seats x y)
[#\. #\.] [#\S #\S]
[#\# (if (<= 4 (adjacent-occupied)) #\L #\#)]
[#\L (if (zero? (adjacent-occupied)) #\# #\L)]))
(define (line-of-sight x y)
(define (cast-los x y dir)
(let* ([x (+ x (head dir))] [y (+ y (tail dir))]
[next (peek seats x y)])
(if (eq? next #\.) (cast-los x y dir)
(pair x y))))
(if (eq? #\L (peek seats x y))
(map (λ dir -> (cast-los x y dir)) directions)
#f))
(define line-of-sight-cache
((λ results -> (list->vector (map list->vector results)))
(map (λ y -> (map (λ x -> (line-of-sight x y))
(iota (vector-length (vector-ref seats 0)))))
(iota (vector-length seats)))))
(define (part-2-rule seats x y)
(define (visible)
(count (λ p -> (eq? #\# (peek seats (head p) (tail p))))
(vector-ref (vector-ref line-of-sight-cache y) x)))
(case (peek seats x y)
[#\. #\.] [#\S #\S]
[#\# (if (<= 5 (visible)) #\L #\#)]
[#\L (if (zero? (visible)) #\# #\L)]))
(define (reseat rule seats)
(let ([next (vector-map vector-copy seats)])
(do ([y 0 (inc y)])
[(= y (vector-length seats))]
(let ([row (vector-ref next y)])
(do ([x 0 (inc x)])
[(= x (vector-length row))]
(vector-set! row x (rule seats x y)))))
next))
(define (count-occupied seats)
(let ([sigma 0])
(vector-for-each
(λ row -> (vector-for-each
(λ c -> (when (eq? c #\#) (set! sigma (inc sigma))))
row))
seats)
sigma))
(define (simulate rule seats)
(let loop ([next (reseat rule seats)] [previous-count 0])
(let ([count (count-occupied next)])
(if (= count previous-count) next
(loop (reseat rule next) count)))))
(let ([p1 (time (simulate part-1-rule seats))]
[p2 (time (simulate part-2-rule seats))])
(printf "~s \n" (count-occupied p1)) ;; 2183
(printf "~s \n" (count-occupied p2))) ;; 1990
| false |
593cdb49c5371bdc78a075375aad785b7d60ba9d | 9345867d5616f00e9add07095db49e97fcc1cf02 | /t/builtin/set.xire | 78706bedc0d45b87a85a5ae01bb43aac04ee3d7d | [
"MIT"
]
| permissive | kana/vim-xire | 91eb2cf417d68b9e598f992c6b5442f72a928594 | e4e97d8926fcdf1488d3e59a85a4af0253a5de01 | refs/heads/master | 2016-09-06T06:17:05.007579 | 2011-12-07T12:46:17 | 2011-12-07T12:46:17 | 588,299 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 50 | xire | set.xire | (set! foo 123)
(echo foo)
; vim: filetype=scheme
| false |
c6fce4214f9f04dbfa0dd98b3cfab3a6a8f40a7b | 569eb7a16d4cfb02c4fb5d92c7452aa13d22d7b8 | /scheme/gui/gui01.scm | bce124fc09be05caf69aef7c87c0bb5919d0a626 | []
| no_license | geofmatthews/csci322 | 7917acd8ee84588db7c549b38deb721d961d555a | 4d2687a1a2161d3b07154631cc5bee01507ada92 | refs/heads/master | 2021-01-13T13:47:29.722467 | 2016-03-02T18:45:53 | 2016-03-02T18:45:53 | 49,018,195 | 2 | 2 | null | null | null | null | UTF-8 | Scheme | false | false | 1,431 | scm | gui01.scm | #lang racket
;; Geoffrey Matthews
;; 2013
;; Building gui's with racket
(require racket/gui)
;; demo of DrScheme's objects
;; Simple object:
(define my-object%
(class object%
;; public methods:
(public get-number get-string set-number! set-string!)
;; private data:
(init-field (a-number 99) (a-string "Hello"))
;; define whatever procedures you want here,
;; only the "public" ones declared above will be
;; available:
(define (get-number) a-number)
(define (get-string) a-string)
(define (set-number! n) (set! a-number n))
(define (set-string! s) (set! a-string s))
;(set! a-string "xxxxxxxx")
;; Each class must initialize its superclass:
(super-new)
))
;; 3 ways to make objects, which are instances of a class:
(define a (make-object my-object% 1))
(define b (new my-object% (a-string "Goodbye")))
(define c (instantiate my-object% (12 "Whaa?")))
(define d (instantiate my-object% (3) (a-string "fun")))
;; sending messages to objects:
(print
(+ (send a get-number) (send b get-number)
(send c get-number) (send d get-number)))
(newline)
(print
(list
(send a get-string)
(send b get-string)
(send c get-string)
(send d get-string))
)
(newline)
(send a set-string! "Foo!")
(send b set-string! "Blarf")
(print
(list
(send a get-string)
(send b get-string)
(send c get-string)
(send d get-string))
)
(newline)
| false |
cb701c6e0fba48704b995262cf2e0b706fa19e73 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /System/system/component-model/license-context.sls | 7633e857c449c77e583d0e921f46798c775f65a8 | []
| 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,167 | sls | license-context.sls | (library (system component-model license-context)
(export new
is?
license-context?
set-saved-license-key
get-service
get-saved-license-key
usage-mode)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.ComponentModel.LicenseContext a ...)))))
(define (is? a) (clr-is System.ComponentModel.LicenseContext a))
(define (license-context? a)
(clr-is System.ComponentModel.LicenseContext a))
(define-method-port
set-saved-license-key
System.ComponentModel.LicenseContext
SetSavedLicenseKey
(System.Void System.Type System.String))
(define-method-port
get-service
System.ComponentModel.LicenseContext
GetService
(System.Object System.Type))
(define-method-port
get-saved-license-key
System.ComponentModel.LicenseContext
GetSavedLicenseKey
(System.String System.Type System.Reflection.Assembly))
(define-field-port
usage-mode
#f
#f
(property:)
System.ComponentModel.LicenseContext
UsageMode
System.ComponentModel.LicenseUsageMode))
| true |
01b8591c45210fd9b2450fbf8177b28c7facdc17 | d8bdd07d7fff442a028ca9edbb4d66660621442d | /scam/tests/00-syntax/import/library.scm | 6d19fe196576c2f1f5202cfe8dc2096d3146c1b0 | []
| no_license | xprime480/scam | 0257dc2eae4aede8594b3a3adf0a109e230aae7d | a567d7a3a981979d929be53fce0a5fb5669ab294 | refs/heads/master | 2020-03-31T23:03:19.143250 | 2020-02-10T20:58:59 | 2020-02-10T20:58:59 | 152,641,151 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 191 | scm | library.scm | (import (test narc))
(narc-label "Import Library")
(narc-catch
(:eval (sample))
(:eval (example)))
(import sample)
(narc-expect
(123 (sample))
("howdy" (example)))
(narc-report)
| false |
16d0d06d7e9121db59b0620ca4cb383ba75bac0c | ee79125fc6e61b2f611d9b5724e56190fa8da53a | /versions/raw-typed/library/cal-library/integral1.scm | 00ee8cbdd9a3d94147708accc3d4cf91306fdc54 | [
"Apache-2.0"
]
| permissive | cleoold/calculus-toolbox | b16dce4bea9d81beb824ee8570b12cb3ffe19a91 | e5a6d3d9c5e85c94b335c48f235ba4c8fec7ed9f | refs/heads/master | 2020-04-17T02:38:44.998990 | 2019-08-05T13:35:36 | 2019-08-05T13:35:36 | 166,145,959 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 733 | scm | integral1.scm | #lang typed/racket/base
(provide area-fx-rectangular)
(: area-sq (-> Number Number Number Number))
(define (area-sq x-1 x-2 height) (* (- x-2 x-1) height))
(: area/acc/temp ((Number -> Number) Real Real Number Real ((Listof Number) -> Number) -> Number))
(define (area/acc/temp f b step x-1 x-2 method)
(cond
((>= x-2 b) (area-sq x-1 b (f (method (list x-1 b)))))
(else (+ (area-sq x-1 (+ x-2 step) (f (method (list x-1 (+ x-2 step)))))
(area/acc/temp f b step (+ x-1 step) (+ x-2 step) method)))))
(: area-fx-rectangular ((Number -> Number) Real Real Real -> Number))
(define (area-fx-rectangular f a b step)
(area/acc/temp f b step a a
(lambda (interval) (/ (+ (car interval) (cadr interval)) 2)))) | false |
aa64ef5f09409afcb5e8e9cf23cb77b8e787c47b | b0c1935baa1e3a0b29d1ff52a4676cda482d790e | /lib/srfi/1.sld | 1c71e13c962b6bcebbe8a3e11f6a6b791ae72675 | [
"MIT"
]
| permissive | justinethier/husk-scheme | 35ceb8f763a10fbf986340cb9b641cfb7c110509 | 1bf5880b2686731e0870e82eb60529a8dadfead1 | refs/heads/master | 2023-08-23T14:45:42.338605 | 2023-05-17T00:30:56 | 2023-05-17T00:30:56 | 687,620 | 239 | 28 | MIT | 2023-05-17T00:30:07 | 2010-05-26T17:02:56 | Haskell | UTF-8 | Scheme | false | false | 144 | sld | 1.sld | (define-library (srfi 1)
(export-all)
(import (scheme)
(scheme base)
(scheme cxr))
(include "srfi-1.scm"))
| false |
b84c7d2432e4a55bef6208140354f2238edff24b | c39b3eb88dbb1c159577149548d3d42a942fe344 | /04-side-effects/exercise4-05.scm | 6245cf2a29ad4ac65ba9d78a8c180aea919289a9 | []
| no_license | mbillingr/lisp-in-small-pieces | 26694220205818a03efc4039e5a9e1ce7b67ff5c | dcb98bc847c803e65859e4a5c9801d752eb1f8fa | refs/heads/master | 2022-06-17T20:46:30.461955 | 2022-06-08T17:50:46 | 2022-06-08T17:50:46 | 201,653,143 | 13 | 3 | null | 2022-06-08T17:50:47 | 2019-08-10T16:09:21 | Scheme | UTF-8 | Scheme | false | false | 9,590 | scm | exercise4-05.scm | (import (builtin core)
(libs utils)
(libs book))
; (set!) modified to return old value instead of new)
(define (evaluate e r s k)
(if (atom? e)
(if (symbol? e)
(evaluate-variable e r s k)
(evaluate-quote e r s k))
(case (car e)
((quote) (evaluate-quote (cadr e) r s k))
((if) (evalua-if (cadr e) (caddr e) (cadddr e) r s k))
((begin) (evaluate-begin (cdr e) r s k))
((set!) (evaluate-set! (cadr e) (caddr e) r s k))
((lambda) (evaluate-lambda (cadr e) (cddr e) r s k))
(else (evaluate-application (car e) (cdr e) r s k)))))
(define (evaluate-if ec et ef r s k)
(evaluate ec r s
(lambda (v ss)
(evaluate ((v 'boolify) et ef) r ss k))))
(define (evaluate-begin e* r s k)
(if (pair? (cdr e*))
(evaluate (car e*) r s
(lambda (void ss)
(evaluate-begin (cdr e*) r ss k)))
(evaluate (car e*) r s k)))
(define (r.init id)
(wrong "No binding for id" id))
(define (update s a v)
(lambda (aa)
(if (eqv? a aa) v (s aa))))
(define (update* s a* v*)
;; assume (= (length a*) (length v*))
(if (pair? a*)
(update* (update s (car a*) (car v*)) (cdr a*) (cdr v*))
s))
(define (evaluate-variable n r s k)
(k (s (r n)) s))
(define (evaluate-set! n e r s k)
(let ((old-value (s (r n))))
(evaluate e r s
(lambda (v ss)
(k old-value (update ss (r n) v))))))
(define (evaluate-application e e* r s k)
(define (evaluate-arguments e* r s k)
(if (pair? e*)
(evaluate (car e*) r s
(lambda (v ss)
(evaluate-arguments (cdr e*) r ss
(lambda (v* sss)
(k (cons v v*) sss)))))
(k '() s)))
(evaluate e r s
(lambda (f ss)
(evaluate-arguments e* r ss
(lambda (v* sss)
(if (eq? (f 'type) 'function)
((f 'behavior) v* sss k)
(wrong "Not a function" (car v*))))))))
(define (evaluate-lambda n* e* r s k)
(allocate 1 s
(lambda (a* ss)
(k (create-function
(car a*)
(lambda (v* s k)
(if (= (length n*) (length v*))
(allocate (length n*) s
(lambda (a* ss)
(evaluate-begin e*
(update* r n* a*)
(update* ss a* v*)
k)))
(wrong "Incorrect arity"))))
ss))))
(define (allocate n s q)
(if (> n 0)
(let ((a (new-location s)))
(allocate (- n 1)
(expand-store a s)
(lambda (a* ss)
(q (cons a a*) ss))))
(q '() s)))
(define (expand-store high-location s)
(update s 0 high-location))
(define (new-location s)
(+ 1 (s 0)))
(define s.init
(expand-store 0 (lambda (a) (wrong "No such address" a))))
(define the-empty-list
(lambda (msg)
(case msg
((type) 'null)
((boolify) (lambda (x y) x)))))
(define (create-boolean value)
(let ((combinator (if value (lambda (x y) x) (lambda (x y) y))))
(lambda (msg)
(case msg
((type) 'boolean)
((boolify) combinator)))))
(define (create-symbol v)
(lambda (msg)
(case msg
((type) 'symbol)
((name) v)
((boolify) (lambda (x y) x)))))
(define (create-number v)
(lambda (msg)
(case msg
((type) 'number)
((value) v)
((boolify) (lambda (x y) x)))))
(define (create-function tag behavior)
(lambda (msg)
(case msg
((type) 'function)
((boolify) (lambda (x y) x))
((tag) tag)
((behavior) behavior))))
(define (allocate-list v* s q)
(define (consify v* q)
(if (pair? v*)
(consify (cdr v*) (lambda (v ss)
(allocate-pair (car v*) v ss q)))
(q the-empty-list s)))
(consify v* q))
(define (allocate-pair a d s q)
(allocate 2 s
(lambda (a* ss)
(q (create-pair (car a*) (cadr a*))
(update (update ss (car a*) a) (cadr a*) d)))))
(define (create-pair a d)
(lambda (msg)
(case msg
((type) 'pair)
((boolify) (lambda (x y) x))
((set-car) (lambda (s v) (update s a v)))
((set-cdr) (lambda (s v) (update s d v)))
((car) a)
((cdr) d))))
(define s.global s.init)
(define r.global r.init)
(define (definitial name value)
(allocate 1 s.global
(lambda (a* ss)
(set! r.global (update r.global name (car a*)))
(set! s.global (update ss (car a*) value)))))
(define (defprimitive name value arity)
(definitial name
(allocate 1 s.global
(lambda (a* ss)
(set! s.global (expand-store (car a*) ss))
(create-function
(car a*)
(lambda (v* s k)
(if (= arity (length v*))
(value v* s k)
(wrong "Incorrect arity" name))))))))
(definitial 't (create-boolean #t))
(definitial 'f (create-boolean #f))
(definitial 'nil the-empty-list)
(definitial 'x the-empty-list)
(definitial 'y the-empty-list)
(definitial 'z the-empty-list)
(definitial 'foo the-empty-list)
(definitial 'bar the-empty-list)
(definitial 'fib the-empty-list)
(definitial 'fact the-empty-list)
(defprimitive '<=
(lambda (v* s k)
(if (and (eq? ((car v*) 'type) 'number)
(eq? ((cadr v*) 'type) 'number))
(k (create-boolean (<= ((car v*) 'value)
((cadr v*) 'value)))
s)
(wrong "<= requires numbers")))
2)
(defprimitive '*
(lambda (v* s k)
(if (and (eq? ((car v*) 'type) 'number)
(eq? ((cadr v*) 'type) 'number))
(k (create-number (* ((car v*) 'value)
((cadr v*) 'value)))
s)
(wrong "* requires numbers")))
2)
(defprimitive 'cons
(lambda (v* s k)
(allocate-pair (car v*) (cadr v*) s k))
2)
(defprimitive 'car
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(k (s ((car v*) 'car)) s)
(wrong "Not a pair" (car v*))))
1)
(defprimitive 'cdr
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(k (s ((car v*) 'cdr)) s)
(wrong "Not a pair" (car v*))))
1)
(defprimitive 'set-cdr
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(let ((pair (car v*)))
(k pair ((pair 'set-cdr) s (cadr v*))))
(wrong "Not a pair" (car v*))))
2)
(defprimitive 'set-car
(lambda (v* s k)
(if (eq? ((car v*) 'type) 'pair)
(let ((pair (car v*)))
(k pair ((pair 'set-car) s (cadr v*))))
(wrong "Not a pair" (car v*))))
2)
(defprimitive 'pair?
(lambda (v* s k)
(k (create-boolean (eq? ((car v*) 'type) 'pair)) s))
1)
(defprimitive 'eqv?
(lambda (v* s k)
(k (create-boolean
(if (eq? ((car v*) 'type) ((cadr v*) 'type))
(case ((car v*) 'type)
((null) #t)
((boolean)
(((car v*) 'boolify)
(((cadr v*) 'boolify) #t #f)
(((cadr v*) 'boolify) #f #t)))
((symbol)
(eq? ((car v*) 'name) ((cadr v*) 'name)))
((number)
(eq? ((car v*) 'value) ((cadr v*) 'value)))
((pair)
(and (= ((car v*) 'car) ((cadr v*) 'car))
(= ((car v*) 'cdr) ((cadr v*) 'cdr))))
((function)
(= ((car v*) 'tag) ((cadr v*) 'tag)))
(else #f))
#f))
s))
2)
(define (chapter4-interpreter)
(define (toplevel s)
(evaluate (read)
r.global
s
(lambda (v ss)
(display (transcode-back v ss))
(toplevel ss))))
(toplevel s.global))
(define (transcode-back v s)
(case (v 'type)
((null) '())
((boolean) ((v 'boolify) #t #f))
((symbol) (v 'name))
((string) (v 'chars))
((number) (v 'value))
((pair) (cons (transcode-back (s (v 'car)) s)
(transcode-back (s (v 'cdr)) s)))
((function) v)
(else (wrong "Unknown type" (v 'type)))))
(define (transcode c s q)
(cond ((null? c) (q the-empty-list s))
((boolean? c) (q (create-boolean c) s))
((symbol? c) (q (create-symbol c) s))
((string? c) (q (create-string c) s))
((number? c) (q (create-number c) s))
((pair? c)
(transcode (car c)
s
(lambda (a ss)
(transcode (cdr c)
ss
(lambda (d sss)
(allocate-pair a d sss q))))))))
(define (evaluate-quote c r s k)
(transcode c s k))
(chapter4-interpreter)
| false |
ffbbab46ce151543f4fd67f79d2121c60edfac55 | f8f1f7d45998db2c9b27bd5197b512f32eaa07aa | /scheme.base-interface.scm | 25cdb0410b67a20e5a9f3dbf7f915384a6cecd3e | [
"BSD-2-Clause"
]
| permissive | spurious/chicken5-r7rs-svn | fe386df66560b1783cb59d14e529374d1ccb64fe | d56aabd87224db524c64fd53d44f99649aa1dc9f | refs/heads/master | 2023-04-19T03:13:18.228770 | 2021-04-14T19:42:11 | 2021-04-14T19:42:11 | 365,430,922 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,954 | scm | scheme.base-interface.scm | (export
* + - /
<= < >= = >
abs
and
append
apply
assoc assq assv
begin
binary-port?
boolean? boolean=?
bytevector
bytevector-append
bytevector-copy bytevector-copy!
bytevector-length bytevector-u8-ref bytevector-u8-set!
bytevector?
car cdr
caar cadr cdar cddr
call-with-current-continuation call/cc
call-with-port
call-with-values
case
ceiling
char-ready?
char->integer integer->char
char=? char<? char>? char<=? char>=?
char?
close-input-port close-output-port
close-port
complex?
cond
cond-expand
cons
current-input-port current-output-port current-error-port
define
define-record-type
define-syntax
define-values
denominator numerator
do
dynamic-wind
eof-object
eof-object?
eq? eqv? equal?
error
error-object-irritants error-object-message
error-object?
even? odd?
exact inexact
exact-integer-sqrt
exact-integer?
exact? inexact?
exp
expt
features
file-error?
floor
floor/ floor-quotient floor-remainder
flush-output-port
for-each
gcd lcm
get-output-bytevector
get-output-string
guard
if
#|
import ; provided by the "r7rs" module
import-for-syntax ; same
|#
include
include-ci
input-port-open? output-port-open?
input-port? output-port?
integer?
lambda
length
let let*
letrec letrec*
let-values let*-values
let-syntax letrec-syntax
list list-copy list-ref list-set! list-tail list?
list->vector
make-bytevector
make-list
make-parameter
make-string
make-vector
map
max min
member memq memv
modulo remainder
negative? positive?
newline
not
null?
number->string string->number
number?
open-input-bytevector open-output-bytevector
open-input-string open-output-string
or
pair?
parameterize
peek-char
peek-u8
port?
procedure?
quasiquote
quote
quotient remainder
raise raise-continuable
rational?
rationalize
read-bytevector read-bytevector!
read-char
read-error?
read-line
read-string
read-u8
real?
reverse
round
set!
set-car! set-cdr!
square
string
string->list list->string
string->utf8 utf8->string
string->symbol symbol->string
string->vector
string-append
string-copy
string-copy!
string-fill!
string-for-each
string-length
string-map
string-ref string-set!
string=? string<? string>? string<=? string>=?
string?
substring
symbol=?
symbol?
syntax-error
#|
syntax-rules ; provided by the "r7rs" module
|#
textual-port?
truncate
truncate/ truncate-quotient truncate-remainder
u8-ready?
unless
#|
unquote unquote-splicing ; provided by `quasiquote`
|#
values
vector
vector-append
vector-copy vector-copy!
vector-fill!
vector-for-each
vector-length
vector-map
vector-ref vector-set!
vector->list
vector->string
vector?
when
with-exception-handler
write-bytevector
write-char
write-string
write-u8
zero?
)
| true |
e2aa36bad55c86cd22fbacc2ca8196cdc9dfde1f | 174072a16ff2cb2cd60a91153376eec6fe98e9d2 | /Chap-two/2-33.scm | 96e2f6c536c99e6d69cdf04cdfa55a44babe9e39 | []
| no_license | Wang-Yann/sicp | 0026d506ec192ac240c94a871e28ace7570b5196 | 245e48fc3ac7bfc00e586f4e928dd0d0c6c982ed | refs/heads/master | 2021-01-01T03:50:36.708313 | 2016-10-11T10:46:37 | 2016-10-11T10:46:37 | 57,060,897 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 200 | scm | 2-33.scm | (load "filter.scm")
(define (map p seq)
(acc (lambda (x y) (cons (p x) y) ) '() seq))
(define (append seq1 seq2)
(acc cons seq2 seq1))
(define (length seq)
(acc (lambda (x y )(+ 1 y)) 0 seq))
| false |
9772d849df6b4edc3788b3324e526b8f6bb2f934 | c3523080a63c7e131d8b6e0994f82a3b9ed901ce | /hertfordstreet/schemes/segments.scm | 1f6532df4b11e8d961a08725d8876b28a11ad5d5 | []
| no_license | johnlawrenceaspden/hobby-code | 2c77ffdc796e9fe863ae66e84d1e14851bf33d37 | d411d21aa19fa889add9f32454915d9b68a61c03 | refs/heads/master | 2023-08-25T08:41:18.130545 | 2023-08-06T12:27:29 | 2023-08-06T12:27:29 | 377,510 | 6 | 4 | null | 2023-02-22T00:57:49 | 2009-11-18T19:57:01 | Clojure | UTF-8 | Scheme | false | false | 1,501 | scm | segments.scm | (define (square x) (* x x))
(define (make-point x y)
(cons x y))
(define (xpoint p)
(car p))
(define (ypoint p)
(cdr p))
(define (average p q)
(make-point (/(+ (xpoint p) (xpoint q))2)
(/(+ (ypoint p) (ypoint q))2)))
(define (distance p q)
(sqrt (+ (square (- (xpoint p) (xpoint q)))
(square (-(ypoint p) (ypoint q))))))
(define (make-segment a b)
(cons a b))
(define (start l)
(car l))
(define (end l)
(cdr l))
(define (midpoint l)
(average (start l) (end l)))
(define (length l)
(distance (start l) (end l)))
(define a (make-point 3 0))
(define b (make-point 3 4))
(define c (make-point 0 4))
(define d (make-point 0 0))
;
(define hypotenuse (make-segment a c))
;
(midpoint hypotenuse)
(define (make-quadrilateral a b c d)
(list a b c d))
(define (point q n)
(cond ((= n 0) (car q))
((= n 1) (car (cdr q)))
((= n 2) (car (cdr (cdr q))))
((= n 3) (car (cdr (cdr (cdr q)))))))
(define (side q n)
(cond ((= n 0) (make-segment (point q 0)(point q 1)))
((= n 1) (make-segment (point q 1)(point q 2)))
((= n 2) (make-segment (point q 2)(point q 3)))
((= n 3) (make-segment (point q 3)(point q 0))) ))
(define (perimeter box)
(+ (length (side box 0))
(length (side box 1))
(length (side box 2))
(length (side box 3))))
(define (area box)
(* (length (side box 0))
(length (side box 1))))
(define box (make-quadrilateral a b c d))
(perimeter box)
(area box)
| false |
8391faa1b6576be7b940ef1dc989e4b62e7c9a46 | abc7bd420c9cc4dba4512b382baad54ba4d07aa8 | /src/ws/passes/normalize_source/desugar-pattern-matching.sls | 5fe2d126eb0d1556f15e897efae9f550ba941442 | [
"BSD-3-Clause"
]
| permissive | rrnewton/WaveScript | 2f008f76bf63707761b9f7c95a68bd3e6b9c32ca | 1c9eff60970aefd2177d53723383b533ce370a6e | refs/heads/master | 2021-01-19T05:53:23.252626 | 2014-10-08T15:00:41 | 2014-10-08T15:00:41 | 1,297,872 | 10 | 2 | null | null | null | null | UTF-8 | Scheme | false | false | 13,007 | sls | desugar-pattern-matching.sls | #!r6rs
;;;; .title Pass: Desugar Pattern Matching
;;;; .author Ryan Newton
;;;; This desugars pattern matching in binding forms.
;;;; Once that's done, it can run the type inferencer for the first time.
;;;; NOTE: this pass also desugars type assertions within the formals
;;;; list. It pulls these outside the lambda.
;;;; NOTE: This is messier than I would like, but this pass also
;;;; desugars + into g+ The earlier this happens, the better, and
;;;; this was about as early as it could happen.
;;;; [2007.09.21] One more thing, now it desugars integer constants into gint()s
;;;; TODO: RENAME THIS PASS.
(library (ws passes normalize_source desugar-pattern-matching)
(export pass_desugar-pattern-matching test_desugar-patterns break-pattern)
(import (except (rnrs (6)) error) (ws common))
;; This generates projection code in place of patterns as formal arguments.
(define (break-pattern pat)
(match pat
[(assert-type ,typ ,[form binds _]) (values form binds typ)]
;; The special _ formal argument should never be referenced. We rename them here.
[_ (values (unique-name "_") '() #f)]
[,s (guard (symbol? s))
(values s '() #f)]
[#(,[pv* binds* type-assertion*] ...)
(ASSERT "Not currently allowed to make assertions on sub-parts of the pattern."
(lambda (ls) (for-all not ls)) type-assertion*)
(let ([v (unique-name 'pattmp)]
[len (length pv*)])
(let ([newbinds
`([,pv* 'type (tupref ,(iota len) ,(make-list len len) ,(make-list len v))] ...)])
(values v
`( ,@(filter (lambda (b) (not (eq? (car b) '_))) newbinds)
,@(apply append binds*)
)
#f)))]))
(define (make-let* binds bod)
(match binds
[() bod]
[(,bind . ,[rest]) `(letrec (,bind) ,rest)]))
(define (build-assert t*)
`(,@(map (lambda (t) (or t `(quote ,(unique-name 'alpha)))) t*)
-> ',(unique-name 'beta)))
(define (mangle-projector var fld)
(string->symbol (format ":~a:~a" var fld)))
(define (notype) `',(unique-name 'notypeyet))
(define process-expr
(lambda (expr fallthrough)
(match expr
;; TEMPTOGGLE:
;; Make plain integer constants "gints" by default:
[(quote ,n) (guard (integer? n) (exact? n))
;(inspect n)
`(gint (quote ,n))
]
;; Miscellaneous desugaring -- that must be done early!
;;======================================================================
;; Unadorned arithmetic symbols match onto their generic counterparts:
[+ 'g+] [- 'g-] [* 'g*] [/ 'g/] [^ 'g^]
[(+ ,[a] ,[b]) `(g+ ,a ,b)]
[(- ,[a] ,[b]) `(g- ,a ,b)]
[(* ,[a] ,[b]) `(g* ,a ,b)]
[(/ ,[a] ,[b]) `(g/ ,a ,b)]
[(^ ,[a] ,[b]) `(g^ ,a ,b)]
;;; THESE HACKS BREAK OVERRIDING OF THE PRIMITIVE NAMES:
;; This is a work-around for a name conflict:
[merge '(lambda (x y) ('noty 'noty) (_merge (annotations) x y))]
[(app merge ,[s1] ,[s2]) `(_merge (annotations) ,s1 ,s2)]
; FIXME: is this dangerous?
[(app (src-pos ,sp1 merge) ,[s1] ,[s2])
`(_merge (annotations) ,s1 ,s2)]
[(app readFile ,[args] ...) `(readFile (annotations) ,@args)]
; FIXME: is this dangerous?
[(app (src-pos ,sp1 readFile) ,[args] ...)
`(readFile (annotations) ,@args)]
[(readFile ,[args] ...) `(readFile (annotations) ,@args)]
;; THIS IS A HACK ON A HACK:
[(app ,timer ,[args] ...)
(guard (eq? (peel-annotations timer) 'timer)
(eq? (compiler-invocation-mode) 'wavescript-compiler-nesc)
;; Only when we're NOT splitting into server/node do we do this:
;(not (memq 'split (ws-optimizations-enabled)))
;; NAH, doing it all the time... don't yet support server side timers in a split program.
)
`(app TOS:timer ,@args)]
;; And this is an auxillary hack:
[(app ,timer ,[args] ...)
(guard (eq? (peel-annotations timer) 'Server:timer))
`(timer (annotations) ,@args)]
[(app ,timer ,[args] ...) (guard (eq? (peel-annotations timer) 'timer))
`(timer (annotations) ,@args)]
[(timer ,[args] ...) `(timer (annotations) ,@args)]
;[ref (inspect "HMRM Ref in desugar pat match")'Mutable:ref]
;;======================================================================
[(lambda (,[break-pattern -> formal* binds* type-assertion*] ...) ,types ,[bod])
(let ([lam (if (null? binds*)
`(lambda (,formal* ...) ,types ,bod)
`(lambda (,formal* ...) ,types
,(make-let* (apply append binds*) bod)))])
(if (ormap id type-assertion*)
`(assert-type ,(build-assert type-assertion*) ,lam)
lam))]
[(,let ((,[break-pattern -> lhs* binds* type-assertion*] ,type* ,[rhs*]) ...) ,[bod])
(guard (memq let '(let letrec)))
;; Shouldn't have assertions on the variable names here:
(ASSERT "Shouldn't have assertions on the variable names here:"
(lambda (ls) (for-all not ls)) type-assertion*)
`(,let ([,lhs* ,type* ,rhs*] ... )
,(make-let* (apply append binds*) bod))]
;; This isn't "pattern-matching" but we desugar it here so
;; that the type checker doesn't need to deal with it.
[(let* ,binds ,bod) (process-expr (make-let* binds bod) fallthrough)]
#;
;; Only handles one-armed matches right now:
;; [(match ,[x] [ ,[break-pattern -> var* binds*] ,[rhs*] ] ...)
[(match ,[x] (,[break-pattern -> var binds type-assertion] ,[rhs]))
;; Shouldn't have assertions on the variable names here for now:
(ASSERT (not type-assertion))
`(letrec ([,var ,(notype) ,x] ,binds ...)
,rhs)]
;; I would like to convert this to a form that uses lambdas on the RHS to do the binding.
;; This keeps wscase from being yet another binding form.
;; Unfortunately, we use two different translations of wscase
;; based on what backend we're ultimitely going to be using.
;; For the C++ backend we just treat sums as tuples and
;; minimize the extra machinery required.
;;
;; We only use case for dispatching on the tag of a sum type:
[(wscase ,[x] (,pat* ,[rhs*]) ...)
(let ([newclause*
(map (lambda (pat rhs)
(match pat
[_ `(,default-case-symbol ,rhs)]
[(data-constructor ,tc ,v* ...) (guard (andmap symbol? v*))
(list tc
`(lambda ,v* ,(map (lambda (_) (notype)) v*) ,rhs)
#;
(let ([mode (compiler-invocation-mode)])
(cond
[(memq (compiler-invocation-mode) '(wavescript-compiler-caml))
`(lambda ,v* ,(map (lambda (_) (notype)) v*) ,rhs)]
[(memq (compiler-invocation-mode) '(wavescript-compiler-xstream wavescript-simulator))
;; Feed it back through to break up that tuple pattern:
(process-expr `(lambda (#(,(unique-name 'tag) ,@v*)) (,(notype)) ,rhs)
fallthrough)]
[else (error 'desugar-pattern-matching
"don't know what to do with a case construct in this compiler-invocation-mode: ~s"
(compiler-invocation-mode))]
)))]
[,oth (error 'desugar-pattern-matching
"not supporting this kind of pattern yet: ~s" oth)]))
pat* rhs*)])
`(wscase ,x ,@newclause*))]
[(wscase ,_ ...)
(error 'desugar-pattern-matching "don't support this form of case yet: ~s"
`(wscase . ,_))]
;; [2006.11.15] Going to add special stream-of-tuples field-naming syntax.
;; TODO: make it work for general patterns, not just for flat tuples!
[(let-as (,v (,fldname* ...) ,[rhs]) ,[body])
(guard (symbol? v) (andmap symbol? fldname*))
(let ([len (length fldname*)])
;; Each field-name gets bound to a projection function.
`(letrec ([,v ,(notype) ,rhs])
(letrec ([,(map (curry mangle-projector v) fldname*)
,(map (lambda (_) (notype)) fldname*)
,(map (lambda (i)
#;
`(lambda (s) (iterate (annotations) (lambda (x vq)
(begin (emit vq (tupref ,i ,len x)) vq))
s))
;; Simple tuple projector:
`(lambda (x) (,(notype)) (tupref ,i ,len x))
)
(iota len))]
...)
,body))
)]
;; This is let-as's counterpart for projecting out stream values.
;;
;; For NOW this only works with variables as the projections.
;; This is because of name mangling... can't put general
;; expressions here.
[(dot-project (,projector* ...) ,[src])
(ASSERT (curry andmap symbol?) projector*)
;; For the time being, we only use this syntax on the original variable:
(ASSERT symbol? src)
;; THIS DOES NOT GUARANTEE HYGIENE:
(let ([tmp (unique-name '___tmp___)]
[vq (unique-name '___vq___)]
[make-tuple (lambda (args) (if (= 1 (length args))
(car args) (cons 'tuple args)))])
`(iterate (annotations) (lambda (,tmp ,vq) (,(notype) ,(notype))
(begin (emit ,vq ,(make-tuple
(map (lambda (proj)
`(app ,(mangle-projector src proj) ,tmp))
projector*)))
,vq))
,src))]
;; Likewise, we desugar this construct here as well:
[(dot-record-project (,fld* ...) ,[src])
(let ([body (lambda (var)
(let loop ((fld* fld*))
(if (null? fld*)
'(empty-wsrecord)
`(wsrecord-extend ',(car fld*)
(wsrecord-select ',(car fld*) ,var)
,(loop (cdr fld*))))))])
(if (symbol? (peel-annotations src))
(body src)
(let ([var (unique-name 'dotrecprojtmp)])
`(let ([,var ,(notype) ,src])
,(body var))
)))]
;; We don't desugar this here, it lives for one more pass:
[(using ,M ,[e]) `(using ,M ,e)]
;; [2008.01.27] Here's a bit of extra desugaring for wsc2:
[(assert-type (Stream (Sigseg ,elt)) ,bod)
(guard (wsc2-variant-mode? (compiler-invocation-mode))
(match (peel-annotations bod)
[(app ,rator . ,_)
(eq? (peel-annotations rator) 'readFile)]
[,_ #f]))
(define x (unique-name "x"))
(define vq (unique-name "vq"))
`(iterate (annotations)
(let ()
(lambda (,x ,vq) ((Array ,elt) 'vqty)
(begin (emit ,vq (app toSigseg ,x (gint '0) nulltimebase))
,vq)))
,(process-expr `(assert-type (Stream (Array ,elt)) ,bod) fallthrough))]
[,other (fallthrough other)])))
;; Desugar pattern matching within lambda's, letrecs, and "match" statements. <br>
;; TODO: This should really not go in the source_loader.
(define-pass pass_desugar-pattern-matching
;; We're not quite ready to leave the "sugared" grammar yet. The
;; next pass removes the 'using' construct.
[OutputGrammar sugared_regiment_grammar]
;[OutputGrammar initial_regiment_grammar]
;; TODO: When it works, could redo this with Expr/ExtraArg
[Expr process-expr]
;; After desugaring pattern matching, then we can typecheck the prog for the first time:
[Program (lambda (prog Expr)
(match prog
[(,inputlang '(program ,bod ,other ... ,type))
`(desugar-pattern-matching-language
'(program ,(Expr bod) ,other ... ,type))]))]
)
; ================================================================================
(define-testing test_desugar-patterns
(default-unit-tester "desugar-pattern-matching.ss: For reading regiment source files."
`(["Run a basic test of the pattern match expander."
(cadr (cadadr
(reunique-names
(strip-binding-types
(',pass_desugar-pattern-matching
'(foo '(program (lambda (#(foo #(bar baz)) x) ('t1 't2) foo) UncheckedType)))))))
(lambda (pattmp x)
(letrec ([foo (tupref 0 2 pattmp)])
(letrec ([pattmp_1 (tupref 1 2 pattmp)])
(letrec ([bar (tupref 0 2 pattmp_1)])
(letrec ([baz (tupref 1 2 pattmp_1)])
foo)))))]
[(',reunique-names (values->list (',break-pattern '#(x y))))
(pattmp
((x 'type (tupref 0 2 pattmp))
(y 'type (tupref 1 2 pattmp)))
#f)]
#;
[(',pass_desugar-pattern-matching '(foo '(program (case 3 [x x]) Int)))
(desugar-pattern-matching-language
'(program (letrec ([x unspecified 3]) x) unspecified))]
#;
;; [2007.01.30] BUG: Different behavior in petite and chez.
[(cadr (deep-assq 'aggr
(pass_desugar-pattern-matching
'(verify-regiment-language
'(program
(letrec ([readings 'type_13 (rmap
(lambda (n)
('type_8)
(cons (sense "temp" n) (cons 1 '())))
world)]
[aggr 'type_12 (lambda (x y)
('type_7 'type_6)
(cons
(g+ (car x) (car y))
(cons
(g+ (car (cdr x)) (car (cdr y)))
'())))]
[div 'type_11 (lambda (v)
('type_5)
(if (= (car (cdr v)) 0)
0
(/ (car v) (car (cdr v)))))]
[sums 'type_10 (rfold aggr (cons 0 (cons 0 '())) readings)]
[result 'type_9 (smap div sums)])
result)
'toptype)))))
,(lambda (x)
(match x
[((List (NUM ,v)) (List (NUM ,v2)) -> (List (NUM ,v3))) #t]
[,else #f]))]
#;
(lang '(program (letrec ([test 'typefoo (lambda (x y)
('type_7 'type_6)
(cons
(g+ (car x) (car y))
(cons
(g+ (car (cdr x)) (car (cdr y)))
'())))])
(app test 3))
'toptype))
)))
)
| false |
7bf59a20ef8773d9da88cecd82c0755f3a80cca3 | 86092887e6e28ebc92875339a38271319a87ea0d | /Ch4/4_18.scm | ad69d714d02f40ed67d8762e5bf83564d2f1a565 | []
| no_license | a2lin/sicp | 5637a172ae15cd1f27ffcfba79d460329ec52730 | eeb8df9188f2a32f49695074a81a2c684fe6e0a1 | refs/heads/master | 2021-01-16T23:55:38.885463 | 2016-12-25T07:52:07 | 2016-12-25T07:52:07 | 57,107,602 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 1,340 | scm | 4_18.scm | ; we can show that the case works in the first case but is a problem in the
; second case by transforming the let into lambdas.
(define (solve f y0 dt)
(let ((y '*unassigned*)
(dy '*unassigned*))
(set! y (integral (delay dy) y0 dt))
(set! dy ((stream-map f y)))
y))
; xform this into:
(define (solve f y0 dt)
((lambda (y dy)
(set! y (integral (delay dy) y0 dt))
(set! dy ((stream-map f y)))
y)
'*unassigned*
'*unassigned*))
(define (solve f y0 dt)
(let ((y '*unassigned*) (dy '*unassigned*))
(let ((a (integral (delay dy) y0 dt)) (b (stream-map f y)))
(set! y a)
(set! dy b)
y)))
; xform into lambda
(define (solve f y0 dt)
((lambda (y dy)
(let ((a (integral (delay dy) y0 dt)) (b (stream-map f y)))
(set! y a)
(set! dy b)
y))
'*unassigned*
'*unassigned*))
; we can see that y, dy are '*unassigned' value-wise, but this gets fixed before
; the lambda returns.
; xform other into lambda
(define (solve f y0 dt)
((lambda (y dy)
((lambda (a b)
(set! y a)
(set! dy b)
y)
(integral (delay dy) y0 dt)
(stream-map f y))
'*unassigned*
'*unassigned*)))
; dy, y are both 'unassigned; so
; (integral (delay '*unassigned*) y0 dt)
; (stream-map f '*unassigned*)
; and therefore we have a problem.
| false |
a86054a3b0f64323dd157d9b7c3b9754f184c6a8 | 86092887e6e28ebc92875339a38271319a87ea0d | /Ch2/2_73.scm | 45ec9bbcd343a0220c4534dacd4ab006d195f86b | []
| no_license | a2lin/sicp | 5637a172ae15cd1f27ffcfba79d460329ec52730 | eeb8df9188f2a32f49695074a81a2c684fe6e0a1 | refs/heads/master | 2021-01-16T23:55:38.885463 | 2016-12-25T07:52:07 | 2016-12-25T07:52:07 | 57,107,602 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,815 | scm | 2_73.scm | ; a. because number? and same-variable? are the base cases for the recursion.
; if they were eaten into the data-directed dispatch we'd have an infinite
; recursion.
; b.
(define (sign exp)
(car exp))
(define (rest exp)
(cdr exp))
(define (install-sum-package)
(define (make e1 e2)
(cond ((and (number? e1) (= e1 0)) e2)
((and (number? e2) (= e2 0)) e1)
((and (number? e1) (number? e2)) (+ e1 e2))
(else (list '+ e1 e2))))
(define (lhs sum)
(car sum))
(define (rhs sum)
(cadr sum))
(put 'make '+ make)
(put 'lhs '* lhs)
(put 'rhs '* rhs))
(define (install-mul-package)
(define (make e1 e2)
(cond ((or (and (number? e1) (= e1 0)) (and (number? e2) (= e2 0))) 0)
((and (number? e1) (= e1 1)) e2)
((and (number? e2) (= e2 1)) e1)
((and (number? e1) (number? e2)) (* e1 e2))
(else (list '* e1 e2))))
(define (lhs mul)
(car mul))
(define (rhs mul)
(cadr mul))
(put 'make '* make)
(put 'lhs '* lhs)
(put 'rhs '* rhs))
(define (install-exp-package)
(define (make e1 e2)
(cond ((and (number? e2) (= e2 0)) 1)
((and (number? e2) (= e2 1)) e1)
((and (number? e1) (number? e2)) (expt e1 e2))
(else (list '** e1 e2))))
(define (lhs exp)
(car exp))
(define (rhs exp)
(cadr exp))
(put 'make '** make)
(put 'lhs '** lhs)
(put 'rhs '** rhs))
(define (deriv-sum exp var)
((get 'make '+) (deriv (('get 'lhs (sign exp)) (rest exp)) var)
(deriv (('get 'rhs (sign exp)) (rest exp)) var)))
(define (deriv-mul exp var)
((get 'make '+) (('get 'make '*)
(('get 'lhs (sign exp)) (rest exp))
(deriv (get 'rhs (sign exp)) (rest exp)))
(('get 'make '*)
(('get 'rhs (sign exp)) (rest exp))
(deriv (get 'lhs (sign exp)) (rest exp)))))
(define (deriv-exp exp var)
((get 'make '*) ((get 'lhs (sign exp)) (rest exp))
((get 'make '**) ((get 'rhs (sign exp)) (rest exp))
(if (number? ((get 'lhs (sign exp)) (rest exp)))
(- ((get 'lhs (sign exp)) (rest exp)) 1)
(list '- ((get 'lhs (sign exp)) (rest exp)) 1)
)
)
)
)
(put 'deriv '+ deriv-sum)
(put 'deriv '* deriv-mul)
(put 'deriv '** deriv-exp)
(define (deriv exp var)
(cond ((number? exp) 0)
((variable? exp) (if (same-variable? exp var) 1 0))
(else ((get 'deriv (operator exp)) (operands exp)
var))))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
| false |
ae5073d6c3f254d2d9392d4853bc166d33c2bd26 | 852ee43ffa97f0240b508b268a73dc168064f4fb | /day6/day6.scm | 1934871580d49e018cbff024c1193d30e897cc72 | []
| no_license | lilactown/advent-2020 | 1b5c0f92f03996124fc42f9abc343b10114154a8 | 1dc983332de098ecb0aeb83a0999a29ac36bb924 | refs/heads/main | 2023-01-28T14:29:25.375709 | 2020-12-09T17:00:37 | 2020-12-09T17:00:37 | 317,655,853 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 2,118 | scm | day6.scm | #!/usr/local/bin/guile -L .. -s
!#
(use-modules
;; for list operation
(srfi srfi-1)
;; for format ~d
(ice-9 format)
(ice-9 string-fun)
(common))
(define (parse-groups input)
(-> input
(string-replace-substring "\n\n" "%")
(string-split #\%)))
(define example-input
(parse-groups "abc
a
b
c
ab
ac
a
a
a
a
b"))
(define (part-1 input)
(->> input
(map (lambda (group-string)
;; convert entire group to one list and filter out newlines
(filter
(lambda (c)
(not (char=? c #\newline)))
(string->list group-string))))
(map (lambda (group-list)
;; create hashmap of group's answers
(let f ((group-list group-list)
(group (make-hash-table 26))) ;; max 26 letters
(if (null? group-list)
group
(f (cdr group-list)
(begin
(hashq-set! group (car group-list) #t)
group))))))
(map (lambda (group) (hash-count (const #t) group)))
(apply +)))
(assert "example part 1" (= 11 (part-1 example-input)))
(define input
(parse-groups (read-file-contents "day6-input")))
(format #t "Part 1: ~d\n" (part-1 input))
(define (part-2 input)
(->> input
(map (lambda (group-string)
;; keep each person's choices as a separate list
(map string->list (string-split group-string #\newline))))
(map (lambda (group)
;; count every letter
(count (lambda (letter)
;; that shows up in everyones choices
(every (lambda (choices)
(contains? letter choices))
group))
'(#\a #\b #\c #\d #\e #\f #\g #\h #\i
#\j #\k #\l #\m #\n #\o #\p #\q #\r
#\s #\t #\u #\v #\w #\x #\y #\z))))
(apply +)))
(assert "example part 2" (= 6 (part-2 example-input)))
(format #t "Part 2: ~d\n" (part-2 input))
| false |
d537e2bd72a153373d51357e3e6110b1afc71281 | fba55a7038615b7967256306ee800f2a055df92f | /soulawaker/2.1/ex-2.2.scm | dea672dec6c0fcab598c831ae79084ef302c57d1 | []
| no_license | lisp-korea/sicp2014 | 7e8ccc17fc85b64a1c66154b440acd133544c0dc | 9e60f70cb84ad2ad5987a71aebe1069db288b680 | refs/heads/master | 2016-09-07T19:09:28.818346 | 2015-10-17T01:41:13 | 2015-10-17T01:41:13 | 26,661,049 | 2 | 3 | null | null | null | null | UTF-8 | Scheme | false | false | 433 | scm | ex-2.2.scm | (define (make-segment a b c d)
(cons (make-point a b) (make-point c d)))
(define (start-segment l) (car l))
(define (end-segment l) (cdr l))
(define (make-point x y) (cons x y))
(define (x-point p) (car p))
(define (y-point p) (cdr p))
(define (midpoint-segment l)
(cons (/ (+ (x-point (start-segment l))
(x-point (end-segment l)))
2)
(/ (+ (y-point (start-segment l))
(y-point (end-segment l)))
2)))
| false |
9466253a193f9da07d7397763263c590f86173e5 | d4b2a980f9988b6079564e6d96ad75fc5866b8b8 | /info.ss | b52909889fe4361ba3c12b43b3649fbbbd5a610c | [
"BSD-3-Clause"
]
| permissive | mkwiatkowski/identicons | 3a0b1f2dd3738dbf3b77fe3ed956fbb02ae56d92 | 4de0f20abd9f67b858a20ce203cbbd010002e37e | refs/heads/master | 2021-01-01T17:05:46.551589 | 2012-08-05T09:34:41 | 2012-08-05T09:34:41 | 5,302,278 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 621 | ss | info.ss | #lang setup/infotab
(define name "Identicons")
(define blurb
'("Library for generating identicons from 32-bit numbers. Based on an idea by "
(a ((href "http://www.docuverse.com/blog/donpark/2007/01/18/visual-security-9-block-ip-identification")) "Don Park")
"."))
(define categories '(media net))
(define repositories '("4.x"))
(define can-be-loaded-with 'all)
(define primary-file "identicons.ss")
(define scribblings '(("manual.scrbl" ())))
(define version "1.1")
(define release-notes '("Fixed on-bitmap and display-in-frame methods, and added a new method as-image-snip. Thanks to Danny Yoo for patches!"))
| false |
5603107e639353ff3a17b2a8bae6ad6fe70b3e19 | 1b1828426867c9ece3f232aaad1efbd2d59ebec7 | /Chapter 3/a-stream.scm | 8255117a401bf00b5c0512d98738e31cc2365ff4 | []
| no_license | vendryan/sicp | 60c1338354f506e02c714a96f643275d35a7dc51 | d42f0cc6f985aaf369f2760f962928381ca74332 | refs/heads/main | 2023-06-07T02:04:56.332591 | 2021-06-19T10:28:57 | 2021-06-19T10:28:57 | 369,958,898 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 3,116 | scm | a-stream.scm | (define (memo-proc proc)
(let ((already-run? #f) (result #f))
(lambda ()
(if (not already-run?)
(begin (set! result (proc))
(set! already-run? #t)
result)
result))))
(define-syntax delay
(syntax-rules ()
((delay exp) (memo-proc (lambda () exp)))))
(define-syntax cons-stream
(syntax-rules ()
((cons-stream a b) (cons a (delay b)))))
(define (force delayed-proc)
(delayed-proc))
(define the-empty-stream '())
(define (stream-null? s)
(null? s))
(define (stream-car stream)
(car stream))
(define (stream-cdr stream)
(force (cdr stream)))
(define (stream-ref stream n)
(if (= n 0)
(stream-car stream)
(stream-ref (stream-cdr stream) (- n 1))))
(define (stream-filter pred stream)
(cond ((stream-null? stream) the-empty-stream)
((pred (stream-car stream))
(cons-stream (stream-car stream)
(stream-filter pred
(stream-cdr stream))))
(else (stream-filter pred (stream-cdr stream)))))
(define (stream-map proc . argstream)
(if (stream-null? (car argstream))
the-empty-stream
(cons-stream
(apply proc (map stream-car argstream))
(apply stream-map
(cons proc (map stream-cdr
argstream))))))
(define (display-top10 s)
(display-top-n s 10))
(define (display-top-n s times)
(if (= times 0)
'done
(begin (print (stream-car s))
(display-top-n (stream-cdr s) (- times 1)))))
(define (stream-for-each proc s)
(if (stream-null? s)
'done
(begin (proc (stream-car s))
(stream-for-each proc (stream-cdr s)))))
(define (display-stream s)
(stream-for-each print s))
(define (print . x)
(map (lambda (x) (display x) (newline))
x))
(define (stream-enumerate-interval low high)
(if (> low high)
the-empty-stream
(cons-stream
low
(stream-enumerate-interval (+ low 1) high))))
(define (integers-starting-from n)
(cons-stream n (integers-starting-from (+ n 1))))
(define integers (integers-starting-from 1))
(define (divisible? x y) (= (remainder x y) 0))
(define (add-streams s1 s2)
(stream-map + s1 s2))
(define (scale-stream s factor)
(stream-map (lambda (x) (* x factor)) s))
(define (integrate-series s)
; elegant approach: (stream-map / s integers))
; (define (integrate s n)
; (cons-stream (stream-car s)
; (stream-map (lambda (x) (* x (/ 1 n)))
; (integrate s (+ n 1)))))
(define (integrate s n)
(cons-stream (/ (stream-car s) n)
(integrate (stream-cdr s) (+ n 1))))
(integrate s 1))
(define (partial-sum s)
(cons-stream (stream-car s)
(stream-map + (stream-cdr s)
(partial-sum s))))
(define (mul-series s1 s2)
(cons-stream (* (stream-car s1)
(stream-car s2))
(add-streams (scale-stream (stream-cdr s2) (stream-car s1))
(mul-series (stream-cdr s1) s2))))
| true |
1919bc2812841ff1c1e44a24b212ebd1919bb618 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /UnityEngine/unity-engine/collision.sls | bbfaf2ba2c73d3609ae3813edcda8b482e27b6d4 | []
| 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,922 | sls | collision.sls | (library (unity-engine collision)
(export new
is?
collision?
get-enumerator
relative-velocity
rigidbody
collider
transform
game-object
contacts
impact-force-sum
friction-force-sum
other)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...) #'(clr-new UnityEngine.Collision a ...)))))
(define (is? a) (clr-is UnityEngine.Collision a))
(define (collision? a) (clr-is UnityEngine.Collision a))
(define-method-port
get-enumerator
UnityEngine.Collision
GetEnumerator
(System.Collections.IEnumerator))
(define-field-port
relative-velocity
#f
#f
(property:)
UnityEngine.Collision
relativeVelocity
UnityEngine.Vector3)
(define-field-port
rigidbody
#f
#f
(property:)
UnityEngine.Collision
rigidbody
UnityEngine.Rigidbody)
(define-field-port
collider
#f
#f
(property:)
UnityEngine.Collision
collider
UnityEngine.Collider)
(define-field-port
transform
#f
#f
(property:)
UnityEngine.Collision
transform
UnityEngine.Transform)
(define-field-port
game-object
#f
#f
(property:)
UnityEngine.Collision
gameObject
UnityEngine.GameObject)
(define-field-port
contacts
#f
#f
(property:)
UnityEngine.Collision
contacts
UnityEngine.ContactPoint[])
(define-field-port
impact-force-sum
#f
#f
(property:)
UnityEngine.Collision
impactForceSum
UnityEngine.Vector3)
(define-field-port
friction-force-sum
#f
#f
(property:)
UnityEngine.Collision
frictionForceSum
UnityEngine.Vector3)
(define-field-port
other
#f
#f
(property:)
UnityEngine.Collision
other
UnityEngine.Component))
| true |
d87b3506209c3fc0893f62254c78f1fc7fb95ede | 320a615ef54449a39e2ca9e59847106e30cc8d7a | /guile/molecule.scm | c55055ad2eb64acd51cfa45d2b5ef2da424411d3 | []
| no_license | alexei-matveev/bgy3d | 5cf08ea24a5c0f7b0d6e1d572effdeef8232f173 | 0facadd04c6143679033202d18017ae2a533b453 | refs/heads/master | 2021-01-01T17:47:22.766959 | 2015-07-10T09:21:49 | 2015-07-10T09:21:49 | 38,872,299 | 2 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 23,142 | scm | molecule.scm | ;;;
;;; Copyright (c) 2013, 2014 Alexei Matveev
;;; Copyright (c) 2013 Bo Li
;;;
;;; Representation of molecular solvents and solutes and site-specific
;;; force field parameters.
;;;
(define-module (guile molecule)
#:use-module (srfi srfi-1) ; list manipulation
#:use-module (srfi srfi-2) ; and-let*
#:use-module (srfi srfi-11) ; let-values
#:use-module (ice-9 match) ; match-lambda
#:use-module (ice-9 rdelim) ; read-line
#:use-module (ice-9 pretty-print) ; pretty-print
#:use-module (guile math) ; erfc
#:use-module (guile tinker) ; tinker-table
#:use-module (guile utils) ; memoize
#:use-module (guile atoms) ; covalent-radius, canonical-name
#:use-module (guile compat) ; unless
#:export
(make-molecule
move-molecule
translate-molecule
scale-molecule-charge
molecule-name
molecule-sites
molecule-positions
molecule-bounding-box
molecule-charge
molecule-dipole
sites->species
molecule-self-energy
make-force-field
scan-property
scan-self-energy
find-molecule
find-entry
print-molecule/xyz
read-xyz
kj->kcal
kcal->kj
kelvin->kcal
kcal->kelvin
from-ab
from-re
from-cc
make-site
move-site
site-name
site-position
site-sigma
site-epsilon
site-charge
site-distance
update-param
interpolate
*ff*
site-x
site-y
site-z))
;;;
;;; ITC Calorie here. See also bgy3d.h:
;;;
(define (kj->kcal num)
(/ num 4.1868))
(define (kcal->kj num)
(* num 4.1868))
(define (kelvin->kcal T)
(let ((kboltzman (/ 8.3144621 (kcal->kj 1000))))
(* kboltzman T)))
(define (kcal->kelvin E)
(let ((kboltzman (/ 8.3144621 (kcal->kj 1000))))
(/ E kboltzman)))
;;;
;;; Database contains entries in non-native units such as kJ/mol
;;; represented by an s-expression like (kJ 0.3640). Convert them to
;;; working units kcal & angstrom. FIXME: mutually recursive with
;;; find-entry!
;;;
(define (expand-forms ast)
(if (not (pair? ast))
ast
(match ast
(('A num)
(expand-forms num)) ; for completeness, default
(('r0 num)
(* (expand-forms num)
(expt 2 5/6))) ; (r0 x) -> x * 2^(5/6)
(('^2 num) ; (^2 x) -> x^2
(let ((num (expand-forms num)))
(* num num)))
(('kcal num)
(expand-forms num)) ; for completeness, default
(('kJ num)
(kj->kcal (expand-forms num))) ; (kJ 0.3640) -> 0.08694
(('geometry name) ; Do not copy FF params
(let ((sites (molecule-sites (find-entry name)))) ; Recursion here!
(map (lambda (s)
(make-site (site-name s)
(site-position s)))
sites)))
(ast
(map expand-forms ast)))))
;;;
;;; LJ-type VdW interaction may take several forms.
;;;
;;; σε form: 4ε [-(σ/r)^6 + (σ/r)^12]
;;; Rε form: ε [-2(R/r)^6 + (R/r)^12]
;;; AB form: -(A/r)^6 + (B/r)^12
;;; 6-12 form: -C6 / r^6 + C12 / r^12
;;;
(define (from-ab params)
(let ((A (first params))
(B (second params)))
(list (/ (* B B) A) ; σ = B^2/A
(/ (expt (/ A B) 12) 4)))) ; ε = (A/B)^12 / 4
(define (from-re params)
(let ((r (first params))
(e (second params)))
(list (* r (expt 2 5/6)) ; σ = r * 2^(5/6)
e))) ; ε = ε
(define (from-cc params)
(let ((c6 (first params))
(c12 (second params)))
(list (expt (/ c12 c6) 1/6) ; σ = (c12/c6)^(1/6)
(/ (* c6 c6) (* 4 c12))))) ; ε = c6^2/4c12
;;;
;;; Find a solute/solvent in a database or die. FIXME: mutually
;;; recursive with expand-forms!
;;;
(define (find-entry name)
(and-let* ((solutes (slurp/cached (find-file "guile/solutes.scm")))
(molecule (or (assoc name solutes)
(error "Not in the list:"
name
(map first solutes)))))
(expand-forms molecule)))
(define (find-molecule name)
(tabulate-ff (find-entry name)))
;; (set! find-molecule (memoize find-molecule))
;;;
;;; Find a file in the search patch, or die. Note that find-file
;;; assumes the %load-path contains the repo directory in order to
;;; find "guile/solutes.scm".
;;;
(define (find-file file)
(or (search-path %load-path file)
(error "Not found:" file)))
;;;
;;; Slurps the whole file into a list:
;;;
(define (slurp file)
(with-input-from-file file
(lambda ()
(let loop ((acc (list)))
(let ((sexp (read)))
(if (eof-object? sexp)
(reverse acc)
(loop (cons sexp acc))))))))
;;;
;;; Premature optimization and potential memory hog here. Cache file
;;; contents in memory:
;;;
(define slurp/cached (memoize slurp))
;; (write (slurp "guile/solutes.scm"))
;; (newline)
;;;
;;; Solute parameters are currently represented by a name and a list
;;; of sites:
;;;
;;; ("water"
;;; (("O" (-0.2929 0.0 0.0) 3.1506 0.1521 -0.834)
;;; ("OH" (0.2929 0.757 0.0) 0.4 0.046 0.417)
;;; ("OH" (0.2929 -0.757 0.0) 0.4 0.046 0.417)))
;;;
(define (make-molecule name sites)
(list name sites))
(define molecule-name first)
(define molecule-sites second)
;;; There is also an *optional* third field in the molecule, see
;;; molecule-force-field.
(define (molecule-positions solute)
(map site-position (molecule-sites solute)))
(define (move-molecule solute positions)
(let ((name (molecule-name solute))
(sites (molecule-sites solute)))
(make-molecule name (map move-site sites positions))))
(define (translate-molecule solute dx)
(let* ((positions (molecule-positions solute))
(translated (map (lambda (x) (map + x dx))
positions)))
(move-molecule solute translated)))
(define (scale-molecule-charge solute scale-factor)
(let ((name (molecule-name solute))
(sites (molecule-sites solute)))
(make-molecule name
(map (lambda (site) (scale-site-charge site scale-factor))
sites))))
;;;
;;; Returns two corners of the bounding box.
;;;
(define (molecule-bounding-box mol)
(let ((sites (molecule-sites mol)))
(let ((xs (map site-x sites))
(ys (map site-y sites))
(zs (map site-z sites)))
(list (list (apply min xs)
(apply min ys)
(apply min zs))
(list (apply max xs)
(apply max ys)
(apply max zs))))))
;;;
;;; Return the force field parameter table in each molecule
;;; description. FIXME: A missing table is interpreted as an empty
;;; table that refers to an empty force field:
;;;
(define (molecule-force-field solute)
(or (assoc 'force-field (cdr solute))
'(force-field ()))) ; fake empty force field table
;;;
;;; Two legal ways to call make-site: with and without force-field
;;; parameters. FIXME: This is road to hell, a site created by this
;;; constructor when passed to force-field accessors may fail ...
;;;
(define make-site
(case-lambda
((name position sigma epsilon charge)
(list name position sigma epsilon charge))
((name position)
(list name position))))
(define site-name first)
(define site-position second)
(define site-sigma third)
(define site-epsilon fourth)
(define site-charge fifth)
;;;
;;; update sigma, epsilon and charge with new values
;;;
(define (update-param molecule target-site param value)
(let ((name (molecule-name molecule))
(sites (molecule-sites molecule)))
(define (update-site site)
(match param
("sigma"
(if (equal? target-site (site-name site))
(update-site-sigma site value)
site))
("epsilon"
(if (equal? target-site (site-name site))
(update-site-epsilon site value)
site))
("charge"
(if (equal? target-site (site-name site))
(update-site-charge site value)
site))))
;; Error if target-site is not in the molecule:
(unless (assoc target-site sites)
(error "No such site:" target-site))
(make-molecule name (map update-site sites))))
(define (update-site-sigma site new-sigma)
(match site
((name position old-sigma epsilon charge)
(make-site name position new-sigma epsilon charge))))
(define (update-site-epsilon site new-epsilon)
(match site
((name position sigma old-epsilon charge)
(make-site name position sigma new-epsilon charge))))
(define (update-site-charge site new-charge)
(match site
((name position sigma epsilon old-charge)
(make-site name position sigma epsilon new-charge))))
(define (scale-site-charge site scale-factor)
(match site
((name position sigma epsilon old-charge)
(let ((new-charge (* scale-factor old-charge)))
(make-site name position sigma epsilon new-charge)))))
(define (move-site site new-position)
(match site
((name old-position sigma epsilon charge)
(make-site name new-position sigma epsilon charge))))
(define (site-x site) (first (site-position site)))
(define (site-y site) (second (site-position site)))
(define (site-z site) (third (site-position site)))
(define (dot a b)
(apply + (map * a b)))
(define (site-distance a b)
(let ((xa (site-position a))
(xb (site-position b)))
(let ((d (map - xa xb)))
(sqrt (dot d d)))))
;;;
;;; This extracts the charge field from every site and sums them up.
;;; The molecule needs to be in the "canonical" format, with the
;;; force-field parameters expanded to numbers:
;;;
(define (molecule-charge mol)
(apply + (map site-charge (molecule-sites mol))))
;;;
;;; Dipole moment. Same constraints as for molecule-charge:
;;;
(define (molecule-dipole mol)
(let* ((sites (molecule-sites mol))
(q (map site-charge sites))
(x (map site-x sites))
(y (map site-y sites))
(z (map site-z sites)))
(list (dot q x)
(dot q y)
(dot q z))))
(define (sites->species sites scale)
;;
;; Estimate the length of a typical bond between two such sites:
;;
(define (bond-length a b)
(+ (covalent-radius (site-name a))
(covalent-radius (site-name b))))
;;
;; Comparator for two sites. Returns true if sites are closer than
;; scaled estmate for a typical bond between two such atoms. It
;; should not be used to compare the keys in a dictionary. Because
;; this is NOT an equivalence relation, not even transitive.
;;
(define (close? a b)
(let ((distance (site-distance a b))
(estimate (bond-length a b)))
(< distance (* scale estimate))))
;;
;; A site is connected to a species if it is close to any of the
;; sites of that species:
;;
(define (connected? a species)
(any (lambda (b) (close? a b))
species))
;;
;; Group sites into species recursively. Each new site is connected
;; to zero or more species and thus makes another, eventually
;; larger, species.
;;
(define (classify sites)
(let loop ((sites sites)
(species '()))
(if (null? sites)
(reverse species) ; reverse is optional for a set
(let ((a (car sites)))
;; Partition the species into ones connected to site "a"
;; and other species.
(let-values (((conn other) (partition (lambda (s)
(connected? a s))
species)))
;; A new species will contain the site "a" and zero or
;; more sites of the connected species:
(loop (cdr sites)
(cons (cons a (concatenate conn))
other)))))))
;;
;; Assign a site a numeric ID of the species or #f if not found:
;;
(define (lookup a species)
(let loop ((n 0)
(species species))
(if (null? species)
#f ; not found
(if (memq a (car species))
n
(loop (+ 1 n) (cdr species))))))
;;
;; Return a list of numeric IDs. This list is passed to C/Fortran
;; code occasionally:
;;
(let ((species (classify sites)))
(map (lambda (a)
(lookup a species))
sites)))
(define (print-molecule/xyz solute)
(let ((name (molecule-name solute))
(sites (molecule-sites solute)))
(format #t "~a\n" (length sites))
(format #t "# ~a\n" name)
(for-each (lambda (site)
(format #t "~a ~a ~a ~a\n"
(canonical-name (site-name site))
(site-x site)
(site-y site)
(site-z site)))
sites)))
;; (for-each print-molecule/xyz (slurp (find-file "guile/solutes.scm")))
;; (exit 0)
;;;
;;; Returns a 2-list with the value and derivative:
;;;
(define (lj r)
(let* ((x (/ 1 r))
(x6 (expt x 6))
(x12 (* x6 x6))
(e (* 4 x6 (- x6 1)))
(e' (* -4 x (- (* 12 x12) (* 6 x6)))))
(list e e')))
(define EPSILON0INV 331.84164) ; FIXME: literal from units.f90
(define ALPHA 1.2) ; FIXME: literal from units.f90
(define *short-range* (make-fluid #f))
(define (coulomb/full r)
(let* ((e (/ EPSILON0INV r))
(e' (- (/ e r))))
(list e e')))
;;;
;;; erfc (alpha * r) / r
;;;
(define (coulomb/short r)
(let* ((e (* EPSILON0INV (/ (erfc (* ALPHA r)) r)))
(e' +nan.0)) ; FIXME: will it ever be used?
(list e e')))
;;;
;;; Behaviour depends on a dynvar:
;;;
(define (coulomb r)
(let ((short-range (fluid-ref *short-range*)))
(if short-range
(coulomb/short r)
(coulomb/full r))))
;;;
;;; Uses parameters in p to build a replacement for (lj r):
;;;
(define (make-ff p)
(lambda (r)
(match p
((c6 c3)
(let* ((x (/ 1 r))
(x2 (* x x))
(x3 (* x2 x))
(x4 (* x2 x2))
(x6 (* x4 x2))
(x9 (* x6 x3))
(x12 (* x6 x6))
(e (+ (* c6 x6)
(* c3 x3)))
(e' (* -1 x (+ (* 6 c6 x6)
(* 3 c3 x3)))))
(list e e'))))))
;;;
;;; To avoid possible confusion: coordinates of sites a and b are NOT
;;; used to compute the distance here:
;;;
(define (make-force-field a b)
(define (combine-sigmas sa sb)
(/ (+ sa sb) 2))
(define (combine-epsilons ea eb)
(sqrt (* ea eb)))
(let ((sa (site-sigma a))
(ea (site-epsilon a))
(qa (site-charge a))
(sb (site-sigma b))
(eb (site-epsilon b))
(qb (site-charge b)))
(let ((sab (combine-sigmas sa sb))
(eab (combine-epsilons ea eb))
(qab (* qa qb)))
;;
;; This lambda is the result of make-force-field:
;;
(lambda (rab)
;; ee' is a 2-list, value and derivative
(let* ((ee' (coulomb rab))
(e-coul (* qab (first ee')))
(e-coul' (* qab (second ee')))
(ee' (lj (/ rab sab)))
(e-nonb (if (zero? sab)
0.0
(* eab (first ee'))))
(e-nonb' (if (zero? sab)
0.0
(* eab (/ (second ee') sab))))
(e (+ e-coul e-nonb))
(e' (+ e-coul' e-nonb')))
;; FIXME: this lambda returns the energy, though it also
;; computes the force:
e)))))
(define (energy a b)
(let ((f (make-force-field a b)))
(f (site-distance a b))))
(define (molecule-self-energy m species)
(let ((sites (molecule-sites m)))
(let lp1 ((sites sites)
(species species)
(e 0.0))
(if (null? sites)
e
(let ((a (car sites))
(a-species (car species))
(sites (cdr sites))
(species (cdr species)))
(lp1 sites
species
(let lp2 ((sites sites)
(species species)
(e e))
(if (null? sites)
e
(let ((b (car sites))
(b-species (car species))
(sites (cdr sites))
(species (cdr species)))
(lp2 sites
species
(+ e (if (equal? a-species b-species)
0.0
(energy a b)))))))))))))
;;;
;;; Roughly x * a + (1 - x) * b. Will not choke on a == b even if
;;; those are not numbers.
;;;
(define (interpolate x a b)
(let ((wb x)
(wa (- 1 x)))
(let go ((a a)
(b b))
(cond
((and (null? a) (null? b))
'())
((and (pair? a) (pair? b))
(cons (go (car a)
(car b))
(go (cdr a)
(cdr b))))
((equal? a b) ; pass-through for strings and equal numbers
a)
(else
(+ (* wa a) (* wb b)))))))
;;;
;;; Here m0 and m1 could be two conformant molecule descriptions,
;;; e.g. with different geometries or some force field parameter.
;;;
(define (scan-property prop m0 m1)
(let ((n 100)) ; FIXME: literal here
(map (lambda (i)
(prop (interpolate (/ i (1- n)) m0 m1)))
(iota n))))
(define (scan-self-energy mol x0 x1)
(let* ((species (sites->species (molecule-sites mol) 1.0))) ; Keep species during scan.
(scan-property (lambda (mol)
(molecule-self-energy mol species))
(move-molecule mol x0)
(move-molecule mol x1))))
;;;
;;; This reads the current input port and returns a structure that
;;; resembles a molecule:
;;;
;;; ("Comment line goes here"
;;; (("AtomName1" (x y z)) ...))
;;;
(define (read-xyz)
;; Here let* is used to force evaluation order of expressions that
;; have side-effects:
(let* ((natoms (read)) ; number of atoms
(rest-of-line (read-line)) ; discard the rest of the line
(comment-line (read-line))) ; any text
(let loop ((n natoms)
(acc '()))
(if (zero? n)
(make-molecule comment-line (reverse acc))
(let* ((name (symbol->string (read))) ; yes, let*
(x (read))
(y (read))
(z (read)))
(loop (- n 1)
(cons (make-site name (list x y z)) acc)))))))
;; (let ((m (with-input-from-file "a1.xyz" read-xyz)))
;; (pretty-print m)
;; (sorted-distances m))
;; (exit 0)
;;;
;;; Example to load the ff database as a list, which could be obtained
;;; by tinker-test module. This is for test, ff parameters appear in
;;; each line
;;;
(define *tinker-ff-parameter-file*
"guile/force-fields.scm")
(define (find-force-field force-field)
(let ((contents (slurp/cached (find-file *tinker-ff-parameter-file*))))
;;
;; Force-field name in CAR position is irrelevant for the rest of
;; the code, return only the list of entries:
;;
(assoc-ref contents force-field)))
;;;
;;; Get particular column from a data row as stored in the force-field
;;; data file. Beware of the fixed order of "sigma", "epsilon" and
;;; "charge" parameters:
;;;
;;; (82 HC "Alkane H-C" 1.008 2.5 0.03 0.06)
;;;
;;; or the longer version
;;;
;;; (157 CT "Benzyl Alcohol -CH2OH" 12.011 3.5 0.066 0.2 6 13 4)
;;;
;;; with each field having the following meaning:
;;;
;;; (type symbol descr weight sigma epsilon charge atnum class ligand)
;;;
;;; See e.g. ./force-fields.scm or ./tinker.scm for details.
;;;
(define ff-symbol second)
(define ff-sigma fifth)
(define ff-epsilon sixth)
(define ff-charge seventh)
;;;
;;; This will be called from outside, augment each site in solute with
;;; force field information (if missing):
;;;
(define (tabulate-ff solute)
;;
;; The structure of FF form:
;;
;; (force-field (ff-sym1 ff-sym2 ...)
;; (site-name1 site-sym1) ...)
;;
;; The car position is ignored. The CADR position is a list of force
;; field symbols to combine. CDDR is the translation table of site
;; names to symbols/numbers used in FF tables. FIXME: There is no
;; checking if a site symbols is repeated in multiple rows.
;;
(let* ((force-field-form (molecule-force-field solute))
(force-field-symbols (cadr force-field-form))
(translation-table (cddr force-field-form))
(rows (concatenate (map find-force-field force-field-symbols))))
;;
;; This will derive the atom type 77 from a name "CT3" using a
;; list of entries (("CT3" 77) ...) in the FF table.
;;
(define (ff-type name)
(second (or (assoc name translation-table)
(error "Not in the table:" name))))
;;
;; This will return a row from the parameter file matching the
;; given atom type:
;;
(define (ff-row type)
(or (assoc type rows)
(error "Not in the file:" type)))
;;
;; Returns a list of non-bonding force field parameters: (sigma
;; epsilon charge)
;;
(define (non-bonding name)
(let ((row (ff-row (ff-type name))))
;; (if (not (equal? name (symbol->string (ff-symbol row))))
;; (pk "WARNING: do not match" name row))
(list (ff-sigma row)
(ff-epsilon row)
(ff-charge row))))
;;
;; This function adds missing foce-field parameters to the site
;; description:
;;
(define (new-site site)
(match site
;; 1) Canonical form -> keep a valid site as is
((name position sigma epsilon charge)
site)
;; 2) FF is missing -> append force field params
((name position)
(apply make-site name position (non-bonding name)))
;; 3) A form instead of literal sigma and epsilon
;; -> derive σε from C6 & C12
((name position ('c6/c12 . cc) charge)
(let* ((ff (from-cc cc)) ; cc is a list of two numbers
(sigma (first ff))
(epsilon (second ff)))
(make-site name position sigma epsilon charge)))))
;;
;; FIXME: This check is so far down because of the "define"s above
;; that have to be put at the beginning of the scope.
;;
(unless rows
(error "Did not find force-field:" force-field-symbols))
;;
;; Build new sites and use them to construct a new molecule:
;;
(let ((new-sites (map new-site (molecule-sites solute))))
(make-molecule (molecule-name solute) new-sites))))
| false |
b4fc54c01449130a4bde2730b6d8b67ee551bbb0 | 2e4afc99b01124a1d69fa4f44126ef274f596777 | /apng/resources/dracula/lang/defconst.ss | d40e5d576ed4a1c0d32bfd4bd4d98f55c9b60005 | []
| no_license | directrix1/se2 | 8fb8204707098404179c9e024384053e82674ab8 | 931e2e55dbcc55089d9728eb4194ebc29b44991f | refs/heads/master | 2020-06-04T03:10:30.843691 | 2011-05-05T03:32:54 | 2011-05-05T03:32:54 | 1,293,430 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 819 | ss | defconst.ss | #lang scheme
(provide defconst)
(require (for-syntax "syntax-checks.ss")
"check.ss"
"acl2-app.ss")
(define-syntax (defconst stx)
(syntax-case stx ()
[(_ name expr)
(begin
(unless (legal-constant-name? #'name)
(raise-syntax-error #f
"Constant names must begin and end with asterisks (*)."
stx #'name))
(quasisyntax/loc stx
(begin (define the-const expr)
(define-below-marker-for here #,stx)
(define-syntax name
(check-below-transformer #'here
(lambda (ref)
(unless (identifier? ref)
(raise-syntax-error #f
"invalid reference to defconst name" ref))
#'the-const))))))]))
| true |
155e435c70e8339bbf02a11bb78cb8fecb7e2ce3 | defeada37d39bca09ef76f66f38683754c0a6aa0 | /UnityEngine/unity-engine/unity-event-queue-system.sls | 4bad2ae8fb0d882f216dd93916f0b3ccc5a2ccfc | []
| 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 | 827 | sls | unity-event-queue-system.sls | (library (unity-engine unity-event-queue-system)
(export new
is?
unity-event-queue-system?
get-global-event-queue
generate-event-id-for-payload)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new UnityEngine.UnityEventQueueSystem a ...)))))
(define (is? a) (clr-is UnityEngine.UnityEventQueueSystem a))
(define (unity-event-queue-system? a)
(clr-is UnityEngine.UnityEventQueueSystem a))
(define-method-port
get-global-event-queue
UnityEngine.UnityEventQueueSystem
GetGlobalEventQueue
(static: System.IntPtr))
(define-method-port
generate-event-id-for-payload
UnityEngine.UnityEventQueueSystem
GenerateEventIdForPayload
(static: System.String System.String)))
| true |
47afff91c1afb6a7320ea70f096610c2c89c4c9b | bcfa2397f02d5afa93f4f53c0b0a98c204caafc1 | /scheme/chapter2/ex2_75_test.scm | b0f2725bf71f1442bfce9a5a4700065a9b729fe8 | []
| no_license | rahulkumar96/sicp-study | ec4aa6e1076b46c47dbc7a678ac88e757191c209 | 4dcd1e1eb607aa1e32277e1c232a321c5de9c0f0 | refs/heads/master | 2020-12-03T00:37:39.576611 | 2017-07-05T12:58:48 | 2017-07-05T12:58:48 | 96,050,670 | 0 | 0 | null | 2017-07-02T21:46:09 | 2017-07-02T21:46:09 | null | UTF-8 | Scheme | false | false | 764 | scm | ex2_75_test.scm | ;; SICP Tests 2.75
(test-case "Ex 2.75 -- To Radians"
(assert-in-delta 0.707 (to-rad 45) 0.783))
(test-case "Ex 2.75 -- Data Driven Complex Number"
(let ((c (make-from-mag-ang 1 (to-rad 45))))
(assert-equal 1 (c 'magnitude))
(assert-in-delta (to-rad 45) (c 'angle) 0.001)
(assert-in-delta 0.707 (c 'real-part) 0.001)
(assert-in-delta 0.707 (c 'imag-part) 0.001)))
(test-case "Ex 2.75 -- Data Driven Complex Number 2"
(let ((c (make-from-mag-ang 1 (to-rad 0))))
(assert-equal 1 (c 'magnitude))
(assert-in-delta (to-rad 0) (c 'angle) 0.001)
(assert-in-delta 1 (c 'real-part) 0.001)
(assert-in-delta 0 (c 'imag-part) 0.001)))
| false |
2b830c8afbaad5a54bcc0bae3b6bee0fa01fe418 | ac2a3544b88444eabf12b68a9bce08941cd62581 | /tests/unit-tests/01-fixnum/fxif.scm | bcb83729e5f40ab81b10ad78b100f0a7c0736a59 | [
"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 | 658 | scm | fxif.scm | (include "#.scm")
(check-eqv? (##fxif 0 -1 1) 1)
(check-eqv? (##fxif -1 1 0) 1)
(check-eqv? (##fxif 1 0 -1) -2)
(check-eqv? (fxif 0 -1 1) 1)
(check-eqv? (fxif -1 1 0) 1)
(check-eqv? (fxif 1 0 -1) -2)
(check-tail-exn wrong-number-of-arguments-exception? (lambda () (fxif)))
(check-tail-exn wrong-number-of-arguments-exception? (lambda () (fxif 1 1 1 1)))
(check-tail-exn type-exception? (lambda () (fxif 1 1 0.0)))
(check-tail-exn type-exception? (lambda () (fxif 0.5 1 1)))
(check-tail-exn type-exception? (lambda () (fxif 1 0.5 1)))
(check-tail-exn type-exception? (lambda () (fxif 1 1 0.5)))
(check-tail-exn type-exception? (lambda () (fxif 1 1 1/2)))
| false |
7cb69fd2e9c5b1d8c4b23bf35b62e28ab30948a5 | c38f6404e86123560ae8c9b38f7de6b66e30f1c4 | /fernscode/cdr.ss | 7956bc2f13cd072ced3767e0b431eac0b56e058b | [
"CC-BY-4.0"
]
| permissive | webyrd/dissertation-single-spaced | efeff4346d0c0e506e671c07bfc54820ed95a307 | 577b8d925b4216a23837547c47fb4d695fcd5a55 | refs/heads/master | 2023-08-05T22:58:25.105388 | 2018-12-30T02:11:58 | 2018-12-30T02:11:58 | 26,194,521 | 57 | 4 | null | 2018-08-09T09:21:03 | 2014-11-05T00:00:40 | TeX | UTF-8 | Scheme | false | false | 55 | ss | cdr.ss | (define fcdr (timed-lambda (p) (fcar p) (cdrdollar p))) | false |
4fb8f2d905815dce57006bf8883c7ab8e8f2325b | 91fc138a1cbcbeffaf6cf4eb0e3ae188b2ca257f | /Chapter 1 Exercises/1.40.scm | 4a4278f749a6c6ccea57b6af84fb4939e7ab1a21 | []
| no_license | jlollis/sicp-solutions | 0bd8089aea5a85c7b34e43a0f34db87e4161bee0 | 7b03befcfe82e26a7fb28d94bc99292bc484f9dd | refs/heads/master | 2022-06-15T23:34:10.541201 | 2022-06-02T03:32:46 | 2022-06-02T03:32:46 | 130,729,626 | 9 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 2,239 | scm | 1.40.scm | #lang sicp
#|
Exercise 1.40. Define a procedure cubic that can be used together with the newtons-method
procedure in expressions of the form:
(newtons-method (cubic a b c) 1)
to approximate zeros of the cubic (x^3) + (ax^2) + bx + c.
|#
(define (cube x) (* x x x))
;; define average
(define (average x y)
(/ (+ x y) 2.0))
;; define fixed-point
(define tolerance 0.000000000000000000000001)
(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))
;;;SECTION 1.3.4
(define (average-damp f)
(lambda (x) (average x (f x))))
;: ((average-damp square) 10)
(define (sqrt x)
(fixed-point (average-damp (lambda (y) (/ x y)))
1.0))
(define (cube-root x)
(fixed-point (average-damp (lambda (y) (/ x (square y))))
1.0))
;; Newton's method
(define dx 0.00001)
(define (deriv g)
(lambda (x)
(/ (- (g (+ x dx)) (g x))
dx)))
;: ((deriv cube) 5)
(define (newton-transform g)
(lambda (x)
(- x (/ (g x) ((deriv g) x)))))
(define (newtons-method g guess)
(fixed-point (newton-transform g) guess))
; (define (sqrt-2 x)
; (newtons-method (lambda (y) (- (square y) x))
; 1.0)
;; Fixed point of transformed function
(define (fixed-point-of-transform g transform guess)
(fixed-point (transform g) guess))
(define (sqrt-3 x)
(fixed-point-of-transform (lambda (y) (/ x y))
average-damp
1.0))
(define (sqrt-4 x)
(fixed-point-of-transform (lambda (y) (- (square y) x))
newton-transform
1.0))
#|
Exercise 1.40. Define a procedure cubic that can be used together with the newtons-method
procedure in expressions of the form:
(newtons-method (cubic a b c) 1)
to approximate zeros of the cubic (x^3) + (ax^2) + bx + c.
|#
(define (square x) (* x x))
;(define (cube x)(* x x x))
(define (cubic a b c)
(lambda (x)(+ (cube x))(* a (square x))(* b x)(+ c)))
; not working...getting division by zero error
(newtons-method (cubic 5 4 6) 1)
| false |
b418b556723fa337e06a482db656847a172848b5 | ac2a3544b88444eabf12b68a9bce08941cd62581 | /lib/_prim-vector-gambit#.scm | 07894a94dedb1dc3cc910898310f5e72c3ed7898 | [
"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 | 518 | scm | _prim-vector-gambit#.scm | ;;;============================================================================
;;; File: "_prim-vector-gambit#.scm"
;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved.
;;;============================================================================
;;; Vector operations added by Gambit.
(##namespace ("##"
append-vectors
vector-set
vector-shrink!
subvector
subvector-fill!
subvector-move!
vector-cas!
vector-inc!
))
;;;============================================================================
| false |
66010e561828141863849dbb1d077ec5f684ae5e | b58f908118cbb7f5ce309e2e28d666118370322d | /src/25.scm | cbfa8e0bf4130159c73ae977e8cb1b485c6688ec | [
"MIT"
]
| permissive | arucil/L99 | a9e1b7ad2634850db357f7cc292fa2871997d93d | 8b9a3a8e7fb63efb2d13fab62cab2c1254a066d9 | refs/heads/master | 2021-09-01T08:18:39.029308 | 2017-12-26T00:37:55 | 2017-12-26T00:37:55 | 114,847,976 | 1 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 180 | scm | 25.scm | (load "prelude.scm")
(load "23.scm")
;;; P25
(define (rnd-permu ls)
(rnd-select ls (length ls)))
(test (begin (init-random! 0) (rnd-permu '(a b c d e f g))) '(d a g b f c e))
| false |
2a9a0d86556f180c610ea5c04304bad86d15dafe | bdfa935097ef39f66c7f18856accef422ef39128 | /parts/qa0/tree/scheme/be-bgq-xlc.ss | f72121ad7e3362cd4ef0bf1041878646b798e7d7 | [
"MIT"
]
| permissive | djm2131/qlua | 213f5ed4b692b1b03d2ff1a78d09ea9d2d9fe244 | 737bfe85228dac5e9ae9eaab2b5331630703ae73 | refs/heads/master | 2020-04-18T15:01:06.117689 | 2019-02-06T15:23:27 | 2019-02-06T15:23:27 | 162,349,914 | 0 | 0 | null | null | null | null | UTF-8 | Scheme | false | false | 18,871 | ss | be-bgq-xlc.ss | ;; BG/Q XLC backend
#fload "sfc.sf"
#fload "common.sf"
#fload "error.ss"
#fload "format.ss"
#fload "ast.ss"
#fload "parser.ss"
#fload "attr.ss"
#fload "backend.ss"
#fload "cx2qh.ss"
#fload "cenv.ss"
#fload "cheader.ss"
#fload "verbose.ss"
#fload "be-ckind.ss"
;;
;; (provide machine-bgq/xlc)
;;
(define machine-bgq/xlc
(let ()
(define op-type-table
'((qh-make qh-double)
(qh-real double)
(qh-imag double)
(qh-zero qh-double)
(qh-move qh-double)
(qh-neg qh-double)
(qh-times-plus-i qh-double)
(qh-times-minus-i qh-double)
(qh-add qh-double)
(qh-sub qh-double)
(qh-rmul qh-double)
(qh-rmadd qh-double)
(qh-rmsub qh-double)
(qh-add-i qh-double)
(qh-sub-i qh-double)
(qh-norm-init qh-double)
(qh-norm-add qh-double)
(qh-norm-fini double)
(qh-dot-init qh-double)
(qh-dot-add-a qh-double)
(qh-dot-add-b qh-double)
(qh-dot-add-i-a qh-double)
(qh-dot-add-i-b qh-double)
(qh-dot-sub-a qh-double)
(qh-dot-sub-b qh-double)
(qh-dot-sub-i-a qh-double)
(qh-dot-sub-i-b qh-double)
(qh-dot-fini qh-double)
(qh-mul-a qh-double)
(qh-mul-b qh-double)
(qh-madd-a qh-double)
(qh-madd-b qh-double)
(qh-msub-a qh-double)
(qh-msub-b qh-double)
(qh-cmul-a qh-double)
(qh-cmul-b qh-double)
(qh-cmadd-a qh-double)
(qh-cmadd-b qh-double)
(qh-cmsub-a qh-double)
(qh-cmsub-b qh-double)
(qh->float qh-double)
(double-add double)
(double-div double)
(double-madd double)
(double-msub double)
(double-zero double)
(double-move double)
(double-mul double)
(double-neg double)
(double-sub double)
(int-add int)
(int-and int)
(int-div int)
(int-mod int)
(int-move int)
(int-mul int)
(int-or int)
(int-sub int)
(int-xor int)
(pointer-add pointer)
(pointer-move pointer)
(nop )))
(define op-emit-table
;; op i-count fmt flop-count
'((pointer-move 1 "$0 = %0" 0)
(pointer-add 2 "$0 = %0 + (%1)" 0)
(int-move 1 "$0 = %0" 0)
(int-mul 2 "$0 = %0 * (%1)" 0)
(int-div 2 "$0 = %0 / (%1)" 0)
(int-mod 2 "$0 = %0 % (%1)" 0)
(int-add 2 "$0 = %0 + (%1)" 0)
(int-sub 2 "$0 = %0 - (%1)" 0)
(int-neg 1 "$0 = -(%0)" 0)
(int-and 2 "$0 = %0 & (%1)" 0)
(int-or 2 "$0 = %0 | (%1)" 0)
(int-xor 2 "$0 = %0 ^ (%1)" 0)
(int-not 1 "$0 = !(%0)" 0)
(double-zero 0 "$0 = 0.0" 0)
(double-move 1 "$0 = %0" 0)
(double-neg 1 "$0 = - (%0)" 1)
(double-add 2 "$0 = %0 + (%1)" 1)
(double-sub 2 "$0 = %0 - (%1)" 1)
(double-div 2 "$0 = %0 / (%1)" 1)
(double-mul 2 "$0 = %0 * (%1)" 1)
(double-madd 3 "$0 = %0 + (%1) * (%2)" 2)
(double-msub 3 "$0 = %0 - (%1) * (%2)" 2)
(qh-make 2 "$0 = vec_insert(%1,vec_promote(%0,0),1)" 0)
(qh-real 1 "$0 = vec_extract(%0,0)" 0)
(qh-imag 1 "$0 = vec_extract(%0,1)" 0)
(qh-zero 0 "$0 = gZERO" 0)
(qh-move 1 "$0 = %0" 0)
(qh-neg 1 "$0 = vec_neg(%0)" 2)
(qh-times-plus-i 1 "$0 = vec_xxnpmadd(%0, gONE, gZERO)" 1)
(qh-times-minus-i 1 "$0 = vec_xxcpnmadd(%0, gONE, gZERO)" 1)
(qh-add 2 "$0 = vec_add(%0, %1)" 2)
(qh-sub 2 "$0 = vec_sub(%0, %1)" 2)
(qh-rmul 2 "$0 = vec_mul(vec_splats(%0), %1)" 2)
(qh-rmadd 3 "$0 = vec_madd(vec_splats(%1), %2, %0)" 4)
(qh-rmsub 3 "$0 = vec_nmsub(vec_splats(%1), %2, %0)" 4)
(qh-add-i 2 "$0 = vec_xxnpmadd(%1, gONE, %0)" 2)
(qh-sub-i 2 "$0 = vec_xxcpnmadd(%1, gONE, %0)" 2)
(qh-mul-a 2 "$0 = vec_xmul(%0, %1)" 2)
(qh-mul-b 3 "$0 = vec_xxnpmadd(%2, %1, %0)" 4)
(qh-madd-a 3 "$0 = vec_xmadd(%1, %2, %0)" 4)
(qh-madd-b 3 "$0 = vec_xxnpmadd(%2, %1, %0)" 4)
(qh-msub-a 3 "$0 = vec_sub(%0, vec_xmul(%1, %2))" 4)
(qh-msub-b 3 "$0 = vec_xxcpnmadd(%2, %1, %0)" 4)
(qh-cmul-a 2 "$0 = vec_xmul(%0, %1)" 2)
(qh-cmul-b 3 "$0 = vec_xxcpnmadd(%2, %1, %0)" 4)
(qh-cmadd-a 3 "$0 = vec_xmadd(%1, %2, %0)" 4)
(qh-cmadd-b 3 "$0 = vec_xxcpnmadd(%2, %1, %0)" 4)
(qh-cmsub-a 3 "$0 = vec_sub(%0, vec_xmul(%1, %2))" 4)
(qh-cmsub-b 3 "$0 = vec_xxnpmadd(%2, %1, %0)" 4)
(qh-real-cmul-conj-init 0 "$0 = gZERO" 0)
(qh-real-cmul-conj-add 3 "$0 = vec_madd(%2, %1, %0)" 4)
(qh-real-cmul-conj-fini 1 "$0 = vec_extract(%0,0) + vec_extract(%0,1)" 1)
(qh-norm-init 0 "$0 = gZERO" 0)
(qh-norm-add 2 "$0 = vec_madd(%1, %1, %0)" 4)
(qh-norm-fini 1 "$0 = vec_extract(%0,0) + vec_extract(%0,1)" 1)
(qh-dot-init 0 "$0 = gZERO" 0)
(qh-dot-add-a 3 "$0 = vec_xmadd(%1, %2, %0)" 4)
(qh-dot-add-b 3 "$0 = vec_xxcpnmadd(%2, %1, %0)" 4)
(qh-dot-add-i-a 3 "$0 = vec_madd(vec_splats(vec_extract(%1,1)),%2,%0)" 4)
(qh-dot-add-i-b 3 "$0 = vec_xxnpmadd(%2,vec_splats(vec_extract(%1,0)),%0)" 4)
(qh-dot-sub-a 3 "$0 = vec_sub(%0, vec_xmul(%1, %2))" 4)
(qh-dot-sub-b 3 "$0 = vec_xxnpmadd(%2, %1, %0)" 4)
(qh-dot-sub-i-a 3 "$0 = vec_msub(vec_splats(vec_extract(%1,1)),%2,%0)" 4)
(qh-dot-sub-i-b 3 "$0 = vec_xxcpnmadd(%2,vec_splats(vec_extract(%1,0)),%0)" 4)
(qh-dot-fini 1 "$0 = %0" 0)
(qh->float 1 "$0 = vec_rsp(%0)" 0)))
(define load-table
'((int int)
(pointer pointer)
(float double)
(double double)
(qh-float qh-double)
(qh-double qh-double)))
(define op-needing-zero*
'(qh-zero
qh-times-plus-i
qh-times-minus-i
qh-real-cmul-conj-init
qh-norm-init
qh-dot-init
qh-dot-add-i-b
qh-dot-sub-i-b))
(define op-needing-one*
'(qh-times-plus-i
qh-times-minus-i
qh-add-i
qh-sub-i
qh-dot-add-i-a
qh-dot-add-i-b
qh-dot-sub-i-a
qh-dot-sub-i-b))
(define (emit-qh-double-store level addr* value env)
(do-emit level (q-fmt "vec_st2a(~a, 0, (double *)(~a));"
(preemit-input value env)
(preemit-addr* addr* env))))
(define (emit-qh-float-store level addr* value env)
(do-emit level (q-fmt "vec_st2a(~a, 0, (float *)(~a));"
(preemit-input value env)
(preemit-addr* addr* env))))
(define (emit-qh-double-load level output addr* env)
(do-emit level (q-fmt "~a = vec_ld2a(0, (double *)(~a));"
(preemit-output output env)
(preemit-addr* addr* env))))
(define (emit-qh-float-load level output addr* env)
(do-emit level (q-fmt "~a = vec_ld2a(0, (float *)(~a));"
(preemit-output output env)
(preemit-addr* addr* env))))
(define (emit-load level type output addr* env f)
(case type
[(qh-float) (emit-qh-float-load level output addr* env)]
[(qh-double) (emit-qh-double-load level output addr* env)]
[else (do-emit level "~a = *(~a *)(~a);"
(preemit-output output env)
(ce-lookup-x env 'name-of type "BGQ/XLC name of type ~a"
type)
(preemit-addr* addr* env))])
f)
(define (emit-store level type addr* value env f)
(case type
[(qh-float) (emit-qh-float-store level addr* value env)]
[(qh-double) (emit-qh-double-store level addr* value env)]
[else (do-emit level "*(~a *)(~a) = ~a;"
(ce-lookup-x env 'name-of type "BGQ/XLC name of type ~a"
type)
(preemit-addr* addr* env)
(preemit-input value env))])
f)
(define (collect-output* code* env)
(define (add-output* output* type* env)
(cond
[(null? output*) env]
[else (add-output* (cdr output*) (cdr type*)
(add-output (car output*) (car type*) env))]))
(define (add-output output type env)
(variant-case output
[reg (name)
(ce-search-x env 'back-end name
(lambda (v) env)
(lambda () (ce-bind-x env 'back-end name
(list (ck-new-var) type))))]))
(define (add-zero name env)
(if (not (memq name op-needing-zero*)) env
(ce-search-x env 'bgq/xlc 'zero
(lambda (x) env)
(lambda ()
(ce-bind-x env 'bgq/xlc 'zero (ck-new-var))))))
(define (add-one name env)
(if (not (memq name op-needing-one*)) env
(ce-search-x env 'bgq/xlc 'one
(lambda (x) env)
(lambda ()
(ce-bind-x env 'bgq/xlc 'one (ck-new-var))))))
(walk-code* code*
;; operation
(lambda (env name attr* output* input*)
(let* ([env (add-zero name env)]
[env (add-one name env)])
(add-output* output* (be-out-type* env name) env)))
;; load
(lambda (env type attr* output addr*)
(add-output output (be-load-type env type) env))
;; store
(lambda (env type attr* addr* value) env)
;; loop
(lambda (env attr* var low high)
(add-output var 'int env))
;; if
(lambda (env var) env)
env))
(define (bgq/xlc-back-end ast env)
(values (complex->quad-hummer ast) env))
(define (extra-env env)
(let* ([env (ce-add-type env 'qh-double "vector4double" 32 32)]
[env (ce-add-type env 'qh-float "vector4double" 32 32)])
env))
(define (extra-decl* arg-name* arg-type* arg-c-name* arg-c-type* env)
(define (do-constant id init)
(ce-search-x env 'bgq/xlc id
(lambda (v) (do-emit 1 "const vector4double ~a = ~a;"
v init))
(lambda () #t)))
(do-constant 'zero "((vector4double) {0.0, 0.0, 0.0, 0.0})")
(do-constant 'one "((vector4double) {1.0, 1.0, 1.0, 1.0})"))
(define (zo-define* env)
(define (do-define id name def)
(ce-search-x env 'bgq/xlc id
(lambda (v)
(do-emit 0 "#define ~a ~a" name (q-fmt def v)))
(lambda () #t)))
(do-define 'zero "gZERO" "(~a)")
(do-define 'one "gONE" "(~a)"))
(define (extra-postparam* arg-name* arg-type* arg-c-name* arg-c-type* env)
(define (emit-disjoint*)
(do-emit 0 "")
(let loop-a ([a* arg-name*] [t* arg-type*])
(cond
[(null? a*)]
[(not (eq? 'pointer (car t*))) (loop-a (cdr a*) (cdr t*))]
[else
(let ([rn (car (ce-lookup-x env 'back-end (car a*)
"bgq/xlc name for ~a" (car a*)))])
(let loop-b ([b* (cdr a*)] [s* (cdr t*)])
(cond
[(null? b*) (loop-a (cdr a*) (cdr t*))]
[(not (eq? 'pointer (car s*))) (loop-b (cdr b*) (cdr s*))]
[else (do-emit 0 "#pragma disjoint(*~a,*~a)"
rn
(car (ce-lookup-x env 'back-end (car b*)
"bgq/xlc name for ~a"
(car b*))))
(loop-b (cdr b*) (cdr s*))])))])))
(define (emit-align*)
(do-emit 0 "")
(let loop-a ([a* arg-name*] [t* arg-type*])
(cond
[(null? a*) (do-emit 0 "")]
[(not (eq? 'pointer (car t*))) (loop-a (cdr a*) (cdr t*))]
[else
(let ([rn (car (ce-lookup-x env 'back-end (car a*)
"bgq/xlc name for ~a" (car a*)))])
(do-emit 1 "__alignx(16, ~a);" rn)
(loop-a (cdr a*) (cdr t*)))])))
;;;
(emit-disjoint*)
(emit-align*))
(define (zo-undefine* env)
(define (do-undefine id name)
(ce-search-x env 'bgq/xlc id
(lambda (v) (do-emit 0 "#undef ~a" name))
(lambda () #t)))
(do-undefine 'zero "gZERO")
(do-undefine 'one "gONE"))
(build-ckind-back-end 'bgq/xlc ; target-name
8 ; int-size
8 ; int-align
8 ; pointer-size
8 ; pointer-align
op-emit-table ; op-emit-table
op-type-table ; op-type-table
load-table ; ld-type-table
emit-load ; emit-load
emit-store ; emit-store
collect-output* ; collect-outputs
bgq/xlc-back-end ; the-back-end
extra-env ; extra-env
extra-decl* ; extra-decl*
zo-define* ; extra-def*
extra-postparam* ; extra-postparam*
zo-undefine*))) ; extra-undef*
| false |
1f11cebfdf3967338ed4de95e1bd21d02f9a3baf | defeada37d39bca09ef76f66f38683754c0a6aa0 | /mscorlib/system/security/policy/file-code-group.sls | 99f35b0aab8be170da79b2405440d540da4f1ea1 | []
| 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,812 | sls | file-code-group.sls | (library (system security policy file-code-group)
(export new
is?
file-code-group?
get-hash-code
resolve
resolve-matching-code-groups
copy
equals?
merge-logic
attribute-string
permission-set-name)
(import (ironscheme-clr-port))
(define-syntax new
(lambda (e)
(syntax-case e ()
((_ a ...)
#'(clr-new System.Security.Policy.FileCodeGroup a ...)))))
(define (is? a) (clr-is System.Security.Policy.FileCodeGroup a))
(define (file-code-group? a)
(clr-is System.Security.Policy.FileCodeGroup a))
(define-method-port
get-hash-code
System.Security.Policy.FileCodeGroup
GetHashCode
(System.Int32))
(define-method-port
resolve
System.Security.Policy.FileCodeGroup
Resolve
(System.Security.Policy.PolicyStatement
System.Security.Policy.Evidence))
(define-method-port
resolve-matching-code-groups
System.Security.Policy.FileCodeGroup
ResolveMatchingCodeGroups
(System.Security.Policy.CodeGroup System.Security.Policy.Evidence))
(define-method-port
copy
System.Security.Policy.FileCodeGroup
Copy
(System.Security.Policy.CodeGroup))
(define-method-port
equals?
System.Security.Policy.FileCodeGroup
Equals
(System.Boolean System.Object))
(define-field-port
merge-logic
#f
#f
(property:)
System.Security.Policy.FileCodeGroup
MergeLogic
System.String)
(define-field-port
attribute-string
#f
#f
(property:)
System.Security.Policy.FileCodeGroup
AttributeString
System.String)
(define-field-port
permission-set-name
#f
#f
(property:)
System.Security.Policy.FileCodeGroup
PermissionSetName
System.String))
| true |
25b2e14ca0e7b01bea44a0422ec739256bf41c58 | 02dc853159cd8a315280c599020586261bd0dceb | /Informatics Basics/long-arithmetic.scm | 336003c44cbb72e299cabe0718645851ed58fd0b | []
| no_license | belogurow/BMSTU_IU9 | f524380bd11d08eb4a5055687d74ff563dba1eae | 0104470d34458f5c76ccf1348b11bddc60306cfd | refs/heads/master | 2021-01-10T14:08:49.431011 | 2020-06-23T20:08:21 | 2020-06-23T20:08:21 | 55,531,808 | 14 | 1 | null | null | null | null | UTF-8 | Scheme | false | false | 4,343 | scm | long-arithmetic.scm | (define (perevod x)
(- (char->integer x) 48))
(define (perevodobr x)
(integer->char (+ x 48)))
(define (s->l s)
(string->list s))
(define (l->s l)
(list->string l))
;-----------------l+
(define (l+ . args)
(define (iter sum1 xs)
(if (not (null? xs))
(iter (sum sum1 (car xs) 0 '()) (cdr xs))
sum1))
(iter '() args))
(define (sum x y r spis)
(if (and (null? x) (null? y))
(if (equal? r 1)
(append (list (perevodobr r)) spis)
spis)
(let ((a1 (if (null? x) 0 (perevod (car (reverse x)))))
(a2 (if (null? x) '() (reverse (cdr (reverse x)))))
(b1 (if (null? y) 0 (perevod (car (reverse y)))))
(b2 (if (null? y) '() (reverse (cdr (reverse y))))))
(if (> (+ a1 b1 r) 9)
(sum a2 b2 1 (append (list (perevodobr (remainder (+ a1 b1 r) 10))) spis))
(sum a2 b2 0 (append (list (perevodobr (+ a1 b1 r))) spis))))))
;------------------l-
(define (l- . args)
(define (iter razn1 xs)
(if (not (null? xs))
(iter (razn razn1 (car xs) 0 '()) (cdr xs))
razn1))
(iter (car args) (cdr args)))
(define (razn x y r spis)
(if (null? x)
(if (equal? (car spis) #\0)
(cdr spis)
spis)
(let ((a1 (if (null? x) 0 (perevod (car (reverse x)))))
(a2 (if (null? x) '() (reverse (cdr (reverse x)))))
(b1 (if (null? y) 0 (perevod (car (reverse y)))))
(b2 (if (null? y) '() (reverse (cdr (reverse y))))))
(if (< (- a1 b1 r) 0)
(razn a2 b2 1 (append (list (perevodobr (- (+ 10 a1) b1 r))) spis))
(razn a2 b2 0 (append (list (perevodobr (- a1 b1 r))) spis))))))
;-------------l*
(define (l* . args)
(define (iter razn1 xs)
(if (not (null? xs))
(iter (prog 0 razn1 (car xs) '()) (cdr xs))
razn1))
(iter (car args) (cdr args)))
(define (razr xs r)
(if (equal? r 0)
xs
(razr (append xs (list #\0)) (- r 1))))
(define (multi x y r spis)
(if (null? x)
(if (equal? r 0)
spis
(append (list (perevodobr r)) spis))
(let ((a1 (if (null? x) 0 (perevod (car (reverse x)))))
(a2 (if (null? x) '() (reverse (cdr (reverse x)))))
(b1 (if (null? y) 0 (perevod (car (reverse y))))))
(if (>= (+ (* a1 b1) r) 10)
(multi a2 y (quotient (+ (* a1 b1) r) 10) (append (list (perevodobr (remainder (+ (* a1 b1) r) 10))) spis))
(multi a2 y 0 (append (list (perevodobr (+ (* a1 b1) r))) spis))))))
(define (prog i xs ys spis)
(if (not (null? ys))
(prog (+ i 1) xs (reverse (cdr (reverse ys))) (l+ spis (razr (multi xs (list (car (reverse ys))) 0 '()) i)))
spis))
;-------------l=
(define (l= . args)
(if (null? (cdr args))
(null? (cdr args))
(if (equal? (car args) (car (cdr args)))
(l= (cdr args))
(equal? (car args) (car (cdr args))))))
;--------------l/
(define (del2 xs r spis)
(if (null? xs)
(if (equal? (car spis) #\0)
(cdr spis)
spis)
(let* ((a (perevod (car xs)))
(a1 (cdr xs))
(r1 (+ (* r 10) a)))
(del2 a1 (remainder r1 2) (append spis (list (perevodobr (quotient r1 2))))))))
(define (sr a b)
(if (and (null? a) (null? b))
(not (null? a))
(let* ((al (length a))
(bl (length b))
(a1 (perevod (car a)))
(b1 (perevod (car b))))
(if (equal? al bl)
(if (equal? a1 b1)
(sr (cdr a) (cdr b))
(> a1 b1))
(> al bl)))))
(define (del a b x b1)
(let* ((m (del2 (l+ a b) 0 '()))
(mm (l* x m)))
(if (sr (l- b (s->l "1")) a)
(if (sr mm b1)
(del a m x b1)
(del m b x b1))
m)))
(define (l-quotient a b)
(del (s->l "0") a b a))
(define (without0 a)
(if (not (null? a))
(if (equal? (car a) #\0)
(without0 (cdr a))
(cons (car a) (without0 (cdr a))))
'()))
(define (l-remainder a b)
(without0 (l- a (l* (l-quotient a b) b))))
;-------------l-factorial
(define (l-factorial a)
(define (iter a i)
(if (and (equal? a (s->l "0")) (equal? i (s->l "1")))
i
(if (equal? a (s->l "1"))
i
(iter (l- a (s->l "1")) (l* i a)))))
(iter a (s->l "1")))
| false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.