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
85ece4ca766e675dbea95155e1ce0096c84b6871
f6caa76231728a87230cf164417582609d7319a9
/a2.scm
653845760034cccfb50d708262b513ba833ebf66
[]
no_license
TMDeater/Permutation-and-Path-Length-and-orMacro
861b7488f9d225428285287c5c7e8da22b98e590
35eb3d050c3d9076ea79452dc700cd0f893dbebc
refs/heads/master
2021-06-16T10:09:03.113583
2017-04-24T11:53:31
2017-04-24T11:53:31
85,926,941
0
0
null
null
null
null
UTF-8
Scheme
false
false
5,851
scm
a2.scm
;Part1: Permutation (define (takeout x lst) (cond ;if null, return null list ((null? lst) '()) ;if equal letter, takeout the rest list ((equal? x (car lst)) (takeout x (cdr lst)) ) ;if not equal letter, construct x in the takeout list (else (cons (car lst) (takeout x (cdr lst)))) ) ) (define (permu-cal lst) (cond ;base for holding one element ((null? lst) '()) ((= (length lst) 1) (list lst) ) ;hanging combination for each element (else (apply append(map(lambda (i) (map ;add new element i to permutation j (lambda (j)(cons i j)) (permu-cal (takeout i lst)) ) ) lst) ) ) ) ) (define (permute lst) (define permuteList (permu-cal lst)) (printList permuteList) ) ;=================================================below is for list management ;print list (define (printList lst) (cond ((null? lst) #f) ;if reach the end of the list return false (else (display (car lst)) ;for each element display the element out (newline) (printList (cdr lst)) ;recurse to print the rest of the list ) ) ) ;this function will convert ((a b c) (d e f))->(("a" "b" "c")("d" "e" "f"))->("abc" "def") (define (convertPermuToString permuteList) (cond ((null? permuteList) '()) ;end of list return () for initialize the list for cons (else ;cons the changed string form element to the list (cons (apply string-append (map symbol->string (car permuteList))) (convertPermuToString (cdr permuteList)) ) ) ) ) ;this function convert ("abc" "def")->((#\a #\b #\c)(#\d #\e #\f))->(("a" "b" "c")("d" "e" "f"))->((a b c)(d e f)) (define (reverseConvertPermuToString permuteListString) (cond ((null? permuteListString) '()) ;end of list return () for initialize the list for cons (else ;cons the changed symbol form element to the list (cons (map string->symbol (map string (string->list (car permuteListString)))) (reverseConvertPermuToString (cdr permuteListString)) ) ) ) ) (define (checkContainInList lst obj) (cond ((null? lst) #f) ;search to end return false ((equal? (car lst) obj) #t) ;if found in list return true (else (cond ((equal? #t (checkContainInList (cdr lst) obj)) #t) ;else keep on search until T/F (else #f) ) ) ) ) (define (checkDictionary dictionary permuteList) (cond ((null? permuteList) '() ) ;end, do nothing , or initially the list is empty ((null? dictionary) '() ) ;no dictionary , return empty list ((equal? #t (checkContainInList dictionary (car permuteList))) ;the word is contained in dictionary so cons in list and continue search (cons (car permuteList)(checkDictionary dictionary (cdr permuteList))) ) (else ;the word car out is not in dictionary, invalid word so keep on search (checkDictionary dictionary (cdr permuteList)) ) ) ) (define (anagram dictionary lst) (define stringDict (map symbol->string dictionary)) ;change the element in dictionary from symbol to string (define permuteList (permu-cal lst)) (define permuStringList (convertPermuToString permuteList)) ;convert the permutation list to string (define result (checkDictionary stringDict permuStringList)) (define resultSymbol (reverseConvertPermuToString result)) ;convert back the string list to symbol (printList resultSymbol) ) (display '(============================Part1===========================))(newline) (display '(The following dictionary is defined for you: dictionary '(a act ale at ate cat eat etc tea) ))(newline) (display '(For the first function, when you type : (anagram dictionary '(a t e))) )(newline) (display '(The following result would be displayed:))(newline) (define dictionary '(a act ale at ate cat eat etc tea)) (anagram dictionary '(a e t)) (newline) ;========================================= ;Part2 my-or (define-macro my-or (lambda (x y) `(let ([temp ,x]) (if temp temp ,y)))) (display '(===============================Part2==========================))(newline) (display '(for original my-or macro, if you input))(newline) (display '(>(define temp 3)))(newline) (display '(>(my-or #f temp)))(newline) (display '(The result would be:))(newline) (define temp 3) (display (my-or #f temp))(newline) (define-syntax new-my-or (syntax-rules () [(new-my-or) #f] ;if no element return false [(_ element) element] ;if one element return that element [(_ x y ...) ;if two element (let ([temp x]) ;let temp be x first (if temp temp ;if temp is not false, return it (new-my-or y ...) ;if temp is false check the second element by (new-my-or y) ) ) ] ) ) (newline) (display '(for new new-my-or macro, if you input again))(newline) (display '(>(define temp 3)))(newline) (display '(>(new-my-or #f temp)))(newline) (display '(The result would be:))(newline) (display (new-my-or #f temp))(newline) (newline) (display '(if you input (new-my-or 1) the output is))(newline) (display (new-my-or 1))(newline) (newline) (display '(if you input (new-my-or 2 1) the output is))(newline) (display (new-my-or 2 1))
true
70dd002db912b434f85801f77ced669b4e0b5dfd
eef5f68873f7d5658c7c500846ce7752a6f45f69
/spheres/algorithm/random/sample-tree.scm
403cffc114e326d43d418a0c3bc9a575527f1527
[ "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
6,395
scm
sample-tree.scm
;;!!! Random sampling of trees ;; .author Oleg Kiselyov ;; .author Alvaro Castro-Castilla, 2015. See LICENSE ;;! Select a uniformly distributed random node from a tree in one pass, ;; without an a priori knowledge on the number of nodes in the tree. ;; We consider '() to be the absence of a child. Thus ;; '(a . ()) is a tree with one, left child. ;; '(() . a) is a tree with one right child. ;; We do not count leaves as nodes. Only internal nodes (aka, pairs) ;; count. ;; ;; The algorithm is an instance of a Reservoir sampling: ;; Select at random N records from a sequence -- without a ;; priori knowledge of the total number of records in a sequence ;; (provided that this number is greater than N). The method guarantees ;; that each record is selected with a probability of N/M, where M is the ;; total number of the records in the sequence. ;; ;; See ;; Reservoir Sampling ;; by Paul F. Hultquist and William R. Mahoney ;; Dr. Dobbs J., January 2001, p. 189. ;; The "Algorithm Alley" column. ;; The algorithm was originally developed by Alan Waterman. ;; ;; procedure random-node TREE -> [COUNT NODE] ;; Traverse the TREE _once_ and return COUNT, the total number of nodes ;; in the tree, and NODE -- one node of the tree selected with ;; the probability of 1/COUNT. TREE must be a pair. (define (random-node tree) ;; We assume that a procedure (random i j) returns a random integer k, ;; i <= k <= j, that is uniformly distributed within the interval [i,j] ;; (endpoints included!) (define (random a b) (+ a (random-integer (+ 1 (- b a))))) (let select ((node (car tree)) (p 1) (random-sample tree) (todo (list (cdr tree)))) (if (not (pair? node)) ; Leaves don't count (if (null? todo) (values p random-sample) (select (car todo) p random-sample (cdr todo))) (let* ((p (+ 1 p)) (k (random 1 p)) (random-sample (if (= k 1) node random-sample))) (if (pair? node) (select (car node) p random-sample (cons (cdr node) todo)) (if (null? todo) (values p random-sample) (select (car todo) p random-sample (cdr todo)))))))) ;; Same as random-node, but count leaves too. (define (random-node/leaves tree) ;; We assume that a procedure (random i j) returns a random integer k, ;; i <= k <= j, that is uniformly distributed within the interval [i,j] ;; (endpoints included!) (define (random a b) (+ a (random-integer (+ 1 (- b a))))) (let select ((node (car tree)) (p 1) (random-sample tree) (todo (list (cdr tree)))) (if (null? node) (if (null? todo) (values p random-sample) (select (car todo) p random-sample (cdr todo))) (let* ((p (+ 1 p)) (k (random 1 p)) (random-sample (if (= k 1) node random-sample))) (if (pair? node) (select (car node) p random-sample (cons (cdr node) todo)) (if (null? todo) (values p random-sample) (select (car todo) p random-sample (cdr todo)))))))) ;; Article posting headers: ;; Date: Tue, 15 Apr 2003 22:17:15 -0700 ;; Newsgroups: comp.lang.scheme ;; Subject: Re: random node in tree ;; References: <[email protected]> ;; Message-ID: <[email protected]> ;; $Id: random-tree-node.scm,v 1.1 2003/04/17 02:13:43 oleg Exp oleg $ ;; Proof of the algorithm. ;; Claim: ;; At each invocation of ;; (select node p reservoir todo) ;; p>=1 is the number of previously traversed nodes (up to but not including ;; 'node') ;; 'node' is either '() or the the (p+1)-th node of the tree ;; reservoir is the node randomly selected from the traversed ;; with the probability 1/p ;; todo is the stack of right brothers of 'node' ;; ;; Proof by induction: ;; Base case: initial invocation. ;; 'node' is the left child of the root or '(), todo a singleton list ;; that contains its right brother, p = 1 and reservoir is the traversed ;; node (which is the root). ;; Claim holds. ;; ;; Induction hypothesis: Claim holds after q nodes are traversed, ;; as we enter (select node q reservoir todo) ;; If 'node' does not count (it's '() or a leaf, if we don't count leaves) ;; we skip it and continue the pre-order traversal. ;; If 'node' is the node that counts, we set q' to q+1, k to be a ;; number uniformly distributed 1 <= k <= q'. The number k has the probability ;; 1/q' = 1/(q+1) of being 1. ;; We set reservoir to be 'node' with the probability 1/(q+1), ;; we maintain the current value of the reservoir with the probability ;; 1 - 1/(q+1) = q/(q+1). Thus reservoir is one of the q previously ;; traversed nodes selected with the probability 1/q * q/(q+1) = 1/(q+1). ;; If node has children, we recursively enter select, with ;; the first argument being the left child of 'node' or nil, ;; the second argument (q+1) -- the number of nodes traversed,-- ;; reservoir is the node selected uniformly at random from the traversed, ;; todo is the (grown) stack of the right brothers of the first argument. ;; The claim holds. ;; If 'node' is not a pair but 'todo' is not empty, we re-enter ;; select but the invariant holds. If we don't count leaves as nodes, ;; the latter alternative does not apply. ;; ;; It follows from the claim that when 'select' exits, ;; it returns the total number of nodes in the tree and one node ;; uniformly randomly selected from the them. ;; Tests ;; In the following we define (random i j) to always return its left ;; boundary. ;; (define (random i j) i) ;; With such a definition of "random", (random-node tree) will return ;; the last traversed node. ;; (define (test-random-node tree) ;; (display "Tree: ") (display tree) (newline) ;; (call-with-values ;; (lambda () (random-node tree)) ;; (lambda (count rand-node) ;; (display "total count: ") (display count) ;; (display " selected node: ") (display rand-node) ;; (newline)))) ;; (test-random-node '(a)) ;; (test-random-node '(() . (b c))) ;; (test-random-node '(() . (b . c))) ;; (test-random-node '(* (+ 3 4) 5)) ;; Results of the test runs ;; Tree: (a) ;; total count: 1 selected node: (a) ;; Tree: (() b c) ;; total count: 3 selected node: (c) ;; Tree: (() b . c) ;; total count: 2 selected node: (b . c) ;; Tree: (* (+ 3 4) 5) ;; total count: 6 selected node: (5)
false
d7d85b0da59c94d651d895e30fccca09991560bf
c63772c43d0cda82479d8feec60123ee673cc070
/ch2/65.scm
a3fd7319e7ca67d4cf762c5ebd7441e37453270a
[ "Apache-2.0" ]
permissive
liuyang1/sicp-ans
26150c9a9a9c2aaf23be00ced91add50b84c72ba
c3072fc65baa725d252201b603259efbccce990d
refs/heads/master
2021-01-21T05:02:54.508419
2017-09-04T02:48:46
2017-09-04T02:48:52
14,819,541
2
0
null
null
null
null
UTF-8
Scheme
false
false
1,452
scm
65.scm
#lang racket (require "63.scm") (require "64.scm") (define tree->list tree->list-2) (define (merge xs ys) (cond ((null? xs) ys) ((null? ys) xs) (else (let ((x (car xs)) (y (car ys)) (xt (cdr xs)) (yt (cdr ys))) (cond ((= x y) (cons x (merge xt yt))) ((< x y) (cons x (merge xt ys))) (else (cons y (merge xs yt)))))))) (define (intersect xs ys) (cond ((or (null? xs) (null? ys)) '()) (else (let ((x (car xs)) (y (car ys)) (xt (cdr xs)) (yt (cdr ys))) (cond ((= x y) (cons x (intersect xt yt))) ((< x y) (intersect xt ys)) (else (intersect xs yt))))))) ; (define (union set0 set1) ; (list->tree (merge (tree->list set0) ; (tree->list set1)))) (define (on f g) (lambda (x y) (f (g x) (g y)))) (define (.: f g) (lambda (x y) (f (g x y)))) (define (lift f) (.: list->tree (on f tree->list))) ;; Haskell style :) ;; list->tree .: (merge `on` tree->list) (define union (lift merge)) (define intersection (lift intersect)) (define *obj0* (list->tree '(1 3 5 7 9 11))) (disp *obj0*) (define *obj1* (list->tree '(1 4 7 9 13))) (disp *obj1*) (disp (union *obj0* *obj1*)) (disp (union '(7 () ()) '(9 (7 () ()) (11 () ())))) (disp (intersection '(7 () ()) '(9 (7 () ()) (11 () ()))))
false
2f438f54cfb164ef82443a7c61861b34fc404c36
a2c4df92ef1d8877d7476ee40a73f8b3da08cf81
/ch05-2.scm
46a05c5cbd4513f4b6000fdfcc95ddda2c212741
[]
no_license
naoyat/reading-paip
959d0ec42b86bc01fe81dcc3589e3182e92a05d9
739fde75073af36567fcbdf3ee97e221b0f87c8a
refs/heads/master
2020-05-20T04:56:17.375890
2009-04-21T20:01:01
2009-04-21T20:01:01
176,530
1
0
null
null
null
null
UTF-8
Scheme
false
false
7,066
scm
ch05-2.scm
(require "./cl-emu") ;;;;;;;;; (define (starts-with lis x) ;; Is this a list whose first element is x? ;(format #t "(starts-with lis:~a x:~a)\n" lis x) (and (pair? lis) (eqv? (car lis) x))) ;;;;;;;;; (define (simple-equal? x y) ;; Are x and y equal? (Don't check inside strings.) #| (if (or (cl:atom x) (cl:atom y)) (eqv? x y) (and (simple-equal? (first x) (first y)) (simple-equal? (rest x) (rest y))))) |# (if (and (pair? x) (pair? y)) (and (simple-equal? (first x) (first y)) (simple-equal? (rest x) (rest y))) (eqv? x y)) ) (define (pat-match pattern input) ;; Does pattern match input? Any variable can match anything. (if (variable? pattern) #t #| (if (or (cl:atom pattern) (cl:atom input)) (eqv? pattern input) (and (pat-match (first pattern) (first input)) (pat-match (rest pattern) (rest input)))))) |# (if (and (pair? pattern) (pair? input)) (and (pat-match (first pattern) (first input)) (pat-match (rest pattern) (rest input)) );fi (eqv? pattern input)) )) (define (variable? x) ;; Is x a variable (a symbol beginning with '?')? #;(and (symbol? x) (equal? (char (symbol-name x) 0) #\?)) (and (symbol? x) (equal? (string-ref (symbol->string x) 0) #\?))) ;#?=(pat-match '(I need a ?X) '(I need a vacation)) ;#?=(pat-match '(I need a ?X) '(I really need a vacation)) #;(define (pat-match pattern input) ;; Does pattern match input? Any variable can match anything. (if (variable? pattern) #t (every pat-match pattern input))) #| ;;Exercise 5.1 [s] ;(every pat-match pattern input) #?=(every pat-match '(a b c) '(a)) #?=(every pat-match '(I need a ?X) '(I need a vacation)) #?=(every pat-match '(I need a ?X) '(I really need a vacation)) |# ;(pat-match '(a b c) '(a)) ;(pat-match '(I need a ?X) '(I need a vacation)) ;(pat-match '(I need a ?X) '(I really need a vacation)) #;(sublis '((?X . vacation)) '(what would it mean to you if you got a ?X ?)) #;(define (pat-match pattern input) ;; Does pattern match input? ;; WARNING: buggy version (if (variable? pattern) (list (cons pattern input)) (if (and (pair? pattern) (pair? input)) (append (pat-match (first pattern) (first input)) (pat-match (rest pattern) (rest input))) (eqv? pattern input)))) ;#?=(pat-match '(I need a ?X) '(I need a vacation)) ;#?=(pat-match '(I need a ?X) '(I really need a vacation)) (define fail cl:nil ); Indicates pat-match failure (define no-bindings '((#t . #t)) ); Indicates pat-match success, with no variables (define (get-binding var bindings) ;; Find a (variable . value) pair in a binding list. (assoc var bindings)) (define (binding-val binding) ;; Get the value part of a single binding (cdr binding)) (define (lookup var bindings) ;; Get the value part (for var) from a binding list. (binding-val (get-binding var bindings))) (define (extend-bindings var val bindings) ;; Add a (var . value) pair to a binding list. (cons (cons var val) bindings)) (define (pat-match pattern input . args) (let-optionals* args ((bindings no-bindings)) (cond [(eq? bindings fail) fail] [(variable? pattern) (match-variable pattern input bindings)] [(eqv? pattern input) bindings] [(and (pair? pattern) (pair? input)) (pat-match (rest pattern) (rest input) (pat-match (first pattern) (first input) bindings))] [else fail]))) (define (match-variable var input bindings) (let1 binding (get-binding var bindings) (cond [(not binding) (extend-bindings var input bindings)] [(equal? input (binding-val binding)) bindings] [else fail]))) ;#?=(pat-match '(i need a ?X) '(i need a vacation)) (define (extend-bindings var val bindings) (cons (cons var val) (if (eq? bindings no-bindings) '() bindings))) #| #?=(sublis (pat-match '(i need a ?X) '(i need a vacation)) '(what would it mean to you if you got a ?X ?)) #?=(pat-match '(i need a ?X) '(i really need a vacation)) #?=(pat-match '(this is easy) '(this is easy)) #?=(pat-match '(?X is ?X) '((2 + 2) is 4)) #?=(pat-match '(?X is ?X) '((2 + 2) is (2 + 2))) #?=(pat-match '(?P need . ?X) '(i need a long vacation)) |# (define (pat-match pattern input . args) (let-optionals* args ((bindings no-bindings)) (cond [(eq? bindings fail) fail] [(variable? pattern) (match-variable pattern input bindings)] [(eqv? pattern input) bindings] [(segment-pattern? pattern) (segment-match pattern input bindings)] [(and (pair? pattern) (pair? input)) (pat-match (rest pattern) (rest input) (pat-match (first pattern) (first input) bindings))] [else fail]))) (define (segment-pattern? pattern) (and (pair? pattern) (starts-with (first pattern) '?*))) (define (segment-match pattern input bindings . args) (let-optionals* args ((start 0)) (let ([var (second (first pattern))] [pat (rest pattern)]) (if (null? pat) (match-variable var input bindings) ;; We assume that pat starts with a constant ;; In other words, a pattern cannot have 2 consecutive vars (let1 pos (cl:position (first pat) input :start start :test equal?) (if pos (let1 b2 (pat-match pat (subseq input pos) bindings) (if (eq? b2 fail) (segment-match pattern input bindings (+ pos 1)) (match-variable var (subseq input 0 pos) b2))) fail)))))) #;(pat-match '((?* ?p) need (?* ?x)) '(Mr Hulot and I need a vacation)) #;(pat-match '((?* ?x) is a (?* ?y)) '(what he is is a fool)) ;#?=(pat-match '((?* ?x) a b (?* ?x)) '(1 2 a b a b 1 2 a b)) ;;;;;; (define (segment-match pattern input bindings . args) (let-optionals* args ((start 0)) (let ([var (second (first pattern))] ;cadar [pat (rest pattern)]) (if (null? pat) (match-variable var input bindings) ;; We assume that pat starts with a constant ;; In other words, a pattern cannot have 2 consecutive vars (let1 pos (cl:position (first pat) input :start start :test equal?) (if pos (let1 b2 (pat-match pat (subseq input pos) ;; bindings) (match-variable var (subseq input 0 pos) bindings)) (if (eq? b2 fail) (segment-match pattern input bindings (+ pos 1)) ;; (match-variable var (subseq input 0 pos) b2))))))))) b2)) fail)))))) ;#?=(pat-match '((?* ?x) a b (?* ?x)) '(1 2 a b a b 1 2 a b)) ;#?=(pat-match '((?* ?x) a c (?* ?x)) '(1 2 a b a b 1 2 a b))
false
0c514992dac7d13cfc7beb5993ef1004d22cc1c1
d074b9a2169d667227f0642c76d332c6d517f1ba
/sicp/ch_2/exercise.2.46.scm
d2166453aaddcb5bae49962d1aaad5a0e3ec2d77
[]
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
1,536
scm
exercise.2.46.scm
#lang racket/base (require "../lib/test.rkt") (require "../lib/myutils.scm") ;; Exercise 2.46 ;; A two-dimensional vector v running from the origin to a point can ;; be represented as a pair consisting of an x-coordinate and a ;; y-coordinate. Implement a data abstraction for vectors by giving a ;; constructor `make-vect' and corresponding selectors `xcor-vect' and ;; `ycor-vect'. In terms of your selectors and constructor, implement ;; procedures `add-vect', `sub-vect', and `scale-vect' that perform ;; the operations vector addition, vector subtraction, and multiplying ;; a vector by a scalar: ;; ;; (x_1, y_1) + (x_2, y_2) = (x_1 + x_2, y_1 + y_2) ;; (x_1, y_1) - (x_2, y_2) = (x_1 - x_2, y_1 - y_2) ;; s * (x, y) = (sx, sy) (define make-vect cons) (define xcor-vect car) (define ycor-vect cdr) (define (add-vect v1 v2) (make-vect (+ (xcor-vect v1) (xcor-vect v2)) (+ (ycor-vect v1) (ycor-vect v2)))) (define (sub-vect v1 v2) (make-vect (- (xcor-vect v1) (xcor-vect v2)) (- (ycor-vect v1) (ycor-vect v2)))) (define (scale-vect v x) (make-vect (* (xcor-vect v) x) (* (ycor-vect v) x))) (let ((v1 (make-vect 3 4)) (v2 (make-vect 2 3))) (assert-equal '(3 . 4) v1) (assert-equal 3 (xcor-vect v1)) (assert-equal 4 (ycor-vect v1)) (assert-equal '(5 . 7) (add-vect v1 v2)) (assert-equal '(1 . 1) (sub-vect v1 v2)) (assert-equal '(6 . 8) (scale-vect v1 2)) (assert-equal '(3/2 . 2) (scale-vect v1 1/2))) ;; (assert-equal x y) (done)
false
541f058f22d6e9e1e9cf0ad2dff089cd0a6f4b70
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/scheme/file/file.sld
44495a5b737ad1f7c92daa40c8041a442362b489
[ "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
253
sld
file.sld
(define-library (scheme file) (namespace "") (export call-with-input-file call-with-output-file delete-file file-exists? open-binary-input-file open-binary-output-file open-input-file open-output-file with-input-from-file with-output-to-file ))
false
84c6fe64c4237e352b2dc09c003180648e018112
4678ab3f30bdca67feeb16453afc8ae26b162e51
/fmt/fmt-js.scm
280d41f2c936d5a50fb11b7a8e9ae6babd4c41f4
[ "Apache-2.0" ]
permissive
atship/thunderchez
93fd847a18a6543ed2f654d7dbfe1354e6b54c3d
717d8702f8c49ee0442300ebc042cb5982b3809b
refs/heads/trunk
2021-07-09T14:17:36.708601
2021-04-25T03:13:24
2021-04-25T03:13:24
97,306,402
0
0
null
2017-07-15T09:42:04
2017-07-15T09:42:04
null
UTF-8
Scheme
false
false
2,296
scm
fmt-js.scm
;;;; fmt-js.scm -- javascript formatting utilities ;; ;; Copyright (c) 2011-2012 Alex Shinn. All rights reserved. ;; BSD-style license: http://synthcode.com/license.txt ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (js-expr x) (fmt-let 'gen js-expr/sexp (lambda (st) (((or (fmt-gen st) js-expr/sexp) x) st)))) (define (js-expr/sexp x) (cond ((procedure? x) x) ((pair? x) (case (car x) ((%fun function) (apply js-function (cdr x))) ((%var var) (apply js-var (cdr x))) ((eq? ===) (apply js=== (cdr x))) ((>>>) (apply js>>> (cdr x))) ((%array) (js-array x)) ((%object) (js-object (cdr x))) ((%comment) (js-comment x)) (else (c-expr/sexp x)))) ((vector? x) (js-array x)) ((boolean? x) (cat (if x "true" "false"))) ((char? x) (js-expr/sexp (string x))) (else (c-expr/sexp x)))) (define (js-function . x) (let* ((name (and (symbol? (car x)) (car x))) (params (if name (cadr x) (car x))) (body (if name (cddr x) (cdr x)))) (c-block (cat "function " (dsp (or name "")) "(" (fmt-join dsp params ", ") ")") (fmt-let 'return? #t (c-in-stmt (apply c-begin body)))))) (define (js-var . args) (apply c-var 'var args)) (define (js=== . args) (apply c-op "===" args)) (define (js>>> . args) (apply c-op ">>>" args)) (define (js-comment . args) (columnar "// " (apply-cat args))) (define (js-array x) (let ((ls (vector->list x))) (c-wrap-stmt (fmt-try-fit (fmt-let 'no-wrap? #t (cat "[" (fmt-join js-expr ls ", ") "]")) (lambda (st) (let* ((col (fmt-col st)) (sep (string-append "," (make-nl-space col)))) ((cat "[" (fmt-join js-expr ls sep) "]" nl) st))))))) (define (js-pair x) (cat (js-expr (car x)) ": " (js-expr (cdr x)))) (define (js-object ls) (c-in-expr (fmt-try-fit (fmt-let 'no-wrap? #t (cat "{" (fmt-join js-pair ls ", ") "}")) (lambda (st) (let* ((col (fmt-col st)) (sep (string-append "," (make-nl-space col)))) ((cat "{" (fmt-join js-pair ls sep) "}" nl) st)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
false
d51730c3bce919265a8e4389069099d559fc7675
4f6a6e56a909ffdeb9c6a73790200a68f8f0c82c
/lib/tooling/tooling/union.scm
60737fbb41fa323d7cbc5ffd95166caea74ad6ca
[ "MIT" ]
permissive
eshoo/detroit-scheme
c5ddda1bc19ce85b87a309a2b36299e607e7da65
84c2333d1e04dd3425c2275da94375aedab34a9e
refs/heads/master
2021-01-24T23:11:27.991392
2010-03-02T02:21:45
2010-03-02T02:21:45
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
234
scm
union.scm
; Copyright (c) 2009, Raymond R. Medeiros. All rights reserved. ; (union . list) ==> list ; ; Compute the union of a number of sets. ; ; Arguments: a* - sets ; (use list-to-set) (define (union . a*) (list->set (apply append a*)))
false
fec9a03ae5862b39e50ac6773fd0336c564e11c6
382770f6aec95f307497cc958d4a5f24439988e6
/projecteuler/206/206.scm
21a035d5fa8f19ec4f83c65ca27a4899abb5f15c
[ "Unlicense" ]
permissive
include-yy/awesome-scheme
602a16bed2a1c94acbd4ade90729aecb04a8b656
ebdf3786e54c5654166f841ba0248b3bc72a7c80
refs/heads/master
2023-07-12T19:04:48.879227
2021-08-24T04:31:46
2021-08-24T04:31:46
227,835,211
1
0
null
null
null
null
UTF-8
Scheme
false
false
780
scm
206.scm
;;1_2_3_4_5_6_7_8_9_0 (define max 1929394959697989990) (define min 1020304050607080900) (define start (exact (floor (sqrt min)))) (define end (exact (ceiling (sqrt max)))) (define get-str (lambda (n) (let ([now (number->string n)]) (let f ([i 0] [nls '()]) (cond ((> i 18) (list->string (reverse nls))) (else (f (+ i 2) (cons (string-ref now i) nls)))))))) (let pro ([i start]) (cond ((= i end) #f) ((string=? (get-str (* i i)) "1234567890") i) (else (pro (+ i 10))))) #| (time (let pro ...)) 8782 collections 36.625000000s elapsed cpu time, including 0.109375000s collecting 36.720711400s elapsed real time, including 0.163024200s collecting 36985620432 bytes allocated, including 36988073160 bytes reclaimed 1389019170 |#
false
2965aed2de02e85f7ec03bda9b459aa7980cc225
d8bdd07d7fff442a028ca9edbb4d66660621442d
/scam/tests/00-syntax/define-syntax/reserved-symbols.scm
c0d26e2f0eec1a5b47c2ede55a7cb907587a51c8
[]
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
345
scm
reserved-symbols.scm
(import (only (scheme base) list) (test narc)) (narc-label "Define Syntax With Reserved Symbols") (define-syntax sym-test (syntax-rules (=> foo) ((sym-test => x xs ...) (list x x)) ((sym-test x) x))) (narc-expect (1 (sym-test 1)) ('(1 1) (sym-test => 1 2 3))) (narc-catch (:syntax (sym-test 1 2 3))) (narc-report)
true
cd2ce7c305ef1c74d699d4e2418e8e6dc8925f5d
648776d3a0d9a8ca036acaf6f2f7a60dcdb45877
/queries/yuck/locals.scm
677281b0bc984774dcf0dd57264b7659f4c4128c
[ "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
272
scm
locals.scm
[ (ast_block) (list) (array) (expr) (json_array) (json_object) (parenthesized_expression) ] @scope (symbol) @reference (keyword) @definition.field (json_object (simplexpr (ident) @definition.field)) (ast_block (symbol) (ident) @definition.type)
false
f41c901bc89192a15f3429f6117fd721571a12ac
01a7d3740477d33d84a574a909571d0128b31e43
/c34-heap.scm
54530050bd09775b1c6d59bc512555d4fe7760bd
[]
no_license
propella/3imp-westwood
7a19f2113555d7d531d6a6acd087f96fb9eb93d4
9c7912ac1b2596e62dc7736d10ef73362296c001
refs/heads/master
2021-01-23T13:23:04.505262
2010-01-12T19:51:58
2010-01-12T19:51:58
456,584
1
0
null
null
null
null
UTF-8
Scheme
false
false
3,374
scm
c34-heap.scm
;; 3.4 Implementing the Heap-Based Model (require "./c21-prims") ;; Both applications and call/cc expressions are treated slightly ;; differently if they appear in the tail position. (p59) (define tail? (lambda (next) (eq? (car next) 'return))) ;; 3.4.2 Translation. (p56) (define compile (lambda (x next) (cond [(symbol? x) (list 'refer x next)] [(pair? x) (record-case x [quote (obj) (list 'constant obj next)] [lambda (vars body) (list 'close vars (compile body '(return)) next)] [if (test then else) (let ([thenc (compile then next)] [elsec (compile else next)]) (compile test (list 'test thenc elsec)))] [set! (var x) (compile x (list 'assign var next))] [call/cc (x) (let ([c (list 'conti (list 'argument (compile x '(apply))))]) (if (tail? next) c (list 'frame next c)))] [else (recur loop ([args (cdr x)] [c (compile (car x) '(apply))]) (if (null? args) (if (tail? next) c (list 'frame next c)) (loop (cdr args) (compile (car args) (list 'argument c)))))])] [else (list 'constant x next)]))) ;; Extend builds the new environment by creating a pair from the ;; variable and value ribs. (p42, p62) (define extend (lambda (env vars vals) (cons (cons vars vals) env))) ;; 3.4.3 Evaluation. (p59) ;; a: the accumulator ;; x: the next expression ;; e: the current environment ;; r: the current value rub ;; s: the current stack (p51) (define VM (lambda (a x e r s) (record-case x [halt () a] [refer (var x) (VM (car (lookup var e)) x e r s)] [constant (obj x) (VM obj x e r s)] [close (vars body x) (VM (closure body e vars) x e r s)] [test (then else) (VM a (if a then else) e r s)] [assign (var x) (set-car! (lookup var e) a) (VM a x e r s)] [conti (x) ;(print (continuation s)) (VM (continuation s) x e r s)] ;; Save stack to the accumulator. [nuate (s var) (VM (car (lookup var e)) '(return) e r s)] [frame (ret x) (VM a x e '() (call-frame ret e r s))] [argument (x) (VM a x e (cons a r) s)] [apply () (record (body e vars) a (VM a body (extend e vars r) '() s))] [return () (record (x e r s) s (VM a x e r s))] [else (error "undefined instruction" (car x))]))) ;; Lookup is same as chapter 2.5 (define lookup (lambda (var e) (recur nxtrib ([e e]) (when (null? e) (error "lookup failed:" var)) (recur nxtelt ([vars (caar e)] [vals (cdar e)]) (cond [(null? vars) (nxtrib (cdr e))] [(eq? (car vars) var) vals] [else (nxtelt (cdr vars) (cdr vals))]))))) ;; Closure creates a new closure object, which is simply a list of a ;; body, an environment, and a list of variables. (p61) (define closure (lambda (body e vars) (list body e vars))) ;; Continuation creates a new continuation object. (p61) (define continuation (lambda (s) (closure (list 'nuate s 'v) '() '(v)))) ;; Call-frame makes a list of its arguments, a return address, an ;; environment, a rib, and a stack, i.e., the next frame in the ;; stack. (p61) (define call-frame (lambda (x e r s) ; (print 'call-frame (list x e r s)) (list x e r s))) ;; Evaluate starts things off. (p62) (define evaluate (lambda (x) (VM '() (compile x '(halt)) '() '() '())))
false
cdf675d9eede06b19cde45d698a5482fcd0dce31
5355071004ad420028a218457c14cb8f7aa52fe4
/1.2/e-1.21.scm
e35d0b4272c417750ed255fbb79857587b3702b8
[]
no_license
ivanjovanovic/sicp
edc8f114f9269a13298a76a544219d0188e3ad43
2694f5666c6a47300dadece631a9a21e6bc57496
refs/heads/master
2022-02-13T22:38:38.595205
2022-02-11T22:11:18
2022-02-11T22:11:18
2,471,121
376
90
null
2022-02-11T22:11:19
2011-09-27T22:11:25
Scheme
UTF-8
Scheme
false
false
306
scm
e-1.21.scm
; Exercise 1.21. Use the smallest-divisor procedure to find the ; smallest divisor of each of the following numbers: 199, 1999, 19999. (load "1.2.scm") (display (smallest-divisor 199)) ; 199 (newline) (display (smallest-divisor 1999)) ; 1999 (newline) (display (smallest-divisor 19999)) ; 7 (newline)
false
a236c1bf892528c6c0930f9d7a62579c232184cf
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/packages/srfi/%3a69/basic-hash-tables.sls
36818c2b2381102ddbfd46ab8f840c1b7a5baba2
[ "MIT", "X11-distribute-modifications-variant" ]
permissive
evilbinary/scheme-lib
a6d42c7c4f37e684c123bff574816544132cb957
690352c118748413f9730838b001a03be9a6f18e
refs/heads/master
2022-06-22T06:16:56.203827
2022-06-16T05:54:54
2022-06-16T05:54:54
76,329,726
609
71
MIT
2022-06-16T05:54:55
2016-12-13T06:27:36
Scheme
UTF-8
Scheme
false
false
4,842
sls
basic-hash-tables.sls
#!r6rs ;; Copyright (C) 2009 Andreas Rottmann. All rights reserved. Licensed ;; under an MIT-style license. See the file LICENSE in the original ;; collection this file is distributed with. (library (srfi :69 basic-hash-tables) (export ;; Type constructors and predicate make-hash-table hash-table? alist->hash-table ;; Reflective queries hash-table-equivalence-function hash-table-hash-function ;; Dealing with single elements hash-table-ref hash-table-ref/default hash-table-set! hash-table-delete! hash-table-exists? hash-table-update! hash-table-update!/default ;; Dealing with the whole contents hash-table-size hash-table-keys hash-table-values hash-table-walk hash-table-fold hash-table->alist hash-table-copy hash-table-merge! ;; Hashing hash string-hash string-ci-hash hash-by-identity) (import (rename (rnrs) (string-hash rnrs:string-hash) (string-ci-hash rnrs:string-ci-hash))) (define make-hash-table (case-lambda ((eql? hash) (make-hashtable hash eql?)) ((eql?) (cond ((eq? eql? eq?) (make-eq-hashtable)) ((eq? eql? eqv?) (make-eqv-hashtable)) ((eq? eql? equal?) (make-hashtable equal-hash eql?)) ((eq? eql? string=?) (make-hashtable rnrs:string-hash eql?)) ((eq? eql? string-ci=?) (make-hashtable rnrs:string-ci-hash eql?)) (else (assertion-violation 'make-hash-table "unrecognized equivalence predicate" eql?)))) (() (make-hashtable equal-hash equal?)))) (define hash-table? hashtable?) (define not-there (list 'not-there)) (define (alist->hash-table alist . args) (let ((table (apply make-hash-table args))) (for-each (lambda (entry) (hashtable-update! table (car entry) (lambda (x) (if (eq? x not-there) (cdr entry) x)) not-there)) alist) table)) (define hash-table-equivalence-function hashtable-equivalence-function) (define hash-table-hash-function hashtable-hash-function) (define (failure-thunk who key) (lambda () (assertion-violation who "no association for key" key))) (define hash-table-ref (case-lambda ((table key thunk) (let ((val (hashtable-ref table key not-there))) (if (eq? val not-there) (thunk) val))) ((table key) (hash-table-ref table key (failure-thunk 'hash-table-ref key))))) (define hash-table-ref/default hashtable-ref) (define hash-table-set! hashtable-set!) (define hash-table-delete! hashtable-delete!) (define hash-table-exists? hashtable-contains?) (define hash-table-update! (case-lambda ((table key proc thunk) (hashtable-update! table key (lambda (val) (if (eq? val not-there) (thunk) (proc val))) not-there)) ((table key proc) (hash-table-update! table key proc (failure-thunk 'hash-table-update! key))))) (define hash-table-update!/default hashtable-update!) (define hash-table-size hashtable-size) (define (hash-table-keys table) (vector->list (hashtable-keys table))) (define (hash-table-values table) (let-values (((keys values) (hashtable-entries table))) (vector->list values))) (define (hash-table-walk table proc) (let-values (((keys values) (hashtable-entries table))) (vector-for-each proc keys values))) (define (hash-table-fold table kons knil) (let-values (((keys values) (hashtable-entries table))) (let ((size (vector-length keys))) (let loop ((i 0) (val knil)) (if (>= i size) val (loop (+ i 1) (kons (vector-ref keys i) (vector-ref values i) val))))))) (define (hash-table->alist table) (hash-table-fold table (lambda (k v l) (cons (cons k v) l)) '())) (define hash-table-copy hashtable-copy) (define (hash-table-merge! table1 table2) (hash-table-walk table2 (lambda (k v) (hashtable-set! table1 k v))) table1) (define (make-hasher hash-proc) (case-lambda ((obj) ;; R6RS doesn't guarantee that the result of the hash procedure ;; is non-negative, so we use mod. (mod (hash-proc obj) (greatest-fixnum))) ((obj bound) (mod (hash-proc obj) bound)))) (define hash (make-hasher equal-hash)) (define hash-by-identity (make-hasher equal-hash)) ;; Very slow. (define string-hash (make-hasher rnrs:string-hash)) (define string-ci-hash (make-hasher rnrs:string-ci-hash)) )
false
d5078eca16bfcfdba4a503951274157dd6d9e655
c3523080a63c7e131d8b6e0994f82a3b9ed901ce
/hertfordstreet/schemes/evenmorelists.scm
b67b0804790a769a658a7d3d5c3e6354684ad246
[]
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
726
scm
evenmorelists.scm
(define a (list 1 2)) (define b (list 3 4)) (define l (list a b)) (define q (list 1 2 3 4)) (define (atom? x) (not (pair? x))) (define (reverse l) (if (null? l) l (append (reverse (cdr l))(list (car l))))) q (reverse q) l (reverse l) (define (deep-reverse l) (cond ((atom? l) l) (else (append (deep-reverse (cdr l))(list (deep-reverse (car l))))))) (deep-reverse l) (define (iter-reverse l) (define (reverse-helper a b) (if (null? a) b (reverse-helper (cdr a)(cons (car a) b)))) (reverse-helper l ())) (iter-reverse l) (define (fringe l) (cond ((null? l) ()) ((atom? l) (list l)) (else (append (fringe (car l)) (fringe (cdr l)))))) (list l l q) (fringe (list l l q))
false
0871683907ad21e0a846506bc0aa2d4717392c04
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/threading/mutex.sls
f24b0a976ec95528c9083624871daa736b133233
[]
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,104
sls
mutex.sls
(library (system threading mutex) (export new is? mutex? set-access-control release-mutex open-existing get-access-control) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Threading.Mutex a ...))))) (define (is? a) (clr-is System.Threading.Mutex a)) (define (mutex? a) (clr-is System.Threading.Mutex a)) (define-method-port set-access-control System.Threading.Mutex SetAccessControl (System.Void System.Security.AccessControl.MutexSecurity)) (define-method-port release-mutex System.Threading.Mutex ReleaseMutex (System.Void)) (define-method-port open-existing System.Threading.Mutex OpenExisting (static: System.Threading.Mutex System.String System.Security.AccessControl.MutexRights) (static: System.Threading.Mutex System.String)) (define-method-port get-access-control System.Threading.Mutex GetAccessControl (System.Security.AccessControl.MutexSecurity)))
true
fd3a365c333378f08b54779e09e2fd56268d4c96
5d06c6072f6bab2882b0a18a7aee395e9295925f
/seminars/09/streams.scm
392b2b850f4fa601ef1139498833242eaf88ee3a
[]
no_license
timadevelop/functional-programming
3ad73dad38a0f6d4258230a35f999e2fb4d1dc55
7d23f94589668671db36b3141efa970b6827a23e
refs/heads/master
2021-05-03T14:33:33.823055
2018-02-15T13:57:44
2018-02-15T13:57:44
120,458,222
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,033
scm
streams.scm
#lang scheme (define the-empty-stream '()) ;(define (cons-stream h t) (cons h (delay t))) (define head car) (define (tail s) (force (cdr s))) (define empty-stream? null?) (define s (cons-stream 1 (cons-stream 2 (cons-stream 3 the-empty-stream)))) ;(head s) ;; 1 ;(tail s) ;; (2.promise) ;(head (tail s)) ;; 2 ;(head (tail (tail s))) ;; 3 ;; error bcs of substitution model ;; (cons-stream 3 <....all this must be a promise>) ;(define s2 (cons-stream 3 (cons-stream ; b ; the-empty-stream))) ;; --> we need a special form for (cons-stream) (define-syntax delay (syntax-rules () ((delay x) (lambda() x)))) (define-syntax cons-stream (syntax-rules () ((cons-stream h t) (cons h (delay t))))) ;(define s2 (cons-stream ; 3 ; (cons-stream ; b the-empty-stream))) ;; ? TODO ;; zad (define (enum a b) (if (> a b) the-empty-stream (cons-stream a (enum (+ 1 a) b)))) (define (first n s) (if (or (empty-stream? s) (= 0 n)) '() (cons (head s) (first (- n 1) (tail s))))) (define (search-stream p? s) (cond ((empty-stream? s) #f) ((p? (head s)) s) (else (search-stream p? (tail s))))) ;; indirect (define (generate-fibs a b) (cons-stream a (generate-fibs b (+ a b)))) (define fibs (generate-fibs 0 1)) ;; high-order procedures (define (map-stream f s) (cons-stream (f (head s)) (map-stream f (tail s)))) (define (filter-stream p? s) (if (p? (head s)) (cons-stream (head s) (filter-stream p? (tail s))) (filter-stream p? (tail s)))) (define (zip-stream op s1 s2) (cons-stream (op (head s1) (head s2)) (zip-stream (tail s1) (tail s2)))) ;; direct resursion (define (1+ x) (+ x 1)) (define ones (cons-stream 1 ones)) (define nats (cons-stream 0 (map-stream 1+ nats)))
true
0b9b177c67b9b8196d3c86ede901f1a7fa1ef04a
961ccc58c2ed4ed1d84a78614bedf0d57a2f2174
/scheme/chapter2/same-parity.scm
82a368f202bdb707f40378bdcb1a9c300f5f9d18
[]
no_license
huangjs/mostly-lisp-code
96483b566b8fa72ab0b73bf0e21f48cdb80dab0d
9fe862dbb64f2a28be62bb1bd996238de018f549
refs/heads/master
2021-01-10T10:11:50.121705
2015-11-01T08:53:22
2015-11-01T08:53:22
45,328,850
0
0
null
null
null
null
UTF-8
Scheme
false
false
276
scm
same-parity.scm
;:*======================= ;:* the test of dotted-tail notation which can accept arbitrary numbers of arguments. (define (same-parity a . items) (define (same-parity? b) (cond ((odd? a) (odd? b)) ((even? a) (even? b)))) (cons a (filter items same-parity?)))
false
c05959ca12b937ddc20d1205f4e7d90a6b12502d
2e50e13dddf57917018ab042f3410a4256b02dcf
/t/byteio.scm
e0770a270237c5af5e653f26595f065a31e9fa13
[ "MIT" ]
permissive
koba-e964/picrin
c0ca2596b98a96bcad4da9ec77cf52ce04870482
0f17caae6c112de763f4e18c0aebaa73a958d4f6
refs/heads/master
2021-01-22T12:44:29.137052
2016-07-10T16:12:36
2016-07-10T16:12:36
17,021,900
0
0
MIT
2019-05-17T03:46:41
2014-02-20T13:55:33
Scheme
UTF-8
Scheme
false
false
898
scm
byteio.scm
(import (scheme base) (scheme write) (scheme file)) (let ((string-port (open-input-string "hello"))) (display "read-string: ") (write (read-string 4 string-port)) (newline) (display "read-string more: ") (write (read-string 4 string-port)) (newline)) (let ((byte-port (open-input-bytevector (bytevector 1 2 3 4 5 6 7 8))) (buf (make-bytevector 4 98))) (display "read-u8: ") (write (read-u8 byte-port)) (newline) (display "peek-u8: ") (write (peek-u8 byte-port)) (newline) (display "read-bytevector: ") (write (read-bytevector 4 byte-port)) (newline) (display "read-bytevector!: read size: ") (write (read-bytevector! buf byte-port 1 3)) (display ": read content: ") (write buf) (newline) (display "read-bytevector!: read size: ") (write (read-bytevector! buf byte-port)) (display ": read content: ") (write buf) (newline))
false
c919c988757faaa4f85c13eed0cf3f6ed181d3da
b60cb8e39ec090137bef8c31ec9958a8b1c3e8a6
/test/R5RS/VUB-projects/mountainvale.scm
8a20f0eff0a87a8f433e6dbbba549c4a0a56101b
[]
no_license
acieroid/scala-am
eff387480d3baaa2f3238a378a6b330212a81042
13ef3befbfc664b77f31f56847c30d60f4ee7dfe
refs/heads/master
2021-01-17T02:21:41.692568
2021-01-15T07:51:20
2021-01-15T07:51:20
28,140,080
32
16
null
2020-04-14T08:53:20
2014-12-17T14:14:02
Scheme
UTF-8
Scheme
false
false
350,237
scm
mountainvale.scm
;; Copyright 2001 Tom Van Cutsem ;; ;; 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. ;; Notice: this file contains a modified version of the original program written by Tom Van Cutsem. This file also is a merger of all files involved in the original program. ;; Some, but not all, modifications have been indicated in comments. Significant changes have been made to the file icons.scm, as our implementation does not support icons. ;; Dummy variables have been introduced to avoid top-level defines being interleaved with program expressions. ;; Extra code to avoid user input. (define user-inputs '(Tom help necromancer yes Coen monk no yes difficulty hard (GAME SETUP OPTIONS) icons off (Coen LOOKS AROUND) (Tom CASTS summon_deamon) (Coen ATTACKS Tom) melee (Coen FLEES) (Tom ASKS spellbook) (Tom CASTS curse) yeran (Coen LOOKS AROUND) (Coen MOVES south) (Coen MOVES east) (Coen GETS lightning-bolt) (Tom ASKS STATUS) (Coen STEALS) (Tom ASKS EXITS) (Coen DROPS ALL) (GAME QUIT Tom) (GAME QUIT Coen))) (define (read) (if (null? user-inputs) (error "No more user inputs.") (let ((first (car user-inputs))) (set! user-inputs (cdr user-inputs)) first))) ;; ;; MOUNTAINVALE ;; ;;Binary Search Tree ADT (define (create-bst . options) ;;Takes a conscell '(key . data) as input (let ((content '()) (same? (if (null? options) = (car options))) (less? (if (null? options) < (cadr options)))) ;node abstraction (define (key-item item) (car item)) (define (content-item item) (cdr item)) (define (make-node item left right) (list item left right)) (define (node-item node) (car node)) (define (node-left node) (cadr node)) (define (node-right node) (caddr node)) (define (node-set-item! node item) (set-car! node item)) (define (node-set-left! node son) (set-car! (cdr node) son)) (define (node-set-right! node son) (set-car! (cddr node) son)) (define null-tree '()) (define (null-tree? tree) (null? tree)) (define (is-leaf? node) (and (null-tree? (node-left node)) (null-tree? (node-right node)))) ;non basic operations (define (traverse tree order action) (define (traverse-preorder tree) (cond ((null-tree? tree) #t) (else (action (content-item (node-item tree))) (traverse-preorder (node-left tree)) (traverse-preorder (node-right tree))))) (define (traverse-inorder tree) (cond ((null-tree? tree) #t) (else (traverse-inorder (node-left tree)) (action (content-item (node-item tree))) (traverse-inorder (node-right tree))))) (define (traverse-postorder tree) (cond ((null-tree? tree) #t) (else (traverse-postorder (node-left tree)) (traverse-postorder (node-right tree)) (action (content-item (node-item tree)))))) (case order ((preorder) (traverse-preorder tree)) ((inorder) (traverse-inorder tree)) ((postorder) (traverse-postorder tree)) (else (error "Unknown tree traversal order")))) (define (tree-acc tree operator init function) (define (acc-aux tree) (if (null-tree tree) init (operator (function (content-item (node-item tree))) (acc-aux (node-left tree)) (acc-aux (node-right tree))))) (acc-aux tree)) ;operations (define (empty?) (null-tree? content)) (define (lookup element) (define (lookup-aux node) (cond ((null-tree? node) #f) ((same? element (key-item (node-item node))) (content-item (node-item node))) ((less? element (key-item (node-item node))) (lookup-aux (node-left node))) (else (lookup-aux (node-right node))))) (lookup-aux content)) (define (insert element) (define (insert-aux node parent) (cond ((null-tree? node) (let ((new-node (make-node element null-tree null-tree))) (if parent (if (less? (key-item element) (key-item (node-item parent))) (node-set-left! parent new-node) (node-set-right! parent new-node)) (set! content new-node))) #t) ((less? (key-item element) (key-item (node-item node))) (insert-aux (node-left node) node)) (else (insert-aux (node-right node) node)))) (insert-aux content #f)) (define (delete element) (define (replace parent node new-node) (if (eq? (node-left parent) node) (node-set-left! parent new-node) (node-set-right! parent new-node))) (define (parent-of-leftmost-node node parent) (if (null-tree? (node-left node)) parent (parent-of-leftmost-node (node-left node) node))) (define (delete-aux node parent) (cond ((null-tree? node) #f) ((same? element (key-item (node-item node))) (cond ((null-tree? (node-left node)) ; node has no left child (if parent (replace parent node (node-right node)) (set! content (node-right node)))) ((null-tree? (node-right node)) ; node has no right child (if parent (replace parent node (node-left node)) (set! content (node-left node)))) (else ; node has two children (let ((temp (parent-of-leftmost-node (node-right node) #f))) (if (not temp) (begin (node-set-item! node (node-item (node-right node))) (node-set-right! node (node-right (node-right node)))) (begin (node-set-item! node (node-item (node-left temp))) (node-set-left! temp (node-right (node-left temp)))))))) #t) ((less? element (key-item (node-item node))) (delete-aux (node-left node) node)) (else (delete-aux (node-right node) node)))) (delete-aux content #f)) (define (map a-function) (tree-acc content make-node null-tree a-function)) (define (for-each-element a-action) (traverse content 'inorder a-action)) (define (dispatch msg . args) (cond ((eq? msg 'empty?) (empty?)) ((eq? msg 'insert) (insert (car args))) ((eq? msg 'delete) (delete (car args))) ((eq? msg 'lookup) (lookup (car args))) ((eq? msg 'map) (map (car args))) ((eq? msg 'for-each) (for-each-element (car args))) ((eq? msg 'display) (for-each-element (lambda (x) (display x) (newline)))) (else (error "unknown request -- create-BST" msg)))) dispatch)) ;;Red Black Tree ADT, changed the input to take an element of the form (key . sattelite data) (define (create-redblack-tree . options) (define (make-null-tree) (list (cons (cons 'leaf 'leaf) 'black) '() '() '())) (let* ((content (make-null-tree)) (same? (if (null? options) equal? (car options))) (less? (if (null? options) < (cadr options)))) ;node abstraction (define (get-node-key item) (car item)) (define (get-node-info item) (cdr item)) (define (make-node item left right parent) (list (cons item 'red) left right parent)) (define (node-item node) (car (car node))) (define (node-color node) (cdr (car node))) (define (node-left node) (cadr node)) (define (node-right node) (caddr node)) (define (node-parent node) (cadddr node)) (define (node-set-item! node item) (set-car! (car node) item)) (define (node-set-color! node color) (set-cdr! (car node) color)) (define (node-set-color-red! node) (set-cdr! (car node) 'red)) (define (node-set-color-black! node) (set-cdr! (car node) 'black)) (define (node-set-left! node son) (set-car! (cdr node) son)) (define (node-set-right! node son) (set-car! (cddr node) son)) (define (node-set-parent! node parent) (set-car! (cdddr node) parent)) (define (null-tree? tree) (eq? 'leaf (get-node-key (node-item tree)))) (define (is-leaf? node) (and (null-tree? (node-left node)) (null-tree? (node-right node)))) (define (traverse tree order action) (define (traverse-preorder tree) (cond ((null-tree? tree) #t) (else (action (node-item tree) (node-color tree)) (traverse-preorder (node-left tree)) (traverse-preorder (node-right tree))))) (define (traverse-inorder tree) (cond ((null-tree? tree) #t) (else (traverse-inorder (node-left tree)) (action (node-item tree) (node-color tree)) (traverse-inorder (node-right tree))))) (define (traverse-postorder tree) (cond ((null-tree? tree) #t) (else (traverse-postorder (node-left tree)) (traverse-postorder (node-right tree)) (action (node-item tree) (node-color tree))))) (case order ((preorder) (traverse-preorder tree)) ((inorder) (traverse-inorder tree)) ((postorder) (traverse-postorder tree)) (else (error "Unknown tree traversal order")))) (define (tree-acc tree operator init function) (define (acc-aux tree) (if (null-tree? tree) init (operator (function (get-node-info (node-item tree))) (acc-aux (node-left tree)) (acc-aux (node-right tree)) '()))) (acc-aux tree)) ;rotation operations (define (left-rotate node-x) (let ((node-y (node-right node-x))) (if (null-tree? node-y) 'done (begin (node-set-right! node-x (node-left node-y)) (node-set-parent! (node-left node-y) node-x) (node-set-parent! node-y (node-parent node-x)) (if (not (null-tree? (node-parent node-x))) (if (same? (get-node-key (node-item node-x)) (get-node-key (node-item (node-left (node-parent node-x))))) (node-set-left! (node-parent node-x) node-y) (node-set-right! (node-parent node-x) node-y)) (set! content node-y)) (node-set-left! node-y node-x) (node-set-parent! node-x node-y))))) (define (right-rotate node-y) (let ((node-x (node-left node-y))) (if (null-tree? node-x) 'done (begin (node-set-left! node-y (node-right node-x)) (node-set-parent! (node-right node-x) node-y) (node-set-parent! node-x (node-parent node-y)) (if (not (null-tree? (node-parent node-y))) (if (same? (get-node-key (node-item node-y)) (get-node-key (node-item (node-left (node-parent node-y))))) (node-set-left! (node-parent node-y) node-x) (node-set-right! (node-parent node-y) node-x)) (set! content node-x)) (node-set-right! node-x node-y) (node-set-parent! node-y node-x))))) (define (parent-is-in node-x node-branch then-rotate other-rotate) (let ((node-y (node-branch (node-parent (node-parent node-x))))) (cond ((equal? 'red (node-color node-y)) (node-set-color-black! (node-parent node-x)) (node-set-color-black! node-y) (node-set-color-red! (node-parent (node-parent node-x))) (evaluate-redblack-conditions (node-parent (node-parent node-x)))) (else (if (and (not (null-tree? (node-branch (node-parent node-x)))) (same? (get-node-key (node-item node-x)) (get-node-key (node-item (node-branch (node-parent node-x)))))) (begin (set! node-x (node-parent node-x)) (then-rotate node-x))) (node-set-color-black! (node-parent node-x)) (node-set-color-red! (node-parent (node-parent node-x))) (other-rotate (node-parent (node-parent node-x))) (evaluate-redblack-conditions node-x))))) (define (evaluate-redblack-conditions node-x) (if (and (not (same? (get-node-key (node-item node-x)) (get-node-key (node-item content)))) (equal? 'red (node-color (node-parent node-x))) (not (null-tree? (node-parent (node-parent node-x))))) (cond ((and (not (null-tree? (node-left (node-parent (node-parent node-x))))) (same? (get-node-key (node-item (node-parent node-x))) (get-node-key (node-item (node-left (node-parent (node-parent node-x))))))) (parent-is-in node-x node-right left-rotate right-rotate)) (else (parent-is-in node-x node-left right-rotate left-rotate))))) (define (child-is-in node-x main-branch other-branch main-rotate other-rotate) (let ((node-w (main-branch (node-parent node-x)))) (if (equal? 'red (node-color node-w)) (begin (node-set-color-red! (node-parent node-x)) (node-set-color-black! node-w) (main-rotate (node-parent node-x)) (set! node-w (main-branch (node-parent node-x))))) (if (and (not (null-tree? node-w)) (eq? 'black (node-color (node-left node-w))) (eq? 'black (node-color (node-right node-w)))) (begin (node-set-color-red! node-w) (fixup-redblack-conditions (node-parent node-x))) (begin (if (and (not (null-tree? node-w)) (eq? 'black (node-color (main-branch node-w)))) (begin (node-set-color-black! (other-branch node-w)) (node-set-color-red! node-w) (other-rotate node-w) (set! node-w (main-branch (node-parent node-w))))) (node-set-color! node-w (node-color (node-parent node-x))) (node-set-color-black! (node-parent node-x)) (if (not (null-tree? node-w)) (node-set-color-black! (main-branch node-w))) (main-rotate (node-parent node-x)) (fixup-redblack-conditions content))))) (define (fixup-redblack-conditions node-x) (if (and (not (same? (get-node-key (node-item node-x)) (get-node-key (node-item content)))) (equal? 'black (node-color node-x))) (cond ((same? (get-node-key (node-item node-x)) (get-node-key (node-item (node-left (node-parent node-x))))) (child-is-in node-x node-right node-left left-rotate right-rotate)) (else (child-is-in node-x node-left node-right right-rotate left-rotate))) (node-set-color-black! node-x))) ;operations (define (empty?) (null-tree? content)) (define (lookup element) (define (lookup-aux node) (cond ((null-tree? node) #f) ((same? element (get-node-key (node-item node))) (get-node-info (node-item node))) ((less? element (get-node-key (node-item node))) (lookup-aux (node-left node))) (else (lookup-aux (node-right node))))) (lookup-aux content)) (define (insert element) (define (insert-aux node parent) (cond ((null-tree? node) (let ((new-node (make-node element (make-null-tree) (make-null-tree) (make-null-tree)))) (node-set-parent! (node-left new-node) new-node) (node-set-parent! (node-right new-node) new-node) (if (not (null-tree? parent)) (begin (node-set-parent! new-node parent) (if (less? (get-node-key element) (get-node-key (node-item parent))) (node-set-left! parent new-node) (node-set-right! parent new-node)) (evaluate-redblack-conditions new-node)) (begin (set! content new-node))) (node-set-color-black! content) #t)) ((less? (get-node-key element) (get-node-key (node-item node))) (insert-aux (node-left node) node)) (else (insert-aux (node-right node) node)))) (insert-aux content (make-null-tree))) (define (delete element) (define (left-most-node node parent) (if (null-tree? (node-left node)) node (left-most-node (node-left node) node))) (define (delete-aux node) (cond ((null-tree? node) #f) ((same? element (get-node-key (node-item node))) (let* ((node-y (if (or (null-tree? (node-left node)) (null-tree? (node-right node))) node (left-most-node (node-right node) #f))) (node-x (if (null-tree? (node-left node-y)) (node-right node-y) (node-left node-y)))) (node-set-parent! node-x (node-parent node-y)) (if (null-tree? (node-parent node-y)) (set! content node-x) (if (and (not (null-tree? (node-left (node-parent node-y)))) (same? (get-node-key (node-item node-y)) (get-node-key (node-item (node-left (node-parent node-y)))))) (node-set-left! (node-parent node-y) node-x) (node-set-right! (node-parent node-y) node-x))) (if (not (same? (get-node-key (node-item node-y)) (get-node-key (node-item node)))) (begin (node-set-item! node (node-item node-y)))) (if (eq? 'black (node-color node-y)) (fixup-redblack-conditions node-x)) #t)) ((less? element (get-node-key (node-item node))) (delete-aux (node-left node))) (else (delete-aux (node-right node))))) (delete-aux content)) (define (display-rb-tree) (traverse content 'preorder (lambda (element color) (display "key: ") (display (get-node-key element)) (display " content: ") (display-line (get-node-info element))))) (define (rb-tree-foreach a-function) (traverse content 'inorder (lambda (element color) (a-function (get-node-info element))))) ;;expects procedure of 2 args: key and info (define (dispatch msg . args) (cond ((eq? msg 'empty?) (empty?)) ((eq? msg 'insert) (insert (car args))) ;;expects conscell (key . satelite data) ((eq? msg 'delete) (delete (car args))) ((eq? msg 'lookup) (lookup (car args))) ((eq? msg 'for-each) (rb-tree-foreach (car args))) ((eq? msg 'map) (tree-acc content make-node (make-null-tree) (car args))) ((eq? msg 'display) (display-rb-tree)) (else (error "unknown request -- create RBT" msg)))) dispatch)) ;;Changed Priority Queue ADT ;;Element abstractions (define (make-item priority element) (cons priority element)) (define (get-priority item) (car item)) (define (get-element item) (cdr item)) (define (create-priority-queue) (let ((front (cons 'boe '()))) (define (content) (cdr front)) (define (insert-after! cell item) (let ((new-cell (cons item '()))) (set-cdr! new-cell (cdr cell)) (set-cdr! cell new-cell))) (define (find-prev-cell priority) (define (find-iter rest prev) (cond ((null? rest) prev) ((<= (get-priority (car rest)) priority) (find-iter (cdr rest) rest)) (else prev))) (find-iter (content) front)) (define (empty?) (null? (content))) (define (enqueue element priority) (insert-after! (find-prev-cell priority) (make-item priority element)) #t) (define (dequeue) (if (null? (content)) #f (let ((temp (car (content)))) (set-cdr! front (cdr (content))) (get-element temp)))) (define (serve) (if (null? (content)) #f (car (content)))) (define (do-for-each afunction) (define (iter content) (if (null? content) 'done (begin (afunction (car content)) (iter (cdr content))))) (iter (content))) (define (delete element) (define (iter content) (cond ((null? (cdr content)) #f) ((eq? (get-element (car (cdr content))) element) (set-cdr! content (cdr (cdr content))) #t) (else (iter (cdr content))))) (iter front)) (define (dispatch m . args) (cond ((eq? m 'empty?) (empty?)) ((eq? m 'enqueue) (enqueue (car args) (cadr args))) ((eq? m 'dequeue) (dequeue)) ((eq? m 'serve) (serve)) ((eq? m 'for-each) (do-for-each (car args))) ((eq? m 'delete) (delete (car args))) (else (error "unknown request -- create-priority-queue" m)))) dispatch)) ;;Graph ADT, Edge list representation (define (create-graph eq-label-ft directed? weighted?) (let ((nodes '())) ;edge abstraction (define (make-edge node1 node2 . info) (if weighted? (list node1 node2 '() (car info)) (list node1 node2 '() 'notused))) (define (get-first-node edge) (car edge)) (define (get-second-node edge) (cadr edge)) (define (get-next-edge edge) (caddr edge)) (define (set-next-edge! edge next-edge) (set-car! (cddr edge) next-edge)) (define (get-edge-info edge) (cadddr edge)) (define (set-edge-info! edge info) (set-car! (cdddr edge) info)) ;node abstraction (define (make-node label info . status) (list label info '() (if (null? status) 'not-used (car status)))) (define (get-label node) (car node)) (define (set-label! node label) (set-car! node label)) (define (get-node-info node) (cadr node)) (define (set-node-info! node a-info) (set-car! (cdr node) a-info)) (define (get-node-status node) (cadddr node)) (define (set-node-status! node status) (set-car! (cdddr node) status)) (define (get-edges node) (caddr node)) (define (set-edges! node edges) (set-car! (cddr node) edges)) (define (add-to-edges node edge) (set-next-edge! edge (get-edges node)) (set-edges! node edge)) (define (find-node label) (define (find-iter current) (cond ((null? current) #f) ((eq-label-ft label (get-label (car current))) (car current)) (else (find-iter (cdr current))))) (find-iter nodes)) (define (find-edge label1 label2) (define (find-iter current node) (cond ((null? current) #f) ((eq? node (get-second-node current)) current) (else (find-iter (get-next-edge current) node)))) (let ((node1 (find-node label1)) (node2 (find-node label2))) (if directed? (if (and node1 node2) (find-iter (get-edges node1) node2) #f) (if (and node1 node2) (cons (find-iter (get-edges node1) node2) (find-iter (get-edges node2) node1)) (cons #f #f))))) (define (insert-node label info) (let ((node (find-node label))) (cond (node (set-node-info! node info)) (else (set! nodes (cons (make-node label info) nodes)) #t)))) (define (insert-edge label1 label2 . info) (let ((edge (find-edge label1 label2))) (cond ((and directed? edge) (if weighted? (set-edge-info! edge (car info))) #t) ((and (not directed?) (car edge) (cdr edge)) (if weighted? (begin (set-edge-info! (car edge) (car info)) (set-edge-info! (cdr edge) (car info)))) #t) (else (let* ((node1 (find-node label1)) (node2 (find-node label2))) (if (and node1 node2) (let ((edge (if weighted? (make-edge node1 node2 (car info)) (make-edge node1 node2)))) (if directed? (add-to-edges node1 edge) (let ((edge-dupl (if weighted? (make-edge node2 node1 (car info)) (make-edge node2 node1)))) (add-to-edges node1 edge) (add-to-edges node2 edge-dupl))) #t) #f)))))) (define (delete-edge label1 label2) (define (delete-iter current previous node1 node2) (cond ((null? current) #f) ((eq? (get-second-node current) node2) (if previous (set-next-edge! previous (get-next-edge current)) (set-edges! node1 (get-next-edge current))) #t) (else (delete-iter (get-next-edge current) current node1 node2)))) (let ((node1 (find-node label1)) (node2 (find-node label2))) (if (and node1 node2) (if directed? (delete-iter (get-edges node1) #f node1 node2) (and (delete-iter (get-edges node1) #f node1 node2) (delete-iter (get-edges node2) #f node2 node1))) #f))) (define (delete-node label) (define (delete-iter current prev) (cond ((null? current) #f) ((eq-label-ft label (get-label (car current))) (foreach-neighbour label (lambda (from-lbl from-info to-lbl to-info edge-info) (delete-edge from-lbl to-lbl))) (if prev (set-cdr! prev (cdr current)) (set! nodes (cdr nodes))) #t) (else (delete-iter (cdr current) current)))) (delete-iter nodes #f)) (define (lookup-node-info label) (let ((node (find-node label))) (if node (get-node-info node) #f))) (define (change-node-info label info) (let ((node (find-node label))) (if node (set-node-info! node info) #f))) (define (lookup-node-status label) (let ((node (find-node label))) (if node (get-node-status node) #f))) (define (change-node-status label status) (let ((node (find-node label))) (if node (set-node-status! node status) #f))) (define (lookup-edge label1 label2) (let ((edge (find-edge label1 label2))) (if directed? (if edge (if weighted? (get-edge-info edge) #t) #f) (if (and (car edge) (cdr edge)) (if weighted? (get-edge-info (car edge)) #t) #f)))) (define (empty?) (null? nodes)) (define (map-over-nodes a-function) ;a-function takes two argument, i.e. label and info of the node (define (map-iter current result) (if (null? current) (reverse result) (map-iter (cdr current) (cons (a-function (get-label (car current)) (get-node-info (car current))) result)))) (map-iter nodes '())) (define (foreach-node a-action) ;a-action takes two argument, i.e. label and info of the node (define (foreach-iter current) (cond ((null? current) #t) (else (a-action (get-label (car current)) (get-node-info (car current))) (foreach-iter (cdr current))))) (foreach-iter nodes)) (define (map-over-neighbours label a-function) ;;a-function takes 5 arguments ;;from-label from-info to-label to-info edge-info ;;edge-info is not used in a non weighted graph (let ((node (find-node label))) (define (edges-iter current result) (if (null? current) result (let* ((neigbour-node (get-second-node current)) (res (a-function (get-label node) (get-node-info node) (get-label neigbour-node) (get-node-info neigbour-node) (get-edge-info current)))) (edges-iter (get-next-edge current) (cons res result))))) (if node (edges-iter (get-edges node) '()) #f))) (define (foreach-neighbour label a-action) ;;a-action takes 5 arguments ;;from-label from-info to-label to-info edge-info ;;edge-info is not used in a non weighted graph (let ((node (find-node label))) (define (edges-iter current) (if (null? current) #t (let* ((neigbour-node (get-second-node current))) (a-action (get-label node) (get-node-info node) (get-label neigbour-node) (get-node-info neigbour-node) (get-edge-info current)) (edges-iter (get-next-edge current))))) (if node (edges-iter (get-edges node)) #f))) (define (dispatch msg . args) (cond ((eq? msg 'empty?) (empty?)) ((eq? msg 'insert-node) (apply insert-node args)) ((eq? msg 'delete-node) (apply delete-node args)) ((eq? msg 'insert-edge) (apply insert-edge args)) ((eq? msg 'delete-edge) (apply delete-edge args)) ((eq? msg 'lookup-node-info) (apply lookup-node-info args)) ((eq? msg 'change-node-info) (apply change-node-info args)) ((eq? msg 'lookup-node-status) (apply lookup-node-status args)) ((eq? msg 'change-node-status) (apply change-node-status args)) ((eq? msg 'lookup-edge) (apply lookup-edge args)) ((eq? msg 'map-over-nodes) (apply map-over-nodes args)) ((eq? msg 'foreach-node) (apply foreach-node args)) ((eq? msg 'map-over-neighbours) (apply map-over-neighbours args)) ((eq? msg 'foreach-neighbour) (apply foreach-neighbour args)) ((eq? msg 'find-node) (apply find-node args)) (else (error "unknown request -- create-graph" msg)))) dispatch)) ;;Hashtable ADT (define (create-hashtable-adt size hash-function . equal-function) ;;External Chaining implementation (let ((content (make-vector size '())) (same? (if (null? equal-function) = (car equal-function)))) ;;Abstractions: (define (make-item key info) (cons key info)) (define (key item) (car item)) (define (info item) (cdr item)) ;;Done (define (insert a-key info) (let* ((position (hash-function a-key)) (data (vector-ref content position))) (vector-set! content position (cons (make-item a-key info) data)) #t)) (define (delete a-key) (let* ((position (hash-function a-key)) (data (vector-ref content position))) (define (delete a-key a-list) (cond ((null? a-list) a-list) ((eq? (key (car a-list)) a-key) (cdr a-list)) (else (cons (car a-list) (delete a-key (cdr a-list)))))) (if (null? data) #t (begin (vector-set! content position (delete a-key data)) #t)))) (define (search a-key) (let* ((position (hash-function a-key)) (data (vector-ref content position))) (define (search-in-list a-key a-list) (cond ((null? a-list) #f) ((eq? (key (car a-list)) a-key) (info (car a-list))) (else (search-in-list a-key (cdr a-list))))) (if (null? data) #f (search-in-list a-key data)))) (define (show) (define (iter n) (if (= n (- (vector-length content) 1)) (newline) (begin (let ((data (vector-ref content n))) (for-each (lambda (item) (display "Key: ") (display (key item)) (display " ") (display "Content: ") (display (info item)) (newline)) data)) (iter (+ 1 n))))) (iter 0)) (define (dispatch m . args) (cond ((eq? m 'insert) (insert (car args) (cadr args))) ((eq? m 'delete) (delete (car args))) ((eq? m 'search) (search (car args))) ((eq? m 'show) (show)) (else (error "Could not handle your message -- Create Hashtable ADT" m)))) dispatch)) ;;Another Hashtable ADT (define (create-hashtable-w-bst-adt size hash-function . equal-function) ;;External Chaining implementation, buckets are binary search trees (define (filled-vector n) (let ((the-vector (make-vector n))) (do ((counter 0 (+ 1 counter))) ((= counter n) the-vector) (vector-set! the-vector counter (create-bst eq? tree-less?))))) (let ((content (filled-vector size)) (same? (if (null? equal-function) = (car equal-function))) (nr-of-empty-buckets 0)) ;;to test performance ;;Abstractions: (define (make-item key info) (cons key info)) (define (key item) (car item)) (define (info item) (cdr item)) ;;Done (define (insert a-key info) (let* ((position (hash-function a-key)) (the-tree (vector-ref content position))) (the-tree 'insert (make-item a-key info)) #t)) (define (delete a-key) (let* ((position (hash-function a-key)) (the-tree (vector-ref content position))) (the-tree 'delete a-key))) (define (search a-key) (let* ((position (hash-function a-key)) (the-tree (vector-ref content position))) (if (the-tree 'empty?) #f (the-tree 'lookup a-key)))) (define (show) (define (iter n) (if (= n (- (vector-length content) 1)) (newline) (begin (let ((the-tree (vector-ref content n))) (if (not (the-tree 'empty?)) (begin (display "Data on key ") (display n) (display ": ") (the-tree 'for-each (lambda (element) (display (if (procedure? element) (element 'give-name) element)) (display " "))) (newline)) (set! nr-of-empty-buckets (+ 1 nr-of-empty-buckets)))) (iter (+ 1 n))))) (iter 0) (begin (display nr-of-empty-buckets) (display-line " empty buckets") (set! nr-of-empty-buckets 0) 'done)) (define (dispatch m . args) (cond ((eq? m 'insert) (insert (car args) (cadr args))) ((eq? m 'delete) (delete (car args))) ((eq? m 'search) (search (car args))) ((eq? m 'tree) (vector-ref content (car args))) ((eq? m 'show) (show)) (else (error "Could not handle your message -- Hashtable with BST ADT" m)))) dispatch)) ;;THe Eventhandler ADT ;;Implemented with the Modified Priority Queue ADT (define (create-eventhandler-ADT starting-time) (let ((action-queue (create-priority-queue)) (time starting-time) ;;internal time of the eventhandler (runtime starting-time)) ;;Runtime is a variable that will be useful when the eventhandler is ;;executing to prevent loops (define (the-time element) (car element)) (define (the-action element) (cdr element)) (define (for-each-action do-something) (action-queue 'for-each do-something)) (define (execute an-action) ;;Asks the ADT action to execute itself (an-action 'execute)) (define (execute-step step) (define (iter) (if ;;Checks whether the time is smaller than the step size ;;and whether the queue is empty or not (and (not (action-queue 'empty?)) (<= (the-time (action-queue 'serve)) (+ time step))) (begin (let ((new-action (action-queue 'serve))) (action-queue 'dequeue) (execute (the-action new-action))) (iter)) (begin (set! time (+ time step)) 'done))) (set! runtime (+ time step 1)) (iter)) (define (add an-action a-time) (cond ((null? a-time) ;;Execute the action directly if no time is given (execute an-action)) ((eq? (the-time a-time) 'hold) ;;If the action must be held, enqueue it with highest priority (action-queue 'enqueue an-action 0)) ;;Enqueue the action with the time as its priority (else (action-queue 'enqueue an-action (the-time a-time))))) (define (delete an-action a-player) ;;Delete all actions of a type from a player from the eventhandler queue (for-each-action (lambda (element) (if (and (eq? an-action ((the-action element) 'give-name)) (eq? a-player ((the-action element) 'give-executer))) ;;Asks the ADT action who performed the action (action-queue 'delete (the-action element)))))) (define (delete-all a-player) ;;Delete all actions of a player in the queue (for-each-action (lambda (element) (if (eq? a-player ((the-action element) 'give-executer)) (action-queue 'delete (the-action element)))))) (define (show) ;;Shows the queue (if (action-queue 'empty?) 'empty (begin (for-each-action (lambda (element) (display "Time: ") (display (the-time element)) (display " Executer: ") (display ((the-action element) 'give-executer)) (display " Action: ") (display-line ((the-action element) 'give-name)))) (display "Eventhandler time is: ") (display-line time)))) (define (change-time new-time) ;;Change the eventhandler's time (set! time new-time) 'done) (define (dispatch m . args) ;;Functions are immediately executed with given arguments (cond ((eq? m 'add) (add (car args) (cdr args))) ;;Expects action ADT and (optionally) an integer or symbol hold ((eq? m 'delete) (delete (car args) (cadr args))) ;;Expects action symbol and player symbol ((eq? m 'for-each-action) (for-each-action (car args))) ;;Expects procedure ((eq? m 'delete-all) (delete-all (car args))) ;;Expects player symbol ((eq? m 'show) (show)) ((eq? m 'execute-step) (execute-step (car args))) ;;Expects integer ((eq? m 'change-time) (change-time (car args))) ;;Expects integer ((eq? m 'give-time) time) ;;Returns integer ((eq? m 'give-runtime) runtime) ;;Returns integer (else (error "Eventhandler ADT Could not handle your message " m)))) dispatch)) ;;The Action ADT (define (create-action-adt name an-executor parameterlist) ; <<== Changed. ;;name is a symbol representing an action ;;an-executor is also a symbol representing an executor ;;parameterlist is a list of extra parameters (if (not (the-actions-table 'lookup name)) (error "Action Type not found in The Action Table -- Create Action ADT" name) ;;Creates an action ADT that will keep track of the executer of a function ;;The function is actually the function that will execute the specified action ;;This function will be looked up in the action table ;;The action table is a globally defined instance of the object (action-table) (let ((action-name name) (action-function (the-actions-table 'give-function name)) (action-executor an-executor) (action-parameters parameterlist)) (define (dispatch m) (cond ((eq? m 'give-name) action-name) ;;Returns symbol ((eq? m 'give-function) action-function) ;;Returns procedure ((eq? m 'give-executer) action-executor) ;;Returns an ADT ((eq? m 'give-parameters) action-parameters) ;;Returns list of parameters ((eq? m 'execute) (apply action-function (cons action-executor action-parameters))) (else (error "Could not handle your request -- Create Action ADT" m)))) dispatch))) ;;The Table ADT ;;For use as an efficient dictionary thanks to the hashtable implementation (define (create-table-adt size equalfunction) (define (the-hashfunction key) (modulo (chars->numbers key) size)) (let ((the-table (create-hashtable-adt size the-hashfunction equalfunction)) (items-in-table 0 .0) (loadfactor 1)) (define (update-loadfactor updateproc) (set! items-in-table (updateproc items-in-table 1)) (set! loadfactor (/ items-in-table size))) (define (add key entry) (update-loadfactor +) (the-table 'insert key entry)) (define (delete key) (update-loadfactor -) (the-table 'delete key)) (define (lookup key) (the-table 'search key)) (define (show) (the-table 'show) (display "Items in table: ") (display-line items-in-table)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args) (cadr args))) ;;Expects symbol and an ADT ((eq? m 'delete) (delete (car args))) ;;Expects symbol ((eq? m 'lookup) (lookup (car args))) ;;Expects symbol ((eq? m 'give-loadfactor) loadfactor) ((eq? m 'show) (show)) (else (error "Create-Table-ADT could not handle your request" m)))) dispatch)) ;;Another Table ADT, but this one uses the Hashtable with ;;rehashing in BST's as underlying implementation (define (create-bst-table-adt size equalfunction) (define (the-hashfunction key) (modulo (chars->numbers key) size)) (let ((the-table (create-hashtable-w-bst-adt size the-hashfunction equalfunction)) (items-in-table 0 .0) (loadfactor 1)) (define (update-loadfactor updateproc) (set! items-in-table (updateproc items-in-table 1)) (set! loadfactor (/ items-in-table size))) (define (add key entry) (update-loadfactor +) (the-table 'insert key entry)) (define (delete key) (update-loadfactor -) (the-table 'delete key)) (define (lookup key) (the-table 'search key)) (define (show) (the-table 'show) (display "Items in table: ") (display-line items-in-table)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args) (cadr args))) ;;Expects symbol and an ADT ((eq? m 'delete) (delete (car args))) ;;Expects symbol ((eq? m 'lookup) (lookup (car args))) ;;Expects symbol ((eq? m 'give-loadfactor) loadfactor) ((eq? m 'show) (show)) (else (error "Binary Search Tree Table could not handle your request" m)))) dispatch)) ;;Inventory Tree ADT ;;this is the Tree which will store all weapons and items of a player (define (create-inventory-tree) (let ((the-tree (create-redblack-tree eq? tree-less?))) ;;The Tree is a Red Black Tree ;;a Binary Search tree, which takes as input a conscell of the form '(key . data) ;;Abstractions (define (create-package name adt) (cons name adt)) (define (the-name item) (car item)) (define (the-adt item) (cdr item)) ;;Done (define (add an-item) (the-tree 'insert (create-package (an-item 'give-name) an-item))) (define (delete an-item) (the-tree 'delete an-item)) (define (lookup an-item) (the-tree 'lookup an-item)) (define (show) (the-tree 'for-each (lambda (item) (display-line (item 'give-name))))) (define (for-each an-action) (the-tree 'for-each an-action)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args))) ;;Expects item ADT ((eq? m 'delete) (delete (car args))) ;;Expects symbol ((eq? m 'lookup) (lookup (car args))) ;;Expects symbol ((eq? m 'for-each) (for-each (car args))) ;;Expects procedure ((eq? m 'show) (show)) (else (error "Could not handle your request -- Create Inventory" m)))) dispatch)) ;;The Inventory ADT (define (create-inventory-adt possesor-name) ;;Based on an Inventory Tree ADT ;;An inventory stocks 2 different ADT's, it stocks Items and Weapons (let ((the-inventory (create-inventory-tree)) (inventory-possesor possesor-name)) (define (add item) (if (symbol? item) (error "expects ADT not a name -- ADD -- INVENTORY" item) ;;Expects an ADT as an input (begin (set-item-possesor item inventory-possesor) (the-inventory 'add item)))) (define (give item) (if (symbol? item) (the-inventory 'lookup item) (error "Expect symbol not an ADT -- GIVE -- INVENTORY" item))) (define (drop item) (if (symbol? item) (let ((the-item (give item))) (if the-item (begin (set-item-possesor the-item 'nobody) (the-inventory 'delete item)) (display-line "You haven't got that item"))) (error "Expects symbol not an ADT -- DROP -- INVENTORY" item))) (define (use item) (let ((the-item (if (symbol? item) (give item) item))) (if the-item (if (eq? (the-item 'give-possesor) 'nobody) (begin (set-item-possesor the-item inventory-possesor) (the-item 'use)) (the-item 'use)) (begin (display "The item ") (display (get-object-name item)) (display-line " was not found in your inventory"))))) (define (for-each an-action) (the-inventory 'for-each an-action)) (define (show) (the-inventory 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args))) ;;Expects Weapon/Item ADT ((eq? m 'drop) (drop (car args))) ;;Expects symbol ((eq? m 'give) (give (car args))) ;;Expects symbol ((eq? m 'use) (use (car args))) ;;Expects symbol ((eq? m 'for-each) (for-each (car args))) ;;Expects procedure ((eq? m 'show) (show)) (else (error "Could not handle your request -- Create Inventory ADT" m)))) dispatch)) ;;The Item ADT (define (create-item-adt name) (if (not (the-items-table 'give-name name)) (error "Item Stats not found in the Items Table -- Create Item ADT" name) ;;An item is not a weapon or a spell, it is an object ;;Relevant info is looked up in the items table (let* ((item-name (the-items-table 'give-name name)) (item-description (the-items-table 'give-description name)) (item-action-names (the-items-table 'give-functions name)) (item-possesor 'nobody) (extras (the-items-table 'give-extra name))) (define (use) ;;First, the name of the action of this item is looked up in the items table ;;Then, an Action ADT is made of the name found in the items table ;;This Action ADT is passed to the eventhandler ;;The item possesor is just a symbol, to get the ADT, look it up in the character table (for-each (lambda (item-action) (let* ((item-action-name (car item-action)) (item-action-pars (cdr item-action)) (item-actions (create-action-adt item-action-name item-possesor (list item-action-pars)))) (core-eventhandler 'add item-actions 'hold))) item-action-names) (if (eq? extras 'delete-after-use) (delete-item-for-character item-name item-possesor)) (execute-actions)) (define (dispatch m . args) (cond ((eq? m 'give-name) item-name) ;;Returns symbol ((eq? m 'give-description) item-description) ;;Returns string ((eq? m 'give-possesor) item-possesor) ;;Returns symbol ((eq? m 'use) (use)) ((eq? m 'set-description!) (set! item-description (car args))) ;;Expects string ((eq? m 'set-possesor!) (set! item-possesor (car args))) ;;Expects symbol ((eq? m 'get-type) 'item) ;;to identify between weapons and items (else (error "Could not handle your request -- Create Item ADT" m)))) dispatch))) ;;The Weapon ADT (define (create-weapon-adt name) ;;Weapons are: swords, shields, axes, but also Helmets and other Equipment ;;Each weapon has a name, a description, a bonus (for some "Magical" Weapons), but ;;Most important: a series of Combat Modifiers ;;Looks up arguments in the weapons table (if (not (the-weapons-table 'give-name name)) (error "Weapon was not found in the Weapons Database -- Create Weapon ADT" name) (let* ((weapon-name (the-weapons-table 'give-name name)) (weapon-description (the-weapons-table 'give-description name)) (weapon-statistics (the-weapons-table 'give-statistics name)) (weapon-bonus (the-weapons-table 'give-bonus name)) (weapon-possesor 'nobody) (attack-damage (list-ref weapon-statistics 0)) (defense-damage (list-ref weapon-statistics 1)) (attack-bonus (list-ref weapon-statistics 2)) (defense-bonus (list-ref weapon-statistics 3)) (extras (the-weapons-table 'give-extra name))) (define (use) ;;First, the name of the action of this weapon is looked up in the items table ;;Then, an Action ADT is made of the name found in the weapons table ;;This Action ADT is passed to the eventhandler ;;The weapon possesor is just a symbol, to get the ADT, look it up in the character table (for-each (lambda (weapon-action) (let* ((weapon-action-name (car weapon-action)) (weapon-action-pars (cdr weapon-action)) (weapon-actions (create-action-adt weapon-action-name weapon-possesor (list weapon-action-pars)))) (core-eventhandler 'add weapon-actions 'hold))) weapon-bonus) (if (eq? extras 'delete-after-use) (delete-item-for-character weapon-name weapon-possesor)) (execute-actions)) ;;A weapon has 4 combat modifiers: ;;Attack Damage: the damage the weapon can (maximally) deal ;;Defense Damage: the damage a weapon deals when the defender makes a counter-attack ;;These are expressed as a pair of (number of dice . number of sides of the dice) ;;Eg. '(2 . 6) => 2d6 => 2 dice of 6 sides, so maximum damage is 12 ;;Attack Bonus: some weapons will give the wielder a bonus ;;Defense Bonus: items like Helmets and Plate Mail Armor ;;will give the wearer defensive bonusses (define (dispatch m . args) (cond ((eq? m 'give-name) weapon-name) ;;Returns symbol ((eq? m 'give-description) weapon-description) ;;Returns string ((eq? m 'give-possesor) weapon-possesor) ;;Returns symbol ((eq? m 'give-attack-damage) attack-damage) ;;Returns pair ((eq? m 'give-defense-damage) defense-damage) ;;Returns pair ((eq? m 'give-attack-bonus) attack-bonus) ;;Returns integer ((eq? m 'give-defense-bonus) defense-bonus) ;;Returns integer ((eq? m 'set-attack-damage!) (set! attack-damage (car args))) ;;Expects pair ((eq? m 'set-defense-damage!) (set! defense-damage (car args))) ;;Expects pair ((eq? m 'set-attack-bonus!) (set! attack-bonus (car args))) ;;Expects integer ((eq? m 'set-defense-bonus!) (set! defense-bonus (car args))) ;;Expects integer ((eq? m 'set-description!) (set! weapon-description (car args))) ;;Expects string ((eq? m 'set-possesor!) (set! weapon-possesor (car args))) ;;Expects symbol ((eq? m 'use) (use)) ((eq? m 'get-type) 'weapon) ;;to identify between weapons and items (else (error "Could not handle your request -- Create Weapon ADT" m)))) dispatch))) ;;The Location ADT (define (create-location-adt name) ;;Locations are 'rooms' in the world ;;Looks up its arguments in the location table automatically ;;the-location-table is a table created by the object location-table (if (not (the-locations-table 'lookup name)) (error "The record of that Location Name was not found in the Location table -- Create location ADT" name) (let* ((locations the-locations-table) (location-name (locations 'give-name name)) (location-monsters (locations 'give-monster name)) (location-npcs (locations 'give-npc name)) (location-description (locations 'give-description name)) (location-alterdescr (locations 'give-alterdescription name)) (location-items (locations 'give-item name)) (location-actions (locations 'give-actions name)) (location-players '())) (define (give key) ;;Gives the data asked for (cond ((eq? key 'name) location-name) ((eq? key 'monster) location-monsters) ((eq? key 'npc) location-npcs) ((eq? key 'description) location-description) ((eq? key 'alterdescription) location-alterdescr) ((eq? key 'item) location-items) ((eq? key 'actions) location-actions) ((eq? key 'players) location-players) (else (error "wrong key type -- Give --Create Location ADT" key)))) (define (set-item! key new-value) ;;Changes the data asked for ;;NOTE: these changes only affect the local parameters, ;;so the Location TABLE itself will NOT be changed! (cond ((eq? key 'name) (set! location-name new-value) #t) ((eq? key 'monster) (set! location-monsters new-value) #t) ((eq? key 'npc) (set! location-npcs new-value) #t) ((eq? key 'description) (set! location-description new-value) #t) ((eq? key 'alterdescription) (set! location-alterdescr new-value) #t) ((eq? key 'item) (set! location-items new-value) #t) ((eq? key 'action) (set! location-actions new-value) #t) ((eq? key 'players) (set! location-players new-value) #t) (else (error "wrong key type -- Set-item! --Create Location ADT" key)))) (define (dispatch m . args) ;;The dispatcher dispatches to the give and set-item procedures, ;;to minimize complexity (cond ((eq? m 'give-name) (give 'name)) ;;Returns symbol ((eq? m 'give-monster) (give 'monster)) ;;Returns list of symbols ((eq? m 'give-npc) (give 'npc)) ;;Returns list of symbols ((eq? m 'give-description) (give 'description)) ;;Returns string ((eq? m 'give-alterdescription) (give 'alterdescription)) ;;Returns string ((eq? m 'give-players) (give 'players)) ;;Returns list of symbols ((eq? m 'give-item) (give 'item)) ;;Returns list of symbols ((eq? m 'give-actions) (give 'actions)) ;;Returns list of symbols ((eq? m 'set-name!) (set-item! 'name (car args))) ;;Expects symbol ((eq? m 'set-monster!) (set-item! 'monster (car args))) ;;Expects list of symbols ((eq? m 'set-npc!) (set-item! 'npc (car args))) ;;Expects list of symbols ((eq? m 'set-description!) (set-item! 'description (car args))) ;;Expects string ((eq? m 'set-alterdescription!) (set-item! 'alterdescription (car args))) ;;Expects string ((eq? m 'set-item!) (set-item! 'item (car args))) ;;Expects list of adts ((eq? m 'set-action!) (set-item! 'action (car args))) ;;Expects list of symbols ((eq? m 'set-players!) (set-item! 'players (car args))) ;;Expects list of symbols (else (error "Create Location ADT could not handle your request" m)))) dispatch))) ;;The Monster ADT (define (create-monster-adt name class startingpoint . route-of-travelling) ;;Monsters will be the enemies of players (if (not (the-class-table 'lookup class)) (error "Class not found in Class table -- Create Monster ADT" class) (let* ((monster-name name) (monster-class class) (class-parameters (the-class-table 'give-parameters class)) (strength (car class-parameters)) (constitution (cadr class-parameters)) (wisdom (list-ref class-parameters 2)) (intelligence (list-ref class-parameters 3)) (dexterity (list-ref class-parameters 4)) (charisma (list-ref class-parameters 5)) (heropoints (+ (abs (- strength constitution)) wisdom)) (monster-respawn (the-class-table 'give-respawn class)) (monster-location startingpoint) (monster-world the-world) ;;monsters always reside in 'the world' (monster-hitpoints (the-class-table 'give-hitpoints class)) (monster-inventory (create-inventory-adt name)) (monster-spellbook (create-spellbook-adt name)) (route (if (null? route-of-travelling) monster-location (car route-of-travelling))) (current-offensive-weapon (car (the-class-table 'give-weapons class))) (current-defensive-weapon (cadr (the-class-table 'give-weapons class))) (status 'new)) ;;The following three procedures will setup the monster's possesions (define (fill-items) ;;the possesions is a list of NAMES of the monster's possesions ;;the items are created here. (define (iter objects) (if (null? objects) 'done (begin (monster-inventory 'add (create-item-adt (car objects))) (iter (cdr objects))))) (let ((possesions (the-class-table 'give-items class))) (iter possesions))) (define (fill-weapons) (define (iter objects) (if (null? objects) 'done (begin (monster-inventory 'add (create-weapon-adt (car objects))) (iter (cdr objects))))) (let ((possesions (the-class-table 'give-weapons class))) (iter possesions))) (define (fill-spellbook) (define (iter spells) (if (null? spells) 'done (begin (monster-spellbook 'add (create-spell-adt (car spells))) (iter (cdr spells))))) (let ((possesions (the-class-table 'give-spells class))) (iter possesions))) (define (walk-through-route) ;;This algorithm lets a monster travel through a given route (let ((time (core-eventhandler 'give-runtime))) ;;Rotates the routelist and changes the monster location (define (last alist) (if (null? (cdr alist)) alist (last (cdr alist)))) (define (rotate) ;;Destructively manipulate the routelist (let ((next-el (cdr route)) (last-el (last route))) (set-cdr! last-el (list (car route))) (set-cdr! route '()) (set! route next-el) ;;Changes monster location and changes locations (monster-location 'set-monster! (delete-list monster-name (monster-location 'give-monster))) (set! monster-location (car route)) (monster-location 'set-monster! (cons monster-name (monster-location 'give-monster))) ;;The monster automatically enqueues that he will travel again in 20 turns (let ((walk-again-action (create-action-adt 'monster-travelling monster-name '()))) (core-eventhandler 'add walk-again-action (+ 20 time))) #t)) (if (list? route) (rotate)))) (define (has-item? an-item) (monster-inventory 'search an-item)) (define (has-spell? a-spell) (monster-spellbook 'search a-spell)) (define (show-inventory) (display-line "Monster Possesions: ") (monster-inventory 'show) (newline)) (define (show-spellbook) (display-line "Monster Spells: ") (monster-spellbook 'show) (newline)) (define (show-status) (display "Information about monster: ") (display-line monster-name) (display "Class: ") (display-line monster-class) ;(display-line monster-description) ; <<== Changed. (display-line "Personal Parameters:") (display "Current Hitpoints: ") (display-line monster-hitpoints) (display "Strength: ") (display-line strength) (display "Constitution: ") (display-line constitution) (display "Wisdom: ") (display-line wisdom) (display "Intelligence: ") (display-line intelligence) (display "Dexterity: ") (display-line dexterity) (display "Charisma: ") (display-line charisma) (newline) (display "Current Location: ") (display-line (monster-location 'give-name)) (display "Currently equiped offensive weapon: ") (display-line (get-object-name current-offensive-weapon)) (display "Currently equiped defensive weapon: ") (display-line (get-object-name current-defensive-weapon)) (display "Path guarded: ") (if (list? route) (for-each (lambda (location) (display (location 'give-name)) (display " ")) route) (display "monster does not guard a path")) (newline) (show-inventory) (show-spellbook)) (define (set-monster-hitpoints! value) (set! monster-hitpoints value) (if (< monster-hitpoints 1) (begin (set! status 'dead) (core-eventhandler 'delete-all monster-name) ;;Delete monster from its location (let ((monsters-in-location (monster-location 'give-monster))) (monster-location 'set-monster! (delete-list monster-name monsters-in-location))) (drop-all monster-name display-off) (the-character-table 'delete monster-name) (respawn monster-name monster-class monster-location route monster-respawn) ;;some monsters can respawn when they die (display monster-name) (display-line " is dead.")))) (define (dispatch m . args) (cond ((eq? m 'give-name) monster-name) ;;Returns symbol ((eq? m 'give-class) monster-class) ;;Returns symbol ((eq? m 'give-strength) strength) ;;Returns integer ((eq? m 'give-constitution) constitution) ;;Returns integer ((eq? m 'give-wisdom) wisdom) ;;Returns integer ((eq? m 'give-intelligence) intelligence) ;;Returns integer ((eq? m 'give-dexterity) dexterity) ;;Returns integer ((eq? m 'give-charisma) charisma) ;;Returns integer ((eq? m 'give-heropoints) heropoints) ;;Returns integer ((eq? m 'give-location) monster-location) ;;Returns location ADT ((eq? m 'give-world) monster-world) ;;Returns world ADT ((eq? m 'give-hitpoints) monster-hitpoints) ;;Returns integer ((eq? m 'give-route) route) ;;Returns list of location ADTs ((eq? m 'give-respawn) monster-respawn) ;;Returns boolean or number ((eq? m 'give-status) status) ;;Returns symbol ((eq? m 'give-offensive-weapon) current-offensive-weapon) ;;Returns Weapon ADT ((eq? m 'give-defensive-weapon) current-defensive-weapon) ;;Returns Weapon ADT ((eq? m 'add-item) (monster-inventory 'add (car args))) ;;Expects Item ADT ((eq? m 'drop-item) (monster-inventory 'drop (car args))) ;;Expects Item symbol ((eq? m 'add-spell) (monster-spellbook 'add (car args))) ;;Expects Spell ADT ((eq? m 'erase-spell) (monster-spellbook 'erase (car args))) ;;Expects Spell symbol ((eq? m 'walk-through-route) (walk-through-route)) ((eq? m 'has-item?) (has-item? (car args))) ;;Returns boolean ((eq? m 'has-spell?) (has-spell? (car args))) ;;Returns boolean ((eq? m 'show-status) (show-status)) ((eq? m 'show-inventory) (show-inventory)) ((eq? m 'show-spellbook) (show-spellbook)) ((eq? m 'set-name!) (set! monster-name (car args))) ;;Expects symbol ((eq? m 'set-strength!) (set! strength (car args))) ;;Expects integer ((eq? m 'set-constitution!) (set! constitution (car args))) ;;Expects integer ((eq? m 'set-wisdom!) (set! wisdom (car args))) ;;Expects integer ((eq? m 'set-intelligence!) (set! intelligence (car args))) ;;Expects integer ((eq? m 'set-dexterity!) (set! dexterity (car args))) ;;Expects integer ((eq? m 'set-charisma!) (set! charisma (car args))) ;;Expects integer ((eq? m 'set-heropoints!) (set! heropoints (car args))) ;;Expects integer ((eq? m 'set-location!) (set! monster-location (car args))) ;;Expects location ADT ((eq? m 'set-hitpoints!) (set-monster-hitpoints! (car args))) ;;Expects integer ((eq? m 'set-route!) (set! route (car args))) ;;Expects list of Location ADTs ((eq? m 'set-offensive-weapon!) (set! current-offensive-weapon (car args))) ;;Expects Weapon ADT ((eq? m 'set-defensive-weapon!) (set! current-defensive-weapon (car args))) ;;Expects Weapon ADT ((eq? m 'set-status!) (set! status (car args))) ;;Expects symbol ((eq? m 'give-inventory) monster-inventory) ;;Returns inventory ADT ((eq? m 'give-spellbook) monster-spellbook) ;;Returns spellbook ADT ((eq? m 'character-type) 'monster) ;;to distinguish between monsters players and NPC's (else (error "Create Monster ADT could not handle your request" m)))) (if (eq? status 'new) ;;Initialise monster (begin (fill-items) (fill-weapons) (fill-spellbook) (set! status 'alive) ;;Begin the guarding route (walk-through-route) dispatch) dispatch)))) ;;The NPC ADT (define (create-npc-adt name) (if (not (the-npc-table 'give-name name)) (error "Name not found in NPC table -- Create NPC ADT" name) (let ((npc-name (the-npc-table 'give-name name)) (npc-location (the-npc-table 'give-startingpoint name)) (npc-conversation (the-npc-table 'give-conversation name)) (npc-description (the-npc-table 'give-description name)) (npc-conditions (the-npc-table 'give-q-conditions name)) (npc-quest (the-npc-table 'give-quest name)) (npc-inventory (create-inventory-adt name)) (status 'new)) (define (fill-items) (define (iter objects) (if (null? objects) 'done (begin (npc-inventory 'add (create-item-adt (car objects))) (iter (cdr objects))))) (let ((possesions (the-npc-table 'give-items name))) (iter possesions))) (define (fill-weapons) (define (iter objects) (if (null? objects) 'done (begin (npc-inventory 'add (create-weapon-adt (car objects))) (iter (cdr objects))))) (let ((possesions (the-npc-table 'give-weapons name))) (iter possesions))) (define (has-item? an-item) (npc-inventory 'give an-item)) (define (initiate-conversation a-player) ;;This is the most important part of the ADT ;;This algorithm will make a player converse with an NPC, ;;and while doing so, it will check for quests and update them ;;if necessary (let ((the-npc-quest (if (eq? npc-quest 'none) 'none (create-quest-adt npc-quest)))) ;;the NPC converses with a player ;;The npc-conditions is a list of predicates, ;;contained in lambda exps, with a player as parameter, ;;eg ((lambda (a-player) (eq? aname (a-player 'give-name)) (lambda (...))) (define (check-conditions conditionlist) ;;checks whether a player has fulfilled a quest (cond ((null? conditionlist) #t) (((car conditionlist) a-player) ;;check the condition by applying it to the player (check-conditions (cdr conditionlist))) (else #f))) (define (execute-quest) ;;when the player fulfilled a quest, trigger the proper events (mark-quest-as-done the-npc-quest (get-character-questlog a-player)) (newline) (the-npc-quest 'trigger a-player) (display-line npc-conversation) (set! npc-quest 'none)) ;;There are several situations to consider, the following is a ;;tree walk of choices an NPC can make (if (eq? the-npc-quest 'none) ;;npc has no quest? (display-line npc-conversation) ;;yes, just talk (if (give-quest-from-character the-npc-quest a-player) ;;player knows about the quest? (if (check-conditions npc-conditions) ;;player fullfilled quest? (execute-quest) ;;yes, execute it (display-line npc-conversation)) ;;no, just talk (begin (add-quest-for-character the-npc-quest a-player) ;;let the player know about the quest (display-line npc-conversation)))))) ;;and just talk (define (show-inventory) (display-line "NPC Possesions: ") (npc-inventory 'show) (newline)) (define (show-status) (display-line "Information about NPC: ") (display "Name: ") (display-line npc-name) (display-line npc-description) (display "Current Location: ") (display-line npc-location) (show-inventory)) (define (dispatch m . args) (cond ((eq? m 'give-name) npc-name) ;;Returns symbol ((eq? m 'give-location) npc-location) ;;Returns Location ADT ((eq? m 'give-status) status) ;;Returns symbol ((eq? m 'give-description) npc-description) ;;Returns string ((eq? m 'add-item) (npc-inventory 'add (car args))) ;;Expects Item ADT ((eq? m 'drop-item) (npc-inventory 'drop (car args))) ;;Expects symbol ((eq? m 'has-item?) (has-item? (car args))) ;;Returns boolean ((eq? m 'show-status) (show-status)) ((eq? m 'show-inventory) (show-inventory)) ((eq? m 'set-name!) (set! npc-name (car args))) ;;Expects symbol ((eq? m 'set-location!) (set! npc-location (car args))) ;;Expects location ADT ((eq? m 'conversation) (initiate-conversation (car args))) ;;Returns string, expects player ADT ((eq? m 'set-conversation!) (set! npc-conversation (car args))) ;;Expects string ((eq? m 'set-status!) (set! status (car args))) ;;Expects symbol ((eq? m 'set-quest!) (set! npc-quest (car args))) ;;Expects Quest ADT or symbol none ((eq? m 'give-inventory) npc-inventory) ;;Returns Inventory ADT ((eq? m 'character-type) 'npc) (else (error "Create NPC ADT could not handle your request" m)))) (if (eq? status 'new) (begin (fill-items) (fill-weapons) (set! status 'alive) dispatch) dispatch)))) ;;The Player ADT (define (create-player-adt name class) (if (not (the-class-table 'lookup class)) (error "Class not found in Class table -- Create Player ADT" class) (let* ((player-name name) (player-class class) (class-parameters (the-class-table 'give-parameters class)) (strength (car class-parameters)) (constitution (cadr class-parameters)) (wisdom (list-ref class-parameters 2)) (intelligence (list-ref class-parameters 3)) (dexterity (list-ref class-parameters 4)) (charisma (list-ref class-parameters 5)) (player-location (the-world 'startpoint?)) (player-world the-world) (player-previous-worlds '()) (player-previous-locations '()) (player-hitpoints (the-class-table 'give-hitpoints class)) (player-inventory (create-inventory-adt name)) (player-questlog (create-questlog-adt name)) (player-spellbook (create-spellbook-adt name)) (player-hero-points 0) (current-offensive-weapon (car (the-class-table 'give-weapons class))) (current-defensive-weapon (cadr (the-class-table 'give-weapons class))) (status 'new)) (define (fill-items) ;;the possesions is a list of NAMES of the player's possesions ;;the items are created here. (define (iter objects) (if (null? objects) 'done (begin (player-inventory 'add (create-item-adt (car objects))) (iter (cdr objects))))) (let ((possesions (the-class-table 'give-items class))) (iter possesions))) (define (fill-weapons) (define (iter objects) (if (null? objects) 'done (begin (player-inventory 'add (create-weapon-adt (car objects))) (iter (cdr objects))))) (let ((possesions (the-class-table 'give-weapons class))) (iter possesions))) (define (fill-spellbook) ;;the spells is a list of NAMES of the player's spells ;;the spells are created here. (define (iter spells) (if (null? spells) 'done (begin (player-spellbook 'add (create-spell-adt (car spells))) (iter (cdr spells))))) (let ((possesions (the-class-table 'give-spells class))) (iter possesions))) (define (has-item? an-item) (player-inventory 'search an-item)) (define (has-spell? a-spell) (player-spellbook 'search a-spell)) (define (show-inventory) (display-line "Your Possesions: ") (player-inventory 'show) (newline)) (define (show-spellbook) (display-line "Your Spells: ") (player-spellbook 'show) (newline)) (define (show-questlog) (display "Current Quests: ") (newline) (player-questlog 'show) (newline) (let ((done-quests (player-questlog 'give-completed))) (if (not (null? done-quests)) (begin (display "Done Quests: ") (display-list done-quests)))) (newline)) (define (show-status) (display "Information about player: ") (display-line player-name) (display "Class: ") (display-line player-class) (newline) (display-line "Personal Parameters:") (display "Hero Points: ") (display-line player-hero-points) (display "Current Hitpoints: ") (display-line player-hitpoints) (display "Strength: ") (display-line strength) (display "Constitution: ") (display-line constitution) (display "Wisdom: ") (display-line wisdom) (display "Intelligence: ") (display-line intelligence) (display "Dexterity: ") (display-line dexterity) (display "Charisma: ") (display-line charisma) (newline) (display "Current Location: ") (display-line (player-location 'give-name)) (display "Currently equipped offensive weapon: ") (display-line (get-object-name current-offensive-weapon)) (display "Currently equipped defensive weapon: ") (display-line (get-object-name current-defensive-weapon)) (show-inventory) (show-spellbook) (show-questlog)) (define (set-player-hitpoints! value) ;;checks whether a player isn't dead (set! player-hitpoints value) (if (< player-hitpoints 1) (begin (set! status 'dead) (display name) (display-line " is dead.") (core-eventhandler 'delete-all player-name) (drop-all player-name display-off) (delete-player-from-location player-name player-location) (the-current-players 'delete player-name) (the-character-table 'delete player-name)))) (define (set-player-hero-points! value) ;;checks whether a player has won the game (set! player-hero-points value) (let ((heropoints-to-win (get-heropoints-to-win global-options))) (if (>= player-hero-points heropoints-to-win) (player-wins-game player-name) 'done))) (define (dispatch m . args) (cond ((eq? m 'give-name) player-name) ;;Returns symbol ((eq? m 'give-class) player-class) ;;Returns symbol ((eq? m 'give-strength) strength) ;;Returns integer ((eq? m 'give-constitution) constitution) ;;Returns integer ((eq? m 'give-wisdom) wisdom) ;;Returns integer ((eq? m 'give-intelligence) intelligence) ;;Returns integer ((eq? m 'give-dexterity) dexterity) ;;Returns integer ((eq? m 'give-charisma) charisma) ;;Returns integer ((eq? m 'give-location) player-location) ;;Returns Location ADT ((eq? m 'give-world) car player-world) ;;Returns world ADT ((eq? m 'give-previous-worlds) player-previous-worlds) ;;Returns world ADTs ((eq? m 'give-previous-locations) player-previous-locations) ;;Returns location ADTs ((eq? m 'give-hitpoints) player-hitpoints) ;;Returns integer ((eq? m 'give-status) status) ;;Returns symbol ((eq? m 'give-heropoints) player-hero-points) ;;Returns integer ((eq? m 'give-offensive-weapon) current-offensive-weapon) ;;Returns Weapon ADT ((eq? m 'give-defensive-weapon) current-defensive-weapon) ;;Returns Weapon ADT ((eq? m 'add-item) (player-inventory 'add (car args))) ;;Expects Item/Weapon ADT ((eq? m 'drop-item) (player-inventory 'drop (car args))) ;;Expects symbol ((eq? m 'add-spell) (player-spellbook 'add (car args))) ;;Expects Spell ADT ((eq? m 'erase-spell) (player-spellbook 'erase (car args))) ;;Expects symbol ((eq? m 'use-item) (player-inventory 'use (car args))) ;;Expects Item/Weapon ADT ((eq? m 'cast-spell) (player-spellbook 'cast (car args))) ;;Expects Spell ADT ((eq? m 'add-quest) (player-questlog 'add (car args))) ;;Expects Quest ADT ((eq? m 'done-quest) (player-questlog 'mark-as-done (car args))) ;;Expects quest ADT ((eq? m 'has-item?) (has-item? (car args))) ;;Returns boolean, expects symbol ((eq? m 'has-spell?) (has-spell? (car args))) ;;Returns boolean, expects symbol ((eq? m 'show-status) (show-status)) ((eq? m 'show-inventory) (show-inventory)) ((eq? m 'show-spellbook) (show-spellbook)) ((eq? m 'show-questlog) (show-questlog)) ((eq? m 'set-name!) (set! player-name (car args))) ;;Expects symbol ((eq? m 'set-strength!) (set! strength (car args))) ;;Expects integer ((eq? m 'set-constitution!) (set! constitution (car args))) ;;Expects integer ((eq? m 'set-wisdom!) (set! wisdom (car args))) ;;Expects integer ((eq? m 'set-intelligence!) (set! intelligence (car args))) ;;Expects integer ((eq? m 'set-dexterity!) (set! dexterity (car args))) ;;Expects integer ((eq? m 'set-charisma!) (set! charisma (car args))) ;;Expects integer ((eq? m 'set-location!) (set! player-location (car args))) ;;Expects Location ADT ((eq? m 'set-world!) (set! player-world (car args))) ;;Expects world ADT ((eq? m 'set-previous-worlds!) (set! player-previous-worlds (car args))) ;;Expects world ADTs ((eq? m 'set-previous-locations!) (set! player-previous-locations (car args))) ;;Expects location ADTs ((eq? m 'set-hitpoints!) (set-player-hitpoints! (car args))) ;;Expects integer ((eq? m 'set-heropoints!) (set-player-hero-points! (car args))) ;;Expects integer ((eq? m 'set-offensive-weapon!) (set! current-offensive-weapon (car args))) ;;Expects Weapon ADT ((eq? m 'set-defensive-weapon!) (set! current-defensive-weapon (car args))) ;;Expects Weapon ADT ((eq? m 'give-inventory) player-inventory) ;;Returns Inventory ADT ((eq? m 'give-spellbook) player-spellbook) ;;Returns Spellbook ADT ((eq? m 'give-questlog) player-questlog) ;;Returns Questlog ADT ((eq? m 'set-status!) (set! status (car args))) ;;Expects symbol ((eq? m 'character-type) 'player) ;;To distinguish between players monsters and NPC's (else (error "Create Player ADT could not handle your request" m)))) (if (eq? status 'new) ;;Player is initialised (begin (fill-items) (fill-weapons) (fill-spellbook) ;;Let the location know the player is in the room (let ((players-in-location (player-location 'give-players))) (player-location 'set-players! (cons name players-in-location))) (set! status 'alive) ;;Player has to be added to the current players list! (the-current-players 'add player-name) dispatch) dispatch)))) ;;The Quest ADT (define (create-quest-adt name) (if (not (the-quest-table 'lookup name)) (error "The Quest was not found in the quest table -- Create Quest ADT" name) (let ((quest-name name) (title (the-quest-table 'give-title name)) (status 'uncompleted) (description (the-quest-table 'give-description name)) (trigger-events (the-quest-table 'give-trigger name)) (quest-points (the-quest-table 'give-heropoints name))) (define (trigger a-player) (let ((the-player (get-character-adt a-player))) ;;The triggerlist contains names of action ADTs looked up in the action table ;;A quest is always triggered by a player (through an NPC) (define (loop-over-triggers triggerlist) (if (null? triggerlist) 'done (begin ((car triggerlist) the-player) ;;each trigger is a lambda with one parameter (loop-over-triggers (cdr triggerlist))))) (loop-over-triggers trigger-events) (do-heropoints-up quest-points the-player) ;;The player's heropoints are automatically adjusted (display (get-character-name the-player)) (display " has solved a quest and gains ") (display quest-points) (display-line " heropoints.") (set! status 'completed) (the-quest-table 'delete name))) (define (dispatch m . args) (cond ((eq? m 'give-name) quest-name) ;;Returns symbol ((eq? m 'give-title) title) ;;Returns string ((eq? m 'give-status) status) ;;Returns symbol ((eq? m 'give-description) description) ;;Returns string ((eq? m 'trigger) (trigger (car args))) ((eq? m 'give-heropoints) quest-points) ;;Returns integer ((eq? m 'set-status!) (set! status (car args))) ;;Expects symbol (else (error "Could not handle your request -- Create Quest ADT" m)))) dispatch))) ;;The Questlog ADT (define (create-questlog-adt posessor) ;;Questlog is based on an inventory tree ;;It stocks Quest ADTs (let ((quests (create-inventory-tree)) (questlog-posessor posessor) (completed-quests '())) ;;Abstractions (define (the-name quest) (car quest)) (define (the-quest quest) (cdr quest)) (define (title quest) (quest 'title)) (define (status quest) (quest 'status)) (define (description quest) (quest 'description)) (define (trigger quest) (quest 'trigger)) (define (heropoints quest) (quest 'give-heropoints)) (define (add quest) ;;Adds a quest to the player's questlog (if (symbol? quest) (error "Expected procedure not a symbol -- QUESTLOG" quest) (quests 'add quest))) (define (mark-as-done quest) (let ((quest-name (if (symbol? quest) quest (get-object-name quest)))) ;;Deletes the quest and writes the quest to the log (begin (set! completed-quests (cons quest-name completed-quests)) (quests 'delete quest-name)))) (define (give key name) ;;Gives valid information about a quest (let ((the-quest (quests 'lookup name))) (if the-quest (cond ((eq? key 'title) (title the-quest)) ((eq? key 'status) (status the-quest)) ((eq? key 'description) (description the-quest)) ((eq? key 'heropoints) (heropoints the-quest)) (else (error "Wrong key -- Give -- Create Questbook ADT" key))) (error "Quest not found -- Give -- Create Questbook ADT" name)))) (define (give-quest a-quest) (let ((quest-name (if (symbol? a-quest) a-quest (a-quest 'give-name)))) (quests 'lookup quest-name))) (define (for-each-quest an-action) (quests 'for-each an-action)) (define (show-quests) (quests 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args))) ;;Expects a Quest ADT ((eq? m 'mark-as-done) (mark-as-done (car args))) ;;Expects a Quest ADT or name ((eq? m 'give) (give-quest (car args))) ;;Expects a quest ADT or a quest name ((eq? m 'give-title) (give 'title (car args))) ;;Returns string, expects symbol ((eq? m 'give-status) (give 'status (car args))) ;;Returns symbol, expects symbol ((eq? m 'give-description) (give 'description (car args))) ;;Returns string, expects symbol ((eq? m 'give-heropoints) (give 'heropoints (car args))) ;;Returns integer, expects symbol ((eq? m 'give-completed) completed-quests) ;;Returns list ((eq? m 'for-each) (for-each-quest (car args))) ;;Expects procedure ((eq? m 'show) (show-quests)) (else (error "Could not handle your request -- Create Questlog ADT" m)))) dispatch)) ;;The Spell ADT (define (create-spell-adt name) ;;Looks up its arguments in the spell table (if (not (the-spells-table 'give-name name)) (error "Spell not found in the Spell Database -- Create Spell ADT" name) (let* ((spell-name (the-spells-table 'give-name name)) (spell-description (the-spells-table 'give-spell-description name)) (cast-description (the-spells-table 'give-cast-description name)) (spell-action-list (the-spells-table 'give-actions name)) (spell-possesor 'nobody) (spells-cast-max (the-spells-table 'give-max-castings name)) (spell-reset-time (the-spells-table 'give-reset-time name)) (spells-cast-so-far 0)) ;;A word about the structure: ;;The actions of a spell are stored in a list, each element of the list, ;;is the name of an action, and some extra parameters, so ;;actionlist => '((action1name . action1parameters) (action2name . action2paramaters) etc) (define (cast) ;;The most important part of this ADT, the Cast Algorithm, ;;will trigger all events this spell has, and take care of all ;;side-effects the spell introduces (let ((spell-possesor-adt (the-character-table 'lookup spell-possesor))) (if (= spells-cast-so-far spells-cast-max) ;;Spell casts exceeded? (begin (display "Cannot cast spell ") (display spell-name) (display-line ": maximum casts a day exceeded") (display "You can cast this spell again in ") (display spell-reset-time) (display-line " turns") (let ((spell-reset (create-action-adt 'reset-spell spell-possesor (list name))) (eventhandler-time (core-eventhandler 'give-runtime))) ;;spell-reset is an action ADT, ready to be passed to ;;The eventhandler, as its priority, it receives the reset time ;;because, once the eventhandler increases its time with the reset time, ;;the spell can be cast again ;;Spell-reset is created using an action 'reset-spell, ;;already in the action table, which will reset the spells-cast-so-far to 0, ;;enabling the player to cast the spells again (core-eventhandler 'add spell-reset (+ spell-reset-time eventhandler-time)))) (begin (set! spells-cast-so-far (+ 1 spells-cast-so-far)) ;;We start a loop through our actionlist, ;;We select the first action, and create our action ADT as usual ;;(remember what the structure of our actionlist is like), ;;We then pass it to the eventhandler, but ask it to hold it, ;;When we queued all the actions, we let the eventhandler execute them all (letrec ((run-through-actions (lambda (actionlist) (if (null? actionlist) 'done (let* ((first-action (car actionlist)) (first-action-name (car first-action)) (first-action-pars (cdr first-action)) (the-action (create-action-adt first-action-name spell-possesor (if (null? first-action-pars) '() (list first-action-pars))))) (core-eventhandler 'add the-action 'hold) (run-through-actions (cdr actionlist)))))) (display-action (create-action-adt 'display-spell spell-possesor (list spell-name)))) ;;display action will display the actual casting on the screen, ;;it passes an action ADT to the eventhandler ;;This adt (display-spell) expects 2 arguments: ;;the spell name, and its description (core-eventhandler 'add display-action 'hold) (run-through-actions spell-action-list)) ;;Execute the actions if playstyle is automatic (execute-actions))))) (define (dispatch m . args) (cond ((eq? m 'give-name) spell-name) ((eq? m 'give-spell-description) spell-description) ((eq? m 'give-cast-description) cast-description) ((eq? m 'give-actions) spell-action-list) ((eq? m 'give-possesor) spell-possesor) ((eq? m 'give-spells-cast-max) spells-cast-max) ((eq? m 'give-spell-reset-time) spell-reset-time) ((eq? m 'give-spells-cast-so-far) spells-cast-so-far) ((eq? m 'set-spell-description!) (set! spell-description (car args))) ((eq? m 'set-cast-description!) (set! cast-description (car args))) ((eq? m 'set-actions!) (set! spell-action-list (car args))) ((eq? m 'set-possesor!) (set! spell-possesor (car args))) ((eq? m 'set-spells-cast-max!) (set! spells-cast-max (car args))) ((eq? m 'set-spell-reset-time!) (set! spell-reset-time (car args))) ((eq? m 'set-spells-cast-so-far!) (set! spells-cast-so-far (car args))) ((eq? m 'priest-spell?) (eq? spell-type 'priest)) ((eq? m 'wizard-spell?) (eq? spell-type 'wizard)) ((eq? m 'get-type) 'spell) ;;to separate spells from items and weapons ((eq? m 'cast) (cast)) (else (error "Could not handle your request -- Create Spell ADT" m)))) dispatch))) ;;The Spellbook ADT (define (create-spellbook-adt possesor) ;;Based on an inventory tree adt ;;A spellbook stores the spells of a wizard or a priest ;;it expects a spell ADT as an input if you want to stock it, not a name (let ((the-spellbook (create-inventory-tree)) (spellbook-possesor possesor)) (define (add spell) (if (symbol? spell) (error "expects ADT not a symbol -- ADD -- SPELLBOOK" spell) ;;Expects an ADT as an input (begin (spell 'set-possesor! spellbook-possesor) (the-spellbook 'add spell)))) (define (give spell) (if (symbol? spell) (the-spellbook 'lookup spell) (error "expects symbol not an ADT -- GIVE -- SPELLBOOK" spell))) (define (erase spell) (let ((the-spell (if (symbol? spell) (give spell) spell))) (if the-spell (begin (the-spell 'set-possesor! 'nobody) (the-spellbook 'delete (get-object-name the-spell))) (display-line "You haven't got that Spell")))) (define (cast spell) (if (symbol? spell) ;;The spell is cast, if it has enough free casts (let ((the-spell (give spell))) (if the-spell (the-spell 'cast) (begin (display "The Spell ") (display spell) (display-line " was not found in your spellbook")))) (error "expects symbol not an ADT -- CAST -- SPELLBOOK"))) (define (for-each an-action) (the-spellbook 'for-each an-action)) (define (show) (the-spellbook 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args))) ;;Expects Spell ADT ((eq? m 'erase) (erase (car args))) ;;Expects Spell ADT or symbol ((eq? m 'give) (give (car args))) ;;Expects symbol ((eq? m 'cast) (cast (car args))) ;;Expects symbol ((eq? m 'for-each) (for-each (car args))) ;;Expects procedure ((eq? m 'show) (show)) (else (error "Could not handle your request -- Create Spellbook ADT" m)))) dispatch)) ;;The World ADT (define (create-world-adt name startpoint) ;; <<== Changed. ;;The world is represented by a directed weighted graph. ;;The weights of the edges are directions (north east south west) ;;The graph is implemented with edge lists ;;The startpoint indicates where a player begins his journey in the world, ;;It must be a Location ADT (let ((the-world-graph (create-graph eq? #t #t)) (world-name name) (start startpoint)) ;;The information will be tagged: ;;Via a conscell: car = location or world - cdr = the actual object (define (create-info tag object) (cons tag object)) (define (tag info) (car info)) (define (object info) (cdr info)) (define (insert-world a-world) ;;Graph expects a label and info ;;The world's name will be the label, ;;the info will be the ADT world itself (the-world-graph 'insert-node (a-world 'give-name) (create-info 'world a-world))) (define (insert-location a-location) ;;Graph expects a label and info ;;The location's name will be the label, ;;the info will be the ADT world itself (the-world-graph 'insert-node (a-location 'give-name) (create-info 'location a-location))) (define (insert-road location1 location2 direction . reversed?) ;;The direction must be north east south or west ;;If reversed is true; the world will create the reversed road automatically (define (reverse dir) (cond ((eq? dir 'east) 'west) ((eq? dir 'west) 'east) ((eq? dir 'north) 'south) ((eq? dir 'south) 'north) (else (error "Wrong direction -- Create World - Rerverse" dir)))) (the-world-graph 'insert-edge (location1 'give-name) (location2 'give-name) direction) (if (not (null? reversed?)) (the-world-graph 'insert-edge (location2 'give-name) (location1 'give-name) (reverse direction)))) (define (delete-location a-location) ;;Graph expects a label ;;This function also deletes worlds (the-world-graph 'delete-node (a-location 'give-name))) (define (delete-road location1 location2) ;;Graph expects 2 labels (the-world-graph 'delete-edge (location1 'give-name) (location2 'give-name))) (define (check-for a-tag a-location) ;;Graph expects a label, asks the information of a ;;location/world and checks its tag (let ((result (the-world-graph 'lookup-node-info (a-location 'give-name)))) (if result (eq? a-tag (tag result)) #f))) (define (give-location a-name) ;;Will check the world for a location with the given name ;;and returns that object (object (the-world-graph 'lookup-node-info a-name))) (define (give-neighbour a-location a-direction) (let ((the-neighbour 'unknown)) ;;graph expects a label and a action ;;a-action takes 5 arguments: ;;from-label from-info to-label to-info edge-info (the-world-graph 'foreach-neighbour (a-location 'give-name) (lambda (fromlbl frominfo tolbl toinfo edgeinfo) ;;If the direction equals the direction of the edge, ;;give the location ADT in that direction (if (eq? a-direction edgeinfo) (set! the-neighbour toinfo)))) ;;The foreach will return #t so we will have to ;;assign our neighbour manually (if (eq? the-neighbour 'unknown) 'not-found (object the-neighbour)))) (define (for-each-location do-something) ;;Graph expects a function with two arguments: the label and the info (the-world-graph 'foreach-node (lambda (node-label node-info) (do-something (object node-info))))) (define (map-over-locations do-something) ;;Graph expects a function with two arguments: the label and the info (the-world-graph 'map-over-nodes (lambda (node-label node-info) (do-something (object node-info))))) (define (for-each-neighbour location do-something) ;;Expects procedure with 5 arguments: fromlbl frominfo tolbl toinfo edgeinfo (the-world-graph 'foreach-neighbour (location 'give-name) do-something)) (define (give-road fromlocation tolocation) (the-world-graph 'lookup-edge (fromlocation 'give-name) (tolocation 'give-name))) (define (show) (for-each-location (lambda (location1) (for-each-location (lambda (location2) (if (give-road location1 location2) (begin (display "Road From ") (display (location1 'give-name)) (display " going ") (display (give-road location1 location2)) (display " to ") (display-line (location2 'give-name))))))))) (define (dispatch m . args) (cond ((eq? m 'give-name) world-name) ((eq? m 'insert-world) (insert-world (car args))) ;;Expects World ADT ((eq? m 'insert-location) (insert-location (car args))) ;;Expects Insert ADT ((eq? m 'insert-road) (apply insert-road args)) ;;Expects 2 location ADTs, a symbol and option ((eq? m 'delete-location) (delete-location (car args))) ;;Expects symbol ((eq? m 'delete-road) (delete-road (car args) (cadr args))) ;;Expects two symbols ((eq? m 'startpoint?) start) ;;Returns Location ADT ((eq? m 'set-startlocation!) (set! start (car args))) ;;Expects location ADT ((eq? m 'isworld?) (check-for 'world (car args))) ;;Expects ADT ((eq? m 'islocation?) (check-for 'location (car args))) ;;Expects ADT ((eq? m 'give-location) (give-location (car args))) ;;Returns Location/World ADT ((eq? m 'give-neighbour) (give-neighbour (car args) (cadr args))) ;;expects direction symbol ((eq? m 'for-each-location) (for-each-location (car args))) ;;Expects procedure with 2 arguments ((eq? m 'map-over-locations) (map-over-locations (car args))) ;;Expects procedure with 2 arguments ((eq? m 'for-each-neighbour) (for-each-neighbour (car args) (cadr args))) ((eq? m 'give-road) (give-road (car args) (cadr args))) ;;Expects 2 Location ADTs ((eq? m 'show) (show)) (else (error "Could not handle your request -- Create World ADT" m)))) dispatch)) ;;The Current Players ADT (define (current-players-adt) ;;A list of all active players (let ((player-list '())) (define (add player-name) ;;Accepts the name of a player (set! player-list (cons player-name player-list)) #t) (define (delete player-name) (define (delete-list name alist) (cond ((null? alist) '()) ((eq? (car alist) name) (cdr alist)) (else (cons (car alist) (delete-list name (cdr alist)))))) (set! player-list (delete-list player-name player-list)) (if (null? player-list) (begin (display-line "No more Players Alive") (set! game-over? #t)) #t)) (define (lookup player-name) ;;Checks whether the player is an active player, when found ;;it searches the ADT in the character table. (define (search pname plist) (cond ((null? plist) #f) ((eq? pname (car plist)) (get-character-adt (car plist))) (else (search pname (cdr plist))))) (search player-name player-list)) (define (show) (display-line "Players in the game: ") (for-each (lambda (player) (display-line player)) player-list)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args))) ;;Expects symbol ((eq? m 'delete) (delete (car args))) ;;Expects symbol ((eq? m 'lookup) (lookup (car args))) ;;Expects symbol ((eq? m 'give-player-list) player-list) ((eq? m 'show) (show)) (else (error "Could not handle your request -- Current Players" m)))) dispatch)) ;;all user options are stored here (define (the-options) (let ((difficulty 'normal) (heropoints-to-win 500) (playstyle 'continuous) (nr-of-actions-allowed 4) (action-execution 'automatic) (action-hold-offset 10) (iconmode 'on)) (define (change-difficulty value) ;;standard difficulty is normal ;;determines monster power and AI ;;choose between easy normal and hard (if (member value '(easy normal hard)) (begin (set! difficulty value) 'ok) 'failed)) (define (change-heropoints-to-win value) ;;standard is 500 ;;if a player reaches this heropoint total, he/she wins the game ;;choose any integer value you like (if (number? value) (begin (set! heropoints-to-win value) 'ok) 'failed)) (define (change-playstyle value turns) ;;standard is continuous ;;continuous playstyle does not require turns ;;turnbased playstyle requires the players to ;;play in a certain order, an integer must be given to ;;specify how many actions one may undertake in a turn ;;choose between continuous and turnbased (cond ((eq? value 'continuous) (set! playstyle 'continuous) 'ok) ((eq? value 'turnbased) (if (null? turns) 'failed (begin (set! playstyle 'turnbased) (set! nr-of-actions-allowed (car turns)) (the-turn-status 'reset-turncounter) ;;to reset the turns for all players ;;to the new number of turns 'ok))) (else 'failed))) (define (change-action-execution value) ;;standard is automatic ;;if automatic, then the eventhandler will automatically execute actions ;;if manual, then the players can themselves execute the actions at ;;the times they want ;;choose between automatic and manual (if (member value '(automatic manual)) (begin (set! action-execution value) 'ok) 'failed)) (define (change-action-hold-offset value) ;;standard is 10 ;;it is an offset for holding actions ;;eg, if a player types 'hold 5 <action>', ;;the eventhandler will add 10 (the offset) ;;to the 5, resulting in an enqueue with priority 15 (if (number? value) (begin (set! action-hold-offset value) 'ok) 'failed)) (define (change-iconmode value) ;;standard is on ;;display action icons or not (if (or (eq? value 'on) (eq? value 'off)) (begin (set! iconmode value) 'ok) 'failed)) (define (show) (newline) (display-line "*** GLOBAL OPTIONS ***") (display "Difficulty: ") (display difficulty) (display-line " (Standard is Normal - Easy/Normal/Hard)") (display "Heropoints needed to win: ") (display heropoints-to-win) (display-line " (Standard is 500 - Choose any number)") (display "Action Execution: ") (display action-execution) (display-line " (Standard is Automatic - Automatic/Manual)") (display "Playstyle: ") (display playstyle) (display " Turns: ") ; <<== Changed. (display nr-of-actions-allowed) (display-line " (Standard is Continuous - Continuous/Turnbased (enter list with number of turns))") (display "Action Offset: ") (display action-hold-offset) (display-line " (Standard is 10 - Choose any number)") (display "Iconmode: ") (display iconmode) (display-line " (Standard is on - On / Off)") (newline)) (define (dispatch m . args) (cond ((eq? m 'difficulty) difficulty) ((eq? m 'heropoints-to-win) heropoints-to-win) ((eq? m 'playstyle) playstyle) ((eq? m 'action-execution) action-execution) ((eq? m 'action-hold-offset) action-hold-offset) ((eq? m 'iconmode) iconmode) ((eq? m 'set-difficulty) (change-difficulty (car args))) ((eq? m 'set-heropoints-to-win) (change-heropoints-to-win (car args))) ((eq? m 'set-playstyle) (change-playstyle (car args) (cdr args))) ((eq? m 'nr-of-actions-allowed) nr-of-actions-allowed) ((eq? m 'set-action-execution) (change-action-execution (car args))) ((eq? m 'set-action-hold-offset) (change-action-hold-offset (car args))) ((eq? m 'set-iconmode) (change-iconmode (car args))) ((eq? m 'show) (show)) (else (error "Could not handle your request -- Options" m)))) dispatch)) (define (action-table) ;;The table consists of a hashtable containing all the info of the actions (let ((actions (create-table-adt 73 eq?))) ;;Abstractions (define (create-package name function) (cons name function)) (define (the-name data) (car data)) (define (the-function data) (cdr data)) ;;Done (define (add a-name a-function) ;;The key is the name of the action, it will be unique ;;Other parameters are: ;;The function which will be called to execute the given action (actions 'add a-name (create-package a-name a-function))) (define (delete a-name) (actions 'delete a-name)) (define (lookup a-name) (actions 'lookup a-name)) (define (show) (actions 'show)) (define (give key a-name) (cond ((eq? key 'name) (the-name (lookup a-name))) ((eq? key 'function) (the-function (lookup a-name))) (else (error "wrong key type -- Give -- Action table ADT" key)))) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args) (cadr args))) ((eq? m 'delete) (delete (car args))) ((eq? m 'lookup) (lookup (car args))) ((eq? m 'show) (show)) ((eq? m 'give-name) (give 'name (car args))) ((eq? m 'give-function) (give 'function (car args))) ((eq? m 'give-loadfactor) (actions 'give-loadfactor)) (else (error "Actions table could not handle your request" m)))) dispatch)) (define (character-table) ;;Keeps track of all characters in the game: ;;Monsters, NPCs and players ;;Based on a Table, more specific on a Hash Table with BST ADT (let ((the-characters (create-bst-table-adt 149 eq?))) (define (add-binding an-adt) ;;Expects ADT (the-characters 'add (an-adt 'give-name) an-adt)) (define (delete-binding a-character-name) ;;Expects symbol (the-characters 'delete a-character-name)) (define (lookup-adt name-of-adt) ;;Expects symbol (the-characters 'lookup name-of-adt)) (define (show-bindings) (the-characters 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (add-binding (car args))) ((eq? m 'delete) (delete-binding (car args))) ((eq? m 'lookup) (lookup-adt (car args))) ((eq? m 'give-loadfactor) (the-characters 'give-loadfactor)) ((eq? m 'show) (show-bindings)) (else (error "Could not handle your request -- Create Characters Table " m)))) dispatch)) (define (class-table) ;;Based on a Table ADT ;;The class table stores player classes (fighter, priest, wizard, rogue) ;;But also monster classes (zombie, dragon, elf, orc,...) ;;Also special monsters (like bosses) are stored here ;;The parameters of a class are variable, so parameters are randomly assigned ;;through the helpfunction random-range ;;The first item in the inventory MUST be an offensive weapon! The second must be a defensive weapon. (define (random-range lower upper) ;;Creates a random number between a lower and an upper bound (+ (quotient (* (random 100) (+ (- upper lower) 1)) 100) lower)) ;;The class table stores for players: ;;their parameters, possesions (items weapons and spells) and HP ;;for monsters their possesions, HP parameters and an additional description ;;IMPORTANT: the given parameters are COUPLES of the form '(lower . upper) ;;The class table will store the lower and upper boundaries and when asked for ;;a specific class, the class table will return a random value between the boundaries ;;This way, all monsters and players will be unique ;;Parameterlist = (strength constitution wisdom intelligence dexterity charisma) ;;each parameter is a couple (lower . upper) (let ((characters (create-table-adt 30 eq?))) ;;Abstractions (define (create-package class parameterlist hitpoints itemlist weaponlist spelllist . respawn) (list class parameterlist hitpoints itemlist weaponlist spelllist respawn)) (define (the-class data) (list-ref data 0)) (define (the-parameterlist data) (list-ref data 1)) (define (the-hitpoints data) (list-ref data 2)) (define (the-itemlist data) (list-ref data 3)) (define (the-weaponlist data) (list-ref data 4)) (define (the-spelllist data) (list-ref data 5)) (define (the-respawn-time data) (if (equal? (list-ref data 6) (list '())) 'none (caar (list-ref data 6)))) (define (lowerb couple) (car couple)) (define (upperb couple) (cdr couple)) ;;Done (define (add class parameterlist hitpoints itemlist weaponlist spelllist . respawn) (characters 'add class (create-package class parameterlist hitpoints itemlist weaponlist spelllist respawn))) (define (delete class-name) (characters 'delete class-name)) (define (lookup class-name) (characters 'lookup class-name)) (define (give-random-value a-couple) (random-range (lowerb a-couple) (upperb a-couple))) (define (give-random-values list-of-couples) (if (null? list-of-couples) '() (cons (give-random-value (car list-of-couples)) (give-random-values (cdr list-of-couples))))) (define (give key name) (let ((found-class (lookup name))) (if found-class (cond ((eq? key 'class) (the-class found-class)) ((eq? key 'parameters) (give-random-values (the-parameterlist found-class))) ((eq? key 'hitpoints) (give-random-value (the-hitpoints found-class))) ((eq? key 'weapons) (the-weaponlist found-class)) ((eq? key 'items) (the-itemlist found-class)) ((eq? key 'spells) (the-spelllist found-class)) ((eq? key 'respawn) (the-respawn-time found-class)) (else (error "Wrong key -- Give -- Class Table" key))) (error "Class not found in class Table" name)))) (define (show) (characters 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (apply add args)) ((eq? m 'delete) (delete (car args))) ((eq? m 'lookup) (lookup (car args))) ((eq? m 'give-class) (give 'class (car args))) ((eq? m 'give-parameters) (give 'parameters (car args))) ((eq? m 'give-hitpoints) (give 'hitpoints (car args))) ((eq? m 'give-weapons) (give 'weapons (car args))) ((eq? m 'give-items) (give 'items (car args))) ((eq? m 'give-spells) (give 'spells (car args))) ((eq? m 'give-respawn) (give 'respawn (car args))) ((eq? m 'give-loadfactor) (characters 'give-loadfactor)) ((eq? m 'show) (show)) (else (error "Could not handle your request -- Class Table" m)))) dispatch)) (define (items-table) ;;The table consists of a hashtable containing a binding ;;between the name of an item and the action that the item can perform, ;;it also contains a description of an item ;;Extras are parameters for the actions of the item, if none please enter '() (let ((items (create-table-adt 41 eq?))) ;;Abstractions (define (create-package name description function-list extra) (list name description function-list extra)) (define (the-name data) (car data)) (define (the-description data) (cadr data)) (define (the-functions data) (caddr data)) (define (extras data) (cadddr data)) ;;Done (define (add name description function-list extra) ;;Adds an item (that is: its name, its description and the actions it can perform ;;That actions is just a list of names of actions that can be looked up in the action table (items 'add name (create-package name description function-list extra))) (define (delete name) (items 'delete name)) (define (give key name) ;;Gives relevant information about the item (let ((the-item (items 'lookup name))) (if the-item (cond ((eq? key 'name) (the-name the-item)) ((eq? key 'description) (the-description the-item)) ((eq? key 'functions) (the-functions the-item)) ((eq? key 'extra) (extras the-item)) (else (error "Wrong key -- Give -- Items Table" key))) (error "Item was not found in the Items Table -- Items Table" name)))) (define (show) (items 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (add (car args) (cadr args) (caddr args) (cadddr args))) ((eq? m 'delete) (delete (car args))) ((eq? m 'give-name) (give 'name (car args))) ((eq? m 'give-description) (give 'description (car args))) ((eq? m 'give-functions) (give 'functions (car args))) ((eq? m 'give-extra) (give 'extra (car args))) ((eq? m 'give-loadfactor) (items 'give-loadfactor)) ((eq? m 'show) (show)) (else (error "Could not handle your request -- Items Table" m)))) dispatch)) (define (location-table) ;;The table consists of a hashtable containing all the info of the locations (let ((locations (create-table-adt 100 eq?))) ;;Abstractions (define (create-package name monsterlst npclst description alterdescription itemlst actions-on-enter-lst) (list name monsterlst npclst description alterdescription itemlst actions-on-enter-lst)) (define (the-name data) (list-ref data 0)) (define (monsterlst data) (list-ref data 1)) (define (npclst data) (list-ref data 2)) (define (description data) (list-ref data 3)) (define (alterdescription data) (list-ref data 4)) (define (itemlst data) (list-ref data 5)) (define (actionlst data) (list-ref data 6)) ;;Done (define (add name monsterlst npclst description alterdescription itemlst actions-lst) ;;The key is the name of the location, it will be unique ;;Other parameters are: ;;Monsterlist: list of monsters in the room ;;NPClist: list of npcs in the room ;;Description: the description of the room ;;alterdescription: an alternative description ;;Items: the items and weapons to be found in the room ;;Actions: the actions performed when a player enters the room (locations 'add name (create-package name monsterlst npclst description alterdescription itemlst actions-lst))) (define (delete name) (locations 'delete name)) (define (lookup name) (locations 'lookup name)) (define (show) (locations 'show)) (define (give key name) (cond ((eq? key 'name) (the-name (lookup name))) ((eq? key 'monster) (monsterlst (lookup name))) ((eq? key 'npc) (npclst (lookup name))) ((eq? key 'description) (description (lookup name))) ((eq? key 'alterdescription) (alterdescription (lookup name))) ((eq? key 'item) (itemlst (lookup name))) ((eq? key 'action) (actionlst (lookup name))) (else (error "wrong key type -- Give -- Locations ADT" key)))) (define (dispatch m . args) (cond ((eq? m 'add) (apply add args)) ((eq? m 'delete) (delete (car args))) ((eq? m 'lookup) (lookup (car args))) ((eq? m 'show) (show)) ((eq? m 'give-name) (give 'name (car args))) ((eq? m 'give-monster) (give 'monster (car args))) ((eq? m 'give-npc) (give 'npc (car args))) ((eq? m 'give-description) (give 'description (car args))) ((eq? m 'give-alterdescription) (give 'alterdescription (car args))) ((eq? m 'give-item) (give 'item (car args))) ((eq? m 'give-actions) (give 'action (car args))) ((eq? m 'give-loadfactor) (locations 'give-loadfactor)) (else (error "Locations Table could not handle your request" m)))) dispatch)) (define (npc-table) ;;Based on a Table adt ;;Name: the NPC name ;;Description: a brief description of the NPC ;;Startingpoint: where the NPC is found ;;Conversation: the text the NPC displays when you talk to him/her ;;Possesionlist: NPC possesions ;;Quest-Conditions: a list of conditions who need to be satisfied to trigger a quest ;;Quest-to-trigger: the name of the quest to trigger when the quest conditions are satisfied, ;;Quest conditions are checked when a player converses with an NPC (let ((npcs (create-table-adt 100 eq?))) ;;Abstractions (define (create-package name description startingpoint conversation itemlist weaponlist quest-conditions quest-to-trigger) (list name description startingpoint conversation itemlist weaponlist quest-conditions quest-to-trigger)) (define (the-name data) (list-ref data 0)) (define (the-description data) (list-ref data 1)) (define (the-startingpoint data) (list-ref data 2)) (define (the-conversation data) (list-ref data 3)) (define (the-items data) (list-ref data 4)) (define (the-weapons data) (list-ref data 5)) (define (the-q-conditions data) (list-ref data 6)) (define (the-q-to-trigger data) (list-ref data 7)) ;;Done (define (add name description startingpoint conversation itemlist weaponlist quest-conditions quest-to-trigger) (npcs 'add name (create-package name description startingpoint conversation itemlist weaponlist quest-conditions quest-to-trigger))) (define (delete name) (npcs 'delete name)) (define (give key name) (let ((the-npc (npcs 'lookup name))) (if the-npc (cond ((eq? key 'name) (the-name the-npc)) ((eq? key 'conversation) (the-conversation the-npc)) ((eq? key 'items) (the-items the-npc)) ((eq? key 'weapons) (the-weapons the-npc)) ((eq? key 'startingpoint) (the-startingpoint the-npc)) ((eq? key 'description) (the-description the-npc)) ((eq? key 'q-conditions) (the-q-conditions the-npc)) ((eq? key 'q-to-trigger) (the-q-to-trigger the-npc)) (else (error "Wrong Key -- Give -- NPC Table" key))) (error "NPC not found in table -- Give -- NPC Table" name)))) (define (show) (npcs 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (apply add args)) ((eq? m 'delete) (delete (car args))) ((eq? m 'give-name) (give 'name (car args))) ((eq? m 'give-conversation) (give 'conversation (car args))) ((eq? m 'give-items) (give 'items (car args))) ((eq? m 'give-weapons) (give 'weapons (car args))) ((eq? m 'give-startingpoint) (give 'startingpoint (car args))) ((eq? m 'give-description) (give 'description (car args))) ((eq? m 'give-q-conditions) (give 'q-conditions (car args))) ((eq? m 'give-quest) (give 'q-to-trigger (car args))) ((eq? m 'give-loadfactor) (npcs 'give-loadfactor)) ((eq? m 'show) (show)) (else (error "Could not handle your request -- NPC Table" m)))) dispatch)) (define (quest-table) (let ((the-quests (create-table-adt 30 eq?))) ;;Abstractions ;;Quests are a list of (name title description (triggerlist) heropoints) (define (create-package name title description triggers heropoints) (list name title description triggers heropoints)) (define (the-name quest) (list-ref quest 0)) (define (the-title quest) (list-ref quest 1)) (define (the-description quest) (list-ref quest 2)) (define (triggerlist quest) (list-ref quest 3)) (define (heropoints quest) (list-ref quest 4)) (define (add questname questtitle questdescription questtriggerlist herop) (the-quests 'add questname (create-package questname questtitle questdescription questtriggerlist herop))) (define (delete name) (the-quests 'delete name)) (define (lookup name) (the-quests 'lookup name)) (define (show) (the-quests 'show)) (define (give key name) (let ((the-quest (the-quests 'lookup name))) (if the-quest (cond ((eq? key 'name) (the-name the-quest)) ((eq? key 'title) (the-title the-quest)) ((eq? key 'description) (the-description the-quest)) ((eq? key 'triggers) (triggerlist the-quest)) ((eq? key 'heropoints) (heropoints the-quest)) (else (error "Wrong key -- Give -- Quest Table" key))) (error "Could not find Quest in Quest Table -- Quest Table" name)))) (define (dispatch m . args) (cond ((eq? m 'add) (apply add args)) ((eq? m 'delete) (delete (car args))) ((eq? m 'lookup) (lookup (car args))) ((eq? m 'show) (show)) ((eq? m 'give-name) (give 'name (car args))) ((eq? m 'give-title) (give 'title (car args))) ((eq? m 'give-description) (give 'description (car args))) ((eq? m 'give-trigger) (give 'triggers (car args))) ((eq? m 'give-heropoints) (give 'heropoints (car args))) ((eq? m 'give-loadfactor) (the-quests 'give-loadfactor)) (else (error "Could not handle your request -- Quest Table" m)))) dispatch)) (define (spell-table) ;;Based on Table ADT ;;A spell can only be used by wizards and priests ;;It consists of a name, a description for the caster (what the spell does), ;;a description for the game (what is shown when the spell is cast), a number of actions in a list, ;;the maximum number of times the spell can be cast, and the reset time of the spell, ;;That is: the time it takes for the player to be able to use the spell again ;;A word on the action list: it is of the form '((actionname . actionparameters) ( ... etc)) (let ((spells (create-table-adt 30 eq?))) ;;Abstractions (define (create-package name spelldescription castdescription actionlist max reset) (list name spelldescription castdescription actionlist max reset)) (define (the-name data) (list-ref data 0)) (define (the-spell-description data) (list-ref data 1)) (define (the-cast-description data) (list-ref data 2)) (define (the-actions data) (list-ref data 3)) (define (the-maximum-nr-of-casts data) (list-ref data 4)) (define (the-reset-time data) (list-ref data 5)) ;;Done (define (add name spelldescription castdescription actionlist max reset) (spells 'add name (create-package name spelldescription castdescription actionlist max reset))) (define (delete name) (spells 'delete name)) (define (give key name) (let ((the-spell (spells 'lookup name))) (if the-spell (cond ((eq? key 'name) (the-name the-spell)) ((eq? key 'spelldescription) (the-spell-description the-spell)) ((eq? key 'castdescription) (the-cast-description the-spell)) ((eq? key 'actions) (the-actions the-spell)) ((eq? key 'max-casts) (the-maximum-nr-of-casts the-spell)) ((eq? key 'reset-time) (the-reset-time the-spell)) (else (error "Wrong key -- Give -- Spell Table" key))) (error "Spell not found in the Spell Table -- Spell Table" name)))) (define (show) (spells 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (apply add args)) ((eq? m 'delete) (delete (car args))) ((eq? m 'give-name) (give 'name (car args))) ((eq? m 'give-spell-description) (give 'spelldescription (car args))) ((eq? m 'give-cast-description) (give 'castdescription (car args))) ((eq? m 'give-actions) (give 'actions (car args))) ((eq? m 'give-max-castings) (give 'max-casts (car args))) ((eq? m 'give-reset-time) (give 'reset-time (car args))) ((eq? m 'give-loadfactor) (spells 'give-loadfactor)) ((eq? m 'show) (show)) (else (error "Could not handle your request -- Spell Table" m)))) dispatch)) (define (weapons-table) ;;Based on the Table ADT (let ((weapons (create-table-adt 50 eq?))) ;;Abstractions (define (create-package name description statistics bonus-list extras) (list name description statistics bonus-list extras)) (define (the-name data) (car data)) (define (the-description data) (cadr data)) (define (the-statistics data) (caddr data)) (define (the-bonus data) (cadddr data)) (define (extras data) (list-ref data 4)) ;;Done (define (add name description statistics bonus extra) ;;Adds a weapon to the table (that is: its name, its description, its ;;Combat Modifiers and its Bonus, if it has no bonus, ;;please enter the symbol 'none ;;That bonus is just a name of an action (or actions) ;;that can be looked up in the action table ;;Extras are special messages, ;;like a message that only allows one usage of the bonus (weapons 'add name (create-package name description statistics bonus extra))) (define (delete name-of-weapon) (weapons 'delete name-of-weapon)) (define (give key name) ;;Gives relevant information about the weapon (let ((the-weapon (weapons 'lookup name))) (if the-weapon (cond ((eq? key 'name) (the-name the-weapon)) ((eq? key 'description) (the-description the-weapon)) ((eq? key 'statistics) (the-statistics the-weapon)) ((eq? key 'bonus) (the-bonus the-weapon)) ((eq? key 'extra) (extras the-weapon)) (else (error "Wrong key -- Give -- Weapons Table" key))) (error "Weapon was not found in the Weapons Table -- Weapons Table" name)))) (define (show) (weapons 'show)) (define (dispatch m . args) (cond ((eq? m 'add) (apply add args)) ((eq? m 'delete) (delete (car args))) ((eq? m 'give-name) (give 'name (car args))) ((eq? m 'give-description) (give 'description (car args))) ((eq? m 'give-statistics) (give 'statistics (car args))) ((eq? m 'give-bonus) (give 'bonus (car args))) ((eq? m 'give-extra) (give 'extra (car args))) ((eq? m 'give-loadfactor) (weapons 'give-loadfactor)) ((eq? m 'show) (show)) (else (error "Could not handle your request -- Weapons Table" m)))) dispatch)) ;;All abstractions involving actions on ADTs are listed here ;;Various ;;Little auxiliary functions (define (add-list name alist) (cons name alist)) (define (delete-list name alist) (cond ((null? alist) '()) ((eq? (car alist) name) (cdr alist)) (else (cons (car alist) (delete-list name (cdr alist)))))) (define (display-list alist) (for-each (lambda (item) (display item) (display " ")) alist)) (define (display-line x) (display x) (newline)) (define (chars->numbers a-symbol) ;;converts symbols into a number (let* ((a-string (symbol->string a-symbol)) (stringlist (string->list a-string))) (define (iter a-list result n) (cond ((null? a-list) result) (else (iter (cdr a-list) (+ result (* n (char->integer (car a-list)))) (+ n 1))))) (iter stringlist 0 1))) (define (tree-less? x y) (< (chars->numbers x) (chars->numbers y))) ;;******** Player and monster ADTs ********* (define (get-character-adt character) (if (symbol? character) (the-character-table 'lookup character) character)) ;;Useful function if it is not known wheter the action receives a player ADT or player symbol (define (get-from-character message character) ((get-character-adt character) message)) (define (write-to-character message data character) ((get-character-adt character) message data)) ;;Various abstractions to get character items (define (get-character-inventory character) (get-from-character 'give-inventory character)) (define (get-character-location character) (get-from-character 'give-location character)) (define (get-character-world character) (get-from-character 'give-world character)) (define (get-character-spellbook character) (get-from-character 'give-spellbook character)) (define (get-character-questlog character) (get-from-character 'give-questlog character)) (define (get-character-status character) (get-from-character 'give-status character)) (define (get-character-name character) (get-from-character 'give-name character)) (define (get-character-class character) (get-from-character 'give-class character)) (define (get-character-dexterity character) (get-from-character 'give-dexterity character)) (define (get-character-strength character) (get-from-character 'give-strength character)) (define (get-character-wisdom character) (get-from-character 'give-wisdom character)) (define (get-character-intelligence character) (get-from-character 'give-intelligence character)) (define (get-character-constitution character) (get-from-character 'give-constitution character)) (define (get-character-charisma character) (get-from-character 'give-charisma character)) (define (get-offensive-weapon character) (give-item-from-character (get-from-character 'give-offensive-weapon character) character)) (define (get-defensive-weapon character) (give-item-from-character (get-from-character 'give-defensive-weapon character) character)) (define (get-character-heropoints character) (get-from-character 'give-heropoints character)) (define (get-character-hitpoints character) (get-from-character 'give-hitpoints character)) (define (get-previous-worlds character) (get-from-character 'give-previous-worlds character)) (define (get-previous-locations character) (get-from-character 'give-previous-locations character)) (define (set-character-location locationadt character) (write-to-character 'set-location! locationadt character)) (define (set-character-status value character) (write-to-character 'set-status! value character)) (define (set-offensive-weapon item character) (write-to-character 'set-offensive-weapon! item character)) (define (set-defensive-weapon item character) (write-to-character 'set-defensive-weapon! item character)) (define (set-character-world world character) (write-to-character 'set-world! world character)) (define (set-previous-worlds worldlist character) (write-to-character 'set-previous-worlds! worldlist character)) (define (set-previous-locations locationlist character) (write-to-character 'set-previous-locations! locationlist character)) ;;Abstractions to change location and world pointers for a character (define (add-previous-world-for-character world character) (let ((the-character-worldlist (get-previous-worlds character))) (set-previous-worlds (add-list world the-character-worldlist) character))) (define (delete-previous-world-for-character world character) (let ((the-character-worldlist (get-previous-worlds character))) (set-previous-worlds (delete-list world the-character-worldlist) character))) (define (add-previous-location-for-character location character) (let ((the-character-locationlist (get-previous-locations character))) (set-previous-locations (add-list location the-character-locationlist) character))) (define (delete-previous-location-for-character location character) (let ((the-character-locationlist (get-previous-locations character))) (set-previous-locations (delete-list location the-character-locationlist) character))) ;;Abstractions to alter numerical values of a player (define (change-stats get-message write-message sign amount character) (let ((stat (get-from-character get-message character))) (write-to-character write-message (sign stat amount) character))) (define (do-hitpoints-up amount character) (change-stats 'give-hitpoints 'set-hitpoints! + amount character)) (define (do-hitpoints-down amount character) (change-stats 'give-hitpoints 'set-hitpoints! - amount character)) (define (do-heropoints-up amount character) (change-stats 'give-heropoints 'set-heropoints! + amount character)) (define (do-strength-up amount character) (change-stats 'give-strength 'set-strength! + amount character)) (define (do-constitution-up amount character) (change-stats 'give-constitution 'set-constitution! + amount character)) (define (do-wisdom-up amount character) (change-stats 'give-wisdom 'set-wisdom! + amount character)) (define (do-intelligence-up amount character) (change-stats 'give-intelligence 'set-intelligence! + amount character)) (define (do-dexterity-up amount character) (change-stats 'give-dexterity 'set-dexterity! + amount character)) (define (do-charisma-up amount character) (change-stats 'give-charisma 'set-charisma! + amount character)) (define (do-strength-down amount character) (change-stats 'give-strength 'set-strength! - amount character)) (define (do-constitution-down amount character) (change-stats 'give-constitution 'set-constitution! - amount character)) (define (do-wisdom-down amount character) (change-stats 'give-wisdom 'set-wisdom! - amount character)) (define (do-intelligence-down amount character) (change-stats 'give-intelligence 'set-intelligence! - amount character)) (define (do-dexterity-down amount character) (change-stats 'give-dexterity 'set-dexterity! - amount character)) (define (do-charisma-down amount character) (change-stats 'give-charisma 'set-charisma! - amount character)) (define (alive? character) (let ((character-adt (get-character-adt character))) (if character-adt (if (eq? 'alive (get-character-status character-adt)) #t #f) #f))) (define (dead? character) (let ((character-adt (get-character-adt character))) (if character-adt (if (eq? 'alive (get-character-status character-adt)) #f #t) #t))) ;;Manipulations on a player Inventory (define (add-item-for-character item character) (let ((inv (get-character-inventory character))) (inv 'add item))) (define (delete-item-for-character item character) (let ((inv (get-character-inventory character))) (inv 'drop item))) (define (drop-item-for-character item character) (let ((inv (get-character-inventory character)) (off-weapon (get-offensive-weapon character)) (def-weapon (get-defensive-weapon character))) (inv 'drop item) (cond ((eq? item off-weapon) (set-offensive-weapon 'none character)) ((eq? item def-weapon) (set-defensive-weapon 'none character))))) (define (use-item-for-character item character) (let ((inv (get-character-inventory character))) (inv 'use item))) (define (give-item-from-character item character) (let ((inv (get-character-inventory character))) (inv 'give item))) ;;Manipulations on a character Spellbook (define (add-spell-for-character spell character) (let ((spb (get-character-spellbook character))) (spb 'add spell))) (define (erase-spell-for-character spell character) (let ((spb (get-character-spellbook character)) (spell-name (get-object-name spell))) (if spell-name (spb 'erase spell-name) #f))) (define (cast-spell-for-character spell character) (let ((spb (get-character-spellbook character))) (spb 'cast spell))) (define (give-spell-from-character spell character) (if (procedure? spell) spell (let ((spb (get-character-spellbook character))) (spb 'give spell)))) ;;Manipulations on a character Questlog (define (add-quest-for-character quest character) (let ((qlog (get-character-questlog character))) (qlog 'add quest))) (define (delete-quest-for-character quest character) (let ((qlog (get-character-questlog character)) (quest-name (get-object-name quest))) (if quest-name (qlog 'delete quest-name) #f))) (define (trigger-quest-for-character quest character) (let ((qlog (get-character-questlog character))) ((qlog 'give quest) 'trigger character))) (define (give-quest-from-character quest character) (let ((qlog (get-character-questlog character))) (qlog 'give quest))) ;;Tests whether a character is a player, a monster or an npc (define (typecheck character type) ;;predicate that tests for an active player (let ((the-character (get-character-adt character))) (if the-character (eq? (the-character 'character-type) type) #f))) (define (isplayer? character) (typecheck character 'player)) (define (ismonster? character) (typecheck character 'monster)) (define (isnpc? character) (typecheck character 'npc)) ;;********** NPC ADTs ********** (define (get-npc-adt npc) (if (symbol? npc) (the-character-table 'lookup npc) npc)) ;;Useful function if it is not known wheter the action ;;receives a npc ADT or npc symbol (define (get-from-npc message npc) ((get-npc-adt npc) message)) (define (write-to-npc message data npc) ((get-npc-adt npc) message data)) ;;Various abstractions to get npc items (define (get-npc-inventory npc) (get-from-npc 'give-inventory npc)) (define (get-npc-location npc) (get-from-npc 'give-location npc)) (define (get-npc-status npc) (get-from-npc 'give-status npc)) (define (get-npc-name npc) (get-from-npc 'give-name npc)) (define (set-npc-status! value npc) (write-to-npc 'set-status! value npc)) (define (get-npc-conversation npc) (get-from-npc 'give-conversation npc)) (define (get-npc-description npc) (get-from-npc 'give-description npc)) ;;Manipulations on a npc Inventory (define (add-item-for-npc item npc) (let ((inv (get-npc-inventory npc))) (inv 'add item))) (define (drop-item-for-npc item npc) (let ((inv (get-npc-inventory npc)) (item-name (get-object-name item))) (inv 'drop item-name))) (define (use-item-for-npc item npc) (let ((inv (get-npc-inventory npc))) (inv 'use item))) ;;*********** Location ADT *********** (define (get-location-adt location . a-world) (let ((search-world (if (null? a-world) the-world (car a-world)))) (if (symbol? location) (search-world 'give-location location) location))) (define (test-for-presence a-character-list) ;;Tests whether there are any characters in the room (not (null? a-character-list))) (define (test-characters object a-charlist) ;;shows all characters in the room (if (test-for-presence a-charlist) (begin (display object) (display " in this area: ") (display-list a-charlist) (newline)) (begin (display "There are no ") (display object) (display " in this area.") (newline)))) ;;Useful function if it is not known wheter the action ;;receives a location ADT or location symbol (define (get-from-location message location world) ((get-location-adt location world) message)) (define (write-to-location message data location world) ((get-location-adt location world) message data)) (define (get-location-name location world) (get-from-location 'give-name location world)) (define (get-location-description location world) (get-from-location 'give-description location world)) (define (get-location-items location world) (get-from-location 'give-item location world)) (define (set-location-items location newdata world) (write-to-location 'set-item! newdata location world)) (define (get-location-monsters location world) (get-from-location 'give-monster location world)) (define (get-location-players location world) (get-from-location 'give-players location world)) (define (get-location-npcs location world) (get-from-location 'give-npc location world)) (define (get-location-alterdescription location world) (get-from-location 'give-alterdescription location world)) (define (get-exit-to-direction location world) (car (get-from-location 'give-monster location world))) (define (exit-location? a-location a-world) (let* ((location (get-location-adt a-location a-world)) (possible-directions (location 'give-monster))) (or (member 'north possible-directions) (member 'east possible-directions) (member 'south possible-directions) (member 'west possible-directions)))) (define (add-character-to-location type character location) (let ((search-world (get-character-world character))) (cond ((eq? type 'player) (write-to-location 'set-players! (add-list character (get-location-players location search-world)) location search-world)) ((eq? type 'monster) (write-to-location 'set-monster! (add-list character (get-location-monsters location search-world)) location search-world)) ((eq? type 'npc) (write-to-location 'set-npc! (add-list character (get-location-npcs location search-world)) location search-world)) (else (error "Wrong type -- Add character to location -- Abstractions " type))))) (define (delete-character-from-location type character location) (let ((search-world (get-character-world character))) (cond ((eq? type 'player) (write-to-location 'set-players! (delete-list character (get-location-players location search-world)) location search-world)) ((eq? type 'monster) (write-to-location 'set-monster! (delete-list character (get-location-monsters location search-world)) location search-world)) ((eq? type 'npc) (write-to-location 'set-npc! (delete-list character (get-location-npcs location search-world)) location search-world)) (else (error "Wrong type -- Delete character to location -- Abstractions " type))))) (define (add-player-to-location player location) (add-character-to-location 'player (get-character-name player) location)) (define (add-monster-to-location monster location) (add-character-to-location 'monster (get-character-name monster) location)) (define (add-npc-to-location npc location) (add-character-to-location 'npc (get-npc-name npc) location)) (define (delete-player-from-location player location) (delete-character-from-location 'player (get-character-name player) location)) (define (delete-monster-from-location monster location) (delete-character-from-location 'monster (get-character-name monster) location)) (define (delete-npc-from-location npc location) (delete-character-from-location 'npc (get-npc-name npc) location)) ;;*********** Various for Inventory/Spellbook/Questlog and Objects ********** (define (write-to-adt message data adt) (adt message data)) (define (get-from-object message object) ((get-object-adt object) message)) (define (get-object-adt object) (if (symbol? object) (error "Expects object not a symbol -- Get object ADT " object) object)) (define (get-object-name object) (if (symbol? object) object (object 'give-name))) ;;************** Spell ADT ************* (define (spell? spell-adt) (eq? 'spell (spell-adt 'get-type))) (define (get-spell-description spell) (get-from-object 'give-spell-description spell)) (define (get-cast-description spell) (get-from-object 'give-cast-description spell)) (define (get-spell-max spell) (get-from-object 'give-spells-cast-max spell)) (define (get-spell-current spell) (get-from-object 'give-spells-cast-so-far spell)) ;;*********** Inventory ADT *********** ;;An object is an Item or a weapon (define (add-object-to-inventory object inventory) (write-to-adt 'add (get-object-adt object) inventory)) (define (delete-object-from-inventory object inventory) (write-to-adt 'delete (get-object-name object) inventory)) (define (lookup-object-in-inventory object inventory) (write-to-adt 'give (get-object-name object) inventory)) (define (use-object-in-inventory object inventory) (write-to-adt 'use (get-object-name object) inventory)) ;;*********** Spellbook ADT ************ (define (add-spell-to-spellbook spell spellbook) (write-to-adt 'add (get-object-adt spell) spellbook)) (define (delete-spell-from-spellbook spell spellbook) (write-to-adt 'delete (get-object-name spell) spellbook)) (define (lookup-spell-in-spellbook spell spellbook) (write-to-adt 'give (get-object-adt spell) spellbook)) (define (cast-spell-in-spellbook spell spellbook) (write-to-adt 'cast (get-object-adt spell) spellbook)) ;;*********** Questlog ADT ************ (define (add-quest-to-questlog quest questlog) (write-to-adt 'add (get-object-adt quest) questlog)) (define (mark-quest-as-done quest questlog) (write-to-adt 'mark-as-done (get-object-adt quest) questlog)) (define (give-quest-heropoints quest questlog) (write-to-adt 'give-heropoints (get-object-name quest) questlog)) ;;************ Item ADT ************ (define (item? item-adt) (eq? 'item (item-adt 'get-type))) (define (set-item-possesor item possesor) (item 'set-possesor! possesor)) ;;************ Weapon ADT *********** (define (weapon? weapon-adt) (eq? 'weapon (weapon-adt 'get-type))) (define (change-stat givestat putstat sign amount weapon) (weapon putstat (sign (weapon givestat) amount))) (define (increase-attack-bonus amount weapon) (change-stat 'give-attack-bonus 'set-attack-bonus! + amount weapon)) (define (increase-defense-bonus amount weapon) (change-stat 'give-defense-bonus 'set-defense-bonus! + amount weapon)) ;;All command handler abstractions are listed here ;;These tests classify user commands (define (the-executor command) (car command)) (define (the-keyword command) (cadr command)) (define (other-parameters command) (cddr command)) (define (keyword-extension command) (caddr command)) (define (command-keyword-with-pars? keyword command) (if (list? command) (and (eq? (the-keyword command) keyword) (symbol? (the-executor command)) (not (null? (other-parameters command)))) #f)) (define (command-keyword? keyword command) (if (list? command) (and (eq? (the-keyword command) keyword) (symbol? (the-executor command))) #f)) (define (move-command? command) (command-keyword-with-pars? 'moves command)) (define (cast-command? command) (command-keyword-with-pars? 'casts command)) (define (drop-all-command? command) (and (command-keyword-with-pars? 'drops command) (eq? (keyword-extension command) 'all))) (define (get-all-command? command) (and (command-keyword-with-pars? 'gets command) (eq? (keyword-extension command) 'all))) (define (get-command? command) (command-keyword-with-pars? 'gets command)) (define (drop-command? command) (command-keyword-with-pars? 'drops command)) (define (erase-command? command) (command-keyword-with-pars? 'erases command)) (define (use-command? command) (command-keyword-with-pars? 'uses command)) (define (read-command? command) (command-keyword-with-pars? 'reads command)) (define (examine-command? command) (command-keyword-with-pars? 'examines command)) (define (attack-command? command) (command-keyword-with-pars? 'attacks command)) (define (look-command? command) (command-keyword? 'looks command)) (define (talk-command? command) (command-keyword? 'talks command)) (define (flee-command? command) (command-keyword? 'flees command)) (define (steal-command? command) (command-keyword? 'steals command)) (define (ask-command? command) (command-keyword-with-pars? 'asks command)) (define (ask-exits? command) (and (ask-command? command) (eq? (keyword-extension command) 'exits))) (define (ask-actions? command) (and (ask-command? command) (eq? (keyword-extension command) 'actions))) (define (ask-status? command) (and (ask-command? command) (eq? (keyword-extension command) 'status))) (define (ask-inventory? command) (and (ask-command? command) (eq? (keyword-extension command) 'inventory))) (define (ask-spellbook? command) (and (ask-command? command) (eq? (keyword-extension command) 'spellbook))) (define (ask-questlog? command) (and (ask-command? command) (eq? (keyword-extension command) 'questlog))) (define (equip-command? command) (command-keyword-with-pars? 'equips command)) (define (equip-offense-command? command) (and (equip-command? command) (eq? (keyword-extension command) 'offensive) (eq? (cadddr command) 'weapon))) (define (equip-defense-command? command) (and (equip-command? command) (eq? (keyword-extension command) 'defensive) (eq? (cadddr command) 'weapon))) (define (cancel-actions? command) (and (list? command) (not (null? (cdr command))) (eq? (cadr command) 'cancels) (not (null? (cddr command))))) (define (on-hold? command) (and (eq? (car command) 'hold) (number? (cadr command)) (not (null? (cddr command))))) (define (hold-time command) (cadr command)) (define (dump-hold command) (cddr command)) ;;The command handler will analyze the command, and then dispatch it ;;the execute-command action will take care of the proper execution of ;;the specified command (define (command-handler command time) (cond ((move-command? command) (execute-command 'move (filter-keyword command) time)) ((cast-command? command) (execute-command 'cast (filter-keyword command) time)) ((drop-all-command? command) (execute-command 'drop-all (filter-rest command) time)) ((get-all-command? command) (execute-command 'get-all (filter-rest command) time)) ((drop-command? command) (execute-command 'drop (filter-keyword command) time)) ((erase-command? command) (execute-command 'erase (filter-keyword command) time)) ((get-command? command) (execute-command 'get (filter-keyword command) time)) ((use-command? command) (execute-command 'use (filter-keyword command) time)) ((read-command? command) (execute-command 'player-read (filter-keyword command) time)) ((examine-command? command) (execute-command 'player-examine (filter-keyword command) time)) ((attack-command? command) (execute-command 'combat (filter-keyword command) time)) ((look-command? command) (execute-command 'look (filter-rest command) time)) ((talk-command? command) (execute-command 'converse (filter-keyword command) time)) ((flee-command? command) (execute-command 'flee (filter-keyword command) time)) ((steal-command? command) (execute-command 'steal (filter-keyword command) time)) ((ask-exits? command) (execute-command 'show-exits (filter-rest command) 'no-enqueue)) ((ask-actions? command) (execute-command 'show-actions (filter-rest command) 'no-enqueue)) ((cancel-actions? command) (execute-command 'cancel-actions (filter-keyword command) 'no-enqueue)) ((equip-offense-command? command) (execute-command 'equip-offence (filter-equip command) time)) ((equip-defense-command? command) (execute-command 'equip-defense (filter-equip command) time)) ((ask-status? command) (execute-command 'show-status (filter-rest command) 'no-enqueue)) ((ask-inventory? command) (execute-command 'show-inventory (filter-rest command) time)) ((ask-spellbook? command) (execute-command 'show-spellbook (filter-rest command) time)) ((ask-questlog? command) (execute-command 'show-questlog (filter-rest command) time)) (else (display-line "Bad command. Enter show commands to see a list of valid commands.")))) (define (filter-keyword command) (cons (car command) (cddr command))) (define (filter-rest command) (list (car command))) (define (filter-equip command) (cons (car command) (cddddr command))) (define (execute-command action-type commandpars time) (let* ((command-executor (car commandpars)) (command-type action-type) (command-parameters (cdr commandpars)) (command-action (create-action-adt command-type command-executor command-parameters))) (if (eq? time 'no-enqueue) (core-eventhandler 'add command-action) (core-eventhandler 'add command-action time)) (execute-actions))) ;;The option actions are listed here ;;Global options is the name of the global options ADT created ;;Aliases (define (action-execution-automatic? options) (eq? (options 'action-execution) 'automatic)) (define (get-heropoints-to-win options) (options 'heropoints-to-win)) (define (get-difficulty options) (options 'difficulty)) (define (playstyle-continuous? options) (eq? (options 'playstyle) 'continuous)) (define (icons-on? options) (eq? (options 'iconmode) 'on)) (define (execute-actions) (if (action-execution-automatic? global-options) (core-eventhandler 'execute-step 1) 'done)) (define (show-options) (global-options 'show)) (define (setup-options) (define (change-options choice value) (cond ((eq? choice 'difficulty) (print-change (global-options 'set-difficulty value))) ((eq? choice 'heropoints) (print-change (global-options 'set-heropoints-to-win value))) ((eq? choice 'playstyle) (print-change (if (list? value) (global-options 'set-playstyle (car value) (cadr value)) (global-options 'set-playstyle value)))) ((eq? choice 'action-execution) (print-change (global-options 'set-action-execution value))) ((eq? choice 'action-hold-offset) (print-change (global-options 'set-action-hold-offset value))) ((eq? choice 'icons) (print-change (global-options 'set-iconmode value))) (else (error "Wrong choice -- Change options" choice)))) (define (print-change result) (if (eq? result 'ok) (display-line "Options changed succesfully") (display-line "Wrong value for that option. Options have not changed")) (newline)) (newline) (display-line "*** Welcome to the Setup options menu ***") (global-options 'show) (newline) (display-line "Which option do you want to change?") (display-line "Difficulty -- Heropoints -- Playstyle -- Action-Execution -- Action-Hold-Offset -- Icons") (display "Choose one: ") (let ((choice (read))) (if (member choice '(difficulty heropoints playstyle action-execution action-hold-offset icons)) (begin (display "Enter new value: ") (let ((input (read))) (change-options choice input))) (begin (display "Wrong choice: ") (display-line choice) (newline))))) ;;Various useful actions ;;most are building blocks for spells ;;functions to alter character stats (define (stats-up stat stat-message player an-amount) (let ((amount (if (pair? an-amount) ;;eg 2d6 => (2 . 6) => diceroll needed (dicethrow an-amount) an-amount))) (stat-message amount player) (display (get-character-name player)) (display " gained ") (display amount) (display-line stat))) (define (stats-down stat stat-message player an-amount) (let ((amount (if (pair? an-amount) (dicethrow an-amount) an-amount))) (stat-message amount player) (display (get-character-name player)) (display " lost ") (display amount) (display-line stat))) (define (hp-up player amount) (stats-up " hitpoints" do-hitpoints-up player amount)) (define (heropoints-up player amount) (stats-up " heropoints" do-heropoints-up player amount)) (define (strength-up player amount) (stats-up " strength points" do-strength-up player amount)) (define (dexterity-up player amount) (stats-up " dexterity points" do-dexterity-up player amount)) (define (constitution-up player amount) (stats-up " constitution points" do-constitution-up player amount)) (define (wisdom-up player amount) (stats-up " wisdom points" do-wisdom-up player amount)) (define (intelligence-up player amount) (stats-up " intelligence points" do-intelligence-up player amount)) (define (charisma-up player amount) (stats-up " charisma points" do-charisma-up player amount)) (define (hp-down player amount) (stats-down " hitpoints" do-hitpoints-down player amount)) (define (strength-down player amount) (stats-down " strength points" do-strength-down player amount)) (define (dexterity-down player amount) (stats-down " dexterity points" do-dexterity-down player amount)) (define (constitution-down player amount) (stats-down " constitution points" do-constitution-down player amount)) (define (wisdom-down player amount) (stats-down " wisdom points" do-wisdom-down player amount)) (define (intelligence-down player amount) (stats-down " intelligence points" do-intelligence-down player amount)) (define (charisma-down player amount) (stats-down " charisma points" do-charisma-down player amount)) ;;this function shows all targets and lets you select one (define (select-target-in-room a-player type) (define (show-targets) (cond ((eq? type 'all) (show-targets-in-room a-player 'players) (show-targets-in-room a-player 'monsters)) ((eq? type 'players) (show-targets-in-room a-player 'players)) ((eq? type 'monsters) (show-targets-in-room a-player 'monsters)) ((eq? type 'npcs) (show-targets-in-room a-player 'npcs)) (else (error "Wrong type -- Select Target In room" type)))) (define (test-target target-name) (let* ((current-world (get-character-world a-player)) (current-location (get-character-location a-player)) (possible-human-targets (get-location-players current-location current-world)) (possible-monster-targets (get-location-monsters current-location current-world)) (possible-npc-targets (get-location-npcs current-location current-world))) (cond ((eq? type 'all) (or (memq target-name possible-human-targets) (memq target-name possible-monster-targets))) ((eq? type 'players) (memq target-name possible-human-targets)) ((eq? type 'monsters) (memq target-name possible-monster-targets)) ((eq? type 'npcs) (memq target-name possible-npc-targets))))) (define (select-target) (display "Select Target: ") (let* ((targetname (read)) (target (the-character-table 'lookup targetname))) (if (test-target targetname) (if target target (begin (display-line "That is not a valid target.") #f)) (begin (display-line "That target is not in this area.") #f)))) (if (isplayer? a-player) (begin (display-line "Available Targets: ") (show-targets) (select-target)) (select-random-player (get-character-location a-player)))) ;;this function shows players, monsters or npcs (define (show-targets-in-room a-player charactertype) (let* ((player-world (get-character-world a-player)) (location (get-character-location a-player)) (location-adt (get-location-adt location player-world))) (cond ((eq? charactertype 'monsters) (test-characters 'monsters (get-location-monsters location-adt player-world))) ((eq? charactertype 'players) (test-characters 'players (get-location-players location-adt player-world))) ((eq? charactertype 'npcs) (test-characters 'npcs (get-location-npcs location-adt player-world))) (else (error "Wrong Charactertype -- Show Targets in room -- Various Actions" charactertype))))) ;;action used for monsters to select their target when casting spells (define (select-random-player a-location) (let* ((player-list (a-location 'give-players)) (listlength (length player-list)) (choice (if (null? player-list) #f (random listlength)))) (if choice (get-character-adt (list-ref player-list choice)) choice))) ;;shows all monsters and players, ;;lets you select one and deals an amount of damage to your target (define (deal-x-damage-to-target dealer the-damage) (let* ((damage (if (pair? the-damage) (dicethrow the-damage) the-damage)) (caster-adt (get-character-adt dealer)) (target (if (isplayer? caster-adt) (select-target-in-room dealer 'all) ;;players choose their targets themselves (select-random-player (get-character-location caster-adt))))) ;;monsters choose random players (if target (begin (display (target 'give-name)) (display " suffered ") (display damage) (display-line " damage.") (do-hitpoints-down damage target))))) (define (display-spell caster spell) (let ((spell-adt (give-spell-from-character spell caster))) (if spell-adt (begin (display (get-character-name caster)) (display " is casting a ") (display-line (get-object-name spell)) (display-line (spell-adt 'give-cast-description))) 'done))) (define (reset-spell possesor spell) (let ((spell-adt (give-spell-from-character spell possesor))) (if spell-adt (spell-adt 'set-spells-cast-so-far! 0) 'done))) ;;this might be the case when ;;the wizard dropped the spell in the meanwhile (define (perform-enter-actions-for-location player) ;;Performs all the actions a location should undertake ;;when a player enters the room (define (iter actionlist) (if (null? actionlist) 'done (begin (let* ((action-name (car actionlist)) (action-adt (create-action-adt action-name (get-character-name player) '()))) (core-eventhandler 'add action-adt 'hold)) (iter (cdr actionlist))))) (let* ((the-location (get-character-location player)) (location-actions (the-location 'give-actions))) (if (null? location-actions) (execute-actions) (begin (iter location-actions) (execute-actions))))) ;;All specific spell casting actions are listed here (define (cast-doom caster) ;;casts the spell doom (let ((target (select-target-in-room caster 'all)) (damage (cons 2 4))) (if target (begin (strength-down target damage) (dexterity-down target damage) (constitution-down target damage) (charisma-down target damage) (display (get-character-name target)) (display-line " is doomed") (let ((undo-action (create-action-adt 'undo-doom-effects target '())) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30))))))) (define (cast-judgement caster) ;;casts the spell judgement (let* ((target (select-target-in-room caster 'all)) (caster-charisma (get-character-charisma caster)) (target-charisma (get-character-charisma target)) (damage (- caster-charisma target-charisma))) (if target (if (< damage 0) (begin (display (get-character-name target)) (display-line "has been judged positive")) (begin (strength-down target damage) (dexterity-down target damage) (constitution-down target damage) (charisma-down target damage) (display (get-character-name target)) (display-line " is judged negative") (let ((undo-action (create-action-adt 'undo-doom-effects target (list damage))) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30)))))))) (define (cast-curse caster) ;;casts the spell curse (let ((target (select-target-in-room caster 'all)) (damage (round (/ (get-character-wisdom caster) 3)))) (if target (begin (intelligence-down target damage) (wisdom-down target damage) (display (get-character-name target)) (display-line " is cursed") (let ((undo-action (create-action-adt 'undo-curse-effects target (list damage))) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30))))))) (define (summon caster creature-type) (define (conditions-fulfilled? player creature type) (let* ((the-player (get-character-adt player)) (player-strength (get-character-strength the-player)) (player-wisdom (get-character-strength the-player)) (player-intelligence (get-character-strength the-player)) (player-charisma (get-character-strength the-player)) (creature-strength (get-character-strength creature)) (creature-charisma (get-character-strength creature)) (creature-wisdom (get-character-wisdom creature)) (creature-intelligence (get-character-intelligence creature)) (greater-strength? (> creature-strength player-strength)) (greater-charisma? (> creature-charisma player-charisma)) (greater-intelligence? (> creature-intelligence player-intelligence)) (greater-wisdom? (> creature-wisdom player-wisdom))) (cond ((eq? type 'demon) (if (and greater-strength? greater-charisma?) (begin (combat creature caster) ;;demon turns agains his owner #f) #t)) ((eq? type 'angel) (if (and greater-strength? greater-charisma?) #f #t)) ((eq? type 'imp) (if greater-charisma? #f #t)) ((eq? type 'dragon) (if (and greater-strength? greater-charisma? greater-intelligence? greater-wisdom?) (begin (combat creature caster) ;;dragon turns againts his owner #f) (if (and greater-strength? greater-intelligence?) #f #t))) ((eq? type 'shadow) (if greater-wisdom? #f #t)) (else #t)))) (let* ((summon-location (get-character-location caster)) (summoned-creature (make-monster 'summoned-monster creature-type summon-location)) (unsummon-action (create-action-adt 'unsummon-monster 'summoned-monster (list summoned-creature))) (run-time (core-eventhandler 'give-runtime))) (display "You summoned a ") (display-line creature-type) (display-line "Who do you want it to attack?") (let ((target (select-target-in-room caster 'all))) (if target (if (conditions-fulfilled? caster summoned-creature creature-type) ;;some creatures require conditions to be fulfilled (begin (combat summoned-creature target) ;;engage in combat (core-eventhandler 'add unsummon-action (+ run-time 5)) (display-line "Creature will be unsummoned in 5 turns")) (display-line "Cannot summon: conditions for summoning such creature not fulfilled")))))) (define (cast-force-drop caster) (let ((target (select-target-in-room caster 'all))) (if target (begin (drop-all target) (display-line "Your force drop spell was effective"))))) (define (cast-terror caster) ;;casts the spell terror (let ((target (select-target-in-room caster 'all)) (damage (get-character-intelligence caster))) (if target (begin (strength-down target damage) (dexterity-down target damage) (constitution-down target damage) (charisma-down target damage) (intelligence-down target damage) (wisdom-down target damage) (drop-all target) (display (get-character-name target)) (display-line " is terrorized") (let ((undo-action (create-action-adt 'undo-terror-effects target (list damage))) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 40))))))) ;;undo effects: (define (undo caster type) (let ((undo-action (create-action-adt type (get-character-name caster) '())) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30)))) (define (undo-doom-effects target) (strength-up target '(2 . 4)) (dexterity-up target '(2 . 4)) (constitution-up target '(2 . 4)) (charisma-up target '(2 . 4)) (display "Doom effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-judgement-effects target damage) (strength-up target damage) (dexterity-up target damage) (constitution-up target damage) (charisma-up target damage) (display "Judgement effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-curse-effects target damage) (intelligence-up target damage) (wisdom-up target damage) (display "Curse effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-terror-effects target damage) (strength-up target damage) (dexterity-up target damage) (constitution-up target damage) (charisma-up target damage) (intelligence-up target damage) (wisdom-up target damage) (display "Terror effects on ") (display (get-character-name target)) (display-line " undone")) (define (unsummon-monster summoned-creature-name summoned-creature) (let ((monster-name (get-character-name summoned-creature))) (display "Unsummoning ") (display-line (get-character-class summoned-creature)) (summoned-creature 'set-status! 'dead) (core-eventhandler 'delete-all monster-name) (the-character-table 'delete monster-name))) (define (undo-blessing-effects target) (strength-down target '(2 . 4)) (dexterity-down target '(2 . 4)) (display "Blessing effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-greater-blessing-effects target) (strength-down target '(2 . 4)) (dexterity-down target '(2 . 4)) (wisdom-down target '(3 . 6)) (display "Greater blessing effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-brainstorm-effects target) (intelligence-down target '(2 . 6)) (wisdom-down target '(2 . 6)) (display "Brainstorm effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-bloodlust-effects target) (strength-down target '(4 . 10)) (constitution-up target '(4 . 10)) (display "Bloodlust effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-berserk-effects target) (strength-down target '(4 . 10)) (hp-up target '(3 . 10)) (display "Berserk effects on ") (display (get-character-name target)) (display-line " undone")) ;;All game actions are listed here (define classlist '(fighter priest wizard paladin monk necromancer druid thief ranger)) (define (add-player-to-game) (define (choose-class player-name) (newline) (display "Choose your character class (type help to see a list of classes): ") (let ((class (read))) (cond ((eq? class 'help) (display "Available classes: ") (display-list classlist) (choose-class player-name)) ((the-class-table 'lookup class) (let ((new-player (create-player-adt player-name class))) (the-character-table 'add new-player) (display-line "+++ New Character Created +++") (newline) (display "*** ") (display player-name) (display-line " has entered the game ***"))) (else (display "The class ") (display class) (display-line " does not exist."))))) (newline) (display-line "+++ Create New Player +++") (display "Please enter your character name: ") (let ((chosen-name (read))) (if (symbol? chosen-name) (if (the-character-table 'lookup chosen-name) (display-line "That name already exists, please choose another one") (choose-class chosen-name)) (begin (display chosen-name) (display-line " is an invalid name."))))) (define (delete-player-from-game player) (let* ((player-location (get-character-location player))) (delete-player-from-location player player-location) (drop-all player display-off) (the-current-players 'delete player) (core-eventhandler 'delete-all player) (newline) (display "*** ") (display player) (display-line " has left the game ***") (newline) (the-character-table 'delete player))) (define (player-wins-game a-player) (define (game-over-loop) (display "Do you want to continue with higher heropoint limit (c) or stop the game? (s) ") (let ((continue (read))) (newline) (cond ((or (eq? continue 'c) (eq? continue 'continue)) (display-line "Game will continue, please reset the heropoint limit to a higher number")) ((or (eq? continue 's) (eq? continue 'stop)) (display-line "Game Over -- Bye") (set! game-over? #t)) (else (display-line "Please enter continue or stop") (game-over-loop))))) ;;when a player wins by scoring the limited heropoints (let ((player-name (get-character-name a-player)) (player-adt (get-character-adt a-player))) (newline) (display "*** ") (display player-name) (display-line " has won the game! ***") (display "Congratulations new hero. You have scored ") (display (get-character-heropoints player-adt)) (display-line " heropoints.") (game-over-loop))) ;;The game handler dispatches several commands ;;to create new players, delete players etc (define (game-handler command) (cond ((new-player-command? command) (add-player-to-game)) ((delete-player-command? command) (delete-player-from-game (caddr command))) ((show-options-command? command) (show-options)) ((setup-options-command? command) (setup-options)) ((show-commands-command? command) (show-commands)) ((show-players-command? command) (the-current-players 'show)) (else (display-line "Bad command. That game command does not exist. Type show commands for a list of valid commands.")))) (define (new-player-command? command) (equal? '(game add player) command)) (define (delete-player-command? command) (and (equal? 'game (car command)) (equal? 'quit (cadr command)) (not (null? (cddr command))))) (define (setup-options-command? command) (equal? command '(game setup options))) (define (show-options-command? command) (equal? command '(game show options))) (define (show-commands-command? command) (equal? command '(game show commands))) (define (show-players-command? command) (equal? command '(game show players))) ;;This part contains all actions involving players ;;monsters can sometimes perform the same actions ;;the argument displayhandler is a function that can be used ;;to control the output, you can choose whether or not to display things ;;with the following 2 functions (define (display-on x . special) ;;specials can be: ;;line for newline ;;list for a display-list ;;listline for a combination of the latter two (cond ((eq? x newline) (newline)) ((null? special) (display x)) ((eq? (car special) 'line) (display x) (newline)) ((eq? (car special) 'list) (display-list x)) ((eq? (car special) 'listline) (display-list x) (newline)) (else (display x)))) (define (display-off x . special) 'done) (define (display-player-icon player command) (if (isplayer? player) (display-icon command) 'done)) (define (spellcaster? player) (let ((the-class (get-character-class player))) (memq the-class spellcaster-classes))) (define (rogue? player) (let ((the-class (get-character-class player))) (memq the-class rogue-classes))) (define (show-commands) (display-line "Valid commands: ") (display-line "Name >> Description >> Syntax") (for-each (lambda (command) (let ((name (car command)) (descr (cadr command)) (syntax (caddr command))) (display name) (display ": ") (display descr) (display " ") (display-line syntax))) '(("move " "lets you move around in the world " "player_name MOVES direction") ("look " "lets you look around in a location " "player_name LOOKS AROUND") ("flee " "lets you flee in a random direction " "player_name FLEES") ("talk " "lets you talk to NPC's in the world " "player_name TALKS") ("steal " "lets you steal items from NPC's if you're a rogue " "player_name STEALS") ("cast " "lets you cast a spell if you're a spellcaster " "player_name CASTS spell_name") ("get " "lets you pick up items " "player_name GETS item_name") ("get-all " "lets you pick up all items " "player_name GETS ALL") ("drop " "lets you drop an item from your inventory " "player_name DROPS item_name") ("drop " "lets you drop a spell from your spellbook " "player_name ERASES spell_name") ("drop-all " "lets you drop all your items " "player_name DROPS ALL") ("use " "lets you use an item or a weapon " "player_name USES item_name") ("read " "lets you read a quest " "player_name READS quest_name") ("examine " "lets you examine an item " "player_name EXAMINES item_name") ("equip-offence" "lets you equip your offensive weapon " "player_name EQUIPS OFFENSIVE WEAPON weapon_name") ("equip-defense" "lets you equip your defensive weapon " "player_name EQUIPS DEFENSIVE WEAPON weapon_name") ("attack " "lets you attack other monsters and players " "player_name ATTACKS opponent_name") ("actions " "shows your enqueued actions " "player_name ASKS ACTIONS") ("exits " "shows all possible exits from this location " "player_name ASKS EXITS") ("status " "shows your status " "player_name ASKS STATUS") ("inventory " "shows your inventory " "player_name ASKS INVENTORY") ("spellbook " "shows your spellbook " "player_name ASKS SPELLBOOK") ("questlog " "shows your questlog " "player_name ASKS QUESTLOG") ("cancel " "cancels an action in manual action execution " "player_name CANCELS action_name") ("options " "shows the options " "GAME SHOW OPTIONS") ("setup options " "lets you modify the options " "GAME SETUP OPTIONS") ("add player " "adds a new player to the game " "GAME ADD PLAYER") ("delete player " "a player quits from the game " "GAME QUIT player_name")))) (define (teleport player to-location . options) (let* ((the-player (get-character-adt player)) (old-worlds (if (isplayer? the-player) (get-previous-worlds the-player) '())) (old-world (if (null? old-worlds) #f (car old-worlds))) (from-location (get-character-location the-player))) (set-character-location to-location player) (if (isplayer? player) ;;monsters and players treated differently (begin (add-player-to-location player to-location) (if old-world (if (old-world 'isworld? from-location) 'done ;;we're moving from one world to another (delete-player-from-location player from-location)) ;;top level, we cant go to another world beyond this one (if (the-world 'isworld? from-location) ;;test to treat top level differently 'done ;;nothing to do (delete-player-from-location player from-location)))) (begin (add-monster-to-location player to-location) (delete-monster-from-location player from-location))))) (define (exit-world player direction) ;;lets a player leave the current world and return ;;to the previous one through an exit (let* ((the-player (get-character-adt player)) (oldlocation (get-character-location the-player)) (oldworld (get-character-world the-player)) (previousworlds (get-previous-worlds the-player)) (previouslocations (get-previous-locations the-player)) (newworld (car previousworlds)) (newlocation (car previouslocations))) (set-character-world newworld the-player) (set-character-location newlocation the-player) (delete-previous-location-for-character newlocation the-player) (delete-previous-world-for-character newworld the-player) (delete-player-from-location the-player oldlocation) ;;Deletes the player from the old room ;;Display the event: (display (get-character-name the-player)) (display " moves back from ") (display (get-location-name oldworld newworld)) (display " to ") (display-line (newworld 'give-name)) ;;The player will now move on a higher level in the world (move the-player direction))) (define (move player direction . options) (define (report-move player new-location new-world direction displayhandler) (displayhandler (get-character-name player)) (displayhandler " moves ") (displayhandler direction) (displayhandler " to ") (displayhandler (get-location-name new-location new-world) 'line) (if (isplayer? player) (begin (displayhandler (get-location-description new-location new-world) 'line) (look player)) 'done)) ;;Moves a player to the desired direction (also works for monsters) (let* ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options)))) (oldlocation (get-character-location player)) (oldworld (get-character-world player)) (newlocation (oldworld 'give-neighbour oldlocation direction))) (display-player-icon player 'move) (cond ;;CASE 1: Location not found ((eq? newlocation 'not-found) ;;There is no location in that direction (if (isplayer? player) (begin (displayhandler (get-character-name player)) (displayhandler ", you cannot travel in that direction. " 'line)) 'done)) ;;CASE 2: Location is itself a world ((oldworld 'isworld? newlocation) ;;The new location is actually a world (if (isplayer? player) ;;Only players can travel through worlds (let* ((newworld newlocation) (to-location (newworld 'startpoint?)) (previous-worlds (get-previous-worlds player)) (previous-locations (get-previous-locations player))) (set-character-world newworld player) (add-previous-location-for-character newworld player) (add-previous-world-for-character oldworld player) (teleport player to-location) (report-move player to-location newworld direction displayhandler) (perform-enter-actions-for-location player)) (flee player displayhandler))) ;;monsters flee when entering new world ;;CASE 3: Location is an exit out of this world ((exit-location? newlocation oldworld) ;;The new location is an exit (if (isplayer? player) ;;only players can exit worlds (exit-world player (get-exit-to-direction newlocation oldworld)) (flee player displayhandler))) ;;CASE 4: Location is an ordinary location (else (teleport player newlocation) (report-move player newlocation oldworld direction displayhandler) (perform-enter-actions-for-location player))))) (define (look player) ;;A player looks around, sees the room description, ;;the items and the characters ;;currently in the room (let* ((the-location (get-character-location player)) (the-world (get-character-world player)) (the-description (get-location-alterdescription the-location the-world)) (the-items (get-location-items the-location the-world)) (the-monsterlist (get-location-monsters the-location the-world)) (the-npclist (get-location-npcs the-location the-world)) (the-playerlist (get-location-players the-location the-world))) (display-player-icon player 'look) (display-line the-description) (if (null? the-items) (display-line "There are no items or weapons in this room") (begin (display "Items and weapons in this room: ") (display-list (map (lambda (item) (item 'give-name)) the-items)) (newline))) (test-characters 'Monsters the-monsterlist) (test-characters 'Players the-playerlist) (test-characters 'NPCs the-npclist) (newline))) (define (flee player . options) (let ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options))))) ;;A random direction is chosen and the player moves to that direction ;;also works for monsters (let ((the-direction (+ (random 4) 1)) (display-flee (lambda (direction) (displayhandler (get-character-name player)) (displayhandler " tries to flee ") (displayhandler direction 'line)))) (display-player-icon player 'flee) (cond ((eq? the-direction 1) (display-flee 'north) (move player 'north displayhandler)) ((eq? the-direction 2) (display-flee 'south) (move player 'south displayhandler)) ((eq? the-direction 3) (display-flee 'east) (move player 'east displayhandler)) (else (display-flee 'west) (move player 'west displayhandler)))))) (define (converse player) (display-player-icon player 'talk) ;;A player initiates dialogue with an NPC (let* ((player-adt (get-character-adt player)) (player-location (get-character-location player)) (player-world (get-character-world player)) (npc-list (get-location-npcs player-location player-world))) (test-characters 'NPCs npc-list) (newline) (display "With whom do you want to converse? ") (let* ((the-npc (read)) (npc-adt (get-npc-adt the-npc))) (if (and (memq the-npc npc-list) the-npc) (begin (display the-npc) (display ": ") (npc-adt 'conversation player-adt)) (display "That NPC cannot be talked to. "))))) (define (steal player) ;;A Player with the Rogue Class can steal ;;an item from an NPC, the chance of succes depends on his dexterity (define (rob an-npc a-player) (let* ((npc-inventory (get-npc-inventory an-npc)) (player-inventory (get-character-inventory a-player)) (npc-item (random-item an-npc))) (if (not npc-item) (display-line "NPC has nothing to steal.") (begin ;;Gives random NPC item, deletes it from the NPC inventory ;;and adds it to the player's one (npc-inventory 'drop (get-object-name npc-item)) (player-inventory 'add npc-item) (display (get-character-name a-player)) (display " has stolen ") (display (get-object-name npc-item)) (display " from ") (display-line (get-npc-name an-npc)))))) (define (attempt) (let* ((player-adt (get-character-adt player)) (player-location (get-character-location player)) (player-world (get-character-world player)) (npc-list (get-location-npcs player-location player-world))) (test-characters 'NPCs npc-list) (newline) (display "Who do you want to rob? ") (let* ((the-npc (read)) (npc-adt (get-npc-adt the-npc))) (if (and (memq the-npc npc-list) the-npc) (begin (display "You try to rob ") (display-line (get-npc-name npc-adt)) (rob npc-adt player-adt)) (display "That NPC cannot be robbed."))))) (display-player-icon player 'steal) (if (rogue? player) ;;Tests if the player is a rogue, rogues are the ;;only class allowed to steal. (let* ((the-dexterity (get-character-dexterity player)) (try (random the-dexterity))) ;;The player's trial is based on his dexterity ;;If the player's trial is higher than 8, he can make an attempt (if (< 8 try) (attempt) (display-line "Your attempt to rob someone has failed, due to your lack of dexterity."))) (display-line "You cannot steal, you are not a Rogue."))) (define (cast player spell . options) (let ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (because of dot notation) (caar options) (car options))))) ;;First test whether the player is a spellcaster ;;also works for monsters (display-player-icon player 'cast) (if (and (isplayer? player) (not (spellcaster? player))) (displayhandler "You cannot cast spells, you are not a Spellcaster." 'line) (let* ((player-adt (get-character-adt player)) (spell-adt (give-spell-from-character spell player-adt))) (if (not spell-adt) (displayhandler "You haven't got that spell." 'line) ;;This function lets the player cast its particular spell, ;;the spell itself calls it's own functions (cast-spell-for-character (get-object-name spell-adt) player-adt)))))) (define (use player item . options) ;;also works for monsters (let* ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options)))) (player-adt (get-character-adt player)) (item-adt (give-item-from-character item player-adt))) (display-player-icon player 'use) (if (not item-adt) (displayhandler "You haven't got that item." 'line) (begin (displayhandler (get-character-name player)) (displayhandler " uses ") (displayhandler (get-object-name item-adt) 'line) ;;This function lets the player use its item, ;;the item itself calls it's own functions (use-item-for-character (get-object-name item-adt) player-adt))))) (define (get player item . options) ;;search and delete combines the searching of the item ;;and the deletion of the item from the location list (define (search-and-delete item-name item-list) (define (iter rest deletedlist neededitem) (if (null? rest) (cons neededitem deletedlist) (let ((current-item ((car rest) 'give-name))) (if (eq? item-name current-item) (iter '() (append deletedlist (cdr rest)) (car rest)) (iter (cdr rest) (cons (car rest) deletedlist) '()))))) (iter item-list '() '())) (display-player-icon player 'get) (let ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options))))) ;;A player can pick up an item (or a weapon or spell) in a room (let* ((location (get-character-location player)) (world (get-character-world player)) (location-items (get-location-items location world)) (item-name (get-object-name item)) (items-in-list (search-and-delete item-name location-items))) (if (not (null? (car items-in-list))) (begin (set-location-items location (cdr items-in-list) world) (let* ((the-item (car items-in-list)) (item-type (the-item 'get-type))) (if (eq? item-type 'spell) ;;item picked up is a spell (add-spell-for-character the-item player) (add-item-for-character the-item player))) (displayhandler "You picked up: ") (displayhandler item-name 'line)) (displayhandler "You cannot pick up that item." 'line))))) (define (drop player item . options) (drop-action give-item-from-character drop-item-for-character player item options)) (define (erase player item . options) (drop-action give-spell-from-character erase-spell-for-character player item options)) (define (drop-action get-function put-function player item . the-options) (let* ((options (car the-options)) ;;because extra options are already passed via drop and erase (displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options))))) (display-player-icon player 'drop) ;;A player drops an item in a room (let* ((location (get-character-location player)) (world (get-character-world player)) (location-items (get-location-items location world)) (item-name (get-object-name item)) (item-in-inventory (get-function item player))) (if item-in-inventory (begin (set-location-items location (add-list item-in-inventory location-items) world) (put-function item-name player) (fix-equipment player displayhandler) (displayhandler "You dropped: ") (displayhandler item-name 'line)) (displayhandler "You haven't got that item." 'line))))) ;;checks whether the player has not dropped his current equipment (define (fix-equipment a-player displayhandler) (let* ((player-adt (get-character-adt a-player)) (off-weapon (get-offensive-weapon player-adt)) (def-weapon (get-defensive-weapon player-adt)) (check-off-for-none (eq? 'none (player-adt 'give-offensive-weapon))) (check-def-for-none (eq? 'none (player-adt 'give-defensive-weapon)))) (if (and (not check-off-for-none) ;;player already knows he has no offensive weapon (not off-weapon)) ;;player has thrown away his offensive weapon (equip-offence player-adt 'none displayhandler) 'done) (if (and (not check-def-for-none) ;;player already knows he has no defensive weapon (not def-weapon)) ;;player has thrown away his defensive weapon (equip-defense player-adt 'none displayhandler) 'done))) (define (get-all player . options) (let ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options))))) (display-player-icon player 'get) ;;A player can pick up all items in a room (let* ((location (get-character-location player)) (world (get-character-world player)) (location-items (get-location-items location world))) (if (null? location-items) (displayhandler "There is nothing to pick up in this room." 'line) (begin (displayhandler "You picked up: ") (displayhandler (map (lambda (item) (item 'give-name)) location-items) 'list) (for-each (lambda (item) (if (eq? (item 'get-type) 'spell) ;;item picked up is a spell (add-spell-for-character item player) (add-item-for-character item player))) location-items) (set-location-items location '() world) (displayhandler newline)))))) (define (drop-all player . options) (let ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options))))) (display-player-icon player 'drop) ;;A player drops all of his items in a room (let* ((location (get-character-location player)) (world (get-character-world player)) (location-items (get-location-items location world)) (player-inventory (get-character-inventory player)) (player-spellbook (get-character-spellbook player)) (temp-items-for-location location-items) (temp-items-to-delete '()) (temp-spells-to-delete '())) (player-inventory 'for-each ;;enumerates all items to add to the location (lambda (item) (set! temp-items-to-delete (cons (item 'give-name) temp-items-to-delete)) (set! temp-items-for-location (cons item temp-items-for-location)))) (for-each (lambda (item) ;;all items must be deleted afterwards (drop-item-for-character item player)) temp-items-to-delete) (player-spellbook 'for-each (lambda (spell) (set! temp-spells-to-delete (cons (spell 'give-name) temp-spells-to-delete)) (set! temp-items-for-location (cons spell temp-items-for-location)))) (for-each (lambda (spell) ;;all spells deleted afterwards (erase-spell-for-character spell player)) temp-spells-to-delete) ;;Extend the location items list (set-location-items location temp-items-for-location world) ;;Set the player's equiped weapons to none (equip-offence player 'none displayhandler) (equip-defense player 'none displayhandler) (displayhandler (get-character-name player)) (displayhandler " dropped all of his possesions" 'line)))) (define (player-read player quest) (let* ((the-player (get-character-adt player)) (the-quest (give-quest-from-character quest the-player))) (display-player-icon player 'read) (if the-quest (begin (display-line (the-quest 'give-title)) (display-line (the-quest 'give-description)) (display "This Quest is worth ") (display (the-quest 'give-heropoints)) (display-line " heropoints.")) (display-line "You haven't got that quest.")))) (define (player-examine player item) (let* ((the-player (get-character-adt player)) (the-item (give-item-from-character item the-player))) (display-player-icon player 'examine) (if the-item (if (item? the-item) (begin (display "Examining item: ") (display-line (the-item 'give-description))) (examine-weapon the-item)) (display-line "You haven't got that item.")))) (define (examine-weapon weapon-adt) (define (display-dice dice) (let ((nr (car dice)) (size (cdr dice))) (display nr) (display "d") (display size) (newline))) ;;expects weapon adt (let ((weapon-off-damage (weapon-adt 'give-attack-damage)) (weapon-def-damage (weapon-adt 'give-defense-damage)) (weapon-off-bonus (weapon-adt 'give-attack-bonus)) (weapon-def-bonus (weapon-adt 'give-defense-bonus)) (weapon-description (weapon-adt 'give-description))) (display "Examining weapon: ") (display-line weapon-description) (display "Attack Damage: ") (display-dice weapon-off-damage) (display "Defense Damage: ") (display-dice weapon-def-damage) (display "Attack Bonus: ") (display weapon-off-bonus) (newline) (display "Defense Bonus: ") (display weapon-off-bonus) (newline))) (define (equip player weapon choice . options) (let ((displayhandler (if (null? options) display-on (if (list? (car options)) ;;extra check for apply (caar options) (car options))))) ;;Equips a player with an offensive or defensive weapon, ;;a check is performed to see whether the player has the weapon ;;none is a special symbol indicating the player hasn't got a weapon equiped (let ((the-weapon (give-item-from-character weapon player))) (if (or the-weapon (eq? weapon 'none)) (if (or (eq? weapon 'none) (eq? 'weapon (the-weapon 'get-type))) (cond ((eq? choice 'offence) (display-player-icon player 'equip-offence) (set-offensive-weapon weapon player) (displayhandler "Offensive weapon set to ") (displayhandler (get-object-name weapon) 'line)) ((eq? choice 'defense) (display-player-icon player 'equip-defense) (set-defensive-weapon weapon player) (displayhandler "Defensive weapon set to ") (displayhandler (get-object-name weapon) 'line)) (else (error "Wrong choice offence/defense, given: " choice))) (displayhandler "You cannot equip items." 'line)) (displayhandler "You haven't got that weapon." 'line))))) (define (equip-offence player weapon . displayhandler) (equip player weapon 'offence (if (null? displayhandler) display-on (car displayhandler)))) (define (equip-defense player weapon . displayhandler) (equip player weapon 'defense (if (null? displayhandler) display-on (car displayhandler)))) (define (show-status player) ((get-character-adt player) 'show-status)) (define (show-inventory player) (let ((player-inventory (get-character-inventory player))) (display-player-icon player 'inventory) (display (get-character-name player)) (display-line "'s possesions: ") (player-inventory 'for-each (lambda (item) (display (get-object-name item)) (display ": ") (display-line (item 'give-description)))) (newline))) (define (show-spellbook player) (let ((player-spellbook (get-character-spellbook player))) (display-player-icon player 'spellbook) (display (get-character-name player)) (display-line "'s spells: ") (player-spellbook 'for-each (lambda (spell) (display (get-object-name spell)) (display ": ") (display-line (spell 'give-spell-description)))) (newline))) (define (show-questlog player) (let* ((player-questlog (get-character-questlog player)) (done-quests (player-questlog 'give-completed))) (display-player-icon player 'questlog) (display (get-character-name player)) (display-line "'s quests: ") (player-questlog 'for-each (lambda (quest) (display (get-object-name quest)) (display ": ") (display-line (quest 'give-title)))) (display "Quests already completed: ") (if (null? done-quests) (display "none so far") (display-list (player-questlog 'give-completed))) (newline))) (define (show-exits player) (let* ((the-player (get-character-adt player)) (the-player-world (get-character-world the-player)) (the-location (get-character-location the-player))) (the-player-world 'for-each-neighbour the-location (lambda (fromlbl frominfo tolbl toinfo edgeinfo) (let* ((type (car toinfo)) (location (cdr toinfo)) (direction edgeinfo) (destination tolbl)) (cond ((eq? type 'world) ;;a neighbour is a world (display "A road leading ") (display direction) (display " to the world ") (display-line destination)) ((exit-location? location the-player-world) ;;a neighbour is an exit (let* ((previous-worlds (get-previous-worlds the-player)) (previous-world (car previous-worlds)) (world-name (previous-world 'give-name))) (display "An exit leading ") (display direction) (display " to ") (display-line world-name))) (else ;;a neigbour is a location (display "A road leading ") (display direction) (display " to ") (display-line destination)))))))) (define (show-actions player) (let ((player-name (get-character-name player)) (global-time (core-eventhandler 'give-time))) (display "Actions enqueued for ") (display player-name) (display-line ": ") (core-eventhandler 'for-each-action (lambda (action-pair) (let* ((time (car action-pair)) (action (cdr action-pair)) (executor (action 'give-executer))) (if (and (eq? executor player-name) (not (eq? (action 'give-name) 'monster-attack))) ;;filter out monster attacks (begin (display "Number of turns: ") (display (- time global-time)) (display " ") (display (action 'give-name)) (display " ") (display-line (action 'give-parameters))))))))) (define (cancel-actions player action) (core-eventhandler 'delete action player)) ;;All specific monster actions are listed here ;;some monster actions are also found in the player actions file (define (monster-attack player) ;;A monster in a room attacks a player (let* ((location (get-character-location player)) (world (get-character-world player)) (monsterlist (get-location-monsters location world))) (if (null? monsterlist) 'done (let ((the-monster (car monsterlist))) (combat the-monster player) (attack-in-the-future location world))))) (define (multiple-monster-attack player) ;;Multiple monsters all attack the same player (let* ((location (get-character-location player)) (world (get-character-world player)) (monsterlist (get-location-monsters location world))) (define (multi-attack monsterlist) (if (or (null? monsterlist) (dead? player)) 'done (begin (combat (car monsterlist) player) (multi-attack (cdr monsterlist))))) (cond ((null? monsterlist) 'done) ((= (length monsterlist) 1) (combat (car monsterlist) player)) (else (multi-attack monsterlist))) (attack-in-the-future location world))) ;;Monsters not always attack when a player enters the room, ;;monsters should also attack when a player resides in their room ;;this function takes care of that (define (attack-in-the-future a-location a-world) (let ((location-players (get-location-players a-location a-world)) (location-monsters (get-location-monsters a-location a-world))) (if (or (null? location-monsters) (null? location-players)) 'done (let* ((attack-action (create-action-adt 'monster-attack (car location-players) '())) (time (core-eventhandler 'give-runtime)) (enqueue-time (+ time (random 5) (global-options 'action-hold-offset)))) (core-eventhandler 'add attack-action enqueue-time))))) (define (monster-travelling monster) (let* ((monster-name (get-character-name monster)) (the-monster-adt (the-character-table 'lookup monster-name))) (if the-monster-adt (the-monster-adt 'walk-through-route) #f))) ;;Monster AI choices (define (random-generator C F A N) ;;input percentages of chance: ;;C cast ;;F flee ;;A attack ;;N nothing (let ((choicenumber (random 100)) (accumulatedC C) (accumulatedF (+ C F)) (accumulatedA (+ C F A)) (accumulatedN (+ C F A N))) (cond ((< choicenumber accumulatedC) 'cast) ((< choicenumber accumulatedF) 'flee) ((< choicenumber accumulatedA) 'attack) ((< choicenumber accumulatedN) 'nothing) (else 'nothing)))) (define (check-strength monster opponent) (let* ((monsterstrength (get-character-strength monster)) (monsterintelligence (get-character-intelligence monster)) (opponentstrength (get-character-strength opponent)) (choicefactor (+ (random 20) 5)) (result (- monsterstrength opponentstrength))) (if (< 0 result) ;;losing monster (if (< monsterintelligence choicefactor) ;;dumb monster #t #f) #t))) (define (check-opponent-healthpoints monster opponent) (let* ((monsterhp (get-character-hitpoints monster)) (monsterintelligence (get-character-intelligence monster)) (opponenthp (get-character-hitpoints opponent)) (choicefactor (+ (random 20) 5)) (result (- monsterhp opponenthp))) (if (< 0 result) ;;losing monster (if (< monsterintelligence choicefactor) ;;dumb monster #t #f) #t))) (define (check-opponent-weapon monster opponent) (let* ((monsterweapon (get-offensive-weapon monster)) (monsterintelligence (get-character-intelligence monster)) (opponentweapon (get-offensive-weapon opponent)) (monsterdamage (if (or (not monsterweapon) (eq? monsterweapon 'none)) 0 (rolldice (get-offensive-damage monsterweapon)))) (opponentdamage (if (or (not opponentweapon) (eq? opponentweapon 'none)) 0 (rolldice (get-offensive-damage opponentweapon)))) (choicefactor (+ (random 20) 5)) (result (- monsterdamage opponentdamage))) (if (< 0 result) ;;losing monster (if (< monsterintelligence choicefactor) ;;dumb monster #t #f) #t))) (define (simulate-battle monster opponent) (let* ((monsterstats (car (get-statistics monster 'attacker))) (opponentstats (car (get-statistics opponent 'defender))) (monsterintelligence (get-character-intelligence monster)) (choicefactor (+ (random 20) 5)) (result (- monsterstats opponentstats))) (if (< 0 result) ;;losing monster (if (< monsterintelligence choicefactor) ;;dumb monster #t #f) #t))) (define (check-own-healthpoints monster opponent) (let* ((monsterhp (get-character-hitpoints monster)) (monsterintelligence (get-character-intelligence monster)) (monsterclass (get-character-class monster)) (classhp (the-class-table 'give-hitpoints monsterclass)) (choicefactor (+ (random 20) 5)) (result (/ monsterhp classhp))) (if (< 0 .3 result) ;;monster has critical hp (if (< monsterintelligence choicefactor) ;;dumb monster #t #f) #t))) (define (restore-hp monster) (let* ((monster-inv (get-character-inventory monster)) (monster-spb (get-character-spellbook monster)) (healitem (search-healing-item-in monster-inv)) (healspell (search-healing-spell-in monster-spb))) (if healspell (cast monster healspell display-on) (if healitem (use monster healitem display-on) 'done)))) (define (easy-AI-tree monster-adt opponent-adt) (random-generator 10 30 25 35)) (define (normal-AI-tree monster-adt opponent-adt) ;;Tree structure represented by ifs ;;a positive check returns #t, a negative check returns #f (if (check-own-healthpoints monster-adt opponent-adt) (if (check-strength monster-adt opponent-adt) (random-generator 20 20 40 20) (if (check-opponent-healthpoints monster-adt opponent-adt) (random-generator 20 15 40 25) (random-generator 15 25 30 30))) (restore-hp monster-adt))) (define (hard-AI-tree monster-adt opponent-adt) ;;Tree structure represented by ifs ;;a positive check returns #t, a negative check returns #f (if (check-own-healthpoints monster-adt opponent-adt) (if (check-strength monster-adt opponent-adt) (if (check-opponent-weapon monster-adt opponent-adt) (random-generator 25 5 40 30) (if (simulate-battle monster-adt opponent-adt) (random-generator 23 2 50 25) (random-generator 20 30 25 25))) (if (check-opponent-healthpoints monster-adt opponent-adt) (random-generator 25 5 40 30) (if (simulate-battle monster-adt opponent-adt) (random-generator 23 2 50 25) (random-generator 20 30 25 25)))) (restore-hp monster-adt))) (define (monster-AI-routine monster opponent . options) ;;options are the difficulty and the displayhandler (define (execute-choice choice displayhandler difficulty) (cond ((eq? choice 'cast) (let ((the-spell (random-spell monster))) (if the-spell (cast monster the-spell displayhandler) (execute-actions)))) ((eq? choice 'flee) (flee monster displayhandler)) ((eq? choice 'attack) (combat monster opponent displayhandler #t difficulty)) ((eq? choice 'nothing) (execute-actions)) (else (execute-actions)))) (if (and (alive? monster) (alive? opponent)) (let* ((difficulty (if (null? options) 'normal (cond ((or (equal? (car options) 0 .5) (eq? (car options) 'easy)) 'easy) ((or (eq? (car options) 1) (eq? (car options) 'normal)) 'normal) ((or (eq? (car options) 2) (eq? (car options) 'hard)) 'hard) ((error "Wrong difficulty number -- monster AI Routine" options))))) (displayhandler (if (null? options) display-on (cadr options))) (monster-adt (get-character-adt monster)) (opponent-adt (get-character-adt opponent))) ;;traverse the AI tree, this produces a symbol (flee, attack etc) ;;this symbol is then transformed into an action through execute-choice (cond ((eq? difficulty 'easy) (execute-choice (easy-AI-tree monster-adt opponent-adt) displayhandler difficulty)) ((eq? difficulty 'normal) (execute-choice (normal-AI-tree monster-adt opponent-adt) displayhandler difficulty)) ((eq? difficulty 'hard) (execute-choice (hard-AI-tree monster-adt opponent-adt) displayhandler difficulty)) (else (error "Wrong difficulty -- AI Routine" difficulty)))) (execute-actions))) (define (respawn monster-name monster-class monster-location monster-route monster-respawn) (if (and monster-respawn (not (eq? monster-respawn 'none))) (let* ((runtime (core-eventhandler 'give-runtime)) (enqueuetime (+ runtime (car monster-respawn))) (respawn-action (create-action-adt 'respawn-monster monster-name (list monster-class monster-location monster-route)))) (core-eventhandler 'add respawn-action enqueuetime)) 'done)) (define (respawn-monster monster-name monster-class monster-location monster-route) (make-monster monster-name monster-class monster-location monster-route)) ;;The Combat Actions are listed here ;;Dicethrow will transform a couple like (2 . 6) in ;;a random number (define (dicethrow specs) (define (loop n upper) (if (= n 0) 0 (+ (loop (- n 1) upper) (+ 1 (random upper))))) (let ((nr-of-dice (car specs)) (nr-of-dice-sides (cdr specs))) (loop nr-of-dice nr-of-dice-sides))) (define (get-statistics character choice) ;;looks up all the relevant stats of the character ;;choice is either attacker or defender ;;it returns the calculated damage and the heropoints (let ((the-character (get-character-adt character))) (if the-character (let* ((strength (get-character-strength the-character)) (dexterity (get-character-dexterity the-character)) (heropoints (if (isplayer? the-character) (get-character-heropoints the-character) 'none)) (weapondamage (if (eq? choice 'attacker) (let ((offweapon (get-offensive-weapon the-character))) (if (not offweapon) ;;no equiped weapon strength (dicethrow (offweapon 'give-attack-damage)))) (let ((defweapon (get-defensive-weapon the-character))) (if (not defweapon) dexterity (dicethrow (defweapon 'give-defense-damage)))))) (weaponbonus (if (eq? choice 'attacker) (let ((offweapon (get-offensive-weapon the-character))) (if (not offweapon) ;;no equipped weapon 0 (offweapon 'give-attack-bonus))) (let ((defweapon (get-defensive-weapon the-character))) (if (not defweapon) ;;no equipped weapon 0 (defweapon 'give-defense-bonus))))) (damagefactor (+ 10 (random 10))) (resultingdamage (/ (+ (* weapondamage strength) weaponbonus dexterity) damagefactor))) (cons (round resultingdamage) heropoints)) (error "Character does not exist -- Get Statistics -- Combat actions" character)))) (define (calc-damage attack-stats defense-stats) ;;returns a list of the form '(winner damage attackertype defendertype) (let* ((attackdamage (car attack-stats)) (defensedamage (car defense-stats)) (attackheropoints (cdr attack-stats)) (defenseheropoints (cdr defense-stats)) (winner 'not-known) (result (- attackdamage defensedamage)) (attacker 'not-known) (defender 'not-known)) (if (eq? attackheropoints 'none) (set! attacker 'monster) (set! attacker 'player)) (if (eq? defenseheropoints 'none) (set! defender 'monster) (set! defender 'player)) (if (> result 0) (set! winner 'attacker) (set! winner 'defender)) ;;check whether the 2 characters are players or not (if (and (eq? attacker 'player) (eq? defender 'player)) (let* ((bonus (quotient (abs (- attackheropoints defenseheropoints)) (+ 1 (random 20)))) (resultbonus (round bonus))) (list winner (+ resultbonus (abs result)) attacker defender)) (list winner (abs result) attacker defender)))) (define (prompt-for-spell-cast attacker defender displayhandler spellcast? difficulty) ;;lets the spellcaster decide to cast a spell or not (let ((attacker-name (get-character-name attacker)) (defender-name (get-character-name defender))) (display attacker-name) (display ", do you want to engage in melee combat or cast a spell? (melee/spell) ") (let ((choice (read))) (cond ((eq? choice 'melee) (combat attacker defender displayhandler #f difficulty)) ((eq? choice 'spell) (announce-spell attacker displayhandler)) (else (newline) (display-line "Wrong choice, please select melee or spell") (prompt-for-spell-cast attacker defender displayhandler spellcast? difficulty)))))) (define (display-all-spells caster . options) ;;shows all spells the caster possesses ;;options contains one parameter: ;;if true, then additional spell info is shown ;;if false, then only brief descriptions are shown (let ((info? (if (null? options) #f (car options))) (the-spellbook (get-character-spellbook caster))) (display-line "Spells in possesion:") (the-spellbook 'for-each (lambda (spell-adt) (let ((spell-name (get-object-name spell-adt)) (spell-description (get-spell-description spell-adt)) (spell-cast-points (cons (get-spell-current spell-adt) (get-spell-max spell-adt)))) (display spell-name) (if info? (begin (display ": ") (display spell-description))) (display " (") (display (car spell-cast-points)) (display "/") (display (cdr spell-cast-points)) (display-line ")")))))) (define (announce-spell caster displayhandler) ;;allows the player to select a spell (display-all-spells caster) (display "Which spell do you want to cast? ") (let* ((the-spell (read))) (cast caster the-spell displayhandler))) (define (report-combat attacker defender winner damage displayhandler) (let* ((attackername (get-character-name attacker)) (defendername (get-character-name defender)) (winnername (if (eq? winner 'attacker) attackername defendername)) (losername (if (eq? winner 'attacker) defendername attackername))) (displayhandler attackername) (displayhandler " attacks ") (displayhandler defendername 'line) (displayhandler winnername) (displayhandler " deals ") (displayhandler damage) (displayhandler " damage to ") (displayhandler losername 'line))) (define (legal-combat? attacker defender) ;;A combat is legal if both characters are in the same room ;;if there are no npcs involved ;;and if both characters are still alive (let ((attacker-adt (get-character-adt attacker)) (defender-adt (get-character-adt defender))) (cond ((not attacker-adt) (display "attacker ") (display attacker) (display-line " does not exist") #f) ((not defender-adt) (display "defender ") (display defender) (display-line " does not exist") #f) (else (let ((attackerlocation (get-character-location attacker-adt)) (defenderlocation (get-character-location defender-adt))) (if (and (alive? attacker-adt) (alive? defender-adt) (not (isnpc? attacker-adt)) (not (isnpc? defender-adt)) (eq? attackerlocation defenderlocation)) #t #f)))))) (define (convert value) (cond ((eq? value 'easy) 0 .5) ((eq? value 'normal) 1) ((eq? value 'hard) 2) (else (error "Wrong value to convert -- Convert" value)))) (define (combat attacker defender . options) ;;options are: '(displayhandler spellcast? difficulty) ;;Displayhandler can be used to suppress the output ;;spellcast decides whether a mage is allowed to cast spells in this fight ;;difficulty has 3 values: easy normal and hard and influences the monster's damage (display-player-icon attacker 'attack) (if (not (legal-combat? attacker defender)) ;;check for legal combat (display-line "Illegal Combat, ignoring command. ") (let ((displayhandler (if (null? options) display-on (car options))) (spellcast? (if (null? options) #t (cadr options))) (difficulty (if (null? options) (convert (global-options 'difficulty)) (cond ((eq? (caddr options) 'easy) 0 .5) ((eq? (caddr options) 'normal) 1) ((eq? (caddr options) 'hard) 2) ((error "Wrong difficulty keyword -- Combat" options)))))) ;;If the player is a spellcaster, he can cast a spell ;;instead of engaging melee combat (if (and spellcast? (spellcaster? attacker)) (prompt-for-spell-cast attacker defender displayhandler spellcast? (if (null? options) 'normal (caddr options))) (let* ((attacker-adt (get-character-adt attacker)) (defender-adt (get-character-adt defender)) (attacker-name (get-character-name attacker)) (defender-name (get-character-name defender)) (attacker-stats (get-statistics attacker-adt 'attacker)) (defender-stats (get-statistics defender-adt 'defender)) (results (calc-damage attacker-stats defender-stats)) (winner (list-ref results 0)) ;;winner = attacker or defender (damage-to-deal (list-ref results 1)) ;;the damage (attackertype (list-ref results 2)) ;;type = player or monster (defendertype (list-ref results 3)) (winner-adt (if (eq? winner 'attacker) attacker-adt defender-adt)) (loser-adt (if (eq? winner 'attacker) defender-adt attacker-adt)) (adjusted-damage (* difficulty damage-to-deal)) (add-damage-action (lambda (damage) ;;enqueue the damage action (core-eventhandler 'add (create-action-adt 'deal-x-damage-to loser-adt (list damage)) 'hold))) (add-report-action (lambda (damage) ;;enqueue the report (display) action (core-eventhandler 'add (create-action-adt 'report-combat attacker-name (list defender-name winner damage displayhandler)) 'hold)))) (cond ((and (eq? attackertype 'player) ;;2 players (eq? defendertype 'player)) ;;Execute the actions, and combat is over (add-report-action damage-to-deal) (add-damage-action damage-to-deal) (execute-actions) (distribute-heropoints attacker-adt defender-adt displayhandler)) ;;If a player wins, he gains the other player's heropoints ((and (eq? attackertype 'monster) ;;attacker is a monster (eq? defendertype 'player)) ;;monster can perform an action (add-report-action damage-to-deal) (add-damage-action adjusted-damage) (execute-actions) (distribute-heropoints attacker-adt defender-adt displayhandler) (monster-AI-routine attacker-adt defender-adt difficulty displayhandler)) ((and (eq? attackertype 'player) ;;defender is a monster (eq? defendertype 'monster)) ;;monster can perform an action (add-report-action damage-to-deal) (add-damage-action adjusted-damage) (execute-actions) (distribute-heropoints attacker-adt defender-adt displayhandler) ;;If the monster is dead, player receives points (monster-AI-routine defender-adt attacker-adt difficulty displayhandler)) (else (add-report-action damage-to-deal) (add-damage-action damage-to-deal) (execute-actions) (distribute-heropoints attacker-adt defender-adt displayhandler) (monster-AI-routine defender-adt attacker-adt difficulty displayhandler) (monster-AI-routine attacker-adt defender-adt difficulty displayhandler)))))))) (define (deal-x-damage-to victim damage) (do-hitpoints-down damage victim)) (define (distribute-heropoints attacker defender . options) (define (report-heropoints-up player heropoints displayhandler) (displayhandler (get-character-name player)) (displayhandler " gains ") (displayhandler heropoints) (displayhandler " heropoints." 'line)) (let ((displayhandler (if (null? options) display-on (car options))) (attackerstatus (get-character-status attacker)) (defenderstatus (get-character-status defender)) (points-earned (get-character-heropoints defender))) (cond ((and (eq? attackerstatus 'alive) (eq? defenderstatus 'dead)) (let ((points-earned (get-character-heropoints defender))) (do-heropoints-up points-earned attacker) (report-heropoints-up attacker points-earned displayhandler))) ((and (eq? attackerstatus 'dead) (eq? defenderstatus 'alive)) (let ((points-earned (get-character-heropoints attacker))) (do-heropoints-up points-earned defender) (report-heropoints-up defender points-earned displayhandler))) (else 'done)))) (define (search-healing-item-in inventory) ;;Expects Inventory ADT (let ((choicelist '())) (inventory 'for-each (lambda (item-adt) (let ((item-name (get-object-name item-adt))) (if (memq item-name healing-items) ;;the item is a healing item (set! choicelist (cons item-adt choicelist)))))) (if (null? choicelist) #f (let* ((choice (random (length choicelist))) (item-chosen (list-ref choicelist choice))) item-chosen)))) (define (search-healing-spell-in spellbook) ;;Expects Spellbook ADT (let ((choicelist '())) (spellbook 'for-each (lambda (spell-adt) (let ((spell-name (get-object-name spell-adt))) (if (memq spell-name healing-spells) ;;the spell is a healing spell (set! choicelist (cons spell-adt choicelist)))))) (if (null? choicelist) #f (let* ((choice (random (length choicelist))) (spell-chosen (list-ref choicelist choice))) spell-chosen)))) (define (random-item character) (let* ((character-adt (get-character-adt character)) (character-inv (get-character-inventory character-adt)) (choicelist '())) (character-inv 'for-each (lambda (item-adt) (set! choicelist (cons item-adt choicelist)))) (if (null? choicelist) #f (let* ((choice (random (length choicelist))) (item-chosen (list-ref choicelist choice))) item-chosen)))) (define (random-spell character) (let* ((character-adt (get-character-adt character)) (character-spb (get-character-spellbook character-adt)) (choicelist '())) (character-spb 'for-each (lambda (spell-adt) (set! choicelist (cons spell-adt choicelist)))) (if (null? choicelist) #f (let* ((choice (random (length choicelist))) (spell-chosen (list-ref choicelist choice))) spell-chosen)))) ;;Initialisation of the tables (define the-actions-table (action-table)) (define the-class-table (class-table)) (define the-items-table (items-table)) (define the-locations-table (location-table)) (define the-npc-table (npc-table)) (define the-quest-table (quest-table)) (define the-spells-table (spell-table)) (define the-weapons-table (weapons-table)) (define the-character-table (character-table)) (define table-loader-dummy (begin (display "Tables Loaded") (newline))) ;;Essentials ;;Setting up options (define global-options (the-options)) ;;The eventhandler (define core-eventhandler (create-eventhandler-ADT 0)) ;; <<== Changed! (define print-eventhandler-dummy (begin (display "Eventhandler loaded") (newline))) ;;The Current Players (define the-current-players (current-players-adt)) (define begin-players-dummy (begin (display "Current Player list loaded") (newline))) ;;Special abilities classes and special item lists (define spellcaster-classes '(priest wizard monk druid necromancer paladin)) (define rogue-classes '(monk druid thief)) (define healing-items '(small-potion medium-potion large-potion super-potion)) (define healing-spells '(heal-light-wounds heal-medium-wounds heal-large-wounds heal-critical-wounds blessing greater-blessing)) ;;This file contains the "driver loop" for the game (define game-over? #f) (define (start-the-game) (initialise-game) (input-loop)) (define (input-loop) (if game-over? (begin (display-line "Game Over, thanks for playing")) (if (playstyle-continuous? global-options) (execute-continuous-turn) (execute-turnbased-turn)))) (define (execute-continuous-turn) (display "(Continuous)Enter new command: ") (let ((user-input (read))) (newline) (cond ((action-execution? user-input) (core-eventhandler 'execute-step (cadr user-input))) ((game-command? user-input) ;;eg new game, new player etc (game-handler user-input)) (else (execute-regular-command user-input))) (newline)) (input-loop)) (define (execute-regular-command user-input . turnbased-player) (let ((turnbased? (if (null? turnbased-player) #f #t)) (offset (global-options 'action-hold-offset)) (eventhandler-time (core-eventhandler 'give-runtime))) (cond ((and (on-hold? user-input) (if turnbased? (check-player (caddr user-input) (car turnbased-player)) (check-player (caddr user-input)))) (command-handler (dump-hold user-input) (+ offset eventhandler-time (hold-time user-input))) (display-line "*** Action Held ***")) ;;action enqueued for the future ((if turnbased? (check-player (car user-input) (car turnbased-player)) (check-player (car user-input))) (command-handler user-input 1)) (else (display-line "That player does not exist or wrong player turn"))))) (define (check-player player-name . player-needed) (if (not (null? player-needed)) (eq? player-name (car player-needed)) (let ((active-players (the-current-players 'give-player-list))) (member player-name active-players)))) (define (turn-status) (let ((turncounter (global-options 'nr-of-actions-allowed)) (listcounter 0)) (define (dispatch m) (cond ((eq? m 'give-listcounter) listcounter) ((eq? m 'increment-listcounter) (if (= (+ listcounter 1) (length (the-current-players 'give-player-list))) (set! listcounter 0) (set! listcounter (+ 1 listcounter)))) ((eq? m 'decrement-turncounter) (set! turncounter (- turncounter 1))) ((eq? m 'give-turncounter) turncounter) ((eq? m 'check-turncounter) (= turncounter 0)) ((eq? m 'set-turncounter-to-0) (set! turncounter 0)) ((eq? m 'reset-turncounter) (set! turncounter (global-options 'nr-of-actions-allowed))) (else (error "Wrong message -- Turn Status" m)))) dispatch)) ;;Object that keeps track of counting the turns and players (define the-turn-status (turn-status)) (define (execute-turnbased-turn) (let* ((current-players (the-current-players 'give-player-list)) (player-position (the-turn-status 'give-listcounter)) (active-player (if (< player-position (length current-players)) (list-ref current-players player-position) (car current-players)))) (display "(Turnbased) ") (display active-player) (display "'s turn (") (display (the-turn-status 'give-turncounter)) (display "): ") (let ((user-input (read))) (newline) (cond ((skip-turn? user-input) (the-turn-status 'set-turncounter-to-0)) ((action-execution? user-input) (core-eventhandler 'execute-step (the-keyword user-input))) ((game-command? user-input) ;;eg new game, new player etc (game-handler user-input)) (else (execute-regular-command user-input active-player) (the-turn-status 'decrement-turncounter) (newline))) (if (the-turn-status 'check-turncounter) (begin (the-turn-status 'reset-turncounter) (the-turn-status 'increment-listcounter) (input-loop)) (input-loop))))) (define (initialise-game) (define (add-player-loop) (add-player-to-game) (display "Add another player? (yes/no): ") (let ((choice (read))) (cond ((eq? choice 'yes) (add-player-loop)) ((eq? choice 'no) (display-line "Players added succesfully") (options?)) (else (display-line "Wrong choice, try again") (add-player-loop))))) (display-line "Adding new players: ") (add-player-loop)) (define (options?) (display "Do you want to change the options? (yes/no): ") (let ((choice (read))) (cond ((eq? choice 'yes) (newline) (setup-options)) ((eq? choice 'no) (newline)) (else (display-line "Wrong choice, try again") (newline) (options?))))) ;;Abstractions (define (action-execution? command) (and (list? command) (eq? (car command) 'go) (not (null? (cdr command))) (number? (cadr command)))) (define (game-command? command) (and (list? command) (eq? (car command) 'game) (not (null? (cdr command))))) (define (skip-turn? command) (or (equal? command 'skip) (equal? command 'skip-turn) (equal? command '(skip turn)))) ;;All aliases to enter game data are listed here (define (create-item name description functions extra) (the-items-table 'add name description functions extra)) (define (create-weapon name description statistics actions extras) (the-weapons-table 'add name description statistics actions extras)) (define (create-spell name spelld castd actions nr-of-casts reset-time) (the-spells-table 'add name spelld castd actions nr-of-casts reset-time)) (define (create-location name monsterlist npclist descr alterdescr items weapons spells actions world) (let ((objects (append (map create-item-adt items) (map create-weapon-adt weapons) (map create-spell-adt spells)))) (the-locations-table 'add name monsterlist npclist descr alterdescr objects actions) (let ((the-location (create-location-adt name))) (world 'insert-location the-location) the-location))) (define (create-class name parameters hitpoints items weapons spells . respawn) (if (null? respawn) (the-class-table 'add name parameters hitpoints items weapons spells) (the-class-table 'add name parameters hitpoints items weapons spells respawn))) (define (make-world-in world name startlocation) (let ((new-world (create-world-adt name startlocation))) (world 'insert-world new-world) new-world)) (define (make-road-in world from-location to-location direction . reversed) (if (null? reversed) (world 'insert-road from-location to-location direction) (world 'insert-road from-location to-location direction reversed))) (define (create-quest name title description triggers heropoints) (the-quest-table 'add name title description triggers heropoints) (create-quest-adt name)) (define (create-npc name description start conversation items weapons questconditions quest-to-trigger) (the-npc-table 'add name description start conversation items weapons questconditions quest-to-trigger) (make-npc name)) (define (make-monster name class location . route) (if (null? route) (let ((the-monster (create-monster-adt name class location))) (the-character-table 'add the-monster) the-monster) (let ((the-monster (create-monster-adt name class location (car route)))) (the-character-table 'add the-monster) the-monster))) (define (make-npc name) (the-character-table 'add (create-npc-adt name))) (define (display-icon command) ;; <<== Changed entire function. (define (display-pause x) (if (icons-on? global-options) (begin (display x) (display " ")) 'done)) (define moveicon '<<shoes>>) (define fleeicon '<<witch-on-broom>>) (define lookicon '<<eye>>) (define talkicon '<<mouth>>) (define stealicon '<<black-gloves>>) (define casticon '<<scroll>>) (define geticon '<<yellow-gloves>>) (define dropicon '<<brown-gloves>>) (define useicon '<<potion-bottle>>) (define readicon '<<open-book>>) (define examineicon '<<open-bag>>) (define offenceicon '<<sword>>) (define defenseicon '<<shield>>) (define attackicon '<<morning-star>>) (define inventoryicon '<<chest>>) (define spellbookicon '<<spell-book>>) (define questlogicon '<<quest-scroll>>) (cond ((eq? command 'move) (display-pause moveicon)) ((eq? command 'flee) (display-pause fleeicon)) ((eq? command 'look) (display-pause lookicon)) ((eq? command 'talk) (display-pause talkicon)) ((eq? command 'steal) (display-pause stealicon)) ((eq? command 'cast) (display-pause casticon)) ((eq? command 'get) (display-pause geticon)) ((eq? command 'drop) (display-pause dropicon)) ((eq? command 'use) (display-pause useicon)) ((eq? command 'read) (display-pause readicon)) ((eq? command 'examine) (display-pause examineicon)) ((eq? command 'equip-offence) (display-pause offenceicon)) ((eq? command 'equip-defense) (display-pause defenseicon)) ((eq? command 'attack) (display-pause attackicon)) ((eq? command 'inventory) (display-pause inventoryicon)) ((eq? command 'spellbook) (display-pause spellbookicon)) ((eq? command 'questlog) (display-pause questlogicon)) (else (error "Wrong Command -- Display-icon" command)))) ;;All Class data is listed here ;;Expects: name parameters hitpoints items weapons spells description (define classes-items-weapons-dummy (begin ;;Player Classes (create-class 'fighter '((12 . 20) (14 . 22) (5 . 8) (5 . 8) (4 . 8) (8 . 12)) '(100 . 180) '(strength-potion small-potion) '(long-sword leather-armor) '() '()) (create-class 'priest '((6 . 14) (8 . 16) (8 . 10) (6 . 12) (14 . 22) (8 . 12)) '(55 . 150) '(wisdom-potion small-potion) '(short-staff leather-armor) '(heal-light-wounds blessing) '()) (create-class 'monk '((12 . 20) (12 . 20) (4 . 6) (4 . 6) (4 . 8) (4 . 8)) '(40 . 150) '(wisdom-potion small-potion) '(long-staff leather-armor) '(heal-light-wounds) '()) (create-class 'necromancer '((12 . 20) (12 . 20) (4 . 6) (4 . 6) (4 . 8) (4 . 8)) '(60 . 150) '(intelligence-potion small-potion) '(long-staff leather-armor) '(curse heal-light-wounds) '()) (create-class 'ranger '((14 . 20) (16 . 22) (4 . 8) (4 . 6) (4 . 6) (2 . 6)) '(80 . 140) '(constitution-potion small-potion) '(bow leather-armor) '() '()) (create-class 'wizard '((8 . 12) (10 . 16) (8 . 14) (10 . 14) (12 . 22) (6 . 12)) '(50 . 120) '(intelligence-potion small-potion) '(short-staff leather-armor) '(heal-light-wounds fireball) '()) (create-class 'druid '((10 . 20) (10 . 20) (6 . 10) (8 . 12) (6 . 8) (14 . 22)) '(40 . 120) '(wisdom-potion small-potion) '(short-sword leather-armor) '(blessing) '()) (create-class 'thief '((8 . 14) (12 . 16) (12 . 20) (5 . 8) (6 . 12) (2 . 6)) '(60 . 120) '(dexterity-potion small-potion) '(small-dagger leather-armor) '() '()) (create-class 'paladin '((10 . 20) (12 . 20) (4 . 8) (6 . 12) (6 . 10) (8 . 14)) '(60 . 130) '(charisma-potion small-potion) '(long-sword shield) '(blessing) '()) ;;Monster Classes (create-class 'zombie '((6 . 12) (6 . 10) (2 . 4) (1 . 6) (2 . 4) (1 . 4)) '(10 . 20) '() '(short-axe leather-armor) '() 15) (create-class 'zombie+ '((10 . 14) (10 . 12) (2 . 5) (1 . 8) (2 . 5) (1 . 6)) '(12 . 30) '() '(heavy-axe-++ leather-armor) '() 15) (create-class 'zombie++ '((12 . 18) (14 . 18) (2 . 6) (1 . 10) (2 . 6) (1 . 6)) '(16 . 34) '(large-potion) '(heavy-axe-++ helmet) '() 15) (create-class 'skeleton '((4 . 12) (4 . 8) (1 . 4) (1 . 4) (1 . 6) (1 . 4)) '(10 . 20) '() '(short-sword leather-armor) '() 20) (create-class 'skeleton+ '((6 . 14) (6 . 10) (1 . 4) (1 . 4) (1 . 6) (1 . 4)) '(14 . 24) '() '(short-sword-+ shield) '() 10) (create-class 'skeleton++ '((8 . 16) (8 . 12) (2 . 4) (2 . 4) (2 . 6) (2 . 4)) '(16 . 30) '() '(spear leather-armor) '() 10) (create-class 'vampire '((8 . 16) (2 . 8) (1 . 4) (1 . 4) (2 . 8) (4 . 10)) '(12 . 26) '() '(long-sword leather-armor) '(bloodlust) 50) (create-class 'aisgen-vampire '((12 . 20) (6 . 12) (1 . 2) (1 . 2) (2 . 8) (4 . 10)) '(16 . 40) '(small-potion) '(long-sword-+ cape) '(bloodlust)) (create-class 'troll '((2 . 6) (12 . 16) (2 . 4) (2 . 4) (8 . 14) (2 . 4)) '(12 . 20) '() '(short-dagger leather-armor) '() 15) (create-class 'troll+ '((4 . 10) (14 . 18) (2 . 4) (2 . 4) (12 . 14) (2 . 4)) '(16 . 22) '(medium-potion) '(heavy-dagger leather-armor) '() 15) (create-class 'troll++ '((2 . 6) (12 . 16) (2 . 4) (2 . 4) (8 . 14) (4 . 10)) '(12 . 20) '(large-potion) '(short-dagger-+ bracers) '(shadowcast) 15) (create-class 'gnoll '((4 . 10) (10 . 16) (4 . 6) (2 . 6) (6 . 10) (4 . 10)) '(8 . 18) '() '(halberd leather-armor) '()) (create-class 'gnoll+ '((8 . 12) (12 . 16) (4 . 6) (6 . 10) (6 . 12) (4 . 10)) '(8 . 30) '() '(halberd leather-armor) '(fireball heal-light-wounds)) (create-class 'gnoll++ '((12 . 18) (14 . 18) (2 . 6) (2 . 6) (8 . 10) (6 . 12)) '(14 . 40) '() '(spear shield) '(blessing)) (create-class 'orc '((6 . 8) (8 . 16) (1 . 4) (1 . 6) (6 . 10) (1 . 2)) '(12 . 24) '() '(short-sword orcisch-armor) '() 30) (create-class 'orc+ '((10 . 14) (10 . 16) (1 . 4) (1 . 6) (8 . 10) (1 . 2)) '(16 . 30) '() '(heavy-axe-++ orcisch-armor) '() 30) (create-class 'orc++ '((12 . 20) (14 . 18) (2 . 4) (2 . 6) (8 . 12) (1 . 2)) '(20 . 45) '() '(short-sword-++ orcisch-armor) '(berserk) 30) (create-class 'orc-shaman '((10 . 14) (10 . 16) (6 . 12) (18 . 24) (6 . 8) (4 . 10)) '(20 . 35) '() '(heavy-dagger orcisch-armor) '(fireball heal-light-wounds berserk) 40) (create-class 'goblin '((2 . 4) (12 . 18) (2 . 4) (2 . 4) (14 . 24) (2 . 8)) '(6 . 26) '() '(short-sword orcisch-armor) '() 20) (create-class 'goblin+ '((4 . 6) (14 . 22) (4 . 6) (4 . 8) (16 . 30) (2 . 10)) '(6 . 30) '() '(short-sword-+ orcisch-armor) '() 15) (create-class 'goblin++ '((6 . 10) (16 . 24) (4 . 6) (6 . 8) (18 . 32) (2 . 8)) '(8 . 32) '(small-potion) '(short-axe orcisch-armor) '(heal-critical-wounds) 20) (create-class 'goblin-king '((8 . 10) (16 . 24) (4 . 8) (6 . 8) (30 . 60) (2 . 8)) '(8 . 32) '(small-potion) '(metal-staff goblin-kings-cape) '(heal-critical-wounds)) (create-class 'werewolf '((18 . 24) (14 . 16) (4 . 8) (2 . 4) (14 . 24) (2 . 6)) '(12 . 30) '() '(claws leather-armor) '()) (create-class 'greater-werewolf '((22 . 28) (16 . 18) (6 . 8) (2 . 4) (16 . 24) (2 . 6)) '(16 . 40) '() '(claws leather-armor) '()) (create-class 'stone-golem '((18 . 24) (20 . 24) (1 . 8) (1 . 4) (4 . 8) (2 . 6)) '(30 . 60) '() '(heavy-axe-++ full-plate-armor) '(curse)) (create-class 'clay-golem '((20 . 30) (14 . 16) (1 . 8) (1 . 4) (4 . 8) (2 . 6)) '(30 . 50) '() '(heavy-axe-++ full-plate-armor) '(judgement)) (create-class 'dark-dwarf '((8 . 16) (14 . 24) (4 . 8) (8 . 14) (4 . 8) (2 . 6)) '(20 . 40) '(constitution-potion) '(heavy-axe-++ full-plate-armor) '() 30) (create-class 'drow-elf '((14 . 20) (16 . 22) (8 . 16) (12 . 16) (6 . 14) (8 . 22)) '(30 . 40) '(elven-potion) '(bow leather-armor) '() 40) (create-class 'elven-sorcerer '((6 . 10) (10 . 14) (10 . 12) (18 . 24) (4 . 6) (10 . 24)) '(20 . 30) '(small-potion) '(long-staff bracers) '(fireball brainstorm heal-medium-wounds lightning-bolt) 50) (create-class 'elven-priest '((6 . 12) (14 . 18) (18 . 32) (12 . 24) (8 . 12) (12 . 20)) '(25 . 35) '() '(long-staff cape) '(brainstorm heal-light-wounds blessing) 50) (create-class 'knight '((14 . 20) (18 . 24) (4 . 8) (6 . 10) (2 . 6) (10 . 16)) '(30 . 50) '() '(bastard-sword full-plate-armor) '() 60) (create-class 'mage '((6 . 10) (8 . 12) (6 . 12) (18 . 34) (6 . 10) (6 . 10)) '(20 . 40) '() '(metal-staff cape) '(icecone lightning-bolt heal-light-wounds) 60) (create-class 'diego '((18 . 20) (18 . 28) (4 . 8) (6 . 10) (4 . 10) (10 . 16)) '(40 . 70) '() '(diegos-dagger leather-armor) '()) (create-class 'demon '((14 . 22) (12 . 24) (10 . 20) (10 . 20) (14 . 24) (16 . 32)) '(30 . 60) '() '(metal-staff-++ cape) '(magic-missile heal-critical-wounds curse)) (create-class 'angel '((14 . 22) (12 . 24) (12 . 20) (8 . 20) (14 . 24) (16 . 32)) '(30 . 60) '() '(long-sword full-plate-armor) '(heal-critical-wounds judgement)) (create-class 'imp '((6 . 6) (12 . 16) (6 . 8) (4 . 8) (4 . 6) (2 . 8)) '(6 . 26) '() '(short-staff bracers) '(icecone lightning-bolt)) (create-class 'shadow '((14 . 30) (12 . 18) (2 . 4) (2 . 2) (16 . 30) (2 . 8)) '(12 . 40) '() '(claws leather-armor) '(bloodlust)) (create-class 'dragon-welp '((18 . 24) (20 . 24) (4 . 8) (4 . 6) (12 . 20) (4 . 8)) '(35 . 60) '(dragon-water) '(claws dragon-armor) '(fireball) 200) (create-class 'dragon '((24 . 36) (40 . 46) (12 . 20) (8 . 16) (18 . 26) (10 . 14)) '(80 . 160) '(dragon-water) '(claws dragon-armor) '(inferno) 250) (create-class 'dark-dragon '((30 . 36) (40 . 50) (14 . 28) (14 . 20) (16 . 20) (10 . 16)) '(100 . 160) '(dragon-water) '(claws dragon-armor) '(inferno) 300) (create-class 'arch-dragon '((60 . 180) (50 . 80) (14 . 24) (18 . 28) (30 . 46) (12 . 18)) '(140 . 320) '(dragon-water) '(claws dragon-armor) '(inferno heal-critical-wounds)) (display "Classes Loaded") (newline) ;;All items are listed here ;;create-item: name description functions extra ;;objects to alter stats (create-item 'small-potion "A green potion in a small bottle" '((hp-up . 20)) 'delete-after-use) (create-item 'medium-potion "A red potion in a bottle" '((hp-up . 40)) 'delete-after-use) (create-item 'large-potion "A blue potion in a glass bottle" '((hp-up . 60)) 'delete-after-use) (create-item 'super-potion "A white potion, it looks like water" '((hp-up . 80)) 'delete-after-use) (create-item 'constitution-potion "A Potion which strengthens your body" '((constitution-up . 3)) 'delete-after-use) (create-item 'dexterity-potion "A Potion which improves your agility" '((dexterity-up . 3)) 'delete-after-use) (create-item 'wisdom-potion "A Potion which enlightens your mind" '((wisdom-up . 3)) 'delete-after-use) (create-item 'intelligence-potion "A Potion which sharpens your thinking" '((intelligence-up . 3)) 'delete-after-use) (create-item 'strength-potion "A Potion that improves your muscles" '((strength-up . 3)) 'delete-after-use) (create-item 'charisma-potion "A Potion that improves your charisma" '((charisma-up . 3)) 'delete-after-use) (create-item 'potion-of-heroism "A Potion that gives you courage" '((heropoints-up . 30)) 'delete-after-use) (create-item 'potion-of-dragon-strength "A Potion that imbues you with the strength of a dragon" '((strength-up . 8) (constitution-up . 5)) 'delete-after-use) (create-item 'dragon-water "It is said dragons of ancient times washed themselves with this water" '((wisdom-up . 4) (intelligence-up . 4)) 'delete-after-use) (create-item 'elven-potion "The fluid of elves, it strengthens one, in all facets, just like the elves excell in all facets" '((strength-up . 2) (constitution-up . 2) (dexterity-up . 2) (charisma-up . 2) (wisdom-up . 2) (intelligence-up . 2)) 'delete-after-use) ;;objects related to quests (create-item 'old-stone "An old stone, it doesn't seem very special" '() '()) (create-item 'a-flower "A purple flower, it smells good" '((charisma-up . 5)) 'delete-after-use) (create-item 'sundance-raider-book "It appears to be a book about tales from the desert" '() '()) (create-item 'apocalypse-book "An enormeous book, guessing from the title, it must be another of one of those prophecy books" '() '()) (create-item 'old-stone "An old stone, it doesn't seem very special" '() '()) (create-item 'dragons-tail "The tail of the archdragon, it's green, and it's besmeared with blood. The spike on the end is lethal" '() '()) (create-item 'dragons-treasure "The famous dragon treasure, more wealth than anyone can ever imagine. All gold an jewelry" '((heropoints-up . 20) (dexterity-down . 5)) '()) (create-item 'ancient-tome "An old dusty tome, arcane signs are subscripted in it. It's all very...old" '() '()) (create-item 'metal "Strong metal, and shiny too, it doesn't seem to rust that quick" '() '()) (create-item 'keys "A golden ring with a set of keys tied to it" '() '()) (create-item 'map-of-mountainvale "A map of the world" '() '()) (display "Items Loaded") (newline) ;;All weapon data is listed here ;;expects name description statistics bonus extra ;;statistics is a list of: (number of dice . number of sides of the dice) ;;swords (create-weapon 'long-sword "A shiny long sword" '((2 . 10) (2 . 10) 15 5) '() 'none) (create-weapon 'broad-sword "A rusty broad sword" '((2 . 8) (2 . 12) 5 10) '() 'none) (create-weapon 'short-sword "A short but swift long sword" '((1 . 8) (1 . 8) 4 2) '() 'none) (create-weapon 'bastard-sword "A sword that requires some strength to handle" '((3 . 8) (2 . 8) 15 5) '() 'none) (create-weapon 'short-sword-+ "A better version of the short sword" '((2 . 8) (2 . 8) 8 4) '() 'none) (create-weapon 'long-sword-+ "A better version of the long sword" '((3 . 10) (3 . 10) 30 10) '() 'none) (create-weapon 'bastard-sword-+ "A better version of the bastard sword" '((2 . 10) (2 . 10) 15 5) '() 'none) (create-weapon 'broad-sword-+ "A better version of the broad sword" '((3 . 8) (3 . 12) 10 20) '() 'none) (create-weapon 'scimitar "An arabian sword" '((2 . 8) (3 . 10) 4 12) '() 'none) (create-weapon 'short-sword-++ "The best non-magical short sword there is" '((2 . 12) (2 . 12) 14 10) '() 'none) (create-weapon 'long-sword-++ "The best non-magical long sword there is" '((3 . 14) (3 . 14) 40 20) '() 'none) (create-weapon 'bastard-sword-++ "The best non-magical bastard sword there is" '((2 . 14) (2 . 14) 20 10) '() 'none) (create-weapon 'broad-sword-++ "The best non-magical broad sword there is" '((3 . 12) (3 . 14) 15 30) '() 'none) (create-weapon 'sword-of-fire "The sword is constantly burning" '((3 . 12) (3 . 12) 14 10) '((cast . fireball)) 'none) (create-weapon 'sword-of-ice "The sword has a blue color, it feels cold" '((3 . 12) (3 . 12) 14 10) '((cast . icecone)) 'none) (create-weapon 'sword-of-heroes "A sword used by many heroes, perhaps you're the next one?" '((3 . 6) (3 . 6) 20 8) '((strength-up . 20)) 'none) (create-weapon 'orc-reaper "A sword forged by Dwarves in their war against the orcs" '((3 . 12) (3 . 14) 15 30) '((damage-orc . 80)) 'none) (create-weapon 'sword-of-doom "A sword carried by the Elven knights in their war against the humans" '((5 . 8) (4 . 4) 35 20) '((cast . doom)) 'delete-after-use) (create-weapon 'excalibur "Legend has it that this sword was worn by a legendary king" '((3 . 12) (3 . 12) 4 10) '() 'none) (create-weapon 'sword-of-violence "A malificent sword, sharp and edgy" '((3 . 12) (1 . 6) 14 10) '() 'none) (create-weapon 'sword-of-chaos "A strange sword, be wary on how to use it" '((8 . 10) (1 . 6) 30 2) '((cast . teleport)) 'delete-after-use) (create-weapon 'elven-sword "A wooden sword made by elves, do not underestimate it" '((1 . 12) (5 . 12) 8 16) '((cast . shield)) 'none) (create-weapon 'defenders-mythe "The sword of true defenders" '((2 . 12) (6 . 12) 6 40) '((cast . shield)) 'none) ;;axes (create-weapon 'short-axe "A short and fragile axe" '((2 . 4) (1 . 12) 4 6) '() 'none) (create-weapon 'large-axe "A large, heavy axe" '((3 . 4) (1 . 12) 8 4) '() 'none) (create-weapon 'double-axe "Looking at this weapon gives you the creeps" '((6 . 4) (1 . 12) 14 4) '() 'none) (create-weapon 'short-axe-+ "A short and fragile axe, improved version" '((2 . 6) (1 . 14) 6 8) '() 'none) (create-weapon 'large-axe-+ "An improved large axe" '((3 . 6) (1 . 14) 12 4) '() 'none) (create-weapon 'double-axe-+ "A fierce weapon" '((6 . 6) (1 . 12) 18 6) '() 'none) (create-weapon 'short-axe-++ "The best non-magical short axe there is" '((3 . 6) (2 . 4) 8 10) '() 'none) (create-weapon 'large-axe-++ "The best non-magical large axe there is" '((4 . 6) (2 . 6) 14 6) '() 'none) (create-weapon 'double-axe-++ "The best non-magical double axe there is" '((8 . 6) (2 . 8) 20 8) '() 'none) (create-weapon 'heavy-axe-++ "The best non-magical heavy axe there is" '((10 . 8) (2 . 10) 18 6) '() 'none) (create-weapon 'short-axe-of-venom "A deadly, venomous weapon" '((3 . 6) (2 . 4) 8 10) '((cast . venom)) 'none) (create-weapon 'wanderers-axe "A swift axe, yet powerful" '((4 . 6) (3 . 6) 10 12) '((dext-up . 30)) 'delete-after-use) (create-weapon 'evils-eye "An axe used for rituals by Priests of Lech'nun" '((3 . 8) (1 . 6) 22 4) '((cast . summon-imp)) 'delete-after-use) (create-weapon 'axe-of-power "The ultimate axe, yet veary heavy to the wielder" '((6 . 22) (2 . 4) 50 4) '((strength-up . 40) (dext-down . 10)) 'none) (create-weapon 'dwarven-axe "Your typical dwarven axe" '((4 . 8) (3 . 4) 10 8) '((constitution-up . 20)) 'none) ;;staffs (create-weapon 'short-staff "A short wooden staff" '((1 . 8) (1 . 10) 6 6) '((hp-up . 30)) 'delete-after-use) (create-weapon 'wooden-staff "A wooden staff" '((1 . 10) (1 . 10) 4 6) '((hp-up . 30)) 'delete-after-use) (create-weapon 'long-staff "A long wooden staff" '((1 . 10) (1 . 12) 4 8) '((hp-up . 30)) 'delete-after-use) (create-weapon 'metal-staff "A short wooden staff" '((1 . 12) (2 . 6) 10 8) '((hp-up . 30)) 'delete-after-use) (create-weapon 'short-staff-+ "A better version of the short wooden staff" '((1 . 8) (1 . 10) 6 6) '((hp-up . 50) (cast . shield)) 'delete-after-use) (create-weapon 'long-staff-+ "A better version of the long wooden staff" '((1 . 10) (1 . 12) 4 8) '((hp-up . 50) (cast . shield)) 'delete-after-use) (create-weapon 'metal-staff-+ "A better version of the short wooden staff" '((1 . 12) (2 . 6) 10 8) '((hp-up . 50) (cast . shield)) 'delete-after-use) (create-weapon 'mystic-staff "A long, shiny staff" '((2 . 8) (2 . 10) 6 6) '((cast . teleport)) 'none) (create-weapon 'ice-staff "A frozen magical staff" '((2 . 10) (2 . 12) 4 8) '((cast . icecone)) 'none) (create-weapon 'fire-staff "The staff is constantly on fire" '((2 . 12) (2 . 12) 4 8) '((cast . fire)) 'none) (create-weapon 'wind-staff "A very long metallic staff" '((2 . 8) (2 . 10) 10 6) '((cast . tornado)) 'none) (create-weapon 'staff-of-nature "A long wooden staff, there are leaves growing on the staff" '((2 . 10) (1 . 12) 6 8) '((cast . force-of-nature)) 'none) (create-weapon 'staff-of-death "A black staff, made of a material you do not know" '((1 . 12) (4 . 6) 4 16) '((cast . summon-demon)) 'none) (create-weapon 'staff-of-elders "An old staff, weird-shaped in the form of an S" '((4 . 4) (4 . 4) 4 4) '((hp-up . 20)) 'none) (create-weapon 'gods-finger "The staff is completely white, and almost doens't weigh anything" '((2 . 22) (2 . 12) 10 22) '((cast . doom)) 'none) (create-weapon 'Arachronox "A very small staff, yet its powers are amazing" '((8 . 4) (12 . 2) 10 8) '((cast . shield) (cast . vision)) 'none) (create-weapon 'Archmaster "A metallic staff with golden encryptions" '((1 . 16) (4 . 8) 12 10) '((hp-up . 10) (strength-up . 10) (constitution-up . 10) (dext-down . 10)) 'none) (create-weapon 'Angel-whisper "A white staff, weird symbols are encrtypted " '((6 . 6) (8 . 6) 4 12) '((cast . summon-angel)) 'none) ;;Daggers (create-weapon 'small-dagger "A small, but sharp dagger" '((1 . 4) (1 . 8) 4 6) '() 'none) (create-weapon 'heavy-dagger "A large dagger" '((2 . 4) (2 . 8) 4 6) '() 'none) (create-weapon 'small-dagger-+ "A better version of the small dagger" '((2 . 4) (2 . 8) 8 4) '() 'none) (create-weapon 'heavy-dagger-+ "A better version of the heavy dagger" '((6 . 4) (4 . 4) 8 4) '() 'none) (create-weapon 'venomous-dagger "A small dagger, used with poision" '((1 . 4) (1 . 8) 4 6) '((cast . poison)) 'delete-after-use) (create-weapon 'magical-dagger "A blue glooming dagger" '((2 . 4) (2 . 8) 4 6) '((hp-up . 5)) 'none) (create-weapon 'dagger-of-sacrifice "A dagger, smeared with blood, in the shape of an S" '((4 . 4) (4 . 6) 10 4) '((cast . summon-zombie)) 'none) (create-weapon 'dagger-of-thieves "This dagger is known well in thieve guilds" '((4 . 4) (2 . 8) 10 14) '((dext-up . 20)) 'none) ;;Miscellaneous (create-weapon 'halberd "A large rusty Halberd" '((2 . 8) (1 . 8) 8 6) '() 'none) (create-weapon 'bow "A wooden bow, with arrows" '((1 . 8) (1 . 4) 10 2) '() 'none) (create-weapon 'spear "A long wooden spear, with a metal arrow at the end" '((2 . 8) (2 . 6) 6 6) '() 'none) (create-weapon 'claws "sharp claws of an animal" '((5 . 4) (3 . 4) 6 4) '() 'none) (create-weapon 'goblin-kings-cape "The red cape of the goblin king" '((5 . 4) (4 . 4) 6 10) '() 'none) (create-weapon 'diegos-dagger "The dagger of the Thief Diego" '((8 . 4) (3 . 4) 4 2) '() 'none) ;;Defense (create-weapon 'leather-armor "Normal leather armor" '((1 . 4) (2 . 8) 2 10) '() 'none) (create-weapon 'studded-armor "Normal studded armor" '((1 . 4) (2 . 10) 2 12) '() 'none) (create-weapon 'metal-plate-armor "Normal metal plate armor" '((1 . 4) (3 . 10) 2 14) '() 'none) (create-weapon 'scale-mail-armor "Normal scale mail armor" '((1 . 4) (2 . 10) 2 20) '() 'none) (create-weapon 'ring-mail-armor "Ring mail armor covering the entire body" '((1 . 4) (3 . 8) 2 10) '() 'none) (create-weapon 'full-plate-armor "Full plate mail, very solid" '((1 . 4) (4 . 8) 2 20) '() 'none) (create-weapon 'heavy-armor "Heavy leather armor" '((1 . 4) (2 . 8) 4 20) '() 'none) (create-weapon 'shield "A shield" '((2 . 4) (2 . 8) 4 20) '() 'none) (create-weapon 'helmet "A solid helmet" '((1 . 4) (1 . 6) 2 20) '() 'none) (create-weapon 'cape "A long mantle" '((1 . 4) (2 . 6) 2 16) '() 'none) (create-weapon 'bracers "Large Wrist Bracers" '((2 . 4) (2 . 6) 2 12) '() 'none) (create-weapon 'dragon-armor "This armor is made from the skin of a dragon" '((2 . 6) (4 . 12) 6 20) '() 'none) (create-weapon 'baldurans-armor "Armor worn by the hero Balduran" '((2 . 4) (4 . 10) 2 20) '((constitution-up . 10) (dext-down . 10)) 'none) (create-weapon 'orcisch-armor "Armor worn by the Orcs, it stinks" '((1 . 4) (2 . 6) 4 6) '() 'none) (display "Weapons Loaded") (newline))) ;;All specific spell casting actions are listed here (define (cast-doom caster) ;;casts the spell doom (let ((target (select-target-in-room caster 'all)) (damage (cons 2 4))) (if target (begin (strength-down target damage) (dexterity-down target damage) (constitution-down target damage) (charisma-down target damage) (display (get-character-name target)) (display-line " is doomed") (let ((undo-action (create-action-adt 'undo-doom-effects target '())) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30))))))) (define (cast-judgement caster) ;;casts the spell judgement (let* ((target (select-target-in-room caster 'all)) (caster-charisma (get-character-charisma caster)) (target-charisma (get-character-charisma target)) (damage (- caster-charisma target-charisma))) (if target (if (< damage 0) (begin (display (get-character-name target)) (display-line "has been judged positive")) (begin (strength-down target damage) (dexterity-down target damage) (constitution-down target damage) (charisma-down target damage) (display (get-character-name target)) (display-line " is judged negative") (let ((undo-action (create-action-adt 'undo-doom-effects target (list damage))) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30)))))))) (define (cast-curse caster) ;;casts the spell curse (let ((target (select-target-in-room caster 'all)) (damage (round (/ (get-character-wisdom caster) 3)))) (if target (begin (intelligence-down target damage) (wisdom-down target damage) (display (get-character-name target)) (display-line " is cursed") (let ((undo-action (create-action-adt 'undo-curse-effects target (list damage))) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30))))))) (define (summon caster creature-type) (define (conditions-fulfilled? player creature type) (let* ((the-player (get-character-adt player)) (player-strength (get-character-strength the-player)) (player-wisdom (get-character-strength the-player)) (player-intelligence (get-character-strength the-player)) (player-charisma (get-character-strength the-player)) (creature-strength (get-character-strength creature)) (creature-charisma (get-character-strength creature)) (creature-wisdom (get-character-wisdom creature)) (creature-intelligence (get-character-intelligence creature)) (greater-strength? (> creature-strength player-strength)) (greater-charisma? (> creature-charisma player-charisma)) (greater-intelligence? (> creature-intelligence player-intelligence)) (greater-wisdom? (> creature-wisdom player-wisdom))) (cond ((eq? type 'demon) (if (and greater-strength? greater-charisma?) (begin (combat creature caster) ;;demon turns agains his owner #f) #t)) ((eq? type 'angel) (if (and greater-strength? greater-charisma?) #f #t)) ((eq? type 'imp) (if greater-charisma? #f #t)) ((eq? type 'dragon) (if (and greater-strength? greater-charisma? greater-intelligence? greater-wisdom?) (begin (combat creature caster) ;;dragon turns againts his owner #f) (if (and greater-strength? greater-intelligence?) #f #t))) ((eq? type 'shadow) (if greater-wisdom? #f #t)) (else #t)))) (let* ((summon-location (get-character-location caster)) (summoned-creature (make-monster 'summoned-monster creature-type summon-location)) (unsummon-action (create-action-adt 'unsummon-monster 'summoned-monster (list summoned-creature))) (run-time (core-eventhandler 'give-runtime))) (display "You summoned a ") (display-line creature-type) (display-line "Who do you want it to attack?") (let ((target (select-target-in-room caster 'all))) (if target (if (conditions-fulfilled? caster summoned-creature creature-type) ;;some creatures require conditions to be fulfilled (begin (combat summoned-creature target) ;;engage in combat (core-eventhandler 'add unsummon-action (+ run-time 5)) (display-line "Creature will be unsummoned in 5 turns")) (display-line "Cannot summon: conditions for summoning such creature not fulfilled")))))) (define (cast-force-drop caster) (let ((target (select-target-in-room caster 'all))) (if target (begin (drop-all target) (display-line "Your force drop spell was effective"))))) (define (cast-terror caster) ;;casts the spell terror (let ((target (select-target-in-room caster 'all)) (damage (get-character-intelligence caster))) (if target (begin (strength-down target damage) (dexterity-down target damage) (constitution-down target damage) (charisma-down target damage) (intelligence-down target damage) (wisdom-down target damage) (drop-all target) (display (get-character-name target)) (display-line " is terrorized") (let ((undo-action (create-action-adt 'undo-terror-effects target (list damage))) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 40))))))) ;;undo effects: (define (undo caster type) (let ((undo-action (create-action-adt type (get-character-name caster) '())) (run-time (core-eventhandler 'give-runtime))) (core-eventhandler 'add undo-action (+ run-time 30)))) (define (undo-doom-effects target) (strength-up target '(2 . 4)) (dexterity-up target '(2 . 4)) (constitution-up target '(2 . 4)) (charisma-up target '(2 . 4)) (display "Doom effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-judgement-effects target damage) (strength-up target damage) (dexterity-up target damage) (constitution-up target damage) (charisma-up target damage) (display "Judgement effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-curse-effects target damage) (intelligence-up target damage) (wisdom-up target damage) (display "Curse effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-terror-effects target damage) (strength-up target damage) (dexterity-up target damage) (constitution-up target damage) (charisma-up target damage) (intelligence-up target damage) (wisdom-up target damage) (display "Terror effects on ") (display (get-character-name target)) (display-line " undone")) (define (unsummon-monster summoned-creature-name summoned-creature) (let ((monster-name (get-character-name summoned-creature))) (display "Unsummoning ") (display-line (get-character-class summoned-creature)) (summoned-creature 'set-status! 'dead) (core-eventhandler 'delete-all monster-name) (the-character-table 'delete monster-name))) (define (undo-blessing-effects target) (strength-down target '(2 . 4)) (dexterity-down target '(2 . 4)) (display "Blessing effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-greater-blessing-effects target) (strength-down target '(2 . 4)) (dexterity-down target '(2 . 4)) (wisdom-down target '(3 . 6)) (display "Greater blessing effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-brainstorm-effects target) (intelligence-down target '(2 . 6)) (wisdom-down target '(2 . 6)) (display "Brainstorm effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-bloodlust-effects target) (strength-down target '(4 . 10)) (constitution-up target '(4 . 10)) (display "Bloodlust effects on ") (display (get-character-name target)) (display-line " undone")) (define (undo-berserk-effects target) (strength-down target '(4 . 10)) (hp-up target '(3 . 10)) (display "Berserk effects on ") (display (get-character-name target)) (display-line " undone")) ;;All spell data is listed here ;;create-spell expects name spelld castd actions nr-of-casts reset-time ;;for reading comfort and convenience, the actions of the spells are defined seperately ;;the actions (define heal-light-actions '((hp-up . (2 . 6)))) (define heal-medium-actions '((hp-up . (3 . 6)))) (define heal-large-actions '((hp-up . (4 . 6)))) (define heal-critical-actions '((hp-up . (6 . 6)))) (define blessing-actions '((strength-up . (2 . 4)) (dexterity-up . (2 . 4)) (undo . undo-blessing-effects))) (define greater-blessing-actions '((strength-up . (2 . 6)) (dexterity-up . (2 . 6)) (wisdom-up . (3 . 6)) (undo . undo-greater-blessing-effects))) (define doom-actions '((cast-doom))) (define judgement-actions '((cast-judgement))) (define curse-actions '((cast-curse))) (define magic-missile-actions '((deal-x-damage-to-target . (3 . 8)))) (define brainstorm-actions '((wisdom-up . (2 . 6)) (intelligence-up . (2 . 6)) (undo . undo-brainstorm-effects))) (define cast-demon-actions '((summon . demon))) (define cast-angel-actions '((summon . angel))) (define cast-imp-actions '((summon . imp))) (define cast-dragon-actions '((summon . dragon))) (define cast-shadow-actions '((summon . shadow))) (define fireball-actions '((deal-x-damage-to-target . (3 . 6)))) (define lightning-bolt-actions '((deal-x-damage-to-target . (4 . 6)))) (define icecone-actions '((deal-x-damage-to-target . (2 . 9)))) (define icecone-actions '((deal-x-damage-to-target . (4 . 10)))) (define force-drop-actions '((cast-force-drop))) (define bloodlust-actions '((strength-up . (4 . 10)) (constitution-down . (4 . 10)) (undo . undo-bloodlust-effects))) (define berserk-actions '((strength-up . (4 . 10)) (hp-down . (3 . 10)) (undo . undo-berserk-effects))) (define terror-actions '((cast-terror))) (define inferno-actions '((deal-x-damage-to-target . (6 . 12)))) ;;the spells (define spells-dummy (begin (create-spell 'heal-light-wounds "Healing spell, heals a small amount of hitpoints" "A small blue vapor heals your wounds" heal-light-actions 4 20) (create-spell 'heal-medium-wounds "Healing spell, heals a medium amount of hitpoints" "A blue vapor heals your wounds" heal-medium-actions 3 30) (create-spell 'heal-large-wounds "Healing spell, heals a good amount of hitpoints" "A blue light flickers and heals your wounds" heal-large-actions 2 40) (create-spell 'heal-critical-wounds "Healing spell, heals most of your hitpoints" "A white light heals your wounds" heal-critical-actions 1 50) (create-spell 'blessing "Increases your strength and dexterity" "A ligth from the heavens strikes down, immediately you feel enlightened" blessing-actions 2 50) (create-spell 'greater-blessing "Increases your strength, dexterity and wisdom" "A bright aura surrounds you, you feel your strength increasing" greater-blessing-actions 1 50) (create-spell 'doom "Dooms an enemy, it lowers his stats" "A black cloud appears over the head of your target" doom-actions 2 30) (create-spell 'judgement "Judges an enemy by his charisma, it lowers his stats" "A Judgement hammer swings above the head of your target" judgement-actions 1 40) (create-spell 'curse "Curses your enemy, lowering his wisdom and intelligence" "Your opponent grows silent and dumb as you cast the spell" curse-actions 2 30) (create-spell 'magic-missile "A missile dealing 3d8 damage" "A shiny flaming arrow shoots forth from your hand" magic-missile-actions 2 80) (create-spell 'brainstorm "Increased intelligence and wisdom" "Your eyes start to flicker" brainstorm-actions 2 50) (create-spell 'summon-demon "Casts a demon that will aid, or destroy you" "As you cast the spell, the ground trembles and a fierce demon arises from the ground" cast-demon-actions 1 60) (create-spell 'summon-angel "Casts an angel, if you're lucky" "As you cast the spell, the heavens clear and an Angel flies down from the skies" cast-angel-actions 1 60) (create-spell 'summon-imp "Casts an imp, if he likes you" "As you cast the spell, a small little imp materialises before you" cast-imp-actions 1 50) (create-spell 'summon-dragon "Casts the most dangerous creature in the world, hard to control" "Suddenly, you hear the flapping of giant wings and the stench of sulfur, an enormous red dragon comes flying in from the horizon" cast-dragon-actions 1 500) (create-spell 'shadowcast "Casts a shadow attacking a target" "Your hands produce pure blackness... living blackness" cast-shadow-actions 1 80) (create-spell 'fireball "Casts a fireball dealing 3d6 damage" "A blazing fireball shoots from your fingertips" fireball-actions 2 30) (create-spell 'icecone "Casts a blue icepeak dealing 2d9 damage" "A blue peak slowly forms in your hands, then, you swing it at your target" icecone-actions 2 30) (create-spell 'lightning-bolt "Casts a lightning spark dealing 4d10 damage" "At the tips of your fingers, an electric charce forms and shoots at your target" lightning-bolt-actions 2 60) (create-spell 'force-drop "lets your target drop all of his possesions" "As you cast your spell, your opponents possesions grow very heavy, causing him to drop them all" force-drop-actions 1 50) (create-spell 'bloodlust "You gain an enormeous strength, but lose a lot of your constitution" "As you cast the spell, your hunger for blood increases" bloodlust-actions 2 60) (create-spell 'berserk "You gain an enormeous strength, but lose some Healthpoints, be careful" "As you cast the spell, you feel like you could slaughter an army" berserk-actions 2 60) (create-spell 'terror "You totally terrorize your opponent" "As you speak the spell words, your opponent gets scared, and starts to scream" terror-actions 1 100) (create-spell 'inferno "All goes up in fire with this one" "After the casting, fire is flowing from the core of the world itself, everything is burning" inferno-actions 1 200) (display "Spells Loaded") (newline))) ;;All worlds are listed here ;;The global world: (define the-world (create-world-adt 'the-world 'warp-room)) (define warp-room (create-location 'warp-room '() '() "The Warproom" "You start out in the warp room, select an exit" '() '() '() '() the-world)) (the-world 'set-startlocation! warp-room) ;;All major places in the world: (define x 'temporary-placeholder) (define northern-plains (make-world-in the-world 'northern-plains x)) (define dwarven-keep (make-world-in the-world 'dwarven-keep x)) (define wizard-school (make-world-in the-world 'wizard-school x)) (define dragonvale (make-world-in the-world 'dragonvale x)) (define goblin-encampment (make-world-in the-world 'goblin-encampment x)) (define elven-fortress (make-world-in the-world 'elven-fortress x)) (define dragons-island (make-world-in the-world 'dragons-island x)) (define ancient-graveyard (make-world-in the-world 'ancient-graveyard x)) (define temple-of-lune (make-world-in the-world 'temple-of-lune x)) (define athela (make-world-in the-world 'athela x)) (define ithilion (make-world-in the-world 'ithilion x)) (define forests-of-echnun (create-location 'forests-of-echnun '(a-goblin a-gnoll) '(an-elf) "The lurky forests of Echnun, no one comes here nowadays, not in the least because of its danger" "The trees are very dark here, yet, the leafs are green and all seems quiet" '(small-potion constitution-potion) '(wooden-staff) '() '(monster-attack) the-world)) ;;The interconnections (roads) between the worlds: (define world-roads-dummy (begin (make-road-in the-world northern-plains wizard-school 'east 'reversed) (make-road-in the-world northern-plains dwarven-keep 'south 'reversed) (make-road-in the-world wizard-school forests-of-echnun 'east 'reversed) (make-road-in the-world wizard-school dragonvale 'south 'reversed) (make-road-in the-world forests-of-echnun athela 'south 'reversed) (make-road-in the-world dwarven-keep dragonvale 'east 'reversed) (make-road-in the-world dwarven-keep goblin-encampment 'south 'reversed) (make-road-in the-world dragonvale dragons-island 'south 'reversed) (make-road-in the-world dragonvale athela 'east 'reversed) (make-road-in the-world dragons-island ithilion 'east 'reversed) (make-road-in the-world dragons-island temple-of-lune 'south 'reversed) (make-road-in the-world goblin-encampment dragons-island 'east 'reversed) (make-road-in the-world goblin-encampment elven-fortress 'south 'reversed) (make-road-in the-world athela ithilion 'south 'reversed) (make-road-in the-world temple-of-lune ancient-graveyard 'east 'reversed) (make-road-in the-world ithilion ancient-graveyard 'south 'reversed) (make-road-in the-world elven-fortress temple-of-lune 'east 'reversed) (make-road-in the-world warp-room northern-plains 'west) (make-road-in the-world warp-room ithilion 'south) (make-road-in the-world warp-room forests-of-echnun 'east))) ;;the exits (define exit-east (create-location 'exit-east '(east) '() " " " " '() '() '() '() the-world)) (define exit-west (create-location 'exit-west '(west) '() " " " " '() '() '() '() the-world)) (define exit-north (create-location 'exit-north '(north) '() " " " " '() '() '() '() the-world)) (define exit-south (create-location 'exit-south '(south) '() " " " " '() '() '() '() the-world)) (define (distribute-exits) ;;exits must be present in each world (define (distribute-loop worldlist) (if (null? worldlist) 'done (begin ((car worldlist) 'insert-location exit-east) ((car worldlist) 'insert-location exit-west) ((car worldlist) 'insert-location exit-north) ((car worldlist) 'insert-location exit-south) (distribute-loop (cdr worldlist))))) (distribute-loop (list northern-plains dwarven-keep wizard-school dragonvale goblin-encampment elven-fortress dragons-island ancient-graveyard temple-of-lune athela ithilion))) (define exits-dummy (begin (distribute-exits) (display "World Set") (newline))) ;;all locations of the world are listed here ;;create-location: name monsterlist npclist descr alterdescr items weapons spells actions world ;;Northern Plains (define small-pool (create-location 'small-pool '() '(old-man) "A small pool" "You don't see anyone or anything around except for an old man" '() '() '() '() northern-plains)) (define tree-forest (create-location 'tree-forest '(drow-elf) '(nymf) "The trees are dense here, it's dark" "A nymf is standing by a tree" '() '(shield) '() '(monster-attack) northern-plains)) (define great-plain (create-location 'great-plain '() '(elven-ranger1 elven-ranger2) "The wide open plains, everything is quit there" "Nothing much to see, a few elven scouts are patrolling in the area" '(small-potion) '() '() '() northern-plains)) (define old-stone-cave (create-location 'old-stone-cave '() '(old-sage) "An old dark little cave, some daylight shines through" "An old sage with a long beard stares at you" '(old-stone) '() '() '() northern-plains)) (define northern-roads-dummy (begin (make-road-in northern-plains small-pool tree-forest 'north 'reversed) (make-road-in northern-plains small-pool great-plain 'west 'reversed) (make-road-in northern-plains great-plain old-stone-cave 'north 'reversed) (make-road-in northern-plains tree-forest old-stone-cave 'west 'reversed) (make-road-in northern-plains small-pool exit-south 'south) (make-road-in northern-plains tree-forest exit-east 'east))) ;;Forests of Echnun ;;See Mountainvale World ;;Wizard School (define apprentices-square (create-location 'apprentices-square '() '(jolo apprentice) "A little square, some apprentices wander around" "An Idyllic sight, those apprentices have a nice backyard" '() '() '() '() wizard-school)) (define the-laboratory (create-location 'the-laboratory '(clay-golem) '() "On the left, some potions are warmed up, a lot of equipment is stored here, in the middle of the room, a large container is broken." "The rooms are dusty, you don't see any wizards" '(super-potion intelligence-potion) '(broad-sword-++) '() '(monster-attack) wizard-school)) (define wizard-school-dorms (create-location 'wizard-school-dorms '() '(mage1 mage2) "The Wizard School Dormitory" "The beds seem ok, in front of each bed stands a coffin, probably full of books" '() '() '() '() wizard-school)) (define stairway (create-location 'stairway '() '() "A small stairway" "It's drafty in here" '() '() '() '() wizard-school)) (define the-garden (create-location 'the-garden '() '(azatar) "The Wizard School Gardens" "Lots of flowers, a few benches, and a wizard looking at you" '(a-flower) '() '() '() wizard-school)) (define masters-square (create-location 'masters-square '() '(master-wizard1 master-wizard2) "This Square is obviously larger than the Apprentices Square" "This is where the master wizards gather" '() '() '() '() wizard-school)) (define headmasters-tower (create-location 'headmasters-tower '() '(headmaster) "The Headmasters quarters. High and Dry." "Nice vieuw of the surrounding area... The headmaster appears busy" '() '() '() '() wizard-school)) (define basement (create-location 'basement '() '() "The Basement, what would they keep in here? Not much it seems." "Except for the cold temperature, nothing draws your attention." '() '(metal-staff-+) '() '() wizard-school)) (define wizard-school-library (create-location 'wizard-school-library '() '() "The Wizard School Library, the place to be if you are in search of books" "You'd expect more wizards in the library, its calm" '(sundance-raider-book apocalypse-book medium-potion) '() '(bloodlust summon-imp blessing) '() wizard-school)) (define wizard-roads-dummy (begin (make-road-in wizard-school apprentices-square the-laboratory 'east 'reversed) (make-road-in wizard-school apprentices-square stairway 'south 'reversed) (make-road-in wizard-school the-laboratory wizard-school-dorms 'east 'reversed) (make-road-in wizard-school the-laboratory the-garden 'south 'reversed) (make-road-in wizard-school stairway headmasters-tower 'south 'reversed) (make-road-in wizard-school the-garden masters-square 'east 'reversed) (make-road-in wizard-school the-garden basement 'south 'reversed) (make-road-in wizard-school masters-square wizard-school-library 'south 'reversed) (make-road-in wizard-school basement wizard-school-library 'east 'reversed) (make-road-in wizard-school headmasters-tower basement 'east 'reversed) (make-road-in wizard-school wizard-school-dorms masters-square 'south 'reversed) (make-road-in wizard-school apprentices-square exit-west 'west) (make-road-in wizard-school masters-square exit-east 'east) (make-road-in wizard-school wizard-school-library exit-south 'south))) ;;Dwarven Keep (define dwarven-tavern (create-location 'dwarven-tavern '() '(drunken-dwarf dwarven-ward) "The Dwarven Tavern is the most crowded place in this entire Keep, it figures." "The Dwarves don't pay attention to you, they're too busy drinking and joking" '(small-potion constitution-potion) '() '() '() dwarven-keep)) (define dwarven-keep-gates (create-location 'dwarven-keep-gates '() '(dwarven-guard-1 dwarven-guard-2) "The wooden gates that lead inward the Dwarven Keep" "Two Guards secure the entrance, they seem to be sleeping, but you can never be sure about that with dwarves" '() '() '() '() dwarven-keep)) (define hyagars-smythe (create-location 'hyagars-smythe '() '(hyagar) "The Dwarven Smythe... its HOT" "Hyagar is busy melting some old swords" '() '(double-axe-++) '(lightning-bolt) '() dwarven-keep)) (define dwarven-workshop (create-location 'dwarven-workshop '() '(dwarven-alchemist dwarven-carpenter) "The noise hurts your ears, everywhere dwarves are busy building tools" "The constant ticking of the hammers and the scratching of the saws makes you crazy" '() '(heavy-axe-++) '(doom) '() dwarven-keep)) (define dwarven-caverns (create-location 'dwarven-caverns '(dwarven-warrior-1) '() "The Dwarven caverns, where dwarves feel at home" "Cold, dark and long hallways, just as the dwarves like them" '() '() '() '(monster-attack) dwarven-keep)) (define dwarven-weaponry (create-location 'dwarven-weaponry '(dwarven-warrior-2 dwarven-warrior-3) '() "The Dwarven weaponry, this is where they keep their famous axes" "The Room is loaded with weapons, all sorts of them, the Dwarven Smith must have his work" '() '(dwarven-axe short-sword-++ orc-reaper fire-staff scale-mail-armor) '(fireball) '(multiple-monster-attack) dwarven-keep)) (define dwarven-kings-room (create-location 'dwarven-kings-room '() '(king-keldorn) "Dwarven King Keldorn's palace" "The King is sitting on a throne in the middle of the room, it's strange there aren't any guards around." '() '(sword-of-chaos) '() '() dwarven-keep)) (define dwarven-roads-dummy (begin (make-road-in dwarven-keep dwarven-tavern dwarven-keep-gates 'east 'reversed) (make-road-in dwarven-keep dwarven-keep-gates dwarven-caverns 'south 'reversed) (make-road-in dwarven-keep dwarven-keep-gates hyagars-smythe 'east 'reversed) (make-road-in dwarven-keep dwarven-workshop dwarven-caverns 'east 'reversed) (make-road-in dwarven-keep dwarven-caverns dwarven-weaponry 'east 'reversed) (make-road-in dwarven-keep dwarven-caverns dwarven-kings-room 'south 'reversed) (make-road-in dwarven-keep dwarven-keep-gates exit-north 'north) (make-road-in dwarven-keep dwarven-weaponry exit-east 'east) (make-road-in dwarven-keep dwarven-kings-room exit-south 'south))) ;;Dragonvale (define town-gates (create-location 'town-gates '() '(dragonvale-guard-1 dragonvale-guard-2) "The entrance to the town of Dragonvale" "Two Soldiers guard the small arc" '() '(long-sword-+) '() '() dragonvale)) (define dragon-museum (create-location 'dragon-museum '() '(supervisor) "This is the old museum, famous for it's collection of Dragon pieces" "The supervisor is keeping an eye on you" '(potion-of-dragon-strength) '(dragon-armor claws) '() '() dragonvale)) (define lord-caevens-home (create-location 'lord-caevens-home '() '(lord-caeven) "The Lord's estate is quite impressive" "The rooms are nicely decorated, and the furniture is quite fancy." '() '() '() '() dragonvale)) (define governors-mansion (create-location 'governors-mansion '() '(the-governor) "The Mansion of the Governor of this province of Mountainvale" "The Governor is seated at his desk, with piles of paper in front of him" '(map-of-mountainvale) '() '() '() dragonvale)) (define dragons-fountain (create-location 'dragons-fountain '() '(a-dragonvale-commoner) "In the middle of the square stands a beautiful fountain." "The fountain is shaped like a dragon and water is flowing from its beak" '(dragon-water) '(short-axe-++) '() '() dragonvale)) (define dragonvale-tavern (create-location 'dragonvale-tavern '(dragonvale-knight) '(a-drunk local-dragonvale-idiot dragonvale-inn-ward) "A nice little tavern. Known for it's Dragon Ale" "Some townsfolk is socialising. The usual drunk is seated at the bar, and some idiot is trying to get some attention." '(small-potion) '() '() '() dragonvale)) (define yeruns-house (create-location 'yeruns-house '() '(yerun-the-dragonslayer) "Yerun's house isn't very large, but it is nicely decorated." "Everywhere you see scalps of Yerun's quests: dragon's wings, claws... even a dragon's eye" '(medium-potion) '(long-sword-++ shield helmet) '() '() dragonvale)) (define dragonvale-roads-dummy (begin (make-road-in dragonvale town-gates dragon-museum 'east 'reversed) (make-road-in dragonvale town-gates governors-mansion 'south 'reversed) (make-road-in dragonvale dragon-museum dragons-fountain 'south 'reversed) (make-road-in dragonvale dragon-museum lord-caevens-home 'east 'reversed) (make-road-in dragonvale governors-mansion dragons-fountain 'east 'reversed) (make-road-in dragonvale dragons-fountain dragonvale-tavern 'east 'reversed) (make-road-in dragonvale dragons-fountain yeruns-house 'south 'reversed) (make-road-in dragonvale town-gates exit-west 'west) (make-road-in dragonvale town-gates exit-north 'north) (make-road-in dragonvale lord-caevens-home exit-east 'east) (make-road-in dragonvale dragonvale-tavern exit-east 'east) (make-road-in dragonvale yeruns-house exit-south 'south))) ;;Dragons Island (define northern-beach (create-location 'northern-beach '(dark-dragon) '() "The Northern beach lies just behind a large cliff wall" "No one around here" '(strength-potion dexterity-potion intelligence-potion) '(claws) '() '() dragons-island)) (define southern-beach (create-location 'southern-beach '(dragon-welp) '() "The Southern beach is less rocky than it's northern brother, still, quite an obscure beach" "No one to see" '(strength-potion dexterity-potion wisdom-potion) '() '() '() dragons-island)) (define dragonlair (create-location 'dragonlair '(archdragon) '() "The lair of the most fiersome weapon in the land" "as your eyes grow weary of the darkness, you see an enormeous dragon lying on a huge treasure" '(dragons-tail dragons-treasure) '(archmaster) '() '(monster-attack) dragons-island)) (define dragons-roads-dummy (begin (make-road-in dragons-island northern-beach dragonlair 'south 'reversed) (make-road-in dragons-island dragonlair southern-beach 'south 'reversed) (make-road-in dragons-island northern-beach exit-west 'west) (make-road-in dragons-island northern-beach exit-north 'north) (make-road-in dragons-island northern-beach exit-east 'east) (make-road-in dragons-island southern-beach exit-west 'west) (make-road-in dragons-island southern-beach exit-south 'south) (make-road-in dragons-island southern-beach exit-east 'east))) ;;Athela (define city-gates (create-location 'city-gates '() '(athelian-guard-1 athelian-guard-2 gatekeeper) "The impressive entrance to the City of Athela" "The typical 2 guards stand next to the door" '() '(long-staff-+) '() '() athela)) (define athela-fountains (create-location 'athela-fountains '() '(athelian-commoner-1 athelian-commoner-2 lord-esthart) "A series of beautiful fountains dominate the square" "Some commoners are wandering about" '(small-potion intelligence-potion) '(small-dagger) '() '() athela)) (define teraks-store (create-location 'teraks-store '() '(terak) "Terak's store: the best potions in the land" "Terak seems busy brewing some potions" '(medium-potion dexterity-potion strength-potion) '(long-sword-++ heavy-axe-++ short-sword-++ long-staff-+ heavy-dagger-+ metal-staff-+) '() '() athela)) (define courtyard (create-location 'courtyard '() '(nobleman noblewoman) "The athelian Courtyard, meeting place for the noble" "Some noble personae wandering about" '() '(cape) '(greater-blessing) '() athela)) (define athelian-market (create-location 'athelian-market '() '(athelian-commoner-3 athelian-commoner-4 athelian-merchant zirtan) "The market, it's quite crowded, the merchants are having a good day" "A few commoners are discussing about some bought wares" '(small-potion large-potion potion-of-heroism) '(large-axe-++ spear bow) '(heal-critical-wounds) '() athela)) (define athelian-tavern (create-location 'athelian-tavern '(athelian-knight) '(athelian-ward hislo) "The Tavern of Athela, the ward is serving some people" "not much people around here, they're all out at the market" '(small-potion) '() '() '() athela)) (define king-dahriens-castle (create-location 'king-dahriens-castle '() '(king-dahrien) "The castle of the King of the land" "It's your typical medieval Castle" '() '() '() '() athela)) (define athelian-barracks (create-location 'athelian-barracks '(captain-gerard athelian-soldier-1 athelian-soldier-2 athelian-mage-soldier) '() "The atelian barracks, dorms for the soldiers" "Some beds, a table, and some weapons is all you see" '(strength-potion constitution-potion) '(helmet shield spear long-sword-++ broad-sword-++) '(lightning-bolt) '(multiple-monster-attack) athela)) (define dyeraks-home (create-location 'dyeraks-home '() '(dyerak) "The house of an ordinary commoner" "Dyerak's home is nothing more than a little cabin in an obscure street" '() '() '() '() athela)) (define city-walls (create-location 'city-walls '() '(old-mage) "The City walls, they surround the entire city" "The walls are about 12 feet thick, large enough to stop a goblin raid" '() '(long-staff-+) '(terror judgement) '() athela)) (define athela-roads-dummy (begin (make-road-in athela city-gates athela-fountains 'south 'reversed) (make-road-in athela athela-fountains athelian-market 'south 'reversed) (make-road-in athela athelian-market courtyard 'west 'reversed) (make-road-in athela athelian-market athelian-tavern 'east 'reversed) (make-road-in athela king-dahriens-castle athelian-barracks 'east 'reversed) (make-road-in athela courtyard king-dahriens-castle 'south 'reversed) (make-road-in athela athelian-barracks dyeraks-home 'east 'reversed) (make-road-in athela athelian-tavern teraks-store 'north 'reversed) (make-road-in athela athelian-barracks city-walls 'south 'reversed) (make-road-in athela athelian-market athelian-barracks 'south 'reversed) (make-road-in athela city-gates exit-west 'west) (make-road-in athela city-gates exit-north 'north) (make-road-in athela city-walls exit-west 'west) (make-road-in athela city-walls exit-south 'south))) ;;Goblin Encampment (define yislings-cave (create-location 'yislings-cave '() '(yisling) "A dark cave, in the middle, a pot is boiling on top of a fire" "A little goblin mage is brewing some redish drink in the pot" '() '() '() '() goblin-encampment)) (define goblin-barracks (create-location 'goblin-barracks '(goblin-warrior-1 goblin-warrior-2 orcish-warrior-1) '() "The goblin army headquarters" "the walls are besmeared with blood, and everywhere on the floor lie bones and weapons" '() '(short-axe) '() '(multiple-monster-attack) goblin-encampment)) (define goblin-tavern (create-location 'goblin-tavern '(goblin-warrior-3 goblin-warrior-4) '() "The goblin tavern, meeting place for the goblins" "Not your typical Human Tavern" '() '(short-staff) '() '(multiple-monster-attack) goblin-encampment)) (define goblin-warrens (create-location 'goblin-warrens '(goblin-warrior-5) '() "The goblin warrens, sort of like a children's creche" "The warrens seem abandoned" '() '(short-sword-+) '() '(monster-attack) goblin-encampment)) (define goblin-kings-palace (create-location 'goblin-kings-palace '(goblin-king goblin-warrior-6 goblin-warrior-7 goblin-warrior-8 orcish-warrior-2 orcish-warrior-3) '() "The residence of the Goblin King" "It's not the kind of 'palace' humans are used to" '() '(gods-finger) '(summon-imp) '(multiple-monster-attack) goblin-encampment)) (define goblin-roads-dummy (begin (make-road-in goblin-encampment yislings-cave goblin-tavern 'south 'reversed) (make-road-in goblin-encampment goblin-barracks goblin-tavern 'east 'reversed) (make-road-in goblin-encampment goblin-tavern goblin-warrens 'east 'reversed) (make-road-in goblin-encampment goblin-kings-palace goblin-tavern 'north 'reversed) (make-road-in goblin-encampment yislings-cave exit-north 'north) (make-road-in goblin-encampment goblin-warrens exit-east 'east) (make-road-in goblin-encampment goblin-kings-palace exit-south 'south))) ;;Ithilion (define gates-of-ithla (create-location 'gates-of-ithla '(evil-mage) '(ithilian-guard-1 ithilian-guard-2) "The gates of the city of Trade" "Although this city seems to be quite safe... looks can be deceiving" '(wisdom-potion) '(heavy-dagger) '() '(monster-attack) ithilion)) (define ithilian-barracks (create-location 'ithilian-barracks '() '(captain-iomund) "The place to be for the Ithla military" "Except for the captain, you see no soldiers around, they must be out patrolling" '() '(spear) '() '() ithilion)) (define city-keepers-mansion (create-location 'city-keepers-mansion '() '(city-keeper) "The mansion of the head of the city" "By the looks of his house, this man must be VERY rich" '(intelligence-potion) '() '() '() ithilion)) (define trademeet (create-location 'trademeet '() '(market-seller-1 market-seller-2) "The core of trading Ithla" "As always, trademeet is crowded, merchants are screaming and customers are bidding for the lowest prices" '(small-potion) '(bow) '(magic-missile) '() ithilion)) (define commerce-district (create-location 'commerce-district '() '(market-seller-3 market-seller-4) "The commercer district, here, the goods are made" "Everyone is quite busy fabricating their wares to sell at the market" '() '(ice-staff) '(heal-large-wounds) '() ithilion)) (define ithilian-market (create-location 'ithilian-market '() '(market-seller-5 peasant customer) "The greatest market in the land" "More people screaming about, telling their wares are the best and the cheapest." '(large-potion metal) '(fire-staff) '() '() ithilion)) (define diegos-house (create-location 'diegos-house '(diego) '() "A typical thieve's house" "In a corner you see a large bag, must be one of his loots" '(small-potion) '() '() '(monster-attack) ithilion)) (define ithilion-roads-dummy (begin (make-road-in ithilion gates-of-ithla trademeet 'south 'reversed) (make-road-in ithilion city-keepers-mansion trademeet 'east 'reversed) (make-road-in ithilion trademeet commerce-district 'east 'reversed) (make-road-in ithilion trademeet ithilian-market 'south 'reversed) (make-road-in ithilion ithilian-market diegos-house 'east 'reversed) (make-road-in ithilion ithilian-barracks commerce-district 'south 'reversed) (make-road-in ithilion gates-of-ithla exit-north 'north) (make-road-in ithilion gates-of-ithla exit-west 'west) (make-road-in ithilion ithilian-market exit-south 'south))) ;;Elven Fortress (define elven-woods (create-location 'elven-woods '(drow-elve elven-warrior) '() "The elven woods, the darkest yet most beautiful woods" "Between the trees, you see the Fortress, completely made of wood" '() '() '(summon-angel) '(multiple-monster-attack) elven-fortress)) (define elven-tower (create-location 'elven-tower '() '(irgis) "The elven tower is used as a lookout, orcish troops are always about" "The tower is a solid wooden construction, like everything else in the fortress" '() '() '() '() elven-fortress)) (define elven-barracks (create-location 'elven-barracks '() '(elven-scout) "The barracks of the elven scouts" "The walls are decorated with animal skins" '() '(halberd bow) '() '() elven-fortress)) (define elven-dorms (create-location 'elven-dorms '() '(eregion) "The elven dormitory, the beds are all empty" "An elf is sitting at a table, reading a book" '(intelligence-potion wisdom-potion dexterity-potion) '(elven-sword) '() '() elven-fortress)) (define fortress-roads-dummy (begin (make-road-in elven-fortress elven-woods elven-tower 'east 'reversed) (make-road-in elven-fortress elven-tower elven-barracks 'east 'reversed) (make-road-in elven-fortress elven-tower elven-dorms 'south 'reversed) (make-road-in elven-fortress elven-tower exit-north 'north) (make-road-in elven-fortress elven-barracks exit-east 'east))) ;;Temple of Lune (define lune-fountain (create-location 'lune-fountain '() '() "The lune fountain" "The water in the lune fountain is the clearest you've ever seen" '(potion-of-heroism) '() '() '() temple-of-lune)) (define lune-altar (create-location 'lune-altar '(elven-priest-1 stone-golem) '() "The lune altar" "The priests of Lune are not known for their friendy behaviour, as you have noticed" '() '() '() '(monster-attack) temple-of-lune)) (define mage-conclave (create-location 'mage-conclave '(elven-sorcerer-1 elven-sorcerer-2) '() "The mage conclave is a meeting place for elven sorcerers" "The sorcerers aren't very happy with unexpected visitors" '(wisdom-potion) '(mystic-staff staff-of-nature) '(shadowcast) '(multiple-monster-attack) temple-of-lune)) (define elven-throne (create-location 'elven-throne '(elven-priest-2) '(elven-king) "The elven throne, the throne of the Elven King" "The king seems to be in deep thoughts" '(elven-potion) '() '() '() temple-of-lune)) (define temple-roads-dummy (begin (make-road-in temple-of-lune lune-fountain lune-altar 'south 'reversed) (make-road-in temple-of-lune lune-altar mage-conclave 'east 'reversed) (make-road-in temple-of-lune lune-altar elven-throne 'south 'reversed) (make-road-in temple-of-lune lune-fountain exit-north 'north) (make-road-in temple-of-lune lune-fountain exit-west 'west) (make-road-in temple-of-lune lune-fountain exit-east 'east))) ;;Ancient Graveyard (define tombstones (create-location 'tombstones '(zombie-1 zombie-2 vampire-1) '() "A large number of tombstones" "This place is creepy" '() '(metal-plate-armor) '() '(multiple-monster-attack) ancient-graveyard)) (define chapel (create-location 'chapel '(zombie-3 vampire-2 skeleton-1 skeleton-2) '() "A small chapel, the stairs lead down to an underground passage" "You hear strange voices as you let your eyes get used to the darkness" '() '() '(summon-demon) '(multiple-monster-attack) ancient-graveyard)) (define unholy-graves (create-location 'unholy-graves '(aisgen-vampire-1 aisgen-vampire-2 aisgen-vampire-3) '() "The Unholy Graves" "You seem to have disturbed a group of vampires" '(ancient-tome) '(wind-staff) '() '(multiple-monster-attack) ancient-graveyard)) (define graveyard-roads-dummy (begin (make-road-in ancient-graveyard tombstones chapel 'south 'reversed) (make-road-in ancient-graveyard chapel unholy-graves 'east 'reversed) (make-road-in ancient-graveyard tombstones exit-north 'north) (make-road-in ancient-graveyard tombstones exit-west 'west))) ;;Set the startlocations (define init-locations-dummy (begin (northern-plains 'set-startlocation! small-pool) (wizard-school 'set-startlocation! apprentices-square) (dwarven-keep 'set-startlocation! dwarven-keep-gates) (dragonvale 'set-startlocation! town-gates) (dragons-island 'set-startlocation! northern-beach) (athela 'set-startlocation! city-gates) (goblin-encampment 'set-startlocation! goblin-tavern) (ithilion 'set-startlocation! gates-of-ithla) (elven-fortress 'set-startlocation! elven-woods) (temple-of-lune 'set-startlocation! lune-fountain) (ancient-graveyard 'set-startlocation! tombstones) (display "Locations Initialised") (newline))) ;;The actions table (define init-actions-dummy (begin (the-actions-table 'add 'show-targets-in-room show-targets-in-room) (the-actions-table 'add 'hp-up hp-up) (the-actions-table 'add 'heropoints-up heropoints-up) (the-actions-table 'add 'strength-up strength-up) (the-actions-table 'add 'dexterity-up dexterity-up) (the-actions-table 'add 'constitution-up constitution-up) (the-actions-table 'add 'wisdom-up wisdom-up) (the-actions-table 'add 'intelligence-up intelligence-up) (the-actions-table 'add 'charisma-up charisma-up) (the-actions-table 'add 'hp-down hp-down) (the-actions-table 'add 'strength-down strength-down) (the-actions-table 'add 'dexterity-down dexterity-down) (the-actions-table 'add 'constitution-down constitution-down) (the-actions-table 'add 'wisdom-down wisdom-down) (the-actions-table 'add 'intelligence-down intelligence-down) (the-actions-table 'add 'charisma-down charisma-down) (the-actions-table 'add 'deal-x-damage-to-target deal-x-damage-to-target) (the-actions-table 'add 'display-spell display-spell) (the-actions-table 'add 'monster-travelling monster-travelling) (the-actions-table 'add 'monster-attack monster-attack) (the-actions-table 'add 'multiple-monster-attack multiple-monster-attack) (the-actions-table 'add 'report-combat report-combat) (the-actions-table 'add 'deal-x-damage-to deal-x-damage-to) (the-actions-table 'add 'reset-spell reset-spell) (the-actions-table 'add 'exit-world exit-world) (the-actions-table 'add 'move move) (the-actions-table 'add 'combat combat) (the-actions-table 'add 'steal steal) (the-actions-table 'add 'flee flee) (the-actions-table 'add 'look look) (the-actions-table 'add 'get get) (the-actions-table 'add 'drop drop) (the-actions-table 'add 'erase erase) (the-actions-table 'add 'get-all get-all) (the-actions-table 'add 'drop-all drop-all) (the-actions-table 'add 'equip-offence equip-offence) (the-actions-table 'add 'equip-defense equip-defense) (the-actions-table 'add 'teleport teleport) (the-actions-table 'add 'converse converse) (the-actions-table 'add 'cast cast) (the-actions-table 'add 'use use) (the-actions-table 'add 'player-read player-read) (the-actions-table 'add 'player-examine player-examine) (the-actions-table 'add 'show-status show-status) (the-actions-table 'add 'show-inventory show-inventory) (the-actions-table 'add 'show-spellbook show-spellbook) (the-actions-table 'add 'show-questlog show-questlog) (the-actions-table 'add 'show-exits show-exits) (the-actions-table 'add 'show-actions show-actions) (the-actions-table 'add 'cancel-actions cancel-actions) (the-actions-table 'add 'undo undo) (the-actions-table 'add 'respawn-monster respawn-monster) (the-actions-table 'add 'undo-blessing-effects undo-blessing-effects) (the-actions-table 'add 'cast-doom cast-doom) (the-actions-table 'add 'cast-judgement cast-judgement) (the-actions-table 'add 'cast-curse cast-curse) (the-actions-table 'add 'summon summon) (the-actions-table 'add 'cast-force-drop cast-force-drop) (the-actions-table 'add 'cast-terror cast-terror) (the-actions-table 'add 'undo-doom-effects undo-doom-effects) (the-actions-table 'add 'undo-judgement-effects undo-judgement-effects) (the-actions-table 'add 'undo-curse-effects undo-curse-effects) (the-actions-table 'add 'undo-terror-effects undo-terror-effects) (the-actions-table 'add 'unsummon-monster unsummon-monster) (the-actions-table 'add 'undo-blessing-effects undo-blessing-effects) (the-actions-table 'add 'undo-greater-blessing-effects undo-greater-blessing-effects) (the-actions-table 'add 'undo-brainstorm-effects undo-brainstorm-effects) (the-actions-table 'add 'undo-bloodlust-effects undo-bloodlust-effects) (the-actions-table 'add 'undo-berserk-effects undo-berserk-effects) (display "Actions loaded") (newline))) ;;these functions are necessary to determine whether ;;the player fullfilled the actions ;;for a given quest (define (player-posseses key object) (if (eq? key 'spell) (lambda (player) ;;all actions eventually returned must take one parameter: a player (give-spell-from-character object player)) (lambda (player) (give-item-from-character object player)))) (define (player-posseses-item item) (player-posseses 'item item)) (define (player-posseses-weapon item) (player-posseses 'weapon item)) (define (player-posseses-spell item) (player-posseses 'spell item)) (define (player-has-stats key amount) (cond ((eq? key 'strength) (lambda (player) (> (get-character-strength player) amount))) ((eq? key 'constitution) (lambda (player) (> (get-character-constitution player) amount))) ((eq? key 'dexterity) (lambda (player) (> (get-character-dexterity player) amount))) ((eq? key 'wisdom) (lambda (player) (> (get-character-wisdom player) amount))) ((eq? key 'intelligence) (lambda (player) (> (get-character-intelligence player) amount))) ((eq? key 'charisma) (lambda (player) (> (get-character-charisma player) amount))) ((eq? key 'heropoints) (lambda (player) (> (get-character-heropoints player) amount))) (else (error "Wrong key -- Player Has Stats" key)))) (define (more-strength-than amount) (player-has-stats 'strength amount)) (define (more-constitution-than amount) (player-has-stats 'constitution amount)) (define (more-wisdom-than amount) (player-has-stats 'wisdom amount)) (define (more-intelligence-than amount) (player-has-stats 'intelligence amount)) (define (more-dexterity-than amount) (player-has-stats 'dexterity amount)) (define (more-charisma-than amount) (player-has-stats 'charisma amount)) (define (more-heropoints-than amount) (player-has-stats 'heropoints amount)) ;;All NPC's are listed here ;;create-npc: name description start conversation items weapons questconditions quest-to-trigger (define init-npc-dummy (begin ;;Northern Plains (create-npc 'old-man "An old man" small-pool "Please, sir, i've lost a most precious stone, please find it" '() '() (list (player-posseses-item 'old-stone)) 'old-man-stone) (create-npc 'nymf "A woodnymf" tree-forest "Hello, traveller, make sure you don't get lost in the woods" '() '() '() 'none) (create-npc 'elven-ranger1 "An elven ranger" tree-forest "Greetings" '() '(short-sword) '() 'none) (create-npc 'elven-ranger2 "Another elven ranger" tree-forest "We're patrolling the area, nowadays, the orcs and goblins are everywhere" '(small-potion) '(short-staff) '() 'none) (create-npc 'old-sage "An old man with a large white beard" old-stone-cave "Traveller, do you see that stone, it might not seem special to you, but looks can be deceiving" '() '(wooden-staff) '() 'none) ;;Forests of Echnun (create-npc 'an-elf "An elven warrior" forests-of-echnun "Greetings. I need your help, I lost my sword, called The Sword of Doom, i really need it, i'd appreciate it if you'd find it." '() '(short-sword-+) (list (player-posseses-weapon 'sword-of-doom)) 'elf-and-sword) ;;Wizard School (create-npc 'jolo "A young apprentice" apprentices-square "Hello. You seem like a hero te me, perhaps you could help me. I'm currently researching a strange culture, and in order to proceed with my studies, I need two objects: a scimitar, and a book, called sundance raiders, could you get that for me?" '() '() (list (player-posseses-item 'sundance-raider-book) (player-posseses-weapon 'scimitar)) 'jolo-desert) (create-npc 'apprentice "Just another Wizard Apprentice" apprentices-square "Good day" '() '(wooden-staff) '() 'none) (create-npc 'mage1 "A mage teacher at the wizard school" wizard-school-dorms "Have you seen my students?" '(wisdom-potion) '(metal-staff) '() 'none) (create-npc 'mage2 "Another teacher" wizard-school-dorms "My friend here has lost his students again, it's always the same... sigh" '() '(metal-staff cape) '() 'none) (create-npc 'azatar "A wise looking mage" the-garden "Greetings, visitor. I have a quest for you, i am in search for the hide of an Orc, for study of course, i'd appreciate you looking into the matter. Good Day." '() '(metal-staff-+) (list (player-posseses-weapon 'orcish-armor)) 'azatar-orc) (create-npc 'master-wizard1 "A wise wizard" masters-square "Ah, a visitor, if you're a true hero, then i might have something for you" '() '(fire-staff) (list (more-heropoints-than 200)) 'master-wizard-offer) (create-npc 'master-wizard2 "A master wizard" masters-square "My friend here is always on the lookout for heroes to train and students to teach" '() '(ice-staff) '() 'none) (create-npc 'headmaster "The headmaster of the Wizard School" headmasters-tower "Hello. I've been expecting you. My studies have lead me to the search of a book, an ancient tome, that I need for my research. Unfortunately our library doesn't posess it. I will reward you if you can find that book for me" '() '(staff-of-elders) (list (player-posseses-item 'ancient-tome)) 'headmaster-book) ;;Dwarven Keep (create-npc 'drunken-dwarf "A drunken dwarf" dwarven-tavern "lemme alone" '() '() '() 'none) (create-npc 'dwarven-ward "The ward of the tavern, a big dwarf" dwarven-tavern "Oi visitor, want some ale?" '() '() '() 'none) (create-npc 'dwarven-guard-1 "This dwarf's beard is extermely long" dwarven-keep-gates "Get going visitor" '() '(dwarven-axe shield) '() 'none) (create-npc 'dwarven-guard-2 "The dwarf is resting on his axe" dwarven-keep-gates "zzzzzzzz" '() '(spear scale-mail-armor) '() 'none) (create-npc 'hyagar "A fierce dwarf, he seems quite strong" hyagars-smythe "I'VE HAD ENOUGH. This metal is worth nothing... when are my dwarves are going to import some decent metal! I beg of you, if you ever find some good metal, be sure to send me some." '(strength-potion) '() (list (player-posseses-item 'metal)) 'hyagars-metal) (create-npc 'dwarven-alchemist "The local alchemist" dwarven-workshop "You need some potions visitor?" '(constitution-potion) '() '() 'none) (create-npc 'dwarven-carpenter "The carpenter, he's busy" dwarven-workshop "Sorry visitor, haven't got time for chit chat" '() '(leather-armor) '() 'none) (create-npc 'king-keldorn "The king is seated in his throne" dwarven-kings-room "Welcome to the dwarven Keep visitor. I need your help, a favor... The Orcs are slaughtering my troops... As a favor, and as a form of friendship to the elves, i want you to get me an Orc's hide. Then you shall always be welcome in my castle" '() '(dwarven-axe helmet cape small-dagger) (list (player-posseses-weapon 'orcish-armor)) 'keldorn-revenge) ;;Dragonvale (create-npc 'dragonvale-guard-1 "A strong guard, equipped with spear and shield" town-gates "Move along citizen" '() '(spear shield) '() 'none) (create-npc 'dragonvale-guard-2 "Looks just like his collegue" town-gates "..." '() '(spear shield) '() 'none) (create-npc 'supervisor "The Museum Supervisor" dragon-museum "Hello, visitor, take a look around, but do not touch anything" '(potion-of-heroism) '() '() 'none) (create-npc 'lord-caeven "A famous lord here in Dragonvale" lord-caevens-home "Good day, hero. Say... can you wield my sword? If you think you can, let me know... i'll reward the man who can wield my sword" '() '() (list (more-strength-than 80)) 'caeven-sword) (create-npc 'the-governor "The Governor of the province" governors-mansion "You want something sir?" '() '() '() 'none) (create-npc 'a-dragonvale-commoner "Just a local" dragons-fountain "Great weather isn't it?" '() '() '() 'none) (create-npc 'a-drunk "The typical drunk" dragonvale-tavern "...." '() '() '() 'none) (create-npc 'local-dragonvale-idiot "A guy in need of some attention" dragonvale-tavern "Welwelwel, what have we here? A hero. A hero, don't make me laugh" '() '() '() 'none) (create-npc 'dragonvale-inn-ward "The ward of the dragonvale Inn" dragonvale-tavern "Can I fetch you a drink?" '() '() '() 'none) (create-npc 'yerun-the-dragonslayer "The famous dragonslayer, Yerun the Great" yeruns-house "You look like an adventurer. I have a quest for you. Probably your last quest... If you can kill the Archdragon in the centre of the world, then you will become the world's most famous hero. Off you go." '(dexterity-potion) '(long-sword-++) (list (player-posseses-item 'map-of-dragonvale) (player-posseses-item 'dragons-tail)) 'yerun-dragon) ;;Athela (create-npc 'athelian-guard-1 "The Guard isn't looking too happy" city-gates "I'm watching you" '() '(spear shield) '() 'none) (create-npc 'athelian-guard-2 "Another Guard" city-gates "Don't mind him" '() '(spear shield) '() 'none) (create-npc 'gatekeeper "The gatekeeper of the city of Athela" city-gates "Hello, Hero, I need your help, I lost my keys, probably left them at my mate's house Dyerak. I would be grateful if you'd get them for me" '(medium-potion) '() (list (player-posseses-item 'keys)) 'gatekeeper-keys) (create-npc 'athelian-commoner-1 "A local commoner" athela-fountains "Good Day adventurer" '() '() '() 'none) (create-npc 'athelian-commoner-2 "Another local commoner" athela-fountains "Greetings" '() '() '() 'none) (create-npc 'lord-esthart "A noble lord from Athela" athela-fountains "Good Day. Do you think you are wise enough to handle this spell?" '(large-potion) '() (list (more-intelligence-than 40)) 'esthart-reward) (create-npc 'terak "A storekeeper" teraks-store "Hello customer, need somethin'?" '() '() '() 'none) (create-npc 'nobleman "A noble from Athela" courtyard "You're an adventurer, i don't like your kind" '() '() '() 'none) (create-npc 'noblewoman "Another noble" courtyard "What he said" '() '() '() 'none) (create-npc 'athelian-commoner-3 "Another athelian commoner" athelian-market "Sorry, no time for talkin'" '(small-potion) '() '() 'none) (create-npc 'athelian-commoner-4 "One of many commoners" athelian-market "Good Day" '() '() '() 'none) (create-npc 'athelian-merchant "An athelian merchant selling his wares" athelian-market "Hellow adventurer, take a look at my wares" '() '() '() 'none) (create-npc 'zirtan "A herald from the north" athelian-market "Greetings, hero, I need your assistance. My sword was stolen by an Elf, if you can bring back my Sword of Chaos I will be most grateful" '() '() (list (player-posseses-weapon 'sword-of-chaos)) 'zirtans-sword) (create-npc 'athelian-ward "The ward of this tavern" athelian-tavern "Good day, are you a hero? If you're a true hero, then you're quite welcome, then I can make you famous *good for my commerce gheghe*" '() '() (list (more-heropoints-than 100)) 'wards-offer) (create-npc 'hislo "An old adventurer" athelian-tavern "Ah a hero, I remember the days I ventured through the world. Enjoy it while it lasts." '() '() '() 'none) (create-npc 'king-dahrien "The king of northeastern Mountainvale" king-dahriens-castle "Hero, I need your assistance. Many have I asked, to go and eliminate my opponent, the Goblin King. Many have failed. Kill that goblin maniac and bring me his cape as evidence." '() '(long-sword cape) (list (player-posseses-weapon 'goblin-kings-cape)) 'dahrien-cape) (create-npc 'dyerak "A young man" dyeraks-home "What's your business here?" '() '() '() 'none) (create-npc 'old-mage "An old army mage" city-walls "The time has come for me to quit the army. I'm far too old for this job" '() '(metal-staff-+) '() 'none) ;;Goblin Encampment (create-npc 'yisling "A small goblin mage" yislings-cave "Gjee, what are you doing here in old Yisling's cave. Anyway, if you're here, can you find me a Heal Greater Wounds spell? I need it for my little drink gjegjeh" '() '() (list (player-posseses-spell 'heal-greater-wounds)) 'yisling-spell) ;;Ithilion (create-npc 'ithilian-guard-1 "An Ithilian Guard" gates-of-ithla "Welcome to the city of Ithilion." '() '(spear shield) '() 'none) (create-npc 'ithilian-guard-2 "Another Ithilian Guard" gates-of-ithla "I hope you have good intentions, troublemakers will be punished" '() '(short-sword helmet) '() 'none) (create-npc 'captain-iomund "The Captain of the Ithilian army" ithilian-barracks "Hello Adventurer, I'm in need of some assistance. As you see, all my soldiers are out patrolling. There's a bunch of thieves in the city, robbing the merchants. One of them is Diego. My men are having a hard time catching him, if you can kill him and give me his dagger, i'd be most thankful." '() '() (list (player-posseses-weapon 'diegos-dagger)) 'iomund-thief) (create-npc 'city-keeper "The Head of the City" city-keepers-mansion "Mmmhellow, if you want to ask me something, make an appointment, i'm rather busy at the moment" '(super-potion) '() '() 'none) (create-npc 'market-seller-1 "A typical market seller" trademeet "Look at these wondrous potions, buy some, they're cheap" '(medium-potion) '() '() 'none) (create-npc 'market-seller-2 "A typical market seller" trademeet "Want some books? I have books, or potions, or swords, you name it, I've got it!" '(wisdom-potion) '() '() 'none) (create-npc 'market-seller-3 "A typical market seller" commerce-district "Hey adventurer, need a new armor? Or interested in a new helmet?" '(intelligence-potion) '() '() 'none) (create-npc 'market-seller-4 "A typical market seller" commerce-district "Bah, I ain't sellin' anything today, lousy stinkin' customers, ain't never happy 'bout my wares" '(strength-potion) '() '() 'none) (create-npc 'market-seller-5 "A typical market seller" ithilian-market "Times are tough with all those thieves in the area, stealing our wares" '(dexterity-potion) '() '() 'none) (create-npc 'peasant "A farmer from the region" ithilian-market "I'm buying some food, that's right, the life of a farmer ain't what it used to be" '() '() '() 'none) (create-npc 'customer "A lady buying wares" ithilian-market "Look at these fine wares I bought today!" '() '() '() 'none) ;;Elven Fortress (create-npc 'irgis "An elven scout, spotting in the tower" elven-tower "This is an excellent outpost, you can see the entire woods from here" '() '() '() 'none) (create-npc 'elven-scout "An elf, getting ready to leave the fortress" elven-barracks "If you'll excuse me, I need to prepare myself for another journey" '() '() '() 'none) (create-npc 'eregion "An old, wise Elf" elven-dorms "It's been a long time since we've had foreign visitors. Can you do me a favor, and head to the Wizard School in the north, to get a book, called Apocalypse, I would like to study it." '() '() (list (player-posseses-item 'apocalypse-book)) 'eregion-book) ;;Temple Of Lune (create-npc 'elven-king "The king of Elves" elven-throne "Hero, you've come this far. If you can prove you are worthy of be�ng called a true hero, then I shall give you a gift, of most powerful value" '() '() (list (more-heropoints-than 1000)) 'elven-king-gift) (display "NPC's Loaded") (newline))) ;;All Monsters's are listed here ;;make-monster: name class location route (define init-monsters-dummy (begin ;;Northern Plains (make-monster 'drow-elf 'drow-elf tree-forest) ;;Forests of Echnun (make-monster 'a-goblin 'goblin forests-of-echnun) (make-monster 'a-gnoll 'gnoll forests-of-echnun) ;;Wizard School (make-monster 'clay-golem 'clay-golem the-laboratory) ;;Dwarven Keep (make-monster 'dwarven-warrior-1 'dark-dwarf dwarven-caverns (list dwarven-caverns dwarven-tavern)) (make-monster 'dwarven-warrior-2 'dark-dwarf dwarven-weaponry) (make-monster 'dwarven-warrior-3 'dark-dwarf dwarven-caverns (list dwarven-weaponry dwarven-caverns)) ;;Dragon's Island (make-monster 'dragon-welp 'dragon-welp southern-beach) (make-monster 'dark-dragon 'dark-dragon northern-beach) (make-monster 'archdragon 'arch-dragon dragonlair) ;;Athela (make-monster 'athelian-knight 'knight athelian-tavern) (make-monster 'captain-gerard 'knight athelian-barracks) (make-monster 'athelian-soldier-1 'knight athelian-barracks) (make-monster 'athelian-soldier-2 'knight athelian-barracks) (make-monster 'athelian-mage-soldier 'mage athelian-barracks) ;;Goblin Encampment (make-monster 'goblin-warrior-1 'goblin+ goblin-barracks) (make-monster 'goblin-warrior-2 'goblin+ goblin-barracks) (make-monster 'orcish-warrior-1 'orc+ goblin-barracks) (make-monster 'goblin-warrior-3 'goblin+ goblin-tavern (list goblin-tavern goblin-barracks)) (make-monster 'goblin-warrior-4 'goblin+ goblin-tavern (list goblin-tavern goblin-barracks)) (make-monster 'goblin-warrior-5 'goblin++ goblin-warrens) (make-monster 'goblin-warrior-6 'goblin++ goblin-kings-palace) (make-monster 'goblin-warrior-7 'goblin++ goblin-kings-palace) (make-monster 'goblin-warrior-8 'goblin++ goblin-kings-palace) (make-monster 'goblin-king 'goblin-king goblin-kings-palace) (make-monster 'orcish-warrior-2 'orc++ goblin-kings-palace) (make-monster 'orcish-warrior-3 'orc++ goblin-kings-palace) ;;Ithilion (make-monster 'evil-mage 'mage gates-of-ithla) (make-monster 'diego 'diego diegos-house) ;;Elven Fortress (make-monster 'drow-elve 'drow-elf elven-woods) (make-monster 'elven-warrior 'drow-elf elven-woods (list elven-woods elven-tower)) ;;Temple Of Lune (make-monster 'elven-priest-1 'elven-priest lune-altar) (make-monster 'stone-golem 'stone-golem lune-altar) (make-monster 'elven-sorcerer-1 'elven-sorcerer mage-conclave) (make-monster 'elven-sorcerer-2 'elven-sorcerer mage-conclave (list mage-conclave lune-altar)) (make-monster 'elven-priest-2 'elven-priest elven-throne) ;;Ancient Graveyard (make-monster 'zombie-1 'zombie tombstones) (make-monster 'zombie-2 'zombie+ tombstones) (make-monster 'vampire-1 'vampire tombstones) (make-monster 'zombie-3 'zombie++ chapel) (make-monster 'vampire-2 'vampire chapel) (make-monster 'skeleton-1 'skeleton chapel) (make-monster 'skeleton-2 'skeleton+ chapel) (make-monster 'aisgen-vampire-1 'aisgen-vampire unholy-graves) (make-monster 'aisgen-vampire-2 'aisgen-vampire unholy-graves) (make-monster 'aisgen-vampire-3 'aisgen-vampire unholy-graves) (display "Monsters Loaded") (newline))) ;;The functions for Quests are listed here (define (get-and-delete-object-from-player object-name get-object-fct delete-object-fct) (lambda (player) (let ((the-object (get-object-fct object-name player))) (if the-object (begin (delete-object-fct object-name player) the-object) (error "Bad Quest: Player needs object to fulfill quest" object-name))))) (define (get-and-delete-item-from-player item-name) (get-and-delete-object-from-player item-name give-item-from-character delete-item-for-character)) (define (get-and-delete-spell-from-player spell-name) (get-and-delete-object-from-player spell-name give-spell-from-character delete-spell-for-character)) (define (give-item-from-npc-to-player item) (lambda (player) (add-item-for-character item player))) (define (give-spell-from-npc-to-player spell) (lambda (player) (add-spell-for-character spell player))) (define (give-item-to-npc npc item) (lambda (player) (add-item-for-character item npc))) (define (give-spell-to-npc npc spell) (lambda (player) (add-spell-for-character spell npc))) (define (swap-item npc item) (lambda (player) ((give-item-to-npc npc ((get-and-delete-item-from-player item) player)) player))) (define (swap-spell npc spell) (lambda (player) ((give-spell-to-npc npc ((get-and-delete-spell-from-player spell) player)) player))) (define (player-set-stats key amount) (cond ((eq? key 'hp) (lambda (player) (do-hitpoints-up amount player))) ((eq? key 'strength) (lambda (player) (do-strength-up amount player))) ((eq? key 'constitution) (lambda (player) (do-constitution-up amount player))) ((eq? key 'dexterity) (lambda (player) (do-dexterity-up amount player))) ((eq? key 'wisdom) (lambda (player) (do-wisdom-up amount player))) ((eq? key 'intelligence) (lambda (player) (do-intelligence-up amount player))) ((eq? key 'charisma) (lambda (player) (do-charisma-up amount player))) ((eq? key 'heropoints) (lambda (player) (do-heropoints-up amount player))) (else (error "Wrong key -- Player Set Stats" key)))) (define (bonus-hp amount) (player-set-stats 'hp amount)) (define (bonus-strength amount) (player-set-stats 'strength amount)) (define (bonus-constitution amount) (player-set-stats 'constitution amount)) (define (bonus-wisdom amount) (player-set-stats 'wisdom amount)) (define (bonus-intelligence amount) (player-set-stats 'intelligence amount)) (define (bonus-dexterity amount) (player-set-stats 'dexterity amount)) (define (bonus-charisma amount) (player-set-stats 'charisma amount)) (define (bonus-heropoints amount) (player-set-stats 'heropoints amount)) (define (change-conversation npc text) (let ((the-npc (get-character-adt npc))) (lambda (player) (the-npc 'set-conversation! text)))) (define (wards-offer) ;;specific quest test (lambda (player) (let ((heropoints (get-character-heropoints player))) (cond ((> heropoints 200) ((bonus-heropoints 100) player)) ((> heropoints 500) ((bonus-heropoints 200) player)) (else 'done))))) ;;All Quest Data is listed here ;;create-quest: name title description triggers heropoints ;;Northern Plains (define old-man-stone (create-quest 'old-man-stone "Retrieve an old stone" "You have to find an old stone. It is of some value for an old man you met in the Northern Plains" (list (bonus-charisma 3) (swap-item 'old-man 'old-stone) (change-conversation 'old-man "I've got my stone now, i'm very happy")) 20)) ;;Forests of Echnun (define elf-and-sword (create-quest 'elf-and-sword "Get the Elf's sword back" "An Elf you met in the Forests wants his sword, sword of chaos, back" (list (bonus-wisdom 3) (bonus-strength 3) (swap-item 'an-elf 'sword-of-doom) (change-conversation 'an-elf "Now that i've got my precious sword back, i can finally kick Orc butt again")) 50)) ;;Wizard School (define jolo-desert (create-quest 'jolo-desert "Get some items from the far deserts" "An apprentice has asked you to find a book, Sundance Raiders, and a Scimitar Sword" (list (swap-item 'jolo 'scimitar) (swap-item 'jolo 'sundance-raider-book) (change-conversation 'jolo "Now that i've got my items, I can start experimenting again")) 60)) (define azatar-orc (create-quest 'azatar-orc "Get an Orcish Hide for Azatar" "Azatar, a master wizard from the wizard school, wants some orcish leather, for experiments no doubt" (list (bonus-intelligence 3) (swap-item 'azatar 'orcish_armor) (change-conversation 'azatar "Mmmm yes, interesting hide, I will start my studies immediately")) 30)) (define master-wizard-offer (create-quest 'master-wizard-offer "A master Wizard's offer" "If you've become a true hero, the master wizards will reward you." (list (bonus-charisma 3) (give-spell-from-npc-to-player 'doom) (give-item-from-npc-to-player 'sword-of-heroes) (change-conversation 'master-wizard1 "True heroes must be rewarded.")) 20)) (define headmaster-book (create-quest 'headmaster-book "The Headmaster's book" "Get an old book for the Headmaster of the Wizard School" (list (bonus-intelligence 3) (swap-item 'headmaster 'ancient-tome) (change-conversation 'headmaster "A most interesting book, this one here, i've been looking for it for a long time")) 60)) ;;Dwarven Keep (define hyagars-metal (create-quest 'hyagars-metal "Hyagar's search for decent metal" "The Dwarven Smith, Hyagar, wants you to look for some good metal for his weapons." (list (swap-item 'hyagar 'metal) (give-spell-from-npc-to-player 'inferno) (give-item-from-npc-to-player 'sword-of-fire) (change-conversation 'hyagar "This metal is EXCELLENT! I can finally create descent material again")) 50)) (define keldorn-revenge (create-quest 'keldorn-revenge "The Dwarven king's revenge" "Keldorn, the dwarven king, wants revenge for his losses. Avenge his people by killing some Orcs" (list (swap-item 'king-keldorn 'orcish-armor) (give-item-from-npc-to-player 'sword-of-ice) (change-conversation 'king-keldorn "This is just the beginning. More Orc Blood will flow")) 20)) ;;Dragonvale (define caeven-sword (create-quest 'caeven-sword "Caeven's test" "Only the most strengthened can wield Caeven's Sword" (list (give-item-from-npc-to-player 'defenders-mythe) (change-conversation 'lord-caeven "My sword now lies in the hands of a strong and mighty hero")) 10)) (define yerun-dragon (create-quest 'yerun-dragon "The Archdragon's Death" "The Quest of true heroes: killing the dragon which terrorises the land" (list (bonus-charisma 5) (bonus-wisdom 2) (bonus-strength 5) (give-item-from-npc-to-player 'baldurans-armor) (change-conversation 'yerun-the-dragonslayer "The Dragon is dead! This is truly a most glorious day, alert the heralds!")) 300)) ;;Athela (define gatekeeper-keys (create-quest 'gatekeeper-keys "Finding The Keys" "The Gatekeeper of Athela wants you to look for the keys of the gates, he lost them." (list (change-conversation 'gatekeeper "Ahh my keys, thank god, I can sleep safe again.")) 40)) (define esthart-reward (create-quest 'esthart-reward "Esthart's questions" "All strength is not important, the smart ones will conquer" (list (give-spell-from-npc-to-player 'curse) (change-conversation 'lord-esthart "The cunning will conquer you all, a true hero is a wise hero.")) 20)) (define zirtans-sword (create-quest 'zirtans-sword "Zirtan lost his sword" "Zirtan, a Herald residing in Athela, has lost his precious sword of chaos, stolen by an Elf" (list (swap-item 'zirtan 'sword-of-chaos) (change-conversation 'zirtan "If I ever find that Elf again, i'll sure rip his...")) 100)) (define wards-offer (create-quest 'wards-offer "The Athelian Ward's offer" "The ward of the tavern of Athela likes heroes in his tavern." (list (bonus-charisma 3) (wards-offer) (change-conversation 'athelian-ward "More Heroes please...*it's good for my business*")) 100)) (define dahrien-cape (create-quest 'dahrien-cape "The Striding Kings" "King Dahrien wants you to destroy his opponent, the Goblin King" (list (swap-item 'king-dahrien 'goblin-kings-cape) (give-item-from-npc-to-player 'angel-whisper) (change-conversation 'king-dahrien "My opponent is out of the way, i'm glad at least some heroes are capable of doing the job.")) 80)) ;;Goblin Encampment (define yisling-spell (create-quest 'yisling-spell "A Goblin mage's quest" "Yisling, a goblin mage, wants you to look for a certain spell, heal greater wounds" (list (swap-spell 'yisling 'heal-greater-wounds) (give-spell-from-npc-to-player 'magic-missile) (change-conversation 'yisling "Gyiiiiaaaaaaaaaa, this spell will make me strongggg yessss")) 30)) ;;Ithilion (define iomund-thief (create-quest 'iomund-thief "Get the Thief" "Iomund wants to get rid of the Thief Diego, get his dagger to prove you killed him." (list (give-spell-from-npc-to-player 'summon-imp) (give-item-from-npc-to-player 'wanderers-axe) (change-conversation 'captain-iomund "This was only one of many thieves who will bite the dust")) 50)) ;;Elven Fortress (define eregion-book (create-quest 'eregion-book "Eregion's book" "Eregion the Elf needs a book from the Wizard School, named Apocalypse" (list (give-spell-from-npc-to-player 'force-drop) (give-item-from-npc-to-player 'excalibur) (change-conversation 'eregion "Ahh, finally, some reading pleasure, most excellent literature.")) 50)) ;;Temple Of Lune (define elven-king-gift (create-quest 'elven-king-gift "The Elven King's gift" "True heroes are rear these days, you think you're one?" (list (give-spell-from-npc-to-player 'summon-dragon) (give-item-from-npc-to-player 'short-axe-of-venom) (give-item-from-npc-to-player 'dragon-armor) (change-conversation 'elven-king "A land like this needs strong heroes.")) 100)) ;;The Players (define amurath (create-player-adt 'amurath 'fighter)) (define lethnan (create-player-adt 'lethnan 'wizard)) (define yeran (create-player-adt 'yeran 'thief)) ;;The character table keeps track of all the characters (NPCs, Monsters and players) in the world (the-character-table 'add amurath) (the-character-table 'add lethnan) (the-character-table 'add yeran) ;;to speed up input data (define (solve-first-quest) (define (break) (newline) (display "Enter something to continue ") (read) (newline)) (display-line "This will solve the first quest, as an example of the game") (display-line "amurath asks locations") (show-exits 'amurath) (break) (display-line "amurath moves west") (move 'amurath 'west) (break) (display-line "amurath talks") (converse 'amurath) (break) (display-line "amurath now knows about the quest") (display-line "amurath reads the quest: ") (player-read 'amurath 'old-man-stone) (break) (display-line "amurath moves north") (move 'amurath 'north) (display-line "amurath engaged in combat") (break) (display-line "amurath moves west") (move 'amurath 'west) (break) (display-line "amurath gets the old stone") (get 'amurath 'old-stone) (break) (display-line "amurath travels back to the old man") (move 'amurath 'east) (break) (move 'amurath 'south) (break) (display-line "amurath talks to the old man again") (converse 'amurath) (break) (display-line "The quest is now solved") (show-status 'amurath)) (display "Initialising Data Done") (newline) (display-line "Welcome to mountainvale") (start-the-game)
false
449edbcddc6678f6ca4fc982b3d8a6e73f8690e5
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/polar.scm
2e50eb49a7663483b7b61b9c0fbc9e1d58e18fda
[]
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
2,014
scm
polar.scm
(define polar ;; (lambda (modulus theta) ;; private data (define data (cons modulus theta)) ;; public interface (define (dispatch m) (cond ((eq? m 'real) (real)) ((eq? m 'imag) (imag)) ((eq? m 'mod) (car data)) ((eq? m 'angle) (cdr data)) ((eq? m 'show)(show)) ((eq? m 'type) 'polar) (else (display "polar: unknown operation error\n")))) ;; private members ;; (define (show) (display real)(display "+")(display imag)(display "i")) ;; (define (real) (* (car data) (cos (cdr data)))) ;; (define (imag) (* (car data) (sin (cdr data)))) ;; ;; returning public interface dispatch)) (define polar-utils ;; static private members ;; (let ((polar-add (lambda (x y) (let ((u (+ (x 'real) (y 'real))) (v (+ (x 'imag) (y 'imag)))) (polar (sqrt (+ (* u u) (* v v))) (atan v u))))) (polar-sub (lambda (x y) (let ((u (- (x 'real) (y 'real))) (v (- (x 'imag) (y 'imag)))) (polar (sqrt (+ (* u u) (* v v ))) (atan v u))))) (polar-mul (lambda (x y) (polar (* (x 'mod) (y 'mod)) (+ (x 'angle) (y 'angle))))) (polar-div (lambda (x y) (polar (/ (x 'mod) (y 'mod)) (- (x 'angle) (y 'angle))))) (polar-eq? (lambda (x y) (and (< (abs (- (x 'real) (y 'real))) 0.0000000001) (< (abs (- (y 'imag) (y 'imag))) 0.0000000001)))) ) (lambda () (define (dispatch m) (cond ((eq? m '+) polar-add) ((eq? m '-) polar-sub) ((eq? m '*) polar-mul) ((eq? m '/) polar-div) ((eq? m '=) polar-eq?) (else (display "polar-utils: unkown operation error\n")))) ;; ;; returning interface dispatch)))
false
c01cbe4def276d982d67aec9f3a13f2393a69e66
ee10242f047e9b4082a720c48abc7d94fe2b64a8
/lazy.sch
55684f032bdf4fa450f68831ad89bcee065360d8
[ "Apache-2.0" ]
permissive
netguy204/brianscheme
168c20139c31d5e7494e55033c78f59741c81eb9
1b7d7b35485ffdec3b76113064191062e3874efa
refs/heads/master
2021-01-19T08:43:43.682516
2012-07-21T18:30:39
2012-07-21T18:30:39
1,121,869
5
0
null
null
null
null
UTF-8
Scheme
false
false
489
sch
lazy.sch
;; Implement the classic delay/force combo directly by representing a ;; delay as the cons of its value (nil of not yet forced) and the ;; closure that computes it (nil if it has been forced) (define-syntax (delay . body) "create a computation that can be completed later" `(cons nil (lambda () . ,body))) (define (force fn) "compute and or return the value of a delay" (when (and (not (null? (cdr fn))) (null? (car fn))) (set-car! fn ((cdr fn))) (set-cdr! fn nil)) (car fn))
true
fa64536c92a1bde36255b2f5e066fd6c7bd4ac73
32130475e9aa1dbccfe38b2ffc562af60f69ac41
/algo/increment.scm
419f3cce16a0cd59ef3dde7485593f09015b9879
[]
no_license
cinchurge/SICP
16a8260593aad4e83c692c4d84511a0bb183989a
06ca44e64d0d6cb379836d2f76a34d0d69d832a5
refs/heads/master
2020-05-20T02:43:30.339223
2015-04-12T17:54:45
2015-04-12T17:54:45
26,970,643
0
0
null
null
null
null
UTF-8
Scheme
false
false
270
scm
increment.scm
(define (increment y) (if (= y 0) 1 (if (= (modulo y 2) 1) (* 2 (increment (quotient y 2))) (+ y 1)))) (display (increment 0))(newline) (display (increment 1))(newline) (display (increment 2))(newline) (display (increment 3))(newline)
false
888042f07960237be2fc2e1c4e12fd7b5570b414
9b2eb10c34176f47f7f490a4ce8412b7dd42cce7
/lib-compat/mit-scheme-yuni/compat/ident.sls
e40fb6f20187c39276bfeac6503b95de1e62748a
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
okuoku/yuni
8be584a574c0597375f023c70b17a5a689fd6918
1859077a3c855f3a3912a71a5283e08488e76661
refs/heads/master
2023-07-21T11:30:14.824239
2023-06-11T13:16:01
2023-07-18T16:25:22
17,772,480
36
6
CC0-1.0
2020-03-29T08:16:00
2014-03-15T09:53:13
Scheme
UTF-8
Scheme
false
false
148
sls
ident.sls
(library (mit-scheme-yuni compat ident) (export ident-impl) (import (yuni scheme)) (define (ident-impl) 'mit-scheme) )
false
5b30b1b37777960badda25dd6c0b1a80a5e77a98
b43e36967e36167adcb4cc94f2f8adfb7281dbf1
/scheme/swl1.3/src/dc/stex/dsm.ss
4903607ae11ab7cc12fe1743fa84c9673fdac76e
[ "SWL", "TCL" ]
permissive
ktosiu/snippets
79c58416117fa646ae06a8fd590193c9dd89f414
08e0655361695ed90e1b901d75f184c52bb72f35
refs/heads/master
2021-01-17T08:13:34.067768
2016-01-29T15:42:14
2016-01-29T15:42:14
53,054,819
1
0
null
2016-03-03T14:06:53
2016-03-03T14:06:53
null
UTF-8
Scheme
false
false
1,977
ss
dsm.ss
;;; dsm.ss ;;; Copyright (c) 1998 Cadence Research Systems ;;; authors: R. Kent Dybvig and Oscar Waddell (define-syntax with-implicit (lambda (x) (syntax-case x () ((_ (tid id ...) . body) (andmap identifier? #'(tid id ...)) #'(with-syntax ((id (datum->syntax-object #'tid 'id)) ...) . body))))) (define-syntax define-syntactic-monad (lambda (x) (syntax-case x () ((_ name formal ...) (andmap identifier? #'(name formal ...)) #'(define-syntax name (lambda (x) (syntax-case x (lambda case-lambda) ((key lambda more-formals . body) (with-implicit (key formal ...) #'(lambda (formal ... . more-formals) . body))) ((key case-lambda (more-formals . body) (... ...)) (with-implicit (key formal ...) #'(case-lambda ((formal ... . more-formals) . body) (... ...)))) ((key proc ((x e) (... ...)) arg (... ...)) (andmap identifier? #'(x (... ...))) (with-implicit (key formal ...) (for-each (lambda (x) (unless (let mem ((ls #'(formal ...))) (and (not (null? ls)) (or (free-identifier=? x (car ls)) (mem (cdr ls))))) (assertion-violationf 'name "unrecognized identifier ~s" x))) #'(x (... ...))) (with-syntax (((t (... ...)) (generate-temporaries #'(arg (... ...))))) #'(let ((p proc) (x e) (... ...) (t arg) (... ...)) (p formal ... t (... ...)))))) ((key proc) #'(key proc ()))))))))) (define-syntax make-undefined (syntax-rules () ((_ x ...) (begin (define-syntax x (lambda (z) (assertion-violationf 'x "undefined"))) ...))))
true
1c49f158f7e92a3c196b1b6bce9f2e5d4d0a7199
88eaf472fcdbb4736ad95d52ede1d2d8c019774a
/scheme/System/time-log.scm
e9748485f7e00e1efa2e82a1025147de176dea5d
[ "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
blakemcbride/Dynace
8ca2ed1a1ba3c91cd4220543fce9880f2a089aa8
9cd122b3cd7977261cc093fae676a978fdb95ab2
refs/heads/master
2023-01-13T09:21:02.214780
2023-01-02T17:57:00
2023-01-02T17:57:00
16,148,303
86
10
null
null
null
null
UTF-8
Scheme
false
false
1,016
scm
time-log.scm
(define *tl:current-time* #f) (define *tl:begining-time* #f) (define *tl:port* #f) (define tl:start-timer (lambda (file) (tl:end-timer) (set! *tl:port* (open-output-file file 'text 'truncate)))) (define tl:end-timer (lambda () (cond (*tl:port* (close-output-port *tl:port*) (set! *tl:port* #f))) (set! *tl:begining-time* #f) (set! *tl:current-time* #f))) (define tl:mark-time (lambda (msg) (let ((last *tl:current-time*) (fmt (lambda (n) (Nfmt n "C" 0 3)))) (set! *tl:current-time* (/ (current-milliseconds) 1000.0)) (if (not *tl:begining-time*) (set! *tl:begining-time* *tl:current-time*)) (display (string-append msg " - ") *tl:port*) (if (not last) (display "timer start" *tl:port*) (begin (display (fmt (- *tl:current-time* *tl:begining-time*)) *tl:port*) (display " " *tl:port*) (display (fmt (- *tl:current-time* last)) *tl:port*))) (newline *tl:port*))))
false
f92e3112d1874c1b0fb50f619199e238dc01a408
b389e2ae98c6a980ac889326e104fd366286c193
/test/testfiles/define5.scm
78a864b3df8e53d0bc45e25c6652f1e9e28e667c
[]
no_license
adamrk/scheme2luac
1a0fbba81b4c2c0e06808bf93137cf5e0f1e9db7
5e64008b57a574c0afce72513363a176c7dcf299
refs/heads/master
2020-05-24T10:51:48.673627
2017-04-21T13:55:49
2017-04-21T13:55:49
84,849,528
22
3
null
null
null
null
UTF-8
Scheme
false
false
38
scm
define5.scm
(begin (define f 5) (define g 100)) g
false
6001e6e7ef3923410bc42790a44c24bfea81dc97
1ed47579ca9136f3f2b25bda1610c834ab12a386
/sec2/q2.29.scm
9a020cda9c2171330e3f8741cb4841c7e7babf06
[]
no_license
thash/sicp
7e89cf020e2bf5ca50543d10fa89eb1440f700fb
3fc7a87d06eccbe4dcd634406e3b400d9405e9c4
refs/heads/master
2021-05-28T16:29:26.617617
2014-09-15T21:19:23
2014-09-15T21:19:23
3,238,591
0
1
null
null
null
null
UTF-8
Scheme
false
false
4,327
scm
q2.29.scm
; ヒャッハー http://d.hatena.ne.jp/nTeTs/20090716/1247671614 ; ; 二進モービル => 原著では binary mobile. ; http://www.google.co.jp/search?q=binary+mobile&um=1&ie=UTF-8&hl=ja&tbm=isch&source=og&sa=N&tab=wi&ei=0EhwT8OeMIOJmQWunNS3Bg&biw=1366&bih=670&sei=EklwT4EkocqYBYfspKUG ; インテリアとかであるやつ。 正しい日本語訳は「モービル」だそうで。 ; 錘(おもり) (define (make-mobile left right) (list left right)) ; structureはおもり(数字) or 別のmobile. (define (make-branch length structure) (list length structure)) ; mobileを作る時は左右にbranchが必要である ; branchは、長さ(第一引数)とその先に繋がる「おもり or mobile」(第二引数)で定義される。 ; branch for test (define b (make-branch 1 5)) ; sample mobile from wiki (define mobile1 (make-mobile (make-branch 2 4) (make-branch 3 (make-mobile (make-branch 2 1) (make-branch 4 2))))) ; (a). 選択子 left-branchとright-branchを書け。 (define (left-branch mobile) (car mobile)) (define (right-branch mobile) (cadr mobile)) ;; ひとつの枝は ;; * length ;; * structure = 単なる錘を表す数 or 別のモービル ;; からなる. (define (branch-length branch) (car branch)) (define (branch-structure branch) (cadr branch)) ; (b). 全重量を返す手続きを書け。 ; サブ手続きhas-weight?を定義。 ; branchにつながっているのはおもりかどうか。(ちがうならmobileがぶら下がってる) (define (has-weight? branch) (if (not (pair? (cadr branch))) #t #f)) ; 回答。 (define (total-weight mobile) (+ (if (has-weight? #?=(left-branch mobile)) (cadr (left-branch mobile)) (total-weight (cadr (left-branch mobile)))) (if (has-weight? #?=(right-branch mobile)) (cadr (right-branch mobile)) (total-weight (cadr (right-branch mobile)))))) ; leftとrightで同じことをしているのでさらに抽象化できそう。 ; 再帰部分で (total-weight (cadr (right-branch mobile) ; とcadrしているのは、lengthを飛び越えてmobileを得るため ; rindaiの回答 - サブ手続きbranch-weightを使う ; どう考えてもhas-weight?よりmobile?のほうがよかった。 (define (total-weight2 mobile) (+ (branch-weight (left-branch mobile)) (branch-weight (left-branch mobile)))) (define (branch-weight branch) (if (number? (branch-structure branch)) (branch-structure branch) (total-weight2 (branch-structure branch)))) ; で、さらにリファクタリング。 (define (total-weight3 mobile) (define (mobile? x) (pair? x)) (if (mobile? mobile) (+ (total-weight3 #?=(left-branch mobile)) (total-weight3 #?=(right-branch mobile))) mobile ; pairじゃなけりゃおもりなのでただの数字として返す。 )) ; あれ、うまくいかない。大きぎる値が返る。 ; (c). モーメントを考えて釣り合うかどうかの判定手続きbalanced?を作る ; 例のWikiではtorqueだった。物理... ; トルク(英語:torque)は、ある固定された回転軸を中心にはたらく、回転軸のまわりの力のモーメントである。一般的には「ねじりの強さ」として表される。力矩、ねじりモーメントとも言う。 from wikipedia ; まずmomentを定義 (define (moment branch) (* (car branch) (if (has-weight? branch) (cadr branch) (total-weight (cadr branch))))) (define (balanced? mobile) (= (moment (left-branch mobile)) (moment (right-branch mobile)))) ; balanced mobile (define mobile2 (make-mobile (make-branch 2 4) (make-branch 8 1))) ; この回答はよかろう。 ; (d). listではなくconsでbranchとmobileを定義するようにした。 (define (make-mobile left right) (cons left right)) (define (make-branch length structure) (cons length structure)) ; mobile1はこんな感じになる ; ((2 . 4) 3 (2 . 1) 4 . 2) ; 影響が出るのは、cdrを取るところ。 ; ; gosh> (cdr (list 1 2)) ; (2) ; gosh> (cadr (list 1 2)) ; 2 ; gosh> (cdr (cons 1 2)) ; 2 ; gosh> (cadr (cons 1 2)) ; !!!Stack Trace:!!! ; ; cadrにしていた部分をすべてcdrにすればok
false
8c975df25da345e9919551d0e9416c2579d3c2b5
9b0c653f79bc8d0dc87526f05bdc7c9482a2e277
/3/3-02.ss
fcc71275edbb666b7d9f0bf755dba0e83f074144
[]
no_license
ndNovaDev/sicp-magic
798b0df3e1426feb24333658f2313730ae49fb11
9715a0d0bb1cc2215d3b0bb87c076e8cb30c4286
refs/heads/master
2021-05-18T00:36:57.434247
2020-06-04T13:19:34
2020-06-04T13:19:34
251,026,570
0
0
null
null
null
null
UTF-8
Scheme
false
false
646
ss
3-02.ss
(define (dn x) (display x) (newline)) (define nil '()) (define true #t) (define false #f) ; ********************** (define (make-monitored f) (define count 0) (define (call-f args) (begin (set! count (+ count 1)) (apply f args))) (define (how-many-calls?) count) (define (reset-count) (!set count 0)) (lambda (first . args) (cond ((eq? 'how-many-calls? first) (how-many-calls?)) ((eq? 'reset-count first) (reset-count)) (else (call-f (cons first args)))))) (define s (make-monitored sqrt)) (dn (s 100)) (dn (s 'how-many-calls?)) (exit)
false
d5322852e57632fc0def9b4c5453ee642adf06af
6f7df1f0361204fb0ca039ccbff8f26335a45cd2
/scheme/ikarus/flonum-formatter.sls
4e6689ace8ce23506df0bdc7b498642b285a73cf
[]
no_license
LFY/bpm
f63c050d8a2080793cf270b03e6cf5661bf3599e
a3bce19d6258ad42dce6ffd4746570f0644a51b9
refs/heads/master
2021-01-18T13:04:03.191094
2012-09-25T10:31:25
2012-09-25T10:31:25
2,099,550
2
0
null
null
null
null
UTF-8
Scheme
false
false
2,986
sls
flonum-formatter.sls
;;; Copyright (c) 2009 Abdulaziz Ghuloum ;;; Modified by Marco Maggi. ;;; ;;; Permission is hereby granted, free of charge, to any person obtaining a ;;; copy of this software and associated documentation files (the "Software"), ;;; to deal in the Software without restriction, including without limitation ;;; the rights to use, copy, modify, merge, publish, distribute, sublicense, ;;; and/or sell copies of the Software, and to permit persons to whom the ;;; Software is furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in ;;; all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ;;; THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING ;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (library (ikarus flonum-formatter) (export ikarus-format-flonum) (import (rnrs)) (define (ikarus-format-flonum pos? digits expt) (define fixnum->string number->string) (define (next x) (if (null? x) (values #\0 '()) (values (car x) (cdr x)))) (define (format-flonum-no-expt expt d0 d*) (cond [(= expt 1) (cons d0 (if (null? d*) '(#\. #\0) (cons #\. d*)))] [else (cons d0 (let-values ([(d0 d*) (next d*)]) (format-flonum-no-expt (- expt 1) d0 d*)))])) (define (format-flonum-no-expt/neg expt d*) (cond [(= expt 0) d*] [else (cons #\0 (format-flonum-no-expt/neg (+ expt 1) d*))])) (define (sign pos? ls) (if pos? (list->string ls) (list->string (cons #\- ls)))) (let ([d0 (car digits)] [d* (cdr digits)]) (cond [(null? d*) (if (char=? d0 #\0) (if pos? "0.0" "-0.0") (if (= expt 1) (if pos? (string d0 #\. #\0) (string #\- d0 #\. #\0)) (if (= expt 0) (if pos? (string #\0 #\. d0) (string #\- #\0 #\. d0)) (string-append (if pos? "" "-") (string d0) "e" (fixnum->string (- expt 1))))))] [(and (null? d*) (char=? d0 #\0)) (if pos? "0.0" "-0.0")] [(<= 1 expt 9) (sign pos? (format-flonum-no-expt expt d0 d*))] [(<= -3 expt 0) (sign pos? (cons* #\0 #\. (format-flonum-no-expt/neg expt digits)))] [else (string-append (if pos? "" "-") (string d0) "." (list->string d*) "e" (fixnum->string (- expt 1)))]))))
false
52e210f5b2b558eb259f9a71df30370bedb3c861
7666204be35fcbc664e29fd0742a18841a7b601d
/code/3-17.scm
9a22d176bd85d8f84444d90e55cfbf5cb3a6d1ef
[]
no_license
cosail/sicp
b8a78932e40bd1a54415e50312e911d558f893eb
3ff79fd94eda81c315a1cee0165cec3c4dbcc43c
refs/heads/master
2021-01-18T04:47:30.692237
2014-01-06T13:32:54
2014-01-06T13:32:54
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
788
scm
3-17.scm
(load "3-set.scm") (define (count-pairs x) (define s (make-new-set)) (define (count t) ;(display "t = ") (display t) (display ", s = ") (display s) (newline) (cond ((not (pair? t)) 0) ((in-set? t s) 0) (else (set! s (adjoint t s)) (+ 1 (count (car t)) (count (cdr t)))))) (count x) (length s)) (define z1 (cons 'a 'b)) (define z2 (cons z1 z1)) (define z3 '(a b c)) (define z4 (cons 'a z2)) (define z7 (cons z2 z2)) (display (count-pairs z3)) (newline) (display (count-pairs z4)) (newline) (display (count-pairs z7)) (newline) (define c (list 'c)) (define b (cons 'b c)) (define a (cons 'a b)) (set-cdr! c a) (display (count-pairs a)) (newline)
false
c426da65a6a69429d5809074ec8de570554ffe7a
434a6f6b2e788eae6f6609d02262f9c9819773a7
/day11/program-a.scm
d8a0fbcbef27685d4c50abbc3d7edd0160350bce
[]
no_license
jakeleporte/advent-of-code-2020
978fc575d580c63386c53bb40fc14f24d5137be7
649292bf17feaccf572e02d4dad711d2c46d66cb
refs/heads/main
2023-02-07T22:29:08.479708
2021-01-03T01:16:22
2021-01-03T01:16:22
318,069,993
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,495
scm
program-a.scm
#!/usr/bin/env guile !# (use-modules (ice-9 rdelim) (ice-9 arrays)) (define (read-grid) "Read in an array of characters representing an initial seat arrangement" (let loop ((seats '()) (line (read-line))) (if (eof-object? line) (list->array 2 (reverse seats)) (loop (cons (string->list line) seats) (read-line))))) (define (count-adjacent-filled seats x y) (define adjacent '((-1 . -1) (-1 . 0) (-1 . 1) (0 . -1) (0 . 1) (1 . -1) (1 . 0) (1 . 1))) (define count 0) (for-each (lambda (coor) (when (and (array-in-bounds? seats (+ x (car coor)) (+ y (cdr coor))) (char=? (array-ref seats (+ x (car coor)) (+ y (cdr coor))) #\#)) (set! count (1+ count)))) adjacent) count) (define (iterate seats) (define next-seats (array-copy seats)) (array-index-map! next-seats (lambda (x y) (cond ((and (char=? (array-ref seats x y) #\L) (= (count-adjacent-filled seats x y) 0)) #\#) ((and (char=? (array-ref seats x y) #\#) (> (count-adjacent-filled seats x y) 3)) #\L) (else (array-ref seats x y))))) next-seats) (define (count-filled seats) (define count 0) (array-for-each (lambda (e) (when (char=? e #\#) (set! count (1+ count)))) seats) count) (define (main) (define first-seats (read-grid)) (let loop ((seats first-seats) (next (iterate first-seats))) (if (array-equal? seats next) (begin (display (count-filled seats)) (newline)) (loop next (iterate next))))) (main)
false
74e279f693bf3b7d0d7ca4ebb9f3f7c4ff2357e6
23122d4bae8acdc0c719aa678c47cd346335c02a
/pe/129.scm
6f63bf0ec872edee2d49f864057824a6b6e7a863
[]
no_license
Arctice/advent-of-code
9076ea5d2e455d873da68726b047b64ffe11c34c
2a2721e081204d4fd622c2e6d8bf1778dcedab3e
refs/heads/master
2023-05-24T23:18:02.363340
2023-05-04T09:04:01
2023-05-04T09:06:24
225,228,308
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,133
scm
129.scm
#!chezscheme (import (scheme) (pe)) ;; A number consisting entirely of ones is called a repunit. We shall define ;; R(k) to be a repunit of length k; for example, R(6) = 111111. ;; Given that n is a positive integer and GCD(n, 10) = 1, it can be shown ;; that there always exists a value, k, for which R(k) is divisible by n, and ;; let A(n) be the least such value of k; for example, A(7) = 6 and A(41) = ;; 5. ;; The least value of n for which A(n) first exceeds ten is 17. ;; Find the least value of n for which A(n) first exceeds one-million. (define (A n) (let ([l (mod n 10)]) (let next ([d 0] [sum n]) (if (zero? sum) d (let* ([first (mod sum 10)] [rotate (let next ([r 0]) (if (= 1 (mod (+ first (* l r)) 10)) r (next (+ r 1))))]) (next (+ d 1) (div (+ sum (* rotate n)) 10))))))) (define (problem-129) (find (λ (n) (if (or (even? n) (zero? (mod n 5))) #f (< 1000000 (A n)))) (map (λ (n) (+ n 1000000)) (iota 1000)))) (define answer-129 '82cd979a2b79600137aea54fa0bd944b)
false
cd86be0ce81782f56450a2fafa9a6df3bd6fd023
a8216d80b80e4cb429086f0f9ac62f91e09498d3
/lib/srfi/165.scm
00b3b0bc1ad33280f3b7628e7de3333a3928b9fc
[ "BSD-3-Clause" ]
permissive
ashinn/chibi-scheme
3e03ee86c0af611f081a38edb12902e4245fb102
67fdb283b667c8f340a5dc7259eaf44825bc90bc
refs/heads/master
2023-08-24T11:16:42.175821
2023-06-20T13:19:19
2023-06-20T13:19:19
32,322,244
1,290
223
NOASSERTION
2023-08-29T11:54:14
2015-03-16T12:05:57
Scheme
UTF-8
Scheme
false
false
9,673
scm
165.scm
;; Copyright (C) Marc Nieper-Wißkirchen (2019). All Rights Reserved. ;; Permission is hereby granted, free of charge, to any person ;; obtaining a copy of this software and associated documentation ;; files (the "Software"), to deal in the Software without ;; restriction, including without limitation the rights to use, copy, ;; modify, merge, publish, distribute, sublicense, and/or sell copies ;; of the Software, and to permit persons to whom the Software is ;; furnished to do so, subject to the following conditions: ;; The above copyright notice and this permission notice (including ;; the next paragraph) shall be included in all copies or substantial ;; portions of the Software. ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS ;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ;; SOFTWARE. (define-record-type Computation-Environment-Variable (make-environment-variable name default immutable? id) environment-variable? (name environment-variable-name) (default environment-variable-default) (immutable? environment-variable-immutable?) (id environment-variable-id)) (define make-computation-environment-variable (let ((count 0)) (lambda (name default immutable?) (set! count (+ count 1)) (make-environment-variable name default immutable? (- count))))) (define (predefined? var) (not (negative? (environment-variable-id var)))) (define variable-comparator (make-comparator environment-variable? eq? (lambda (x y) (< (environment-variable-id x) (environment-variable-id y))) (lambda (x . y) (environment-variable-id x)))) (define default-computation (make-computation-environment-variable 'default-computation #f #f)) (define (environment-global env) (vector-ref env 0)) (define (environment-local env) (vector-ref env 1)) (define (environment-set-global! env global) (vector-set! env 0 global)) (define (environment-set-local! env local) (vector-set! env 1 local)) (define (environment-cell-set! env var box) (vector-set! env (+ 2 (environment-variable-id var)) box)) (define (environment-cell env var) (vector-ref env (+ 2 (environment-variable-id var)))) (define-syntax define-computation-type (syntax-rules () ((define-computation-type make-environment run var ...) (%define-computation-type make-environment run (var ...) 0 ())))) (define-syntax %define-computation-type (syntax-rules () ((_ make-environment run () n ((var default e immutable i) ...)) (begin (define-values (e ...) (values default ...)) (define var (make-environment-variable 'var e immutable i)) ... (define (make-environment) (let ((env (make-vector (+ n 2)))) (environment-set-global! env (hash-table variable-comparator)) (environment-set-local! env (mapping variable-comparator)) (vector-set! env (+ i 2) (box e)) ... env)) (define (run computation) (execute computation (make-environment))))) ((_ make-environment run ((v d) . v*) n (p ...)) (%define-computation-type make-environment run v* (+ n 1) (p ... (v d e #f n)))) ((_ make-environment run ((v d "immutable") . v*) n (p ...)) (%define-computation-type make-environment run v* (+ n 1) (p ... (v d e #t n)))) ((_ make-environment run (v . v*) n (p ...)) (%define-computation-type make-environment run v* (+ n 1) (p ... (v #f e #f n)))))) (define-computation-type make-computation-environment computation-run) (define (computation-environment-ref env var) (if (predefined? var) (unbox (environment-cell env var)) (mapping-ref (environment-local env) var (lambda () (hash-table-ref/default (environment-global env) var (environment-variable-default var))) unbox))) (define (computation-environment-update env . arg*) (let ((new-env (vector-copy env))) (let loop ((arg* arg*) (local (environment-local env))) (if (null? arg*) (begin (environment-set-local! new-env local) new-env) (let ((var (car arg*)) (val (cadr arg*))) (if (predefined? var) (begin (environment-cell-set! new-env var (box val)) (loop (cddr arg*) local)) (loop (cddr arg*) (mapping-set local var (box val))))))))) (define (computation-environment-update! env var val) (if (predefined? var) (set-box! (environment-cell env var) val) (mapping-ref (environment-local env) var (lambda () (hash-table-set! (environment-global env) var val)) (lambda (cell) (set-box! cell val))))) (define (computation-environment-copy env) (let ((global (hash-table-copy (environment-global env) #t))) (mapping-for-each (lambda (var cell) (hash-table-set! global var (unbox cell))) (environment-local env)) (let ((new-env (make-vector (vector-length env)))) (environment-set-global! new-env global) (environment-set-local! new-env (mapping variable-comparator)) (do ((i (- (vector-length env) 1) (- i 1))) ((< i 2) new-env) (vector-set! new-env i (box (unbox (vector-ref env i)))))))) (define (execute computation env) (let ((coerce (if (procedure? computation) values (or (computation-environment-ref env default-computation) (error "not a computation" computation))))) ((coerce computation) env))) (define (make-computation proc) (lambda (env) (proc (lambda (c) (execute c env))))) (define (computation-pure . args) (make-computation (lambda (compute) (apply values args)))) (define (computation-each a . a*) (computation-each-in-list (cons a a*))) (define (computation-each-in-list a*) (make-computation (lambda (compute) (let loop ((a (car a*)) (a* (cdr a*))) (if (null? a*) (compute a) (begin (compute a) (loop (car a*) (cdr a*)))))))) (define (computation-bind a . f*) (make-computation (lambda (compute) (let loop ((a a) (f* f*)) (if (null? f*) (compute a) (loop (call-with-values (lambda () (compute a)) (car f*)) (cdr f*))))))) (define (computation-ask) (lambda (env) env)) (define (computation-local updater computation) (lambda (env) (computation (updater env)))) (define-syntax computation-fn (syntax-rules () ((_ (clause ...) expr ... computation) (%fn (clause ...) () expr ... computation)))) (define-syntax %fn (syntax-rules () ((_ () ((id var tmp) ...) expr ... computation) (let ((tmp var) ...) (computation-bind (computation-ask) (lambda (env) (let ((id (computation-environment-ref env tmp)) ...) expr ... computation))))) ((_ ((id var) . rest) (p ...) expr ... computation) (%fn rest (p ... (id var tmp)) expr ... computation)) ((_ (id . rest) (p ...) expr ... computation) (%fn rest (p ... (id id tmp)) expr ... computation)))) (define-syntax computation-with (syntax-rules () ((_ ((var val) ...) a* ... a) (%with ((var val) ...) () () a* ... a)))) (define-syntax %with (syntax-rules () ((_ () ((x u) ...) ((a b) ...)) (let ((u x) ... (b a) ...) (computation-local (lambda (env) (computation-environment-update env u ...) ) (computation-each b ...)))) ((_ ((var val) . rest) (p ...) () a* ...) (%with rest (p ... (var u) (val v)) () a* ...)) ((_ () p* (q ...) a . a*) (%with () p* (q ... (a b)) . a*)))) (define-syntax computation-with! (syntax-rules () ((_ (var val) ...) (%with! (var val) ... ())))) (define-syntax %with! (syntax-rules () ((_ ((var u val v) ...)) (let ((u var) ... (v val) ...) (computation-bind (computation-ask) (lambda (env) (computation-environment-update! env u v) ... (computation-pure (if #f #f)))))) ((_ (var val) r ... (p ...)) (%with! r ... (p ... (var u val v)))))) (define (computation-forked a . a*) (make-computation (lambda (compute) (let loop ((a a) (a* a*)) (if (null? a*) (compute a) (begin (compute (computation-local (lambda (env) (computation-environment-copy env)) a)) (loop (car a*) (cdr a*)))))))) (define (computation-bind/forked computation . proc*) (apply computation-bind (computation-local computation-environment-copy computation) proc*)) (define (computation-sequence fmt*) (fold-right (lambda (fmt res) (computation-bind res (lambda (vals) (computation-bind fmt (lambda (val) (computation-pure (cons val vals))))))) (computation-pure '()) fmt*))
true
9c5253300c5d385895aca88dcd943a123f0dbf65
42814fb3168a44672c8d69dbb56ac2e8898f042e
/support.ss
fb05c9418d87171da2fc1030fd83aac703c3a498
[]
no_license
dyoo/gui-world
520096c3e66b904a9b361fe852be3c5e2ab35e88
41e52a1c4686cc6ee4014bf7ded2fcbec337f6eb
refs/heads/master
2016-09-06T14:54:13.316419
2009-04-02T19:10:18
2009-04-02T19:10:18
159,708
1
0
null
null
null
null
UTF-8
Scheme
false
false
480
ss
support.ss
#lang scheme/base (require "private/define-graph-function.ss" lang/prim lang/posn (prefix-in world: htdp/world)) (provide (all-from-out "private/define-graph-function.ss") place-image/posn) ;; Auxillary support definitions. (define-primitive place-image/posn (lambda (an-image a-posn a-scene) (world:place-image an-image (posn-x a-posn) (posn-y a-posn) a-scene)))
false
4423f21f6e3f7ba7845d30fc7c5467f650dfdd5c
1b771524ff0a6fb71a8f1af8c7555e528a004b5e
/ex368.scm
ee493d440e1857c31d690a9faaaef940809f88c6
[]
no_license
yujiorama/sicp
6872f3e7ec4cf18ae62bb41f169dae50a2550972
d106005648b2710469067def5fefd44dae53ad58
refs/heads/master
2020-05-31T00:36:06.294314
2011-05-04T14:35:52
2011-05-04T14:35:52
315,072
0
0
null
null
null
null
UTF-8
Scheme
false
false
973
scm
ex368.scm
(define (pairs3 s t) (interleave (stream-map (lambda (x) (list (stream-car s) x)) t) (pairs3 (stream-cdr s) (stream-cdr t)))) この定義が評価されると起こることを考える。 s と t には integers (1 2 3 ...)が与えられる。 smap でストリームが生成される。 (1 1) (1 2) (1 3) (1 4) ... pairs で (2 3 4 ...) なストリームが渡される smap でストリームが生成される (2 2) (2 3) (2 4) ... interleave されるたびに pairs が呼ばれるからそのたびに n+1 の smap が発生していく。 まさに 1 行づつ sn t1..n を生成してるように見えるんだけど。 実行してみよう。 駄目だ。無限ループった。 理由は ... 元の pairs の定義だと pairs の評価は cons-stream の cdr になっ ていたため遅延評価されるけど、上記の定義だと遅延評価にならないから無限 ループになる、ということで終わり。
false
17a59c55ad81c41d9717f53b375c2031a112901b
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/runtime/constrained-execution/pre-prepare-method-attribute.sls
f0cbaac6aae3d7dc4708d3a95df0681e8d910994
[]
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
644
sls
pre-prepare-method-attribute.sls
(library (system runtime constrained-execution pre-prepare-method-attribute) (export new is? pre-prepare-method-attribute?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute a ...))))) (define (is? a) (clr-is System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute a)) (define (pre-prepare-method-attribute? a) (clr-is System.Runtime.ConstrainedExecution.PrePrepareMethodAttribute a)))
true
be78a2473456a055e99edab5349a1ad24971c4c5
bebaa8295104ecb86fcc5becf34bfa92dd8b46fa
/homework/templates/hw2.scm
d3fd83cff5061474c8cb33f3e8689d32e3858993
[]
no_license
labria/cs61a
65fa1570c886bd0394d66ac4f613577b8be1a64c
40df0351622a1afaae0da124ccf65b067e4ef66b
refs/heads/master
2020-04-03T01:41:33.372301
2018-10-24T12:07:19
2018-10-24T12:07:19
154,937,447
7
2
null
null
null
null
UTF-8
Scheme
false
false
3,137
scm
hw2.scm
; Exercise 1 - Define substitute (define (substitute sent old-word new-word) ; Your code here (error "Not yet implemented") ) ; Exercise 2 - Try out the expressions! (lambda (x) (+ x 3)) ;-> returns: ((lambda (x) (+ x 3)) 7) ;-> returns: (define (make-adder num) (lambda (x) (+ x num))) ((make-adder 3) 7) ;-> returns: (define plus3 (make-adder 3)) (plus3 7) ;-> returns: (define (square x) (* x x)) (square 5) ;-> returns: (define sq (lambda (x) (* x x))) (sq 5) ;-> returns (define (try f) (f 3 5)) (try +) ;-> returns: (try word) ;-> returns: ; Exercise 3 #| How many arguments g has: Type of value returned by g: |# ; Exercise 4 - Define f1, f2, f3, f4, and f5 ; Exercise 5 - Try out the expressions (define (t f) (lambda (x) (f (f (f x)))) ) #| 1. ((t 1+) 0) returns: 2. ((t (t 1+)) 0) returns: 3. (((t t) 1+) 0) returns: |# ; Exercise 6 - Try out the expressions (define (s x) (+ 1 x)) #| 1. ((t s) 0) returns: 2. ((t (t s)) 0) returns: 3. (((t t) s) 0) returns: |# ; Exercise 7 - Define make-tester (define (make-tester wd) ; Your code here (error "Not yet implemented") ) ; Exercise 8 - SICP exercises ; SICP 1.31a (define (product term a next b) ; Your code here (error "Not yet implemented") ) (define (estimate-pi) ; Your code here (error "Not yet implemented") ) ; SICP 1.32a (define (accumulate combiner null-value term a next b) ; Your code here (error "Not yet implemented") ) #| Write sum in terms of accumulate: Write product in terms of accumulate: |# ; SICP 1.33 (define (filtered-accumulate combiner null-value term a next b pred) ; Your code here (error "Not yet implemented") ) (define (prime? n) (define (loop i) (cond ((= i n) #t) ((= (remainder n i) 0) #f) (else (loop (+ i 1))))) (if (<= n 1) #f (loop 2))) (define (sum-sq-prime a b) ; Your code here (error "Not yet implemented") ) (define (gcd a b) (if (= b 0) a (gcd b (remainder a b)))) (define (rel-prime? x y) (= (gcd x y) 1)) (define (prod-of-some-numbers n) ; Your code here (error "Not yet implemented") ) ; SICP 1.40 - Define cubic (define (cubic a b c) ; Your code here (error "Not yet implemented") ) ; SICP 1.41 - Define double (define (double proc) ; Your code here (error "Not yet implemented") ) ; SICP 1.43 - Define repeated (define (repeated proc n) ; Your code here (error "Not yet implemented") ) ; Exercise 9 - Define every (define (every proc sent) ; Your code here (error "Not yet implemented") ) ; Exercise 10 - Try out the expressions #| (every (lambda (letter) (word letter letter)) 'purple) -> returns: (every (lambda (number) (if (even? number) (word number number) number)) '(781 5 76 909 24)) -> returns: (keep even? '(781 5 76 909 24)) -> returns: (keep (lambda (letter) (member? letter 'aeiou)) 'bookkeeper) -> returns: (keep (lambda (letter) (member? letter 'aeiou)) 'syzygy) -> returns: (keep (lambda (letter) (member? letter 'aeiou)) '(purple syzygy)) -> returns: (keep (lambda (wd) (member? 'e wd)) '(purple syzygy)) -> returns: |#
false
9a77277adca21d4cfc6c21ade1d1dd41cd765096
c39b3eb88dbb1c159577149548d3d42a942fe344
/08-reflection/primitives.scm
ba05c6d49bd098a3ed6a1d4c6411eb3ed03810ad
[]
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
11,796
scm
primitives.scm
(define (make-primitive obj) obj) (define primitive? procedure?) (define (primitive-address obj) obj) (define (defprimitive0 name value) (definitial name (let* ((arity+1 (+ 0 1)) (behavior (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (begin (set! *val* (value)) (set! *pc* (stack-pop))) (signal-exception #t (list "Incorrect arity" name)))))) (description-extend! name `(function ,name)) (make-primitive behavior)))) (define (defprimitive1 name value) (definitial name (let* ((arity+1 (+ 1 1)) (behavior (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (let ((arg1 (activation-frame-argument *val* 0))) (set! *val* (value arg1)) (set! *pc* (stack-pop))) (signal-exception #t (list "Incorrect arity" name)))))) (description-extend! name `(function ,name a)) (make-primitive behavior)))) (define (defprimitive2 name value) (definitial name (let* ((arity+1 (+ 2 1)) (behavior (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (let ((arg1 (activation-frame-argument *val* 0)) (arg2 (activation-frame-argument *val* 1))) (set! *val* (value arg1 arg2)) (set! *pc* (stack-pop))) (signal-exception #t (list "Incorrect arity" name)))))) (description-extend! name `(function ,name a b)) (make-primitive behavior)))) (define (defprimitive3 name value) (definitial name (let* ((arity+1 (+ 3 1)) (behavior (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (let ((arg1 (activation-frame-argument *val* 0)) (arg2 (activation-frame-argument *val* 1)) (arg3 (activation-frame-argument *val* 2))) (set! *val* (value arg1 arg2)) (set! *pc* (stack-pop))) (signal-exception #t (list "Incorrect arity" name)))))) (description-extend! name `(function ,name a b c)) (make-primitive behavior)))) (define (defprimitive name value arity) (case arity ((0) (defprimitive0 name value)) ((1) (defprimitive1 name value)) ((2) (defprimitive2 name value)) ((3) (defprimitive3 name value)) (else static-wrong "Unsupported primitive arity" name arity))) (definitial 't #t) (definitial 'f #f) (definitial 'nil '()) (defprimitive 'cons cons 2) (defprimitive 'car car 1) (defprimitive 'cdr cdr 1) (defprimitive 'pair? pair? 1) (defprimitive 'symbol? symbol? 1) (defprimitive 'eq? eq? 2) (defprimitive 'null? null? 1) (defprimitive 'set-car! set-car! 2) (defprimitive 'set-cdr! set-cdr! 2) (defprimitive '= = 2) (defprimitive '< < 2) (defprimitive '<= <= 2) (defprimitive '> > 2) (defprimitive '>= >= 2) (defprimitive '+ + 2) (defprimitive '- - 2) (defprimitive '* * 2) (defprimitive '/ / 2) (defprimitive 'display display 1) (defprimitive 'newline newline 0) (definitial 'list (let* ((arity 0) (arity+1 (+ arity 1))) (make-primitive (lambda () (listify! *val* 0) (set! *val* (activation-frame-argument *val* 0)) (set! *pc* (stack-pop)))))) (definitial 'read (let* ((arity 0) (arity+1 (+ arity 1))) (make-primitive (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (begin (set! *val* (read)) (set! *pc* (stack-pop))) (signal-exception #t (list "Incorrect arity" 'read))))))) (definitial 'eof-object? (let* ((arity 0) (arity+1 (+ arity 1))) (make-primitive (lambda () (set! *val* #f) (set! *pc* (stack-pop)))))) ;(definitial 'the-environment ; (let* ((arity 0) ; (arity+1 (+ arity 1))))) ; (make-primitive ; (lambda () ; (if (= arity+1 (activation-frame-argument-length *val*)) ; (begin (set! *val* (export)) ; (set! *pc* stack-pop) ; (signal-exception #t (list "Incorrect arity" 'the-environment))))))) (definitial 'call/cc (let* ((arity 1) (arity+1 (+ arity 1))) (make-primitive (lambda () (if (= arity+1 (activation-frame-argument-length *val*)) (let ((f (activation-frame-argument *val* 0)) (frame (allocate-activation-frame (+ 1 1)))) (set-activation-frame-argument! frame 0 (make-continuation (save-stack))) (set! *val* frame) (set! *fun* f) ; useful for debug (invoke f #t)) (signal-exception #t (list "Incorrect arity" 'call/cc))))))) (definitial 'apply (let* ((arity 2) (arity+1 (+ arity 1))) (make-primitive (lambda () (if (>= (activation-frame-argument-length *val*) arity+1) (let* ((proc (activation-frame-argument *val* 0)) (last-arg-index (- (activation-frame-argument-length *val*) 2)) (last-arg (activation-frame-argument *val* last-arg-index)) (size (+ last-arg-index (length last-arg))) (frame (allocate-activation-frame size))) (define (copy-args i) (if (< i last-arg-index) (begin (set-activation-frame-argument! frame (- i 1) (activation-frame-argument *val* i)) (copy-args (+ i 1))))) (define (copy-args2 i last-arg) (if (not (null? last-arg)) (begin (set-activation-frame-argument! frame i (car last-arg)) (copy-args2 (+ i 1) (cdr last-arg))))) (copy-args 1) (copy-args2 (- last-arg-index 1) last-arg) (set! *val* frame) (set! *fun* proc) ; useful for debug (println *fun*) (println *val*) (invoke proc #t)) (signal-exception #t (list "Incorrect arity" 'apply))))))) (definitial 'enrich (let* ((arity 1) (arity+1 (+ arity 1))) (make-primitive (lambda () (println "entering enrich") (if (>= (activation-frame-argument-length *val*) arity+1) (let ((env (activation-frame-argument *val* 0))) (listify! *val* 1) (if (reified-environment? env) (let* ((names (activation-frame-argument *val* 1)) (len (- (activation-frame-argument-length *val*) 2)) (r (reified-environment-r env)) (sr (reified-environment-sr env)) (frame (allocate-activation-frame (length names)))) (set-activation-frame-next! frame sr) (define (init-frame i) (if (>= i 0) (begin (set-activation-frame-argument! frame i undefined-value) (init-frame (- i 1))))) (init-frame (- len 1)) (if (not (every? symbol? names)) (signal-exception #f (list "Incorrect variable names" names))) (set! *val* (make-reified-environment frame (checked-r-extend* r names))) (set! *pc* stack-pop)) (signal-exception #t (list "Not an environment" env)))) (signal-exception #t (list "Incorrect arity" 'enrich))))))) (define (checked-r-extend* r n*) (let ((old-r (bury-r r 1))) (define (scan n* i) (cond ((pair? n*) (cons (list (car n*) `(checked-local 0 . ,i)) (scan (cdr n*) (+ i 1)))) ((null? n*) (old-r)))) (scan n* 0))) (definitial 'variable-value (let* ((arity 2) (arity+1 (+ arity 1))) (make-primitive (lambda () (println "entering variable-value") (if (= (activation-frame-argument-length *val*) arity+1) (let ((name (activation-frame-argument *val* 0)) (env (activation-frame-argument *val* 1))) (if (reified-environment? env) (if (symbol? name) (let* ((r (reified-environment-r env)) (sr (reified-environment-sr env)) (kind (or (let ((var (assq name r))) (and (pair? var) (cadr var))) (global-variable? g.current name) (global-variable? g.init name)))) (variable-value-lookup kind sr) (set! *pc* (stack-pop))) (signal-exception #f (list "Not a variable name" name))) (signal-exception #t (list "Not an environment" env)))) (signal-exception #t (list "Incorrect arity" 'variable-value))))))) (definitial 'set-variable-value! (let* ((arity 3) (arity+1 (+ arity 1))) (make-primitive (lambda () (println "entering set-variable-value!") (if (= (activation-frame-argument-length *val*) arity+1) (let ((name (activation-frame-argument *val* 0)) (env (activation-frame-argument *val* 1)) (v (activation-frame-argument *val* 2))) (if (reified-environment? env) (if (symbol? name) (let* ((r (reified-environment-r env)) (sr (reified-environment-sr env)) (kind (or (let ((var (assq name r))) (and (pair? var) (cadr var))) (global-variable? g.current name) (global-variable? g.init name)))) (variable-value-update! kind sr v) (set! *pc* (stack-pop))) (signal-exception #f (list "Not a variable name" name))) (signal-exception #t (list "Not an environment" env)))) (signal-exception #t (list "Incorrect arity" 'set-variable-value!))))))) (definitial 'variable-defined? (let* ((arity 2) (arity+1 (+ arity 1))) (make-primitive (lambda () (println "entering variable-defined?") (if (= (activation-frame-argument-length *val*) arity+1) (let ((name (activation-frame-argument *val* 0)) (env (activation-frame-argument *val* 1))) (if (reified-environment? env) (if (symbol? name) (let ((r (reified-environment-r env)) (sr (reified-environment-sr env))) (set! *val* (if (or (let ((var (assq name r))) (and (pair? var) (cadr var))) (global-variable? g.current name) (global-variable? g.init name)) #t #f)) (set! *pc* (stack-pop))) (signal-exception #f (list "Not a variable name" name))) (signal-exception #t (list "Not an environment" env)))) (signal-exception #t (list "Incorrect arity" 'variable-defined?)))))))
false
a3b1b156327cd5d073fadab86144c11ccde08ceb
1a64a1cff5ce40644dc27c2d951cd0ce6fcb6442
/testing/test-objcall/render_sun.scm
575bd9734b5c03616dbab087812c2b24641aaf00
[]
no_license
skchoe/2007.rviz-objects
bd56135b6d02387e024713a9f4a8a7e46c6e354b
03c7e05e85682d43ab72713bdd811ad1bbb9f6a8
refs/heads/master
2021-01-15T23:01:58.789250
2014-05-26T17:35:32
2014-05-26T17:35:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
407
scm
render_sun.scm
(module render_sun mzscheme (require (lib "mred.ss" "mred") (lib "class.ss") "render.scm") (define render_sun% (class render% () ;Declare interface methods (override render) ;Method implementations (define (render) (display 'TESTTEST)) (super-new))) (send (make-object render_sun%) render) (provide render_sun%))
false
fea67470abccb1a2bdab39041247243f7db5ea81
6488db22a3d849f94d56797297b2469a61ad22bf
/bind/bind.setup
2f0d0d339f278ec3b2ac816d7da6c450123b5ed6
[]
no_license
bazurbat/chicken-eggs
34d8707cecbbd4975a84ed9a0d7addb6e48899da
8e741148d6e0cd67a969513ce2a7fe23241df648
refs/heads/master
2020-05-18T05:06:02.090313
2015-11-18T16:07:12
2015-11-18T16:07:12
22,037,751
0
0
null
null
null
null
UTF-8
Scheme
false
false
1,383
setup
bind.setup
;; bind.setup -*- Scheme -*- (use make) (define version "1.5.2") (make (("c.l.scm" ("c.l") (run (csi -s runsilex.scm)) ) ("chicken-bind" ("chicken-bind.scm" "bind-translator.so") (compile -O3 -d0 -S chicken-bind.scm) ) ("bind-translator.so" ("bind-translator.scm" "c.l.scm" "bind-foreign-transformer.scm") (compile -sS -O3 -d0 bind-translator.scm -JS)) ("bind-translator.import.so" ("bind-translator.so") (compile -s -O3 -d0 bind-translator.import.scm) ) ("bind.so" ("bind.scm" "bind-translator.import.so") (compile -s -O3 -d0 bind.scm -JS)) ("bind.import.so" ("bind.import.scm") (compile -s -O3 -d0 bind.import.scm)) ("cplusplus-object.so" ("cplusplus-object.scm") (compile -s -O3 -S -d0 cplusplus-object.scm -J)) ("cplusplus-object.import.so" ("cplusplus-object.import.scm") (compile -s -O3 -d0 cplusplus-object.import.scm))) '("bind.so" "bind-translator.so" "bind.import.so" "bind-translator.import.so" "cplusplus-object.so" "cplusplus-object.import.so" "chicken-bind") ) (install-extension 'bind '("bind.so" "bind.import.so" "bind-translator.so" "bind-translator.import.so") `((version ,version))) (install-extension 'cplusplus-object '("cplusplus-object.so" "cplusplus-object.import.so") `((version ,version))) (install-program 'chicken-bind "chicken-bind" `((version ,version)))
false
a72eac408f04f6c8b5e812b72bdf7a22cb838317
615d58642873ccc58c44b50f8f12e42c7af3bf73
/membero.scm
b8fe7d7156673f97f5ef56881457fd440b01a337
[]
no_license
Kraks/verifyo
80a0c58a6941eaed774cb1cbbe6616334e54c8a3
1e030b36dbb00111341d36eaeef22019b1420b49
refs/heads/master
2020-05-06T15:17:32.100064
2019-05-22T19:28:39
2019-05-22T19:28:39
180,182,093
6
0
null
null
null
null
UTF-8
Scheme
false
false
360
scm
membero.scm
(define (membero x xs) (fresh (a d) (== `(,a . ,d) xs) (conde [(== a x)] [(membero x d)]))) (define (not-membero x xs) (conde [(== xs '())] [(fresh (a d) (== xs `(,a . ,d)) (=/= a x) (not-membero x d))])) (define (∈ x m) (membero x m)) (define (∉ x m) (not-membero x m))
false
548d4c8b9975240d3ec411840c40e83c2313b0c0
c6478f646c59c8ad7ee57c77523d205d67b7cd56
/src/main/scheme/match-test.scm
3046f18176e953eef31eb5044aef02d6789acc03
[]
no_license
hefeix/common
6a03c7e69e2024bc9ad60c67ca1662c86e337c03
1075697af2f00affd7d59311151a7840babfda2f
refs/heads/master
2016-09-05T11:19:59.365074
2014-10-26T14:42:30
2014-10-26T14:42:30
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,973
scm
match-test.scm
(require gnu.kawa.slib.testing) (require match) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; run tests (test-begin "match") (test-equal "any" (match 'any (_ 'ok)) 'ok) (test-equal "symbol" (match 'ok (x x)) 'ok) (test-equal "number" (match 28 (28 'ok)) 'ok) (test-equal "string" (match "good" ("bad" 'fail) ("good" 'ok)) 'ok) (test-equal "literal symbol" (match 'good ('bad 'fail) ('good 'ok)) 'ok) (test-equal "null" (match '() (() 'ok)) 'ok) (test-equal "pair" (match '(ok) ((x) x)) 'ok) (test-equal "vector" (match '#(ok) (#(x) x)) 'ok) (test-equal "any doubled" (match '(1 2) ((_ _) 'ok)) 'ok) (test-equal "and empty" (match '(o k) ((and) 'ok)) 'ok) (test-equal "and single" (match 'ok ((and x) x)) 'ok) (test-equal "and double" (match 'ok ((and (? symbol?) y) 'ok)) 'ok) (test-equal "or empty" (match '(o k) ((or) 'fail) (else 'ok)) 'ok) (test-equal "or single" (match 'ok ((or x) 'ok)) 'ok) (test-equal "or double" (match 'ok ((or (? symbol? y) y) y)) 'ok) (test-equal "not" (match 28 ((not (a . b)) 'ok)) 'ok) (test-equal "pred" (match 28 ((? number?) 'ok)) 'ok) (test-equal "named pred" (match 28 ((? number? x) (+ x 1))) 29) (test-equal "duplicate symbols pass" (match '(ok . ok) ((x . x) x)) 'ok) (test-equal "duplicate symbols fail" (match '(ok . bad) ((x . x) 'bad) (else 'ok)) 'ok) (test-equal "duplicate symbols samth" (match '(ok . ok) ((x . 'bad) x) (('ok . x) x)) 'ok) (test-equal "ellipses" (match '((a . 1) (b . 2) (c . 3)) (((x . y) ___) (list x y))) '((a b c) (1 2 3))) (test-equal "real ellipses" (match '((a . 1) (b . 2) (c . 3)) (((x . y) ...) (list x y))) '((a b c) (1 2 3))) (test-equal "vector ellipses" (match '#(1 2 3 (a . 1) (b . 2) (c . 3)) (#(a b c (hd . tl) ...) (list a b c hd tl))) '(1 2 3 (a b c) (1 2 3))) (test-equal "pred ellipses" (match '(1 2 3) (((? odd? n) ___) n) (((? number? n) ___) n)) '(1 2 3)) (test-equal "failure continuation" (match '(1 2) ((a . b) (=> next) (if (even? a) 'fail (next))) ((a . b) 'ok)) 'ok) (test-equal "let" (match-let ((x 'ok) (y '(o k))) y) '(o k)) (test-equal "let*" (match-let* ((x 'f) (y 'o) ((z w) (list y x))) (list x y z w)) '(f o o f)) (test-equal "getter car" (match '(1 . 2) (((get! a) . b) (list (a) b))) '(1 2)) (test-equal "getter cdr" (match '(1 . 2) ((a . (get! b)) (list a (b)))) '(1 2)) (test-equal "getter vector" (match '#(1 2 3) (#((get! a) b c) (list (a) b c))) '(1 2 3)) (test-equal "setter car" (let ((x '(1 . 2))) (match x (((set! a) . b) (a 3))) x) '(3 . 2)) (test-equal "setter cdr" (let ((x '(1 . 2))) (match x ((a . (set! b)) (b 3))) x) '(1 . 3)) (test-equal "setter vector" (let ((x '#(1 2 3))) (match x (#(a (set! b) c) (b 0))) x) '#(1 0 3)) #| (begin (define-record point x y) (test-equal "record" (match (make-point 123 456) (($ point x y) (list x y))) '(123 456)) (test-equal "record nested" (match (make-point 123 '(456 789)) (($ point x (y z)) (list x y z))) '(123 456 789)) (test-equal "record getter" (let ((p (make-point 123 456))) (match p (($ point x (get! y)) (list x (y))))) '(123 456)) (test-equal "record setter" (let ((p (make-point 123 456))) (match p (($ point x (set! y)) (y 789))) (list (point-x p) (point-y p))) '(123 789)) ) |# (test-equal "single tail" (match '((a . 1) (b . 2) (c . 3)) (((x . y) ... last) (list x y last))) '((a b) (1 2) (c . 3))) (test-equal "single tail 2" (match '((a . 1) (b . 2) 3) (((x . y) ... last) (list x y last))) '((a b) (1 2) 3)) (test-equal "multiple tail" (match '((a . 1) (b . 2) (c . 3) (d . 4) (e . 5)) (((x . y) ... u v w) (list x y u v w))) '((a b) (1 2) (c . 3) (d . 4) (e . 5))) (test-equal "Riastradh quasiquote" (match '(1 2 3) (`(1 ,b ,c) (list b c))) '(2 3)) ;;---------------------------------------------------------------------- (test-equal (match 2 (1 'one) (2 'two) (3 'three)) 'two) (test-equal (match '(1 2 3) ((1 2 3) 'yes) (else 'no)) 'yes) (test-equal (match '(1 2 3) ((1 x 3) (+ x x))) 4) (test-equal (match '(1 x 3) ((1 'x 3) 'yes)) 'yes) (test-equal (match '(1 1 1 1 1 2 3) ((1 ... x 3) (+ x x))) 4) (test-equal (match '(1 2 2 2 2 2 3) ((1 x ... 3) (apply + x))) 10) (test-equal (match '((1 2) (3 4) (5 6)) (((a b) ...) (list a b))) '((1 3 5) (2 4 6))) (test-equal (match 2 ((or 1 3 5) 'odd) ((or 0 2 4) 'even)) 'even) (test-equal (match '(1 2) ((and (a 2) (1 b)) (list a b))) '(1 2)) (test-equal (match '((1 1 1) (2 2)) ((and ((1 ...) (2 ...)) the-list) the-list)) '((1 1 1) (2 2))) (test-equal (match 2 ((not 1) 'yes) (else 'no)) 'yes) ;; Hooking Into The Matching Process ;; Whenever you reach the limits of what can be expressed with the builtin ;; match operators there are (at least) two ways to hook into the matching ;; process. One of them is the predicate match operator ? which allows ;; embedding an arbitrary predicate function in a pattern. The pattern then ;; only matches when that predicate returns #t: (test-equal (match 0 ((? positive?) 'pos) ((? zero?) 'zero) ((? even?) 'even)) 'pos) ;; For those rare cases where even predicate patterns don't cut it, there's ;; another hook: You can jump back into the matching process from inside a ;; match clause's body. This can be done by means of the (=> identifier) ;; form which goes between a clause's pattern and its body. It binds ;; identifier (which is a symbol of your choice) to a a function of zero ;; arguments which you can call for continuing the matching at the next ;; clause: (test-equal (match '(1 2) ((a b) (=> continue) (if (< a 2) (continue) 'first)) ((a b) 'second)) 'second) ;;---------------------------------------------------------------------- (test-end "match")
false
eaa82a1aa09cc14460a944b23f0a9a36ca7da754
5f7a3f1da8e9eb793b2cbb234563730480df6252
/compat.ypsilon.sls
77caa1ac7177d73572c542f894477d613717cbf2
[]
no_license
higepon/spon
27f73fe7c9daa9cb4cefd4da1fbbac886dac51e9
5a9e071aa2ed3ad8f3c378df06ed1a8bd5409a69
refs/heads/master
2020-04-15T11:55:25.569479
2009-12-27T12:36:34
2009-12-27T12:49:06
128,865
8
0
null
null
null
null
UTF-8
Scheme
false
false
1,329
sls
compat.ypsilon.sls
(library (spon compat) (export implementation-name command file-copy make-directory make-symbolic-link current-directory ) (import (rnrs) (only (core) current-directory destructuring-bind process process-wait) (spon config)) (define (implementation-name) "ypsilon") (define (command cmd . args) (destructuring-bind (pid p-stdin p-stdout p-stderr) (apply process cmd args) (zero? (cond ((quiet?) (process-wait pid #f)) ; nohang = #t ((verbose?) (let ((p-message (transcoded-port p-stdout (native-transcoder))) (p-error (transcoded-port p-stderr (native-transcoder)))) (let loop ((status #f)) (when (verbose?) (let ((message (get-string-all p-message))) (unless (eof-object? message) (put-string (current-output-port) message)))) (let ((error (get-string-all p-error))) (unless (eof-object? error) (put-string (current-error-port) error))) (or status (loop (process-wait pid #t)))))))))) ; nohang = #f ) ;[end]
false
d4b2847716a0f15307436ca795a626980b00754c
408a2b292dcb010e67632e15aa9c6d6d76b9402d
/experiment.scm
47782e68a679737b5ef010a59648d8d1e2bb285e
[]
no_license
shanecelis/mc-2013
f0e4832bca1fcbb1cd1c9c79ffcef7872488d50b
19fc6e42ca47a779ea1565148caa1ffa5febe129
refs/heads/master
2021-01-10T19:01:47.043317
2013-12-17T20:10:26
2013-12-17T20:10:26
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,060
scm
experiment.scm
;; experiment.scm ;; I need to simplify this experiment stuff. (define-module (experiment) #:use-module (oop goops) #:use-module (oop goops save) #:export (<experiment> exp:parameters exp:data exp:results exp:save-modules generate-parameters! run-experiment! analyze-data! export-data process-arguments! copy-parameters! clear-experiment! save-experiment read-experiment export-data <parent-experiment> exp:child-experiments read-experiment-cleanup )) (define-class <experiment> () ;; Get rid of these generic places to put data. It only encourages ;; bad behavior. Just create whatever members you need in the ;; subclasses. (parameters #:accessor exp:parameters #:init-value #f) (data #:accessor exp:data #:init-value #f) (results #:accessor exp:results #:init-value #f) (save-modules #:accessor exp:save-modules #:init-form '((oop goops) (oop goops save) (experiment)))) (define-generic process-arguments!) (define-generic generate-parameters!) (define-generic run-experiment!) (define-generic analyze-data!) (define-generic save-experiment) (define-generic export-data) (define-method (process-arguments! (exp <experiment>) args) (format (current-error-port) "warning: no argument processing available for ~a~%" exp) #f) (define-method (generate-parameters! (exp <experiment>)) #f) (define-method (run-experiment! (exp <experiment>)) #f) (define-method (analyze-data! (exp <experiment>)) #f) (define-method (save-experiment (exp <experiment>) filename) (call-with-output-file filename (lambda (port) (save-objects (acons 'experiment exp '()) port '() (exp:save-modules exp))))) (define-method (read-experiment-cleanup (exp <experiment>)) #f) (define-method (read-experiment filename) (let* ((objects (load-objects filename)) (exp (assq-ref objects 'experiment))) ;(read-experiment-cleanup exp) exp)) (define-method (copy-parameters! (dest <experiment>) (src <experiment>)) (set! (exp:parameters dest) (exp:parameters src))) (define-method (clear-experiment! (exp <experiment>)) (set! (exp:parameters exp) #f) (set! (exp:data exp) #f) (set! (exp:results exp) #f)) ;; Let's make it so we can have a hierarchy of experiments. (define-class <parent-experiment> (<experiment>) (child-experiments #:accessor exp:child-experiments #:init-keyword #:child-experiments #:init-form '()) (aggregate-proc #:accessor exp:aggregate-proc #:init-keyword #:aggregate-proc #:init-value #f) ) (define-method (trial-count (exp <parent-experiment>)) (length (exp:child-experiments exp))) (define-method (generate-parameters! (exp <parent-experiment>)) (for-each generate-parameters! (exp:child-experiments exp)) (next-method)) (define-method (run-experiment! (exp <parent-experiment>)) (for-each run-experiment! (exp:child-experiments exp)) (next-method)) (define-method (analyze-data! (exp <parent-experiment>)) (for-each analyze-data! (exp:child-experiments exp)) (next-method) (if (exp:aggregate-proc exp) ((exp:aggregate-proc exp) (exp:child-experiments exp)))) (define-method (clear-experiment! (exp <parent-experiment>)) (next-method) (for-each clear-experiment! (exp:child-experiments exp))) (define-method (copy-parameters! (dest <parent-experiment>) (src <parent-experiment>)) (if (= (trial-count dest) (trial-count src)) (for-each copy-parameters! (exp:child-experiments dest) (exp:child-experiments src)) (scm-error 'invalid-trial-counts 'copy-parameters! "Cannot copy parameters from one <parent-experiment> because they are different sizes: dest has ~a trials and src has ~a trials." (list (trial-count dest) (trial-count src)) #f)))
false
da8f271bf58b82ba0de132bb41fe90e497eb4bbe
927764fbf52b0411142b198b618bee7188308297
/lib/srfi/8.scm
488bfe4cc7057a061696125b4414014495b5de08
[ "MIT" ]
permissive
jcubic/lips
49b60b2f9c4e0dc5882d3a69ddf16081f602b074
cab80df6a208f44f7c91d3da450de117d2f68760
refs/heads/master
2023-08-29T12:43:56.372494
2023-05-27T09:55:00
2023-05-27T09:55:00
122,653,051
320
40
NOASSERTION
2023-04-13T21:30:26
2018-02-23T17:39:04
JavaScript
UTF-8
Scheme
false
false
1,381
scm
8.scm
;; Copyright (C) John David Stone (1999). All Rights Reserved. ;; ;; Permission is hereby granted, free of charge, to any person obtaining a copy ;; of this software and associated documentation files (the "Software"), to deal ;; in the Software without restriction, including without limitation the rights ;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ;; copies of the Software, and to permit persons to whom the Software ;; is furnished to do so, subject to the following conditions: ;; ;; The above copyright notice and this permission notice shall be included in ;; all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS ;; IN THE SOFTWARE. ;; ;; source: https://srfi.schemers.org/srfi-8/srfi-8.html (define-syntax receive (syntax-rules () ((receive formals expression body ...) (call-with-values (lambda () expression) (lambda formals body ...)))))
true
f0dd65e228b62c8537e79850ede03113bcd3e28f
ece1c4300b543df96cd22f63f55c09143989549c
/Chapter4/Exercise4.41.scm
768f79c489999acdcacbcc7a288a8f2cf9168bd8
[]
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
3,715
scm
Exercise4.41.scm
; Exercise 4.41: Write an ordinary Scheme program to solve the multiple dwelling puzzle. #lang racket (require swindle/extra) (require sicp) (require (file "/Users/soulomoon/git/SICP/Chapter4/Exercise4.40.scm")) (define (distinct? items) (cond ((null? items) true) ((null? (cdr items)) true) ((member (car items) (cdr items)) false) (else (distinct? (cdr items))))) (define (reduce f argslist) (if (null? argslist) '() (f (car argslist) (reduce f (cdr argslist))))) (define (filter predicate sequence) (cond ((null? sequence) null) ((predicate (car sequence)) (cons (car sequence) (filter predicate (cdr sequence)))) (else (filter predicate (cdr sequence))))) (define (combiner A L) (define r (list)) (if (null? L) (map list A) (begin (for-each (lambda (a) (for-each (lambda (l) (set! r (cons (cons a l) r))) L)) A) r))) (define predict-list '()) (define (multiple-dwelling) (let ((baker (list 1 2 3 4 5)) (cooper (list 1 2 3 4 5)) (fletcher (list 1 2 3 4 5)) (miller (list 1 2 3 4 5)) (smith (list 1 2 3 4 5))) (define (get-baker possible) (car possible)) (define (get-cooper possible) (cadr possible)) (define (get-fletcher possible) (caddr possible)) (define (get-miller possible) (cadddr possible)) (define (get-smith possible) (car (cddddr possible))) (define all-possible (reduce combiner (list baker cooper fletcher miller smith))) (define muterable-pair (list predict-list)) (define (set-append predicate) (set-car! muterable-pair (cons predicate (car muterable-pair)))) (define (filter-manager predict-list init) (if (null? predict-list) init (filter-manager (cdr predict-list) (filter (car predict-list) init)))) (set-append (lambda (possible) (not (= (get-baker possible) 5)))) (set-append (lambda (possible) (not (= (get-cooper possible) 1)))) (set-append (lambda (possible) (not (or (= (get-fletcher possible) 1) (= (get-fletcher possible) 5))))) (set-append (lambda (possible) (> (get-miller possible) (get-cooper possible)))) (set-append (lambda (possible) (not (= (abs (- (get-smith possible) (get-fletcher possible))) 1)))) (set-append (lambda (possible) (not (= (abs (- (get-cooper possible) (get-fletcher possible))) 1)))) (set-append (lambda (possible) (distinct? possible))) (filter-manager (car muterable-pair) all-possible) )) (display (multiple-dwelling)) (collect-garbage) (define (runtime) (current-milliseconds)) (define (report start_time) (- (runtime) start_time)) (define (test-time n) (let ((starttime 0) (result 0)) (define (iter n) (if (< n 0) result (begin (set! starttime (runtime)) (amb-collect (multiple-dwelling)) (set! result (+ result (report starttime))) (iter (- n 1))))) (iter n))) (newline ) (collect-garbage) (display (test-time 200)) (newline) (collect-garbage) (display (test-time2 200)) ; it is actually faster than the nondeterministic version ; Welcome to DrRacket, version 6.7 [3m]. ; Language: racket, with debugging; memory limit: 512 MB. ; {{3 2 4 5 1}} ; 168 ; 479 ; >
false
43d69c8c52a2e33362c5dfd87c2799edc5853ba4
0768e217ef0b48b149e5c9b87f41d772cd9917f1
/sitelib/srfi/%3a8.scm
5ec6a453c4386dda77948449cd7d0e21cc92b83c
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
fujita-y/ypsilon
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
62e73643a4fe87458ae100e170bf4721d7a6dd16
refs/heads/master
2023-09-05T00:06:06.525714
2023-01-25T03:56:13
2023-01-25T04:02:59
41,003,666
45
7
BSD-2-Clause
2022-06-25T05:44:49
2015-08-19T00:05:35
Scheme
UTF-8
Scheme
false
false
74
scm
%3a8.scm
#!nobacktrace (library (srfi :8) (export receive) (import (srfi srfi-8)))
false
9fd7940a3e540cf0685c9e5148310b1cb137a9e1
5a05fab297275b592ccd554d3f086bf1ccf7956d
/back/sandbox/schemeMacro/let-syntax1.scm
a3c04512dda627989bf40bca72a6035e4504c1ea
[]
no_license
mkiken/x-scala
643af77b7f9f31a32631007d56f5f1be796aed3e
daebc81d36d9f8a69393f02c3241a0c20ed0b864
refs/heads/master
2016-09-06T13:21:29.879990
2014-02-26T13:14:04
2014-02-26T13:14:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
266
scm
let-syntax1.scm
(let-syntax ((when (syntax-rules () ((when test stmt1 stmt2 ...) (if test (begin stmt1 stmt2 ...)))))) (let ((if #t)) (when if (set! if 'now)) if))
false
823851287f826dbfdc9deb250f9454e6121255d2
b9eb119317d72a6742dce6db5be8c1f78c7275ad
/racket/queue.rkt
1e03973127033f9ced091e7cb8e501483acbe097
[]
no_license
offby1/doodles
be811b1004b262f69365d645a9ae837d87d7f707
316c4a0dedb8e4fde2da351a8de98a5725367901
refs/heads/master
2023-02-21T05:07:52.295903
2022-05-15T18:08:58
2022-05-15T18:08:58
512,608
2
1
null
2023-02-14T22:19:40
2010-02-11T04:24:52
Scheme
UTF-8
Scheme
false
false
1,028
rkt
queue.rkt
#! /bin/sh #| Hey Emacs, this is -*-scheme-*- code! exec racket -l errortrace --require "$0" --main -- ${1+"$@"} |# #lang racket (require rackunit rackunit/text-ui) (require racket/async-channel) (define *num-to-produce* 10) (define (consume q) (let loop () (let ([datum (async-channel-get q)]) (cond ((eof-object? datum) (printf "Consumer is done~%")) (else (begin (printf " consumed ~a~%" datum) (sleep (random)) (loop))))))) (define (produce q) (let ([data (build-list *num-to-produce* (lambda (_) (random 100)))]) (for ([datum data]) (printf "Produced ~a~%" datum) (async-channel-put q datum)) (async-channel-put q eof) (printf "Producer is done~%"))) (provide main) (define (main . args) (define q (make-async-channel (/ *num-to-produce* 2))) (let ([p (thread (lambda () (produce q)))] [c (thread (lambda () (consume q)))]) (for ([t (list p c)]) (sync t))))
false
daffc17b43c903e7db695c6b4c2c8d0ea3991802
7301b8e6fbd4ac510d5e8cb1a3dfe5be61762107
/ex-2.63.scm
2fe80cb09ae7fdc564408c87bef081b44fe0aca1
[]
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
4,763
scm
ex-2.63.scm
(load "./sec-2.3.3-sets-as-binary-trees.scm") ;;; Exercise 2.63. ;;; ;;; Each of the following two procedures converts a binary tree to a list. (define (tree->list-1 tree) (if (null? tree) '() (append (tree->list-1 (left-branch tree)) (cons (entry tree) (tree->list-1 (right-branch tree)))))) (define (tree->list-2 tree) (define (copy-to-list tree result-list) (if (null? tree) result-list (copy-to-list (left-branch tree) (cons (entry tree) (copy-to-list (right-branch tree) result-list))))) (copy-to-list tree '())) ;;; a. Do the two procedures produce the same result for every tree? ;;; If not, how do the results differ? ; tree->list-1 converts a given binary tree with the following steps: ; ; (1) Flatten the left branch, ; (2) Flatten the right branch, ; (3) Prepend the entry to the flattened right branch, ; (4) Then concatenate (1) and (3). ; ; tree->list-2 converts a given binary tree with the following steps: ; ; (1) Visit each node from right to left, ; (2) Accumulate visited nodes. ; ; Both procedures convert a binary tree with different strategies, but both ; accumulate nodes from right to left. So that both produce the same result ; for every tree. ;;; What lists do the two procedures produce for the trees in figure 2.16? ;;; 7 3 5 ;;; / \ / \ / \ ;;; 3 9 1 7 3 9 ;;; / \ \ / \ / / \ ;;; 1 5 11 5 9 1 7 11 ;;; \ ;;; 11 ;;; ;;; Figure 2.16: Various binary trees that represent the set {1,3,5,7,9,11}. (define figure-2.16-a (make-tree 7 (make-tree 3 (make-tree 1 '() '()) (make-tree 5 '() '())) (make-tree 9 '() (make-tree 11 '() '())))) (define figure-2.16-b (make-tree 3 (make-tree 1 '() '()) (make-tree 7 (make-tree 5 '() '()) (make-tree 9 '() (make-tree 11 '() '()))))) (define figure-2.16-c (make-tree 5 (make-tree 3 (make-tree 1 '() '()) '()) (make-tree 9 (make-tree 7 '() '()) (make-tree 11 '() '())))) (define-syntax check (syntax-rules () [(check expr) (print 'expr " ==> " expr)])) (check figure-2.16-a) ; figure-2.16-a ==> (7 (3 (1 () ()) (5 () ())) (9 () (11 () ()))) (check figure-2.16-b) ; figure-2.16-b ==> (3 (1 () ()) (7 (5 () ()) (9 () (11 () ())))) (check figure-2.16-c) ; figure-2.16-c ==> (5 (3 (1 () ()) ()) (9 (7 () ()) (11 () ()))) (check (tree->list-1 figure-2.16-a)) ; (tree->list-1 figure-2.16-a) ==> (1 3 5 7 9 11) (check (tree->list-1 figure-2.16-b)) ; (tree->list-1 figure-2.16-b) ==> (1 3 5 7 9 11) (check (tree->list-1 figure-2.16-c)) ; (tree->list-1 figure-2.16-c) ==> (1 3 5 7 9 11) (check (tree->list-2 figure-2.16-a)) ; (tree->list-2 figure-2.16-a) ==> (1 3 5 7 9 11) (check (tree->list-2 figure-2.16-b)) ; (tree->list-2 figure-2.16-b) ==> (1 3 5 7 9 11) (check (tree->list-2 figure-2.16-c)) ; (tree->list-2 figure-2.16-c) ==> (1 3 5 7 9 11) ; (define figure-2.17 ; (make-tree 1 '() ; (make-tree 2 '() ; (make-tree 3 '() ; (make-tree 4 '() ; (make-tree 5 '() ; (make-tree 6 '() ; (make-tree 7 '() '())))))))) ; (check (tree->list-1 figure-2.17)) ; (check (tree->list-2 figure-2.17)) ;;; b. Do the two procedures have the same order of growth in the number of ;;; steps required to convert a balanced tree with n elements to a list? If ;;; not, which one grows more slowly? ; No. tree->list-1 is slower than tree->list-2. ; ; tree->list-1 uses APPEND to concatenate flattend branches, and (append list1 ; list2) makes a resulting list by prepending each item in list1 to list2 by ; CONS. So that APPEND is O(n). Suppose that a balanced binary tree with ; N nodes is given to tree->list-1. ; ; * Each node has a left branch, ; * Each i-th depth node has a left branch with N/(2^i) nodes. ; (note that i=1 for the root node) ; * The number of i-th nodes is estimated to 2^(i-1). ; ; So that the number of CONS operations to tree->list-1 is: ; ; sum_{i=1}^{log_2 N} 2^(i-1) * N/(2^i) ; = sum_{i=1}^{log_2 N} N/2 ; = (log_2 N) * N/2 ; ; Therefore, tree->list-1 is O(N log N). ; ; While tree->list-2 uses only CONS each node from right to left. ; So that it is just O(N).
true
843f9a11dfb55c3d2aa27e4fc9d8419f2a2ab6c7
c8e90ea942ed257e3570ad590ad25ef8492b317a
/srclib/irregex-0.8.1/irregex-chicken.scm
d0e4a86611b7f2f8762e8ea17c0a6e53f9d6ccdb
[]
no_license
klutometis/ai-challenge-ants
2fcfc22d73d13f31ad4915c7384a76f955952b18
1fd28424c205ffcf3c5c3ef14a08517e0bdb6a2d
refs/heads/master
2021-01-16T18:20:17.968652
2011-07-12T09:32:25
2011-07-12T09:32:25
2,034,567
0
0
null
null
null
null
UTF-8
Scheme
false
false
728
scm
irregex-chicken.scm
(cond-expand (compiling (declare (export irregex string->irregex sre->irregex string->sre maybe-string->sre irregex? irregex-match-data? irregex-new-matches irregex-reset-matches! irregex-search irregex-search/matches irregex-match irregex-search/chunked irregex-match/chunked make-irregex-chunker irregex-match-substring irregex-match-subchunk irregex-match-start-source irregex-match-start-index irregex-match-end-source irregex-match-end-index irregex-match-num-submatches irregex-fold irregex-replace irregex-replace/all irregex-dfa irregex-dfa/search irregex-dfa/extract irregex-nfa irregex-flags irregex-lengths irregex-names irregex-num-submatches ))))
false
b0e232edb88d3a4747750ed7d1940e973153df5d
b58f908118cbb7f5ce309e2e28d666118370322d
/src/11.scm
8e47ef47addd39df167f61a300c339b3e5e968f5
[ "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
622
scm
11.scm
(load "prelude.scm") ;;; P11 (define (encode-modified ls) (if (null? ls) '() (let f ([ls (cdr ls)] [x (car ls)] [n 1]) (cond [(null? ls) (list (if (= 1 n) x (list n x)))] [(equal? (car ls) x) (f (cdr ls) x (1+ n))] [else (cons (if (= 1 n) x (list n x)) (f (cdr ls) (car ls) 1))])))) (test (encode-modified '()) '()) (test (encode-modified '(a)) '(a)) (test (encode-modified '(a a)) '((2 a))) (test (encode-modified '(a a b)) '((2 a) b)) (test (encode-modified '(a a a a b c c a a d e e e e)) '((4 a) b (2 c) (2 a) d (4 e)))
false
0b3b3957e97a623a18c2e88a17b5e39755d56414
a2c4df92ef1d8877d7476ee40a73f8b3da08cf81
/ch06-4.scm
a8c4fb25435edc23aa5a88e012a106fb3f6cc112
[]
no_license
naoyat/reading-paip
959d0ec42b86bc01fe81dcc3589e3182e92a05d9
739fde75073af36567fcbdf3ee97e221b0f87c8a
refs/heads/master
2020-05-20T04:56:17.375890
2009-04-21T20:01:01
2009-04-21T20:01:01
176,530
1
0
null
null
null
null
UTF-8
Scheme
false
false
10,847
scm
ch06-4.scm
(require "./debug") (use srfi-1) ;optional [=] for (member) (use srfi-13) ;string-titlecase (use math.const) (define fail cl:nil) (define (tree-search states goal? successors combiner) (dbg :search ";; Search: ~a" states) (cond [(null? states) fail] [(goal? (first states)) (first states)] [else (tree-search (combiner (successors (first states)) (rest states)) goal? successors combiner)])) (define (depth-first-search start goal? successors) (tree-search (list start) goal? successors append)) (define (binary-tree x) (list (* 2 x) (+ 1 (* 2 x)))) (define (is value) (cut eqv? <> value)) ;(lambda (x) (eqv? x value))) ;;; (define (prepend x y) (append y x)) (define (breadth-first-search start goal? successors) (tree-search (list start) goal? successors prepend)) ;;; (define (finite-binary-tree n) (lambda (x) (remove (cut > <> n) (binary-tree x)))) ;;; (define (diff num) (lambda (x) (abs (- x num)))) (define (sorter cost-fn) (lambda (new old) (sort (append new old) (lambda (a b) (< (cost-fn a) (cost-fn b))) ))) (define (best-first-search start goal? successors cost-fn) (tree-search (list start) goal? successors (sorter cost-fn))) (define cl:most-positive-fixnum (greatest-fixnum)) ;;; (define (price-is-right price) (lambda (x) (if (> x price) cl:most-positive-fixnum (- price x)))) ;;; (define (beam-search start goal? successors cost-fn beam-width) ;(dbg :beam "(beam-search ~a ... ~d)" start beam-width) (tree-search (list start) goal? successors (lambda (old new) (let1 sorted ((sorter cost-fn) old new) (if (> beam-width (length sorted)) sorted (subseq sorted 0 beam-width)))))) ;(debug :search) ;(depth-first-search 1 (is 12) binary-tree) ;(breadth-first-search 1 (is 12) binary-tree) ;(depth-first-search 1 (is 12) (finite-binary-tree 15)) ;(best-first-search 1 (is 12) binary-tree (diff 12)) ;(best-first-search 1 (is 12) binary-tree (price-is-right 12)) ;(beam-search 1 (is 12) binary-tree (price-is-right 12) 2) ;(beam-search 1 (is 12) binary-tree (diff 12) 2) ;(define-class <city> () (name long lat)) ;;(type list) (define (city name) (assoc name *cities*)) ;; Find the city with this name. (define (city-name city) (first city)) (define (city-long city) (second city)) (define (city-lat city) (third city)) (define *cities* '((Atlanta 84.23 33.45) (Los-Angeles 118.15 34.03) (Boston 71.05 42.21) (Memphis 90.03 35.09) (Chicago 87.37 41.50) (New-York 73.58 40.47) (Denver 105.00 39.45) (Oklahoma-City 97.28 35.26) (Eugene 123.05 44.03) (Pittsburgh 79.57 40.27) (Flagstaff 111.41 35.13) (Quebec 71.11 46.49) (Grand-Jct 108.37 39.05) (Reno 119.49 39.30) (Houston 105.00 34.00) (San-Francisco 122.26 37.47) (Indianapolis 86.10 39.46) (Tampa 82.27 27.57) (Jacksonville 81.40 30.22) (Victoria 123.21 48.25) (Kansas-City 94.35 39.06) (Wilmington 77.57 34.14))) ;; p198 (define (neighbors city) (filter (lambda (c) (and (not (eq? c city)) (< (air-distance c city) 1000.0))) *cities*)) (define (trip start dest) ;; Search for a way from the start to dest. (beam-search start (is dest) neighbors (cut air-distance <> dest) 1)) ;; p201から先取り (define earth-diameter 12765.0) (define (air-distance city1 city2) (let1 d (distance (xyz-coords city1) (xyz-coords city2)) (* earth-diameter (asin (/ d 2))))) (define (xyz-coords city) (let ([psi (deg->radians (city-lat city))] [phi (deg->radians (city-long city))]) (list (* (cos psi) (cos phi)) (* (cos psi) (sin phi)) (sin psi)))) (define (distance point1 point2) (sqrt (apply + (map (lambda (a b) (expt (- a b) 2)) point1 point2)))) (define (deg->radians deg) ; (* (+ (truncate deg) (* (remainder deg 1) 100/60)) pi 1/180)) (receive (frac int) (modf deg) (* (+ int (* frac 100/60)) pi/180))) #| #?=(trip (city 'San-Francisco) (city 'Boston)) #?=(trip (city 'Boston) (city 'San-Francisco)) |# (define-class <path> () ;; print-path ((state :init-keyword :state :init-value #f) (previous :init-keyword :previous :init-value '()) (cost-so-far :init-keyword :cost-so-far :init-value 0) (total-cost :init-keyword :total-cost :init-value 0))) (define path-state (cut slot-ref <> 'state)) (define path-previous (cut slot-ref <> 'previous)) (define path-cost-so-far (cut slot-ref <> 'cost-so-far)) (define path-total-cost (cut slot-ref <> 'total-cost)) (define-method write-object ((path <path>) port) (print-path path port)) (define (trip start dest . args) (let-optionals* args ((beam-width 1)) (beam-search (make <path> :state start) (is dest :key path-state) (path-saver neighbors air-distance (cut air-distance <> dest)) path-total-cost beam-width))) (define (is value . args) (let-keywords* args ((key identity) (test eqv?)) (lambda (path) (test value (key path))))) (define (path-saver successors cost-fn cost-left-fn) (lambda (old-path) (let1 old-state (path-state old-path) (map (lambda (new-state) (let1 old-cost (+ (path-cost-so-far old-path) (cost-fn old-state new-state)) (make <path> :state new-state :previous old-path :cost-so-far old-cost :total-cost (+ old-cost (cost-left-fn new-state)) ))) (successors old-state) )))) (define (print-path path . args) (let-optionals* args ((stream #t)) ;; (depth #f)) ;; (declare (ignore depth)) (format stream "#<Path to ~a cost ~d>" (path-state path) (path-total-cost path)))) (define (show-city-path path . args) (let-optionals* args ((stream #t)) ;;(format stream "#<Path ~d km: ~{~:(~a~)~^ - ~}>" (path-total-cost path) (format stream "#<Path ~d km: ~a>" (path-total-cost path) (string-join (map (compose string-titlecase x->string) (reverse (map-path city-name path))) " - ")) (values))) (define (map-path fn path) (if (null? path) '() (cons (fn (path-state path)) (map-path fn (path-previous path))))) #| (show-city-path (trip (city 'San-Francisco) (city 'Boston) 1) #t) (newline) (show-city-path (trip (city 'Boston) (city 'San-Francisco) 1) #t) (newline) (show-city-path (trip (city 'Boston) (city 'San-Francisco) 3) #t) (newline) |# ;; p204 (define (iter-wide-search start goal? successors cost-fn . args) (let-keywords* args ((width 1) (max 100)) (dbg :search "; Width: ~d" width) (unless (> width max) (or (cl:thru (beam-search start goal? successors cost-fn width)) (iter-wide-search start goal? successors cost-fn :width (+ width 1) :max max))))) ;(debug :search) ;#?=(iter-wide-search 1 (is 12) (finite-binary-tree 15) (diff 12)) ;; p206 (define (graph-search states goal? successors combiner . args) (let-optionals* args ((state= eqv?) (old-states #f)) (dbg :search ";; Search: ~a" states) (cond [(null? states) fail] [(goal? (first states)) (first states)] [else (graph-search (combiner (new-states states successors state= old-states) (rest states)) goal? successors combiner state= (lset-adjoin state= (first states) old-states :test state=))]))) (define (new-states states successors state= old-states) (remove (lambda (state) (or (member state states state=) (member state old-states state=))) (successors (first states)))) (define (next2 x) (list (+ x 1) (+ x 2))) #| #?=(tree-search '(1) (is 6) next2 prepend) #?=(graph-search '(1) (is 6) next2 prepend) |# ;; A* (define (a*-search paths goal? successors cost-fn cost-left-fn . args) (let-optionals* args ((state= eqv?) (old-paths '())) (dbg :search ";; Search: ~a" paths) (cond [(null? paths) fail] [(goal? (path-state (first paths))) (values (first paths) paths)] [else (let* ([path (pop! paths)] [state (path-state path)]) (set! old-paths (insert-path path old-paths)) (dolist (state2 (successors state)) (let* ([cost (+ (path-cost-so-far path) (cost-fn state state2))] [cost2 (cost-left-fn state2)] [path2 (make <path> :state state2 :previous path :cost-so-far cost :total-cost (+ cost cost2))] [old #f]) (cond [(cl:thru (cl:setf old (find-path state2 paths state=))) (when (better-path path2 old) (set! paths (insert-path path2 (delete old paths))))] [(cl:thru (cl:setf old (find-path state2 old-paths state=))) (when (better-path path2 old) (set! paths (insert-path path2 paths)) (set! old-paths (delete old old-paths)))] [else (set! paths (insert-path path2 paths))]))) (a*-search paths goal? successors cost-fn cost-left-fn state= old-paths))]))) (define (find-path state paths state=) #;(format #t "(find-path ~a ~a state=)..\n" state paths) (cl:find state paths :key path-state :test state=)) (define (better-path path1 path2) ; (format #t "(better-path ~a ~a)...\n" path1 path2) (< (path-total-cost path1) (path-total-cost path2))) (define (insert-path path paths) (cl:merge 'list (list path) paths < :key path-total-cost)) (define (path-states path) (if (null? path) '() (cons (path-state path) (path-states (path-previous path))))) #;(path-states (a*-search (list (make <path> :state 1)) (is 6) next2 (lambda (x y) 1) (diff 6))) (define (search-all start goal? successors cost-fn beam-width) (let1 solutions '() (beam-search start (lambda (x) (when (goal? x) (cl:push x solutions)) #f) successors cost-fn beam-width) solutions))
false
0f9a8484d8c97cce72f86c2fd81e8d82a2e13446
165a4ff581651cdad1bc512ec1c82cebc0ac575a
/src/SICP/2/test.scm
551baaa43537255adb8f5925b0dba205b478b763
[]
no_license
haruyama/yami
5028e416a2caa40a0193d46018fe4be81d7820dc
32997caecc18d9d82a28b88fabe5b414a55e0e18
refs/heads/master
2020-12-25T09:47:04.240216
2018-06-16T08:28:41
2018-06-16T08:28:41
898,824
1
1
null
null
null
null
UTF-8
Scheme
false
false
177
scm
test.scm
(define zero (lambda (f) (lambda (x) x))) (define (add-1 n) (lambda (f) (lambda (x) (f ((n f) x))))) (define (add a b) (if (= a 0) b (add (sub-1 a) (add-1 b))))
false
a1762303cdf0ef6a88e2a50a5ab12873fbac2a79
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/bitcoin/Number/test-number.scm
3ade6937e4f6ee1f63d20548ee2adbf03d623504
[]
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
19,433
scm
test-number.scm
(load "test-abstract.scm") (load "number") (define test-number (let () ; object created from data is message passing interface (define (this data) (lambda (m) (cond ((eq? m 'run) (run data)) (else (error "test-number: unknown instance member" m))))) ; (define (run data) (log-message "Number unit test running ...") (check-zero) (check-one) (check-from-bytes) (check-sign) (check-to-bytes) (check-random) (check-add) (check-mul) (check-negate) (check-to-string) (check-compare-to) (check-hash) (check-number-equals) (check-from-integer) (check-to-integer) (check-bit-length)) ; ; helper function (define (signed-random num-bits) (let ((x (number 'random num-bits)) (flip (number 'random 1))) (if (flip 'equal? (number 'one)) (x 'negate) x))) ; ; syntactic sugar (define (check-num-equals lhs rhs message) (check-equals lhs rhs message (number 'equal?))) ; (define (check-zero) (let ((zero (number 'zero)) (x (number 'random 256))) (let ((y (zero 'add x)) (z (x 'add zero))) (check-num-equals x y "check-zero.1") (check-num-equals x z "check-zero.2" )))) ; (define (check-one) (let ((one (number 'one)) (x (number 'random 256))) (let ((y (one 'mul x)) (z (x 'mul one))) (check-num-equals x y "check-one.1" ) (check-num-equals x z "check-one.2" )))) ; (define (check-from-bytes) ; empty byte string (let ((b0 (list->bytes '()))) (let ((x (number 'from-bytes 1 b0))) (check-num-equals x (number 'zero) "check-from-bytes.1")) (let ((x (number 'from-bytes -1 b0))) (check-num-equals x (number 'zero) "check-from-bytes.2")) (let ((x (number 'from-bytes 0 b0))) (check-num-equals x (number 'zero) "check-from-bytes.3"))) ; single #x00 byte (let ((b1 (list->bytes '(#x00)))) (let ((x (number 'from-bytes 1 b1))) (check-num-equals x (number 'zero) "check-from-bytes.6")) (let ((x (number 'from-bytes -1 b1))) (check-num-equals x (number 'zero) "check-from-bytes.7")) (let ((x (number 'from-bytes 0 b1))) (check-num-equals x (number 'zero) "check-from-bytes.8"))) ; two #x00 bytes (let ((b2 (list->bytes '(#x00 #x00)))) (let ((x (number 'from-bytes 1 b2))) (check-num-equals x (number 'zero) "check-from-bytes.11")) (let ((x (number 'from-bytes -1 b2))) (check-num-equals x (number 'zero) "check-from-bytes.12")) (let ((x (number 'from-bytes 0 b2))) (check-num-equals x (number 'zero) "check-from-bytes.13"))) ; single #x01 byte (let ((b3 (list->bytes '(#x01)))) (let ((x (number 'from-bytes 1 b3))) (check-num-equals x (number 'one) "check-from-bytes.16"))) ; x + (-x) = 0 (let ((b4 (get-random-bytes 32))) (let ((x (number 'from-bytes 1 b4)) (y (number 'from-bytes -1 b4))) (let ((z (x 'add y))) (check-num-equals z (number 'zero) "check-from-bytes.18")))) ; multiplying by -1 (let ((b3 (list->bytes '(#x01)))) (let ((b4 (get-random-bytes 32)) (z (number 'from-bytes -1 b3))) (let ((x (number 'from-bytes 1 b4)) (y (number 'from-bytes -1 b4))) (check-num-equals y (x 'mul z) "check-from-bytes.19")))) ; padding with #x00 bytes (let ((b5 (get-random-bytes 28))) (let ((x (number 'from-bytes 1 b5)) (y (number 'from-bytes -1 b5))) (let ((b6 (list->bytes (cons #x00 (cons #x00 (cons #x00 (cons #x00 (bytes->list b5)))))))) (let ((z (number 'from-bytes 1 b6))) (check-num-equals x z "check-from-bytes.20")) (let ((z (number 'from-bytes -1 b6))) (check-num-equals y z "check-from-bytes.21"))))) ; actual replication (let ((b7 (get-random-bytes 32)) (b8 (make-bytes 1 #xff))) ; b8 = 255 (let ((_256 ((number 'from-bytes 1 b8) 'add (number 'one)))) (let ((x (number 'from-bytes 1 b7)) (y (number 'from-bytes -1 b7))) (let loop ((z (number 'zero)) ; z accumulating to x (t (number 'zero)) ; t accumulating to y (i 0)) ; i = 0 (if (< i 32) (let ((b8 (make-bytes 1 (byte-ref b7 i)))) ; b8 =[b7[i]] (loop ((z 'mul _256) 'add (number 'from-bytes 1 b8)) ((t 'mul _256) 'add (number 'from-bytes -1 b8)) (+ i 1))) (begin ; i = 32 (check-num-equals x z "check-from-bytes.22") (check-num-equals y t "check-from-bytes.23"))))))) ; using to-bytes and sign (let ((b9 (get-random-bytes 32))) (let ((x (number 'from-bytes 1 b9)) (y (number 'from-bytes -1 b9))) (check-equals (x 'sign) 1 "check-from-bytes.24") (check-equals (y 'sign)-1 "check-from-bytes.25") (let ((b10 (x 'to-bytes 32)) (b11 (y 'to-bytes 32))) (check-equals b9 b10 "check-from-bytes.26") (check-equals b9 b11 "check-from-bytes.27"))))) ; (define (check-sign) (check-equals ((number 'zero) 'sign) 0 "check-sign.1") (let ((bs (get-random-bytes 32))) (let ((x (number 'from-bytes 1 bs)) (y (number 'from-bytes -1 bs))) (check-equals (x 'sign) 1 "check-sign.2") (check-equals (y 'sign)-1 "check-sign.3")))) ; (define (check-to-bytes) ; zero (let ((bs ((number 'zero) 'to-bytes 0))) (check-equals (bytes-length bs) 0 "check-to-bytes.0") (check-equals bs (make-bytes 0) "check-to-bytes.1")) (let ((bs ((number 'zero) 'to-bytes 32))) (check-equals (bytes-length bs) 32 "check-to-bytes.2") (let loop ((i 0)) (if (< i 32) (begin (check-equals (byte-ref bs i) #x00 "check-to-bytes.3") (loop (+ i 1)))))) ; one (let ((bs ((number 'one) 'to-bytes 1))) (check-equals (bytes-length bs) 1 "check-to-bytes.5") (check-equals bs (make-bytes 1 #x01) "check-to-bytes.6")) (let ((bs (((number 'one) 'negate) 'to-bytes 1))) (check-equals (bytes-length bs) 1 "check-to-bytes.7") (check-equals bs (make-bytes 1 #x01) "check-to-bytes.8")) (let ((bs ((number 'one) 'to-bytes 32))) (check-equals (bytes-length bs) 32 "check-to-bytes.9") (check-equals (byte-ref bs 31) #x01 "check-to-bytes.10") ; big-endian (let loop ((i 0)) (if (< i 31) ; only testing highest 31 bytes which should #x00 (begin (check-equals (byte-ref bs i) #x00 "check-to-bytes.11") (loop (+ i 1)))))) ; tail recursive ; random (let ((x (number 'random 256))) (let ((y (x 'negate))) (let ((bs (x 'to-bytes 32))) (check-num-equals x (number 'from-bytes 1 bs) "check-to-bytes.12") (check-num-equals y (number 'from-bytes -1 bs) "check-to-bytes.13")) (let ((bs (y 'to-bytes 32))) (check-num-equals x (number 'from-bytes 1 bs) "check-to-bytes.14") (check-num-equals y (number 'from-bytes -1 bs) "check-to-bytes.15"))))) ; (define (check-random) ; checking a random generator should be far more ; involved than anything done here (let ((x (number 'random 0))) ; zero bit number, has to be 0 (check-num-equals x (number 'zero) "check-random.1")) (let ((x (number 'random 1))) ; single bit (check-condition (or (x 'equal? (number 'zero)) (x 'equal? (number 'one))) "check-random.2")) (let ((x (number 'random 256))) ; generates non-negative number (check-equals (x 'sign) 1 "check-random.3")) ; this loop seems to be abnormally slow. TODO: investigate (let loop ((i 0) (count 0)) (if (< i 10000) (let ((x (number 'random 256))) (let ((bs (x 'to-bytes 32))) (let ((y (number 'random 5))) ; selecting byte 0 to 31 (let ((index (y 'to-integer))) (let ((test (byte-ref bs index))) (let ((z (number 'random 3))) ; selecting bit 0 to 7 (let ((bit (z 'to-integer))); testing 'bit' of 'test' (if (equal? 1 (logand (ash test (- bit)) #x01)) (loop (+ i 1) (+ count 1)) ; bit is set (loop (+ i 1) count))))))))) ; bit is not set ; i = 10000 (begin (check-condition (> count 4800) "check-random.4") (check-condition (< count 5200) "check-random.5"))))) ; (define (check-add) (let ((x (signed-random 256)) (y (signed-random 256)) (z (signed-random 256))) ; x + 0 = x (check-num-equals (x 'add (number 'zero)) x "check-add.1") ; 0 + x = x (check-num-equals ((number 'zero) 'add x) x "check-add.2") ; x + (-x) = 0 (check-num-equals (x 'add (x 'negate)) (number 'zero) "check-add.3") ; (-x) + x = 0 (check-num-equals ((x 'negate) 'add x) (number 'zero) "check-add.4") ; x + y = y + x (check-num-equals (x 'add y) (y 'add x) "check-add.5") ; (x + y) + z = x + (y + z) (check-num-equals ((x 'add y) 'add z) (x 'add (y 'add z)) "check-add.6") ; actual check of x + y (let ((n (x 'to-integer)) (m (y 'to-integer))) (let ((check (number 'from-integer (+ n m)))) (check-num-equals check (x 'add y) "check-add.7"))))) ; (define (check-mul) (let ((x (signed-random 256)) (y (signed-random 256)) (z (signed-random 256))) ; x * 0 = 0 (check-num-equals (x 'mul (number 'zero)) (number 'zero) "check-mul.1") ; 0 * x = 0 (check-num-equals ((number 'zero) 'mul x) (number 'zero) "check-mul.2") ; x * 1 = x (check-num-equals (x 'mul (number 'one)) x "check-mul.3") ; 1 * x = x (check-num-equals ((number 'one) 'mul x) x "check-mul.4") ; (-x) * (-y) = x * y (check-num-equals ((x 'negate) 'mul (y 'negate)) (x 'mul y) "check-mul.5") ; x * y = y * x (check-num-equals (x 'mul y) (y 'mul x) "check-mul.6") ; (x * y) * z = x * (y * z) (check-num-equals ((x 'mul y) 'mul z) (x 'mul (y 'mul z)) "check-mul.7") ; (x + y) * z = (x * z) + (y * z) (check-num-equals ((x 'add y) 'mul z) ((x 'mul z) 'add (y 'mul z)) "check-mul.8") ; actual check of x * y (let ((n (x 'to-integer)) (m (y 'to-integer))) (let ((check (number 'from-integer (* n m)))) (check-num-equals check (x 'mul y) "check-mul.9"))))) ; (define (check-negate) (let ((x (signed-random 256))) (let ((y (x 'negate))) ; x + (-x) = 0 (check-num-equals (number 'zero) (x 'add y) "check-negate.1") ; acual check (let ((n (x 'to-integer))) (let ((check (number 'from-integer (- n)))) (check-num-equals check y "check-negate.2")))))) ; (define (check-to-string) ; zero (let ((check1 ((number 'zero) 'to-string))) (check-equals check1 "0" "check-to-string.1")) ; one (let ((check1 ((number 'one) 'to-string))) (check-equals check1 "1" "check-to-string.2")) ; minus one (let ((check1 (((number 'one) 'negate) 'to-string))) (check-equals check1 "-1" "check-to-string.3")) ; random positive (let ((x (number 'random 256))) (let ((check1 (x 'to-string)) (check2 (object->string (x 'to-integer)))) (check-equals check1 check2 "check-to-string.4")))) ; (define (check-compare-to) ; from random (let ((x (number 'random 256))) (let ((y (x 'negate))) (check-equals (x 'compare-to (number 'zero)) 1 "check-compare-to.1") (check-equals ((number 'zero) 'compare-to x) -1 "check-compare-to.2") (check-equals (y 'compare-to (number 'zero)) -1 "check-compare-to.3") (check-equals ((number 'zero) 'compare-to y) 1 "check-compare-to.4"))) ; from bytes (let ((bs (get-random-bytes 32))) (let ((x (number 'from-bytes 1 bs)) (y (number 'from-bytes -1 bs))) (check-equals (x 'compare-to (number 'zero)) 1 "check-compare-to.5") (check-equals ((number 'zero) 'compare-to x) -1 "check-compare-to.6") (check-equals (y 'compare-to (number 'zero)) -1 "check-compare-to.7") (check-equals ((number 'zero) 'compare-to y) 1 "check-compare-to.8"))) ; from signed-random (let ((x (signed-random 256)) (y (signed-random 256))) (let ((n (x 'to-integer)) (m (y 'to-integer))) (check-equals (x 'compare-to y) (if (< n m) -1 1) "check-compare-to.9") (check-equals (y 'compare-to x) (if (< n m) 1 -1) "check-compare-to.10") (let ((z (number 'from-integer n))) ; x = z (check-equals (x 'compare-to z) 0 "check-compare-to.11") (check-equals (z 'compare-to x) 0 "check-compare-to.12")))) ; 0 < 1 (check-equals ((number 'zero) 'compare-to (number 'one)) -1 "check-compare-to.13") (check-equals ((number 'one) 'compare-to (number 'zero)) 1 "check-compare-to.14")) ; (define (check-hash) ; 0 and 1 (let ((hash1 ((number 'zero) 'hash)) (hash2 ((number 'one) 'hash))) (check-condition (not (equal? hash1 hash2)) "check-hash.1")) ; x and -x (let ((x (signed-random 256))) (let ((hash1 (x 'hash)) (hash2 ((x 'negate) 'hash))) (check-condition (not (equal? hash1 hash2)) "check-hash.2"))) ; same number (let ((x (signed-random 256))) (let ((n (x 'to-integer))) (let ((y (number 'from-integer n))) (let ((hash1 (x 'hash)) (hash2 (y 'hash))) (check-equals hash1 hash2 "check-hash.3")))))) ; (define (check-number-equals) ; 0 and 1 ; static member (check-condition (not ((number 'equal?) (number 'zero) (number 'one))) "check-number-equals.1") (check-condition (not ((number 'equal?) (number 'one) (number 'zero))) "check-number-equals.2") ; instance member (check-condition (not ((number 'zero) 'equal? (number 'one))) "check-number-equals.3") (check-condition (not ((number 'one) 'equal? (number 'zero))) "check-number-equals.4") ; x and -x (let ((x (signed-random 256))) ; static member (check-condition (not ((number 'equal?) x (x 'negate))) "check-number-equals.5") (check-condition (not ((number 'equal?) (x 'negate) x)) "check-number-equals.6") ; instance member (check-condition (not (x 'equal? (x 'negate))) "check-number-equals.7") (check-condition (not ((x 'negate) 'equal? x)) "check-number-equals.8")) ; same number (let ((x (signed-random 256))) (let ((n (x 'to-integer))) (let ((y (number 'from-integer n))) ; static member (check-condition ((number 'equal?) x y) "check-number-equals.9") (check-condition ((number 'equal?) y x) "check-number-equals.10") (check-condition ((number 'equal?) x x) "check-number-equals.11") ; instance member (check-condition (x 'equal? y) "check-number-equals.12") (check-condition (y 'equal? x) "check-number-equals.13") (check-condition (x 'equal? x) "check-number-equals.14") ; checking check-num-equals (check-num-equals x y "check-number-equals.15") (check-num-equals y x "check-number-equals.16") (check-num-equals x x "check-number-equals.17"))))) ; (define (check-from-integer) ; 0 (let ((x (number 'from-integer 0)) (y (number 'zero))) (check-num-equals x y "check-from-integer.1")) ;1 (let ((x (number 'from-integer 1)) (y (number 'one))) (check-num-equals x y "check-from-integer.2")) ; signed-random (let ((x (signed-random 256))) (let ((y (number 'from-integer (x 'to-integer)))) (check-num-equals x y "check-from-integer.3")))) ; (define (check-to-integer) ; 0 (let ((n ((number 'zero) 'to-integer))) (check-equals n 0 "check-to-integer.1")) ; 1 (let ((n ((number 'one) 'to-integer))) (check-equals n 1 "check-to-integer.2")) ; signed-random (let ((x (signed-random 256))) (let ((n (x 'to-integer))) (let ((m (bytes->integer (x 'to-bytes 32) 32))) (let ((p (if (equal? 1 (x 'sign)) m (- m)))) (check-equals n p "check-to-integer.3")))))) ; (define (check-bit-length) ; 0 (let ((check1 ((number 'zero) 'bit-length))) (check-equals check1 0 "check-bit-length.1")) ; 1 (let ((check1 ((number 'one) 'bit-length))) (check-equals check1 1 "check-bit-length.2")) ; -1 (let ((check1 (((number 'one) 'negate) 'bit-length))) (check-equals check1 1 "check-bit-length.3")) ; (let ((_2 ((number 'one) 'add (number 'one)))) (let ((_4 (_2 'mul _2))) (let ((_16 (_4 'mul _4))) (let ((_256 (_16 'mul _16))) ; 2 (let ((check1 (_2 'bit-length))) (check-equals check1 2 "check-bit-length.4")) ; -2 (let ((check1 ((_2 'negate) 'bit-length))) (check-equals check1 2 "check-bit-length.5")) ; 4 (let ((check1 (_4 'bit-length))) (check-equals check1 3 "check-bit-length.6")) ; -4 (let ((check1 ((_4 'negate) 'bit-length))) (check-equals check1 3 "check-bit-length.7")) ; 16 (let ((check1 (_16 'bit-length))) (check-equals check1 5 "check-bit-length.8")) ; -16 (let ((check1 ((_16 'negate) 'bit-length))) (check-equals check1 5 "check-bit-length.9")) ; 256 (let ((check1 (_256 'bit-length))) (check-equals check1 9 "check-bit-length.10")) ; -256 (let ((check1 ((_256 'negate) 'bit-length))) (check-equals check1 9 "check-bit-length.11")))))) ; +- 2^256 (let ((bs (make-bytes 33 #x00))) (byte-set! bs 0 #x01) ; high-order byte set to #x01 (let ((x (number 'from-bytes 1 bs)) (y (number 'from-bytes -1 bs))) (check-equals (x 'bit-length) 257 "check-bit-length.12") (check-equals (y 'bit-length) 257 "check-bit-length.13")))) ; ; returning no argument constructor (lambda () (test-abstract 'new (this #f))))) ; test object has no meaningful data (define test (test-number)) (test 'run) (exit 0)
false
7544c8c0d216f51d2ffd2fb674f383daf3fdb5a9
784dc416df1855cfc41e9efb69637c19a08dca68
/src/bootstrap/gerbil/gambit/exact__0.scm
5dc5937540df049ed23b201285142c7987bf8450
[ "LGPL-2.1-only", "Apache-2.0", "LGPL-2.1-or-later" ]
permissive
danielsz/gerbil
3597284aa0905b35fe17f105cde04cbb79f1eec1
e20e839e22746175f0473e7414135cec927e10b2
refs/heads/master
2021-01-25T09:44:28.876814
2018-03-26T21:59:32
2018-03-26T21:59:32
123,315,616
0
0
Apache-2.0
2018-02-28T17:02:28
2018-02-28T17:02:28
null
UTF-8
Scheme
false
false
756
scm
exact__0.scm
(declare (block) (standard-bindings) (extended-bindings)) (begin (define gerbil/gambit/exact#exact-integer?__impl (lambda (_obj581_) (let ((_$e583_ (fixnum? _obj581_))) (if _$e583_ _$e583_ (##bignum? _obj581_))))) (define gerbil/gambit/exact#exact-integer-sqrt (lambda (_y571_) (if (if ((lambda (_obj573_) (let ((_$e576_ (fixnum? _obj573_))) (if _$e576_ _$e576_ (##bignum? _obj573_)))) _y571_) (not (negative? _y571_)) '#f) (let ((_s-r579_ (##exact-int.sqrt _y571_))) (values (car _s-r579_) (cdr _s-r579_))) (error '"exact-integer-sqrt: Argument is not a nonnegative exact integer: " _y571_)))))
false
6e330d19d29687edf1e4b4cc552bf701fbdbeb0c
9bc3d1c5f20d268df5b86e6d4af0402d1bf931b4
/schell.sld
7c00bbbc9bf1e8db56f5e304a23e1fe3389e3137
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
leahneukirchen/schell
86f44cd9701cf49ef624fd31eecf901d0d2ac2f1
3ed181bc19ac9f8f53f5392cffbc1f79255e71f2
refs/heads/master
2023-07-19T23:56:17.339682
2021-08-24T11:08:39
2021-08-24T11:08:39
398,331,477
7
0
null
null
null
null
UTF-8
Scheme
false
false
1,390
sld
schell.sld
; -*- scheme -*- (define-library (schell) (import (meowlisp) (libschell)) (export ;; meowlisp * + - ... / < <= = => > >= _ abs and append apply assoc begin boolean? caar cadr car case cdr cdar cddr ceiling close-input-port close-output-port cond cond-expand cons current-error-port current-input-port current-output-port def define-syntax display do dynamic-wind else eq? error even? expt floor fn for-each if integer? length let list map max member min negative? newline not null? number->string number? odd? or output-port? pair? port? positive? procedure? quasiquote quote real? remainder reverse round set! string string->number string-append string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? syntax-rules truncate unless unquote unquote-splicing when while zero? div mod str pp -> ->> macroexpand puts for do do1 with concat const butlast chomp range with-return ;; schell pipe fork exit dup2 dup close waitpid wait/no-hang getpid cd getenv $ run run/str run/lines glob argv *status* *pipestatus* ~ for run/pipe & wait ) )
true
39e49340216aa73c94ca897b010da26a5d2aca59
710e486f87b70e57cc3c2a411d12c30644544b75
/list.sld
c7e3cff7f8955bff9f16013d640dd535202d25d5
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference", "BlueOak-1.0.0" ]
permissive
ar-nelson/schemepunk
6236a3200343257a9ce15a6e3f4bda1dd450c729
249bf057b256bbb9212f60345a84d84615c61893
refs/heads/master
2021-05-18T07:47:36.721609
2021-04-24T17:05:48
2021-04-24T17:05:48
251,185,680
92
7
NOASSERTION
2021-05-12T14:07:38
2020-03-30T02:53:33
Scheme
UTF-8
Scheme
false
false
4,189
sld
list.sld
(define-library (schemepunk list) (export ; (scheme cxr) procedures caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr ; (scheme list) procedures xcons cons* make-list list-tabulate list-copy circular-list iota proper-list? circular-list? dotted-list? not-pair? null-list? list= first second third fourth fifth sixth seventh eighth ninth tenth car+cdr take drop take-right drop-right take! drop-right! split-at split-at! last last-pair length+ concatenate append! concatenate! reverse! append-reverse append-reverse! zip unzip1 unzip2 unzip3 unzip4 unzip5 count fold unfold pair-fold reduce fold-right unfold-right pair-fold-right reduce-right append-map append-map! map! pair-for-each filter-map map-in-order filter partition remove filter! partition! remove! find find-tail any every list-index take-while drop-while take-while! span break span! break! delete delete-duplicates delete! delete-duplicates! alist-cons alist-copy alist-delete alist-delete! lset<= lset= lset-adjoin lset-union lset-union! lset-intersection lset-intersection! lset-difference lset-difference! lset-xor lset-xor! lset-diff+intersection lset-diff+intersection! ; extra procedures snoc map-with-index intercalate list-gen fold-in-pairs fold-right-in-pairs topological-sort) (import (scheme base) (scheme cxr) (schemepunk syntax)) (cond-expand (chicken (import (srfi 1))) ((library (scheme list)) (import (scheme list))) ((library (srfi 1)) (import (srfi 1))) ((library (std srfi 1)) (import (std srfi 1)))) (begin (define (snoc init last) (append init (list last))) (define (map-with-index f xs) (map f xs (list-tabulate (length xs) (λ(x) x)))) (define (intercalate delim xs) (match xs ((x y . zs) `(,x ,delim ,@(intercalate delim (cons y zs)))) (else xs))) (define (list-gen fn) (define (list-gen-loop accum) (fn (λ(next) (list-gen-loop (cons next accum))) accum)) (reverse (list-gen-loop '()))) (define (fold-right-in-pairs fn seed xs) (match xs (() seed) ((x y . rest) (fn x y (fold-right-in-pairs fn seed rest))))) (define (fold-in-pairs fn seed xs) (match xs (() seed) ((x y . rest) (fold-in-pairs fn (fn x y seed) rest)))) ;; Sorts a list of dependencies in dependency order. ;; ;; dependency-list is an alist, in which the car of each element is ;; a dependency, and the cdr of each element is a list of its dependencies, ;; each of which must be the car of another element. The list must contain ;; no dependency cycles. ;; ;; Raises '(dependency-missing _) if a cdr contains a dependency that is not ;; the car of any element. ;; ;; Raises '(dependency-cycle _) if there is a dependency cycle. ;; (define (topological-sort dependency-list) (%topological-sort dependency-list '())) (define (%topological-sort deps so-far) (define (no-deps entry) (every (λ dep (member dep so-far)) (cdr entry))) (define next (find no-deps deps)) (cond (next (%topological-sort (remove (λ x (equal? (car x) (car next))) deps) (cons (car next) so-far))) ((null? deps) (reverse so-far)) (else (for-each (λ dep (unless (assoc dep deps) (raise `(dependency-missing ,dep)))) (append-map cdr deps)) (raise `(dependency-cycle ,deps)))))))
false
a7e516d61e4227e890f7cfa65d58159be28c2891
e75694971a8d65a860e49d099aba868e1b7ec664
/b4.scm
75e713633107da466d9eae4848c0fc90de643997
[]
no_license
telnet23/sicp
d29088e1bdef7ede3cf5805559e0edb3b0ef54fe
a85fa7f17c7485163c9484ed5709d6ec64e87aaa
refs/heads/master
2023-02-20T09:20:38.216645
2019-04-30T20:15:12
2019-04-30T20:15:12
331,790,140
0
0
null
null
null
null
UTF-8
Scheme
false
false
4,157
scm
b4.scm
"problem 1. (a)" (define (product term a next b) (if (> a b) 1 (* (term a) (product term (next a) next b)))) "problem 1. (b)" (define (product-i term a next b) (define (product-i-help term a next b accumulator) (if (> a b) accumulator (product-i-help term (next a) next b (* accumulator (term a))))) (product-i-help term a next b 1)) "problem 1. (c)" (define (wallis-pi n) (* 2 (product-i (lambda (n) (* (/ (* 2 n) (- (* 2 n) 1)) (/ (* 2 n) (+ (* 2 n) 1)))) 1 (lambda (n) (+ n 1)) n))) "problem 2. (a)" (define (accumulate combiner null-value term a next b) (if (> a b) null-value (combiner (term a) (accumulate combiner null-value term (next a) next b)))) (define (acc-sum term a next b) (accumulate + 0 term a next b)) (define (acc-product term a next b) (accumulate * 1 term a next b)) "problem 2. (b)" (define (catalan n) (accumulate * 1 (lambda (k) (/ (+ n k) k)) 2 (lambda (k) (+ k 1)) n)) "problem 2. (c)" (define (leibniz-pi n) (* 4 (accumulate + ; combiner 0 ; null-value (lambda (k) (/ (expt -1 (- k 1)) (- (* 2 k) 1))) ; term 1 ; a (lambda (k) (+ k 1)) ; next n))) ; b "problem 2. (d)" (define (accumulate-tr combiner null-value term a next b) (define (accumulate-tr-help combiner null-value term a next b acc) (if (> a b) acc (accumulate-tr-help combiner null-value term (next a) next b (combiner (term a) acc)))) (accumulate-tr-help combiner null-value term a next b null-value)) "problem 2. (e)" (define (fact n) (accumulate-tr * 1 (lambda (k) k) 1 (lambda (k) (+ k 1)) n)) "problem 2. (f)" (define (e-to-x x n) (accumulate-tr + 1 (lambda (k) (/ (expt x k) (fact k))) 1 (lambda (k) (+ k 1)) n)) "problem 3. (a)" (define (der f h) (lambda (x) (/ (- (f (+ x h)) (f x)) h))) "problem 3. (b)" (define (fun x) (+ (* 3 x x) (* -2 x) 7)) "problem 3. (c)" (define (nth-deriv f n h) (if (= n 0) f (nth-deriv (der f h) (- n 1) h))) "problem 4. (a)" (define (smooth f dx) (lambda (x) (/ (+ (f (- x dx)) (f x) (f (+ x dx))) 3))) "problem 4. (b)" (define (compose f g) (lambda (x) (f (g x)))) (define (repeated f n) (if (= n 0) (lambda (x) x) (compose (repeated f (- n 1)) f))) (define (n-fold-smooth f dx n) (repeated (smooth f dx) n)) "problem 5." (define (max-fg f g) (lambda (x) (if (> (f x) (g x)) (f x) (g x)))) "problem 6." (define (romberg f a b n m) (define (h n) (/ (- b a) (expt 2 n))) (cond ((and (= n 0) (= m 0)) (* (h 1) (+ (f a) (f b)))) ((and (not (= n 0)) (= m 0)) (+ (/ (romberg f a b (- n 1) 0) 2) (* (h n) (accumulate-tr + 0 (lambda (k) (f (+ a (* (h n) (- (* 2 k) 1))))) 1 (lambda (k) (+ k 1)) (expt 2 (- n 1)))))) (else (+ (romberg f a b n (- m 1)) (/ (- (romberg f a b n (- m 1)) (romberg f a b (- n 1) (- m 1))) (- (expt 4 m) 1))))))
false
856e5513e902d107c0079a751f2d1356d94280ea
a7a99f1f9124d23b04558fdac002f9153079b9c0
/sine/polycommon.ss
dd65f1be44be4e659abd267ef439426507b3b621
[]
no_license
stuhlmueller/sine
a451c3803283de220f3475dba4c6c1fcde883822
ce6ec938e8f46c31925f23b557284405c1ba0b11
refs/heads/master
2016-09-06T10:23:19.360983
2012-07-20T21:09:59
2012-07-20T21:10:11
3,517,254
4
0
null
null
null
null
UTF-8
Scheme
false
false
2,563
ss
polycommon.ss
#!r6rs ;; Utilities used by the polynomial graph-building and ;; equation-generating part of cosh. (library (sine polycommon) (export graph:reachable-terminals graph:notify-ancestors-of-connection! score-ref->terminal-node score-ref->root score-ref? make-score-ref list-of-weights plus/symbolic make-task task->thunk task->last-id task->link-weight task->link-label) (import (rnrs) (cosh continuation) (cosh application) (scheme-tools) (scheme-tools object-id) (scheme-tools hash) (scheme-tools mem) (scheme-tools watcher) (scheme-tools graph) (scheme-tools graph callback) (scheme-tools graph utils) (scheme-tools srfi-compat :1) (sine coroutine-interpreter) (sine coroutine-id)) (define (graph:reachable-terminals graph node) (traverse node (lambda (node) (graph:children graph node)) (lambda (node list-of-terminals) (if (terminal-id? node) (cons node list-of-terminals) (apply append list-of-terminals))) (make-watcher) '())) (define (graph:terminals&callbacks graph node last-node) (let ([terminals (graph:reachable-terminals graph node)] [callbacks (graph:ancestor-callbacks graph last-node)]) (values terminals callbacks))) (define (graph:notify-ancestors-of-connection! graph node last-node) (let-values ([(terminals callbacks) (graph:terminals&callbacks graph node last-node)]) (map (lambda (callback) (map (lambda (terminal) (callback terminal)) terminals)) callbacks))) (define (make-score-ref root-node terminal-node) (list 'score-ref root-node terminal-node)) (define (score-ref? obj) (tagged-list? obj 'score-ref)) (define score-ref->root second) (define score-ref->terminal-node third) (define (list-of-weights weight) (cond [(score-ref? weight) (list weight)] [(number? weight) (list weight)] [(and (list? weight) (not (null? weight)) (eq? (car weight) '+)) (cdr weight)] [else (error weight "unknown weight type")])) (define (plus/symbolic w1 w2) `(+ ,@(list-of-weights w1) ,@(list-of-weights w2))) (define (make-task thunk . args) (append (list 'task thunk) args)) (define task->thunk second) (define task->last-id third) (define task->link-weight fourth) (define task->link-label fifth) )
false
d03be17b80272078bbff24cf37b8f4295bc58502
25a487e394b2c8369f295434cf862321c26cd29c
/test/loitsu/lazy.test.sps
3a807fe7a4ff354fbf2e464ac0e87151f305507b
[]
no_license
mytoh/loitsu
b11e1ed9cda72c0a0b0f59070c9636c167d01a2c
d197cade05ae4acbf64c08d1a3dd9be6c42aac58
refs/heads/master
2020-06-08T02:00:50.563515
2013-12-17T10:23:04
2013-12-17T10:23:04
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
525
sps
lazy.test.sps
(import (rnrs) (pieni check) (loitsu lazy)) ;; lcar (define lz (lcons 1 (lcons 2 (lcons 3 '())))) (check (lcar lz) => 1) ;; lcdr (check (lcar (lcdr lz)) => 2) (check (lcar (lcdr (lcdr lz))) => 3) (check (lcdr (lcdr (lcdr lz))) => '()) ;; lrepeat (define lz1 (lrepeat "a")) (check (lcar lz1) => "a") (check (lcar (lcdr lz1)) => "a") (check (lcar (lcdr (lcdr lz1))) => "a") ;; liota (define lz2 (liota 1 2)) (check (lcar lz2) => 1) (check (lcar (lcdr lz2)) => 3) (check (lcar (lcdr (lcdr lz2))) => 5) (check-report)
false
2417314ccc374f41971bb11b1ae1f10abd817728
dfa3c518171b330522388a9faf70e77caf71b0be
/src/srfi/27/chicken/source.scm
e3872ece77da952fdfc2ac08c57e6709e88cce16
[ "BSD-2-Clause" ]
permissive
dharmatech/abstracting
c3ff314917857f92e79200df59b889d7f69ec34b
9dc5d9f45a9de03c6ee379f1928ebb393dfafc52
refs/heads/master
2021-01-19T18:08:22.293608
2009-05-12T02:03:55
2009-05-12T02:03:55
122,992
3
0
null
null
null
null
UTF-8
Scheme
false
false
14
scm
source.scm
(use srfi-27)
false
e47e65694d9af2c9bdd93983bfa81c5f85547fe7
000dbfe5d1df2f18e29a76ea7e2a9556cff5e866
/ext/socket/sagittarius/tls-socket.scm
59a8f345626262d7a7be50f1b4e3d61fc9c2f0d0
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MIT", "BSD-2-Clause" ]
permissive
ktakashi/sagittarius-scheme
0a6d23a9004e8775792ebe27a395366457daba81
285e84f7c48b65d6594ff4fbbe47a1b499c9fec0
refs/heads/master
2023-09-01T23:45:52.702741
2023-08-31T10:36:08
2023-08-31T10:36:08
41,153,733
48
7
NOASSERTION
2022-07-13T18:04:42
2015-08-21T12:07:54
Scheme
UTF-8
Scheme
false
false
3,673
scm
tls-socket.scm
;;; -*- Scheme -*- ;;; ;;; tls-socket.scm - tls-socket library ;;; ;;; Copyright (c) 2018 Takashi Kato <[email protected]> ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; #!nounbound (library (sagittarius tls-socket) (export socket->tls-socket tls-socket? tls-socket-connect! ;; client handshake tls-socket-accept ;; server handshake sort of tls-socket-send tls-socket-send/range tls-socket-recv tls-socket-recv! tls-socket-shutdown tls-socket-close tls-socket-closed? tls-server-socket-handshake tls-socket-peer-certificate tls-socket-peer-certificate-verifier tls-socket-peer-certificate-verifier-set! tls-socket-peer-certificate-required? tls-socket-selected-alpn tls-socket-authorities tls-socket-authorities-set! tls-socket-client-certificate-callback-set! <tls-socket> ;; don't use this cacually tls-socket-raw-socket) (import (core) (core errors) (clos core) (sagittarius) (only (sagittarius socket) nonblocking-socket? make-socket-read-timeout-error socket-node socket-service) (sagittarius dynamic-module)) (load-dynamic-module "sagittarius--tls-socket") (define (tls-socket-raw-socket sock) (slot-ref sock 'raw-socket)) (define (tls-socket-recv! sock bv start len :optional (flags 0)) (let ((r (%tls-socket-recv! sock bv start len flags))) (when (and (< r 0) (not (nonblocking-socket? (slot-ref sock 'raw-socket)))) (let ((raw-sock (slot-ref sock 'raw-socket))) (raise (condition (make-socket-read-timeout-error sock) (make-who-condition 'tls-socket-recv!) (make-message-condition (format "Read timeout! node: ~a, service: ~a" (socket-node raw-sock) (socket-service raw-sock))) (make-irritants-condition r))))) r)) (define (tls-socket-recv sock len :optional (flags 0)) (let ((r (%tls-socket-recv sock len flags))) (unless (or r (nonblocking-socket? (slot-ref sock 'raw-socket))) (let ((raw-sock (slot-ref sock 'raw-socket))) (raise (condition (make-socket-read-timeout-error sock) (make-who-condition 'tls-socket-recv) (make-message-condition (format "Read timeout! node: ~a, service: ~a" (socket-node raw-sock) (socket-service raw-sock))) (make-irritants-condition r))))) r)) )
false
afcd8dde097ba5312604179c5be03e32d3aaab1e
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/security/permissions/isolated-storage-permission-attribute.sls
b44730f4f62b9262c282ddaae635595f2b1f8a16
[]
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,077
sls
isolated-storage-permission-attribute.sls
(library (system security permissions isolated-storage-permission-attribute) (export is? isolated-storage-permission-attribute? usage-allowed-get usage-allowed-set! usage-allowed-update! user-quota-get user-quota-set! user-quota-update!) (import (ironscheme-clr-port)) (define (is? a) (clr-is System.Security.Permissions.IsolatedStoragePermissionAttribute a)) (define (isolated-storage-permission-attribute? a) (clr-is System.Security.Permissions.IsolatedStoragePermissionAttribute a)) (define-field-port usage-allowed-get usage-allowed-set! usage-allowed-update! (property:) System.Security.Permissions.IsolatedStoragePermissionAttribute UsageAllowed System.Security.Permissions.IsolatedStorageContainment) (define-field-port user-quota-get user-quota-set! user-quota-update! (property:) System.Security.Permissions.IsolatedStoragePermissionAttribute UserQuota System.Int64))
false
a091ee1429bc3d34683b650e047cc59aed233492
a6d6b0f9c9a754d58ed7ec03a1a8770c7a5808e7
/7.scm
7f8b3f4cad0a5c089661573fc907b026a52f2ad6
[]
no_license
andreqwert/functional_programming
acea3a0f36dfbf0d0023410187b27ef6d92338b3
0ac415bde27f97bfe3c8d8a34cc6f8abff48af57
refs/heads/master
2020-03-28T02:29:01.391252
2018-12-07T22:45:11
2018-12-07T22:45:11
147,573,403
0
0
null
null
null
null
UTF-8
Scheme
false
false
734
scm
7.scm
; Реализуйте процедуру (find-number a b c), возвращающее наименьшее число в интервале [a, b], ; которое без остатка делится на c, или #f, если такое число не может быть найдено. (define (find-number a b c) ; если остаток от деления _a на _c равен 0, то вывести _а (if (= (remainder a c) 0) a ; если a<b, то cчитаем заново, но с _a бОльшим на 1 (проходим тем самым диапазон от _а до _b) ; иначе возаращаем #f (if (< a b) (find-number (+ a 1) b c) #f))) (find-number 7 9 3) ; 9 (find-number 3 7 9) ; #f
false
599a884538401ad8b31b3fa39ce8fb504e811a53
fcfe8b0171063fb3563d19713e999e36ed051793
/kanren/load-all.ss
d66d1c4872b4b3c12e91dce10eb0add293fd9309
[]
no_license
heyunen/Type-Inference
52a653ed2bb6c671f16b434c4dca71e451637c4e
5310fc010defcec8ac3f95c12da2d78267ceb401
refs/heads/master
2021-01-16T23:19:52.184194
2018-08-13T12:46:05
2018-08-13T12:46:05
61,482,216
1
2
null
null
null
null
UTF-8
Scheme
false
false
458
ss
load-all.ss
; Load everything (for interactive use) ; $Id: load-all.ss,v 4.50 2005/02/12 00:04:18 oleg Exp $ (load "lib/chez-specific.ss") (load "lib/term.scm") (load "lib/kanren.ss") (load "examples/type-inference.scm") (load "examples/typeclasses.scm") (load "examples/zebra.scm") (load "examples/mirror.scm") (load "examples/mirror-equ.scm") (load "examples/deduction.scm") (load "examples/pure-bin-arithm.scm") ;(load "benchmarks/alg-complexity.scm") ; must be last
false
5d7f89dbbbac70a662be45e2ac7d015a23d3a779
16807220b95bf9a559b97ec0de16665ff31823cb
/mission/tests/torpedoes.scm
c7c6a118aaed1ab56cf17539eaed1b36409c6a34
[ "BSD-3-Clause" ]
permissive
cuauv/software
7263df296e01710cb414d340d8807d773c3d8e23
5ad4d52d603f81a7f254f365d9b0fe636d03a260
refs/heads/master
2021-12-22T07:54:02.002091
2021-11-18T01:26:12
2021-11-18T02:37:55
46,245,987
76
34
null
2016-08-03T05:31:00
2015-11-16T02:02:36
C++
UTF-8
Scheme
false
false
2,525
scm
torpedoes.scm
(include "peacock-prelude") (peacock "Torpedoes Peacock Test" (setup (define timeout 300) (define torpedos-pos #(1 0 2)) ; The 4 holes (define tl-pos #(1 -0.4 1.6)) (define tr-pos #(1 0.4 1.6)) (define bl-pos #(1 -0.4 2.4)) (define br-pos #(1 0.4 2.4)) (define hole-radius 0.1) (define torpedo-trigger 'actuator-desires.trigger-01) (vehicle-set! x: #(-1 0 0.4) ) (note "Beginning single-hole torpedo test.") (>>= (after timeout) (lambda (_) (fail "Timed out."))) (>>= (after 5.0) (lambda (_) (>>= (on 'kalman.depth kalman.depth-ref (lambda (val) (< val 0.1))) (lambda (_) (fail "Surfaced, oh no!"))))) (goals win) (entity board x: torpedos-pos r: 1.3 corporeal: #f xattrs: '(("render". "torpedo_board")) ) (entity top-left x: tl-pos r: hole-radius corporeal: #f xattrs: '(("render". "torpedo_cover")) ) (entity top-right x: tr-pos r: hole-radius corporeal: #f ) (entity bottom-left x: bl-pos r: hole-radius corporeal: #f ) (entity bottom-right x: br-pos r: hole-radius corporeal: #f ) (collision vehicle**board vehicle ** board) (collision vehicle**top-left vehicle ** top-left) (define sway_at_hole 0) (>>= (triggered vehicle**board) (lambda (_) (note "Found board.") (on 'kalman.east kalman.east-ref (lambda (val) (and (< val (+ -0.4 0.05)) (> val (- -0.4 0.05)) (< (kalman.depth-ref) (+ 1.6 0.05)) (> (kalman.depth-ref) (- 1.6 0.05)))))) (lambda (_) (note "Found top left hole.") (set! sway_at_hole (kalman.sway-ref)) (on 'kalman.sway kalman.sway-ref (lambda (val) (or (< val (- sway_at_hole 0.25)) (> val (+ sway_at_hole 0.25)))))) (lambda (_) (note "Slid cover.") (on 'kalman.sway kalman.sway-ref (lambda (val) (and (< val (+ sway_at_hole 0.1)) (> val (- sway_at_hole 0.1)))))) (lambda (_) (note "Returned to hole.") (on 'actuator-desires.trigger-01 actuator-desires.trigger-01-ref (lambda (val) (equal? val 1)))) (lambda (_) ((note "Fired torpedo!") (complete win)))) ) (mission module: "torpedoes" task: "SetCourse") (options debug: #f) ) ; vim: set lispwords+=peacock,vehicle,entity,camera,camera-stream,shape,collision :
false
ff6a95df1fdf6b5522fbda2f5dff08d847048e4e
cbe44707d3b7033b471b1796522227d7b009d38d
/scm-libs/scheme/read.sld
f1e67580de18e696cf3154bca6599f16b5de56a2
[]
no_license
mbillingr/sunny-scheme
ebd5faa598ec9e8ebe56349f3ff6a42737513991
a54ee340428b7b070814cc9d4e1801f8e394db5c
refs/heads/master
2023-05-06T18:50:21.200131
2020-10-16T12:20:46
2020-10-16T12:20:46
282,292,876
0
0
null
2020-08-10T13:34:32
2020-07-24T18:44:06
Rust
UTF-8
Scheme
false
false
77
sld
read.sld
(define-library (scheme read) (export read) (import (native read)))
false
cfbfeec5137d6e56d36e9f27fc2a4f118a93d6ae
2bcf33718a53f5a938fd82bd0d484a423ff308d3
/programming/sicp/ch1/ex-1.41.scm
82a2d6591c27a672798e11308c413d295bb608cd
[]
no_license
prurph/teach-yourself-cs
50e598a0c781d79ff294434db0430f7f2c12ff53
4ce98ebab5a905ea1808b8785949ecb52eee0736
refs/heads/main
2023-08-30T06:28:22.247659
2021-10-17T18:27:26
2021-10-17T18:27:26
345,412,092
0
0
null
null
null
null
UTF-8
Scheme
false
false
642
scm
ex-1.41.scm
;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-12.html#%_thm_1.41 (define (double f) (lambda (x) (f (f x)))) (define (inc x) (+ 1 x)) (((double (double double)) inc) 5) ;; Creates a function that applies inc 16 times to its argument, so returns 21 ;; Explanation: ;; (((double (double double)) f) x) ;; -> (((double double) ((double double) f)) x) ;; -> (((double double) (double (double f))) x) ;; -> (((double (double (double (double f))))) x) ;; Applies f 2 * 2 * 2 * 2 = 16 times ;; ;; Alternately, think of doubling (double double), so there are 4 total doubles ;; so 2 * 2 * 2 * 2
false
bb9a10525685dbc7cc8b1b5f28e5fe2eb9cd4352
0768e217ef0b48b149e5c9b87f41d772cd9917f1
/sitelib/srfi/64/source-info.body.scm
684873587045aeb8ff1139bc252fea386a1b3515
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
fujita-y/ypsilon
e45c897436e333cf1a1009e13bfef72c3fb3cbe9
62e73643a4fe87458ae100e170bf4721d7a6dd16
refs/heads/master
2023-09-05T00:06:06.525714
2023-01-25T03:56:13
2023-01-25T04:02:59
41,003,666
45
7
BSD-2-Clause
2022-06-25T05:44:49
2015-08-19T00:05:35
Scheme
UTF-8
Scheme
false
false
3,434
scm
source-info.body.scm
;; Copyright (c) 2015 Taylan Ulrich Bayırlı/Kammer <[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. ;;; In some systems, a macro use like (source-info ...), that resides in a ;;; syntax-rules macro body, first gets inserted into the place where the ;;; syntax-rules macro was used, and then the transformer of 'source-info' is ;;; called with a syntax object that has the source location information of that ;;; position. That works fine when the user calls e.g. (test-assert ...), whose ;;; body contains (source-info ...); the user gets the source location of the ;;; (test-assert ...) call as intended, and not the source location of the real ;;; (source-info ...) call. ;;; In other systems, *first* the (source-info ...) is processed to get its real ;;; position, which is within the body of a syntax-rules macro like test-assert, ;;; so no matter where the user calls (test-assert ...), they get source ;;; location information of where we defined test-assert with the call to ;;; (source-info ...) in its body. That's arguably more correct behavior, ;;; although in this case it makes our job a bit harder; we need to get the ;;; source location from an argument to 'source-info' instead. (define (canonical-syntax form arg) (cond-expand (kawa arg) (guile-2 form) (else #f))) (cond-expand ((or kawa guile-2) (define-syntax source-info (lambda (stx) (syntax-case stx () ((_ <x>) (let* ((stx (canonical-syntax stx (syntax <x>))) (file (syntax-source-file stx)) (line (syntax-source-line stx))) (quasisyntax (cons (unsyntax file) (unsyntax line))))))))) (else (define-syntax source-info (syntax-rules () ((_ <x>) #f))))) (define (syntax-source-file stx) (cond-expand (kawa (syntax-source stx)) (guile-2 (let ((source (syntax-source stx))) (and source (assq-ref source 'filename)))) (else #f))) (define (syntax-source-line stx) (cond-expand (kawa (syntax-line stx)) (guile-2 (let ((source (syntax-source stx))) (and source (assq-ref source 'line)))) (else #f))) (define (set-source-info! runner source-info) (when source-info (test-result-set! runner 'source-file (car source-info)) (test-result-set! runner 'source-line (cdr source-info)))) ;;; source-info.body.scm ends here
true
04b3afb724eb89cdee58e244b96c2e657b1466ed
3ebfde6d7067223e551c20337c1b9a0cea6084c1
/test.scm
e66ef85895e6976ad0c38d6e6155b4625af7ab56
[]
no_license
Hamayama/eenum
9317318b58368961fb4cd16d041d132154d59f0d
4aa9399ee28852e71c32861a13895db8a84d15ec
refs/heads/master
2021-01-21T14:58:32.005174
2019-12-16T04:15:22
2019-12-16T04:20:48
58,815,504
0
0
null
null
null
null
UTF-8
Scheme
false
false
12,050
scm
test.scm
;; ;; Test eenum ;; (add-load-path "." :relative) (use gauche.test) (use math.const) ; for pi (use srfi-13) ; for string-tabulate (use file.util) ; for null-device (test-start "eenum") (use eenum) (test-module 'eenum) (define-syntax expr-test (syntax-rules () ((_ txt ans expr) (test* (format "~a~a: ~s" txt (if (equal? txt "") "" " ") 'expr) ans expr)) ((_ txt ans expr chk) (test* (format "~a~a: ~s" txt (if (equal? txt "") "" " ") 'expr) ans expr chk)))) (define (make-num-str n :optional (s 1)) (string-tabulate (lambda (i) (integer->char (+ #x30 (modulo (+ i s) 10)))) n)) (test-section "number") (expr-test "" "0" (eenum 0)) (expr-test "" "123" (eenum 123)) (expr-test "" "-123" (eenum -123)) (expr-test "" "0.01" (eenum 1/100)) (expr-test "" "123" (eenum " 123 ")) (expr-test "" "123" (eenum "0123")) (expr-test "" "-123" (eenum "-0123")) (expr-test "" "0" (eenum "00")) (test-section "exponent") (expr-test "" "12.3" (eenum "12.3e0")) (expr-test "" "123" (eenum "12.3e1")) (expr-test "" "1230" (eenum "12.3e2")) (expr-test "" "1.23" (eenum "12.3e-1")) (expr-test "" "0.123" (eenum "12.3e-2")) (expr-test "" "0.0123" (eenum "12.3e-3")) (expr-test "" "0" (eenum "0e1")) (expr-test "" "0.0" (eenum "0e-1")) (expr-test "" "1" (eenum "0.01e2")) (expr-test "" "0.0100" (eenum "1.00e-2")) (test-section "width") (expr-test "" " 123" (eenum "123" :w 4)) (expr-test "" "0.0123" (eenum "12.3e-3" :w 5)) (expr-test "" "0.0123" (eenum "12.3e-3" :w 6)) (expr-test "" " 0.0123" (eenum "12.3e-3" :w 7)) (test-section "digits") (expr-test "" "123.0" (eenum "123" :d 1)) (expr-test "" "123.00" (eenum "123" :d 2)) (expr-test "" "0.012" (eenum "12.3e-3" :d 3)) (expr-test "" "0.0123" (eenum "12.3e-3" :d 4)) (expr-test "" "0.01230" (eenum "12.3e-3" :d 5)) (expr-test "" "123" (eenum "123.45" :d 0)) (expr-test "" "120" (eenum "123.45" :d -1)) (expr-test "" "12300" (eenum "12345" :d -2)) (test-section "round-mode 'truncate") (expr-test "" "120" (eenum "123.456" :d -1 :rm 'truncate)) (expr-test "" "123" (eenum "123.456" :d 0 :rm 'truncate)) (expr-test "" "123.4" (eenum "123.456" :d 1 :rm 'truncate)) (expr-test "" "123.45" (eenum "123.456" :d 2 :rm 'truncate)) (expr-test "" "-120" (eenum "-123.456" :d -1 :rm 'truncate)) (expr-test "" "-123" (eenum "-123.456" :d 0 :rm 'truncate)) (expr-test "" "-123.4" (eenum "-123.456" :d 1 :rm 'truncate)) (expr-test "" "-123.45" (eenum "-123.456" :d 2 :rm 'truncate)) (test-section "round-mode 'floor") (expr-test "" "120" (eenum "123.456" :d -1 :rm 'floor)) (expr-test "" "123" (eenum "123.456" :d 0 :rm 'floor)) (expr-test "" "123.4" (eenum "123.456" :d 1 :rm 'floor)) (expr-test "" "123.45" (eenum "123.456" :d 2 :rm 'floor)) (expr-test "" "-130" (eenum "-123.456" :d -1 :rm 'floor)) (expr-test "" "-124" (eenum "-123.456" :d 0 :rm 'floor)) (expr-test "" "-123.5" (eenum "-123.456" :d 1 :rm 'floor)) (expr-test "" "-123.46" (eenum "-123.456" :d 2 :rm 'floor)) (test-section "round-mode 'ceiling") (expr-test "" "130" (eenum "123.456" :d -1 :rm 'ceiling)) (expr-test "" "124" (eenum "123.456" :d 0 :rm 'ceiling)) (expr-test "" "123.5" (eenum "123.456" :d 1 :rm 'ceiling)) (expr-test "" "123.46" (eenum "123.456" :d 2 :rm 'ceiling)) (expr-test "" "-120" (eenum "-123.456" :d -1 :rm 'ceiling)) (expr-test "" "-123" (eenum "-123.456" :d 0 :rm 'ceiling)) (expr-test "" "-123.4" (eenum "-123.456" :d 1 :rm 'ceiling)) (expr-test "" "-123.45" (eenum "-123.456" :d 2 :rm 'ceiling)) (test-section "round-mode 'round") (expr-test "" "120" (eenum "123.456" :d -1 :rm 'round)) (expr-test "" "123" (eenum "123.456" :d 0 :rm 'round)) (expr-test "" "123.5" (eenum "123.456" :d 1 :rm 'round)) (expr-test "" "123.46" (eenum "123.456" :d 2 :rm 'round)) (expr-test "" "-120" (eenum "-123.456" :d -1 :rm 'round)) (expr-test "" "-123" (eenum "-123.456" :d 0 :rm 'round)) (expr-test "" "-123.5" (eenum "-123.456" :d 1 :rm 'round)) (expr-test "" "-123.46" (eenum "-123.456" :d 2 :rm 'round)) (expr-test "" "123.0" (eenum "123.05" :d 1 :rm 'round)) (expr-test "" "123.2" (eenum "123.15" :d 1 :rm 'round)) (expr-test "" "124.0" (eenum "123.95" :d 1 :rm 'round)) (expr-test "" "-123.0" (eenum "-123.05" :d 1 :rm 'round)) (expr-test "" "-123.2" (eenum "-123.15" :d 1 :rm 'round)) (expr-test "" "-124.0" (eenum "-123.95" :d 1 :rm 'round)) (expr-test "" "123.0" (eenum "123.050" :d 1 :rm 'round)) (expr-test "" "123.2" (eenum "123.150" :d 1 :rm 'round)) (expr-test "" "124.0" (eenum "123.950" :d 1 :rm 'round)) (expr-test "" "-123.0" (eenum "-123.050" :d 1 :rm 'round)) (expr-test "" "-123.2" (eenum "-123.150" :d 1 :rm 'round)) (expr-test "" "-124.0" (eenum "-123.950" :d 1 :rm 'round)) (expr-test "" "1000.00" (eenum "999.995" :d 2 :rm 'round)) (expr-test "" "-1000.00" (eenum "-999.995" :d 2 :rm 'round)) (test-section "round-mode 'round2") (expr-test "" "120" (eenum "123.456" :d -1 :rm 'round2)) (expr-test "" "123" (eenum "123.456" :d 0 :rm 'round2)) (expr-test "" "123.5" (eenum "123.456" :d 1 :rm 'round2)) (expr-test "" "123.46" (eenum "123.456" :d 2 :rm 'round2)) (expr-test "" "-120" (eenum "-123.456" :d -1 :rm 'round2)) (expr-test "" "-123" (eenum "-123.456" :d 0 :rm 'round2)) (expr-test "" "-123.5" (eenum "-123.456" :d 1 :rm 'round2)) (expr-test "" "-123.46" (eenum "-123.456" :d 2 :rm 'round2)) (expr-test "" "123.1" (eenum "123.05" :d 1 :rm 'round2)) (expr-test "" "123.2" (eenum "123.15" :d 1 :rm 'round2)) (expr-test "" "124.0" (eenum "123.95" :d 1 :rm 'round2)) (expr-test "" "-123.1" (eenum "-123.05" :d 1 :rm 'round2)) (expr-test "" "-123.2" (eenum "-123.15" :d 1 :rm 'round2)) (expr-test "" "-124.0" (eenum "-123.95" :d 1 :rm 'round2)) (expr-test "" "123.1" (eenum "123.050" :d 1 :rm 'round2)) (expr-test "" "123.2" (eenum "123.150" :d 1 :rm 'round2)) (expr-test "" "124.0" (eenum "123.950" :d 1 :rm 'round2)) (expr-test "" "-123.1" (eenum "-123.050" :d 1 :rm 'round2)) (expr-test "" "-123.2" (eenum "-123.150" :d 1 :rm 'round2)) (expr-test "" "-124.0" (eenum "-123.950" :d 1 :rm 'round2)) (expr-test "" "1000.00" (eenum "999.995" :d 2 :rm 'round2)) (expr-test "" "-1000.00" (eenum "-999.995" :d 2 :rm 'round2)) (test-section "pad-char") (expr-test "" "123" (eenum "123" :w 2 :pc #\#)) (expr-test "" "123" (eenum "123" :w 3 :pc #\#)) (expr-test "" "#123" (eenum "123" :w 4 :pc #\#)) (expr-test "" "##123" (eenum "123" :w 5 :pc #\#)) (expr-test "" "#-123" (eenum "-123" :w 5 :pc #\#)) (expr-test "" "#+123" (eenum "123" :w 5 :pc #\# :ps #t)) (test-section "plus-sign") (expr-test "" "123" (eenum "123" :ps #f)) (expr-test "" "123" (eenum "+123" :ps #f)) (expr-test "" "-123" (eenum "-123" :ps #f)) (expr-test "" "+123" (eenum "123" :ps #t)) (expr-test "" "+123" (eenum "+123" :ps #t)) (expr-test "" "-123" (eenum "-123" :ps #t)) (test-section "sign-align-left") (expr-test "" "00123" (eenum "123" :w 5 :pc #\0 :sal #t)) (expr-test "" "-0123" (eenum "-123" :w 5 :pc #\0 :sal #t)) (expr-test "" "#-123" (eenum "-123" :w 5 :pc #\# :sal #f)) (expr-test "" "+0123" (eenum "123" :w 5 :pc #\0 :sal #t :ps #t)) (expr-test "" "#+123" (eenum "123" :w 5 :pc #\# :sal #f :ps #t)) (test-section "circular-digits") (expr-test "" "0.33333" (eenum 1/3 :cd 5)) (expr-test "" "-0.33333" (eenum -1/3 :cd 5)) (expr-test "" "0.142857142857" (eenum 1/7 :cd 12)) (expr-test "" "0.25" (eenum 1/4 :cd 10000)) (expr-test "" "299999999.999999999" (eenum 299999999999999999/1000000000)) (expr-test "" (test-error <error>) (eenum 1/3 :cd 1000001)) (test-section "exponential-notation") (expr-test "" "1.23e2" (eenum "123" :en #t)) (expr-test "" "1.23456e2" (eenum "123.456" :en #t)) (expr-test "" "1.2346e2" (eenum "123.456" :d 4 :rm 'round2 :en #t)) (expr-test "" "1.0e-2" (eenum 0.01 :d 1 :rm 'round2 :en #t)) (expr-test "" "1.23" (eenum 1.23 :en #t)) (expr-test "" "1.23e0" (eenum 1.23 :en 'always)) (expr-test "" "0" (eenum 0 :en #t)) (expr-test "" "0e0" (eenum 0 :en 'always)) (expr-test "" "-0.0e0" (eenum -0.0 :en 'always)) (test-section "exponential-digits") (expr-test "" "0.0123e4" (eenum "123" :en #t :ed -1)) (expr-test "" "0.123e3" (eenum "123" :en #t :ed 0)) (expr-test "" "1.23e2" (eenum "123" :en #t :ed 1)) (expr-test "" "12.3e1" (eenum "123" :en #t :ed 2)) (expr-test "" "0.10e4" (eenum 999.999 :d 2 :rm 'round2 :en #t :ed 0)) (expr-test "" "-0.10e4" (eenum -999.999 :d 2 :rm 'round2 :en #t :ed 0)) (test-section "exponent marker") (expr-test "" "1230" (eenum "123e1")) (expr-test "" "1230" (eenum "123E1")) (expr-test "" "1230" (eenum "123s1")) (expr-test "" "1230" (eenum "123S1")) (expr-test "" "1230" (eenum "123f1")) (expr-test "" "1230" (eenum "123F1")) (expr-test "" "1230" (eenum "123d1")) (expr-test "" "1230" (eenum "123D1")) (expr-test "" "1230" (eenum "123l1")) (expr-test "" "1230" (eenum "123L1")) (test-section "incomplete number") (expr-test "" "+" (eenum "+")) (expr-test "" "-" (eenum "-")) (expr-test "" "." (eenum ".")) (expr-test "" "0" (eenum "0.")) (expr-test "" ".0" (eenum ".0")) (expr-test "" "e" (eenum "e")) (expr-test "" "0e" (eenum "0e")) (expr-test "" "e0" (eenum "e0")) (expr-test "" "e+" (eenum "e+")) (expr-test "" "0e-" (eenum "0e-")) (test-section "misc") (expr-test "" "+inf.0" (eenum (/. 1 0))) (expr-test "" "-inf.0" (eenum (/. -1 0))) (expr-test "" "+nan.0" (eenum (/. 0 0))) (expr-test "" "0.0" (eenum (/. 0 +inf.0))) (expr-test "" "-0.0" (eenum (/. 0 -inf.0))) (expr-test "" "31.41592653589793" (eenum (* pi 10))) (expr-test "" "1.797693e308" (eenum 1.797693e308 :en #t)) (expr-test "" "2e308" (eenum 1.797693e308 :en #t :d 0 :rm 'round2)) (expr-test "" "1.8e308" (eenum 1.797693e308 :en #t :d 1 :rm 'round2)) (expr-test "" "-1.797693e308" (eenum -1.797693e308 :en #t)) (expr-test "" "-2e308" (eenum -1.797693e308 :en #t :d 0 :rm 'round2)) (expr-test "" "-1.8e308" (eenum -1.797693e308 :en #t :d 1 :rm 'round2)) (expr-test "" "2.225074e-308" (eenum 2.225074e-308 :en #t)) (test-section "long pattern (not printed)") (with-output-to-file (null-device) (lambda () (expr-test "" (string-append (make-num-str 10001) "." (make-num-str 9999 2)) (eenum (string-append (make-num-str 10000) "." (make-num-str 10000) "e1"))) (expr-test "" (string-append (make-num-str 9999) "." (make-num-str 10001 0)) (eenum (string-append (make-num-str 10000) "." (make-num-str 10000) "e-1"))) (expr-test "" (x->string (%expt 10 10001)) (eenum (string-append (x->string (%expt 10 10000)) "e1"))) (expr-test "" (string-append (x->string (%expt 10 9999)) ".0") (eenum (string-append (x->string (%expt 10 10000)) "e-1"))) )) (test-section "illegal number") (expr-test "" "" (eenum "")) (expr-test "" "" (eenum " ")) (expr-test "" "abc" (eenum "abc")) (expr-test "" "+123a" (eenum "+123a")) (expr-test "" "1 2 3" (eenum " 1 2 3 ")) ;; summary (format (current-error-port) "~%~a" ((with-module gauche.test format-summary))) (test-end)
true
e09627619a65c4739558522aba0767211dfb027c
1b771524ff0a6fb71a8f1af8c7555e528a004b5e
/ex364.scm
cf0440c329df770f02a6be20a46c537b4262517d
[]
no_license
yujiorama/sicp
6872f3e7ec4cf18ae62bb41f169dae50a2550972
d106005648b2710469067def5fefd44dae53ad58
refs/heads/master
2020-05-31T00:36:06.294314
2011-05-04T14:35:52
2011-05-04T14:35:52
315,072
0
0
null
null
null
null
UTF-8
Scheme
false
false
248
scm
ex364.scm
(define (stream-limit s tolerance) (if (< (abs (- (car (stream-cdr s)) (stream-car s))) tolerance) (car (stream-cdr s)) (stream-limit (stream-cdr s) tolerance))) (define (sqrt x tolerance) (stream-limit (sqrt-stream x) tolerance))
false
49cc87d921c240fb299de6e9f83f42af2055829e
958488bc7f3c2044206e0358e56d7690b6ae696c
/scheme/evaluator/environment1.scm
0dacf81c605a2cc891f6838b114db5d4aacc16b3
[]
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
4,857
scm
environment1.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; include guard ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (if (not (defined? included-environment1)) (begin (define included-environment1 #f) (display "loading environment1")(newline) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; one possible implementation of environment (load "frame.scm") (define environment1 ; constructor (let () ; name encapsulation ; object built from data is message passing interface (define (this data) ; data ignored here (lambda(m) (cond ((eq? m 'empty?)(empty? data)) ((eq? m 'define!)(define! data)) ((eq? m 'lookup)(lookup data)) ((eq? m 'defined?)(is-defined data)) ((eq? m 'set!)(set-var! data)) ((eq? m 'delete!)(delete! data)) ((eq? m 'extended)(extended data)) ; returns extended env ((eq? m 'to-string) (to-string data)) (else (error "environment1: unknown operation error: " m))))) ; ; Implementation of public interface ; ; empty environment represented by the pair ('data . '()) ; rather than simply '() so as to make it mutable (define (empty? data) (let frame-loop ((env (cdr data))) (if (null? env) #t (let ((current (car env))) ; else (if (not (current 'empty?)) #f (frame-loop (cdr env))))))) ; else ; (define (to-string data) (let frame-loop ((env (cdr data)) (out "{") (i 0)) (if (null? env) (string-append out "}") (let ((current (car env))) (let ((new-out (string-append out (if (= 0 i) "frame " ", frame ") (number->string i) ": " (current 'to-string)))) (frame-loop (cdr env) new-out (+ i 1))))))) ; ; only add binding to current frame, potentially overwrites existing binding (define (define! data) (lambda (var val) (if (empty? data) (set-cdr! data (list (frame)))) ; adding first frame (let ((current (cadr data))) ((current 'insert!) var val)))) ; (define (lookup data) (lambda (var) (let frame-loop ((env (cdr data))) (if (null? env) (error "Unbound variable -- LOOKUP" var) (let ((current (car env))) (let ((varval ((current 'find) var))) (if (eq? #f varval) ; var not in current frame (frame-loop (cdr env)) (cdr varval)))))))) ; varval is pair (var . val) ; (define (is-defined data) (lambda (var) (let frame-loop ((env (cdr data))) (if (null? env) #f (let ((current (car env))) (let ((varval ((current 'find) var))) (if (eq? #f varval) ; var not in current frame (frame-loop (cdr env)) #t))))))) ; ; overwrites binding in top-most frame where name is visible (define (set-var! data) (lambda (var val) (let frame-loop ((env (cdr data))) (if (null? env) (error "Unbound variable -- SET!" var) (let ((current (car env))) (let ((found ((current 'find) var))) (if (eq? #f found) ; var not in current frame (frame-loop (cdr env)) ((current 'insert!) var val)))))))) ; (define (delete! data) (lambda (var) (let frame-loop ((env (cdr data))) (if (not (null? env)) ; delete! has no impact if var not found (let ((current (car env))) (let ((found ((current 'find) var))) (if (eq? #f found) ; var not in current frame (frame-loop (cdr env)) ((current 'delete!) var)))))))) ; remove binding in frame ; (define (extended data) (lambda (vars vals) ; returning new environment instance, with additional frame (let ((new-frame (make-frame vars vals))) (this (cons 'data (cons new-frame (cdr data))))))) ; (define (display-env data) 'TODO) ; ; Private helper functions ; (define (make-frame vars vals) (let ((new-frame (frame))) ; empty-frame (let loop ((vars vars) (vals vals)) (cond ((null? vars) new-frame) ((symbol? vars) ((new-frame 'insert!) vars vals) new-frame) (else ((new-frame 'insert!) (car vars) (car vals)) (loop (cdr vars) (cdr vals))))))) ; ; returning no argument constructor ; (lambda () (this (cons 'data '()))))) )) ; include guard
false
eff8db906c363131cfd26e6d48f98172a4bc1e1c
923209816d56305004079b706d042d2fe5636b5a
/sitelib/http/header-field/if-match.scm
cd1ec0836c446bdcd43cd1cd69b0f213e87bc3e5
[ "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
300
scm
if-match.scm
(library (http header-field if-match) (export If-Match) (import (rnrs (6)) (http abnf) (http entity-tag)) ;;; 14.24 If-Match (define If-Match (seq (string->rule "If-Match") (char->rule #\:) *LWS ; implicit *LWS (bar (char->rule #\*) (num+ entity-tag)))) )
false
97cb0e87305e6fcdbd9b9e193d5fe59a940c5ed2
ac2a3544b88444eabf12b68a9bce08941cd62581
/lib/_system#.scm
7ef9efcee27773c40315c2151de0f048cfea8e76
[ "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
3,417
scm
_system#.scm
;;;============================================================================ ;;; File: "_system#.scm" ;;; Copyright (c) 1994-2019 by Marc Feeley, All Rights Reserved. ;;;============================================================================ ;;; Representation of exceptions. (define-library-type-of-exception invalid-hash-number-exception id: 3b7674e5-a6d8-11d9-930c-00039301ba52 constructor: #f opaque: (procedure unprintable: read-only: no-functional-setter:) (arguments unprintable: read-only: no-functional-setter:) ) (define-library-type-of-exception unbound-key-exception id: 1a1e928d-8df4-11d9-8894-00039301ba52 constructor: #f opaque: (procedure unprintable: read-only: no-functional-setter:) (arguments unprintable: read-only: no-functional-setter:) ) (define-library-type-of-exception unbound-serial-number-exception id: 3eb844fe-9381-11d9-b22f-00039301ba52 constructor: #f opaque: (procedure unprintable: read-only: no-functional-setter:) (arguments unprintable: read-only: no-functional-setter:) ) ;;;---------------------------------------------------------------------------- ;;; Representation of tables. (macro-case-target ((C) (define-type table id: F3F63A41-2974-4D41-8B24-1744E866741D type-exhibitor: macro-type-table constructor: macro-make-table implementer: implement-type-table opaque: macros: prefix: macro- (flags unprintable:) (test unprintable:) (hash unprintable:) (loads unprintable:) (gcht unprintable:) (init unprintable:) ) ) (else (define-type table id: A7AB629D-EAB0-422F-8005-08B2282E04FC type-exhibitor: macro-type-table constructor: macro-make-table implementer: implement-type-table opaque: macros: prefix: macro- (test unprintable:) (init unprintable:) (hashtable unprintable:) (flags unprintable:) ) )) ;;;---------------------------------------------------------------------------- ;;; Partially initialized structures. (define-type partially-initialized-structure id: cd85663e-b289-472c-b943-a41768e2f8a3 type-exhibitor: macro-type-partially-initialized-structure constructor: macro-make-partially-initialized-structure implementer: implement-type-partially-initialized-structure opaque: macros: prefix: macro- ) ;;;---------------------------------------------------------------------------- ;;; Auxiliary macro for computing hash key. ;; The FNV1a hash algorithm is adapted to hash values, in ;; particular the hashing constants are used (see ;; https://tools.ietf.org/html/draft-eastlake-fnv-12). Because the ;; hash function result is a fixnum and it needs to give the same ;; result on 32 bit and 64 bit architectures, the constants are ;; adapted to fit in a 32 bit fixnum. ;; FNV1a 32 bit constants (##define-macro (macro-fnv1a-prime-32bits) #x01000193) (##define-macro (macro-fnv1a-offset-basis-32bits) #x811C9DC5) ;; constants adapted to fit in 29 bits (tagged 32 bit fixnums) (##define-macro (macro-fnv1a-prime-fixnum32) #x01000193) (##define-macro (macro-fnv1a-offset-basis-fixnum32) #x011C9DC5) ;; 29 bits! (##define-macro (macro-hash-combine a b) `(let ((a ,a) (b ,b)) (##fxand (##fxwrap* (macro-fnv1a-prime-fixnum32) (##fxxor a b)) (macro-max-fixnum32)))) ;;;============================================================================
false
68326260e70395b8a7c12eb908055a7d5c3b2c60
c693dbc183fdf13b8eeab4590b91bb6cac786a22
/scheme/Triangle-Exercises.ss
a5f1722bb74f16766e11af2953e8793414945d38
[]
no_license
qianyan/functional-programming
4600a11400176978244f7aed386718614428fd13
34ba5010f9bf68c1ef4fa41ce9e6fdb9fe5a10b5
refs/heads/master
2016-09-01T21:09:32.389073
2015-08-14T07:58:59
2015-08-14T07:58:59
26,963,148
0
0
null
null
null
null
UTF-8
Scheme
false
false
3,634
ss
Triangle-Exercises.ss
(define draw-asterisk (lambda (n) (display '*))) (define draw-whitespace (lambda (n) (display " "))) (define (draw-horizontal n proc) (proc n) (if (= n 1) (newline) (draw-horizontal (- n 1) proc))) (define (draw-vertical n proc) (proc n) (newline) (if (not (= n 1)) (draw-vertical (- n 1) proc))) ;;; draw a horizontal line (define (draw-a-horizontal-line n) (draw-horizontal n draw-asterisk)) ;;; draw a vertical line (define (draw-a-vertical-line n) (draw-vertical n draw-asterisk)) ;;; Draw a right triangle (define (draw-horizontal-without-newline n proc) (proc n) (if (not (= n 1)) (draw-horizontal-without-newline (- n 1 ) proc))) (define draw-a-right-triangle (lambda (n) (draw-vertical n (lambda (m) (draw-horizontal-without-newline (+ (- n m) 1) draw-asterisk))))) ;;; Diamond Exercises ;;; draw-isosceles-triangle (define draw-isosceles-triangle (lambda (n) (if (zero? n) (newline) (draw-vertical n (lambda (m) (draw-horizontal-without-newline (- (* 2 n) 1) (lambda (c) (if (< (abs (- c n)) (+ 1 (- n m))) (draw-asterisk '()) (draw-whitespace '()))))))))) ;;; draw diamond (define draw-a-diamond (lambda (n) (if (zero? n) (newline) (draw-vertical (- (* 2 n) 1) (lambda (m) (draw-horizontal-without-newline (- (* 2 n) 1) (lambda (c) (if (< (abs (- c n)) (- n (abs (- m n)))) (draw-asterisk '()) (draw-whitespace '()))))))))) ;;; draw-diamond-with-your-name (define draw-diamond-with-your-name (lambda (n) (if (zero? n) (newline) (draw-vertical (- (* 2 n) 1) (lambda (m) (if (= m n) (display "fangzhigang") (draw-horizontal-without-newline (- (* 2 n) 1) (lambda (c) (if (< (abs (- c n)) (- n (abs (- m n)))) (draw-asterisk '()) (draw-whitespace '())))))))))) ;;; FizzBuzz (define (fb s e) (if (> s e) (newline) (draw-vertical (- e s) (lambda (m) (let ((row (+ s (- e s m)))) (cond ((and (zero? (mod row 3)) (zero? (mod row 5))) (display "FizzBuzz")) ((zero? (mod row 3)) (display "Fizz")) ((zero? (mod row 5)) (display "Buzz")) (else (display row)))))))) (define FizzBuzz (lambda () (fb 1 100))) ;;; prime factor (define (is? i n) (cond ((> i (sqrt n)) #t) ((zero? (mod n i)) #f) (else (is? (+ i 1) n)))) (define isPrime? (lambda (n) (is? 2 n))) (define (divable-list i n) (cond ((> i n) '()) ((zero? (mod n i)) (cons i (divable-list (+ i 1) n))) (else (divable-list (+ i 1) n)))) (define (generate n) (filter isPrime? (divable-list 2 n)))
false
aecab3762e2d71a33f84697a71a548bb309714bc
e1fc47ba76cfc1881a5d096dc3d59ffe10d07be6
/ch3/3.52.scm
2b529e6ea59ad16ed2af1ffc46b17c54295f0927
[]
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
716
scm
3.52.scm
(load "3.05.01.stream.scm") (load "3.50.scm") ; generic map (define sum 0) (define (acc-sum x) (set! sum (+ sum x)) sum) (define (disp-sum) (display "sum: ") (display sum) (newline)) (define seq (stream-map acc-sum (stream-enum-interval 1 20))) ; 1 .. (disp-sum) ; single: 1; seq: 1 ;; comment-out each to check ;; or seq ; (define y (stream-filter even? seq)) ; (disp-sum) ; single: 6; seq: 6 (define z (stream-filter (lambda (x) (zero? (remainder x 5))) seq)) ; [1 3 6] 10 .. (disp-sum) ; single: 10; seq: 15 (2,3 repeated) ; (stream-ref y 7) ; (disp-sum) ; single: 136; (display-stream z) (newline) (disp-sum) ; single: 210 (display-stream z) (newline) (disp-sum) ; seq: 410 = 210 + 200 (5-20 repeated)
false
b9b062167660851ef1161390036526049bb5db0d
97f1e07c512c33424c4282875a1c31dc89e56bd2
/limsn/manifest.scm
71461e538a112bab113609241ae4f00d8cbd74c9
[]
no_license
labsolns/limsn
909ebf9bbd0201d5587b02a04909082ed63b178c
f5366a4a6920ac3a80fb80b026b840618d7af6d6
refs/heads/main
2023-07-20T07:59:28.475916
2021-08-25T06:30:51
2021-08-25T06:30:51
399,366,582
0
0
null
null
null
null
UTF-8
Scheme
false
false
112
scm
manifest.scm
(specifications->manifest '("[email protected]" "artanis" "guile-lib" "gnutls" "glibc-utf8-locales" "guile-dbi"))
false
8d626a72e9c6b09c10b1b0069bd24b514e34f8f3
4b2aeafb5610b008009b9f4037d42c6e98f8ea73
/11.4/11.4-1.scm
9f5e81b9d63cd7c4c775f6e0a7d27e2eeb3e6e34
[]
no_license
mrinalabrol/clrs
cd461d1a04e6278291f6555273d709f48e48de9c
f85a8f0036f0946c9e64dde3259a19acc62b74a1
refs/heads/master
2021-01-17T23:47:45.261326
2010-09-29T00:43:32
2010-09-29T00:43:32
null
0
0
null
null
null
null
UTF-8
Scheme
false
false
994
scm
11.4-1.scm
(require-extension syntax-case check) (require '../11.4/section) (import section-11.4) (let ((keys '(10 22 31 4 15 28 17 88 59)) (m 11)) (let ((hash1 (lambda (k) (modulo k m))) (hash2 (lambda (k) (+ 1 (modulo k (- m 1)))))) (let ((linear-table (make-oa-table m (linear-probe hash1 m))) (quadratic-table (make-oa-table m (quadratic-probe hash1 1 3 m))) (double-hash-table (make-oa-table m (double-hash hash1 hash2 m)))) (let ((tables (list linear-table quadratic-table double-hash-table))) (for-each (lambda (table) (for-each (lambda (key) (oa-insert! table key)) keys)) tables) (check (oa-table linear-table) => '#(22 88 #f #f 4 15 28 17 59 31 10)) (check (oa-table quadratic-table) => '#(22 #f 88 17 4 #f 28 59 15 31 10)) (check (oa-table double-hash-table) => '#(22 #f 59 17 4 15 28 88 #f 31 10))))))
false
30d5fa95b444a109975357fb3dc97b72a2f9a6f4
140a499a12332fa8b77fb738463ef58de56f6cb9
/worlds/core/verbcode/48/drop-1.scm
c6dbbd24ac299614e72d64df1da1efe4dca3d76d
[ "MIT" ]
permissive
sid-code/nmoo
2a5546621ee8c247d4f2610f9aa04d115aa41c5b
cf504f28ab473fd70f2c60cda4d109c33b600727
refs/heads/master
2023-08-19T09:16:37.488546
2023-08-15T16:57:39
2023-08-15T16:57:39
31,146,820
10
0
null
null
null
null
UTF-8
Scheme
false
false
426
scm
drop-1.scm
(let ((loc (getprop self "location" $nowhere)) (player-loc (getprop player "location" $nowhere))) (if (= loc player) (try (do (move self player-loc) (player-loc:announce player (cat player.name " drops " self.name ".")) (player:tell "Dropped.")) ;catch (player:tell "Could not drop " self.name "!")) (player:tell "You are not carrying " self.name ".")))
false
63a4415bf6943d3cd1d9e64c12681f76abe3247d
abc7bd420c9cc4dba4512b382baad54ba4d07aa8
/src/old/plt/aggregation_experiments.ss
ec5b2ccb022f793ac543cb71a584169b7f38926c
[ "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
109
ss
aggregation_experiments.ss
(require (lib "include.ss")) (require "simulator_nought.ss") (include "generic/aggregation_experiments.ss")
false
f151b7b7340e287af1f6c4ec9997d2c20ace4b81
eaa28dbef6926d67307a4dc8bae385f78acf70f9
/skripti/freebsd-build.scm
9414d847b7af75cefc9b470d39228cece071762b
[ "Unlicense" ]
permissive
mytoh/pikkukivi
d792a3c20db4738d99d5cee0530401a144027f1f
d3d77df71f4267b9629c3fc21a49be77940bf8ad
refs/heads/master
2016-09-01T18:42:53.979557
2015-09-04T08:32:08
2015-09-04T08:32:08
5,688,224
0
0
null
null
null
null
UTF-8
Scheme
false
false
2,971
scm
freebsd-build.scm
(use gauche.process) (use file.util) (use util.match) (require-extension (srfi 13)) (define-syntax colour-command (syntax-rules () ((_ ?command ?regexp ?string ...) (with-input-from-process ?command (lambda () (port-for-each (lambda (in) (print (regexp-replace* in ?regexp ?string ...))) read-line)))))) (define (process command) (print (string-concatenate `("" "==> " "" ,command))) (colour-command command #/^>>>/ "\\0" #/^=*>/ "\\0" #/^-*/ "\\0" #/(cc|c\+\+|sed|awk|ctfconvert|mkdep)\s+/ "\\0" #/(\/|\s)(\w*\.(cpp))/ "\\1\\2" #/(\/|\s)(\w*\.(c))/ "\\1\\2" #/(\/|\s)(\w*\.(h))/ "\\1\\2" #/(\/|\s)(\w*\.(td))/ "\\1\\2" #/(\/|\s)(\w*\.(po))/ "\\1\\2" #/(\/|\s)(\w*\.(gz))/ "\\1\\2" #/(\/|\s)(\w*\.(sh))/ "\\1\\2" #/(\/|\s)(\w*\.(S))/ "\\1\\2" #/(\/|\s)(\w*\.(so))/ "\\1\\2" #/(\/|\s)(\w*\.\d\.(so))/ "\\1\\2" #/(\/|\s)(\w*\.(o))/ "\\1\\2" #/(\/|\s)(\w*\.(ko))/ "\\1\\2" #/(-\w*)/ "\\1" #/(zfs|libc\+\+|clang|llvm|MYKERNEL)/ "\\1" #/\(\w*\)/ "\\0" #/~*/ "\\0" #/[A-Z]*/ "\\0" ) (print (string-concatenate `("" "==> " " finished " ,command)))) (define (first) (current-directory "/usr/src") (when (file-exists? "/usr/obj") (process "sudo make cleandir") (process "sudo make cleandir") (process "sudo rm -rfv /usr/obj")) (process "sudo make -j 5 buildworld") (process "sudo make -j 5 buildkernel") (process "sudo make installkernel") (print "REBOOT!")) (define (second) (process "mount -u /" ) (process "mount -a -t ufs" ) (run-process '(mergemaster -p ) :wait #true) (current-directory "/usr/src") (process "make installworld" ) (process "yes y | make delete-old" ) (run-process '(mergemaster ) :wait #true) (print "please reboot") (print " # reboot # mount -u / # mount -a -t ufs # cd /usr/src # make delete-old-libs ")) (define (third) (process "mount -u /" ) (process "mount -a -t ufs" ) (current-directory "/usr/src") (process "yes y | make delete-old-libs" )) (define (main args) (match (cadr args) ("first" (first)) ("second" (second)) ("third" (third))))
true
42c9a2be47fc1816fac7452d5443e9f496c57359
a66514d577470329b9f0bf39e5c3a32a6d01a70d
/cairo/types.ss
fb7b385c352b9502fed87af67395aa632c94710a
[ "Apache-2.0" ]
permissive
ovenpasta/thunderchez
2557819a41114423a4e664ead7c521608e7b6b42
268d0d7da87fdeb5f25bdcd5e62217398d958d59
refs/heads/trunk
2022-08-31T15:01:37.734079
2021-07-25T14:59:53
2022-08-18T09:33:35
62,828,147
149
29
null
2022-08-18T09:33:37
2016-07-07T18:07:23
Common Lisp
UTF-8
Scheme
false
false
9,359
ss
types.ss
;; ;; Copyright 2016 Aldo Nicolas Bruno ;; ;; Licensed under the Apache License, Version 2.0 (the "License"); ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (define-ftype unsigned-8* (* unsigned-8)) (define-ftype unsigned-char unsigned-8) (define-ftype cairo-bool-t int) (define-ftype cairo-t (struct)) (define-ftype cairo-surface-t (struct)) (define-ftype cairo-surface-t* (* cairo-surface-t)) (define-ftype cairo-device-t void*) (define-ftype cairo-matrix-t (struct [xx double] [yx double] [xy double] [yy double] [x0 double] [y0 double])) (define-ftype-allocator cairo-matrix-create cairo-matrix-t) (define-ftype cairo-pattern-t (struct)) ; (define-ftype cairo-destroy-func-t (function (void*) void)) (define-ftype cairo-destroy-func-t void*) (define-ftype cairo-user-data-key-t (struct [unused int])) (define-ftype cairo-status-t int) (define-enumeration* cairo-status-enum (success no-memory invalid-restore invalid-pop-group no-current-point invalid-matrix invalid-status null-pointer invalid-string invalid-path-data read-error write-error surface-finished surface-type-mismatch pattern-type-mismatch invalid-content invalid-format invalid-visual file-not-found invalid-dash invalid-dsc-comment invalid-index clip-not-representable temp-file-error invalid-stride font-type-mismatch user-font-immutable user-font-error negative-count invalid-clusters invalid-slant invalid-weight invalid-size user-font-not-implemented device-type-mismatch device-error invalid-mesh-construction device-finished jbig2-global-missing last-status)) (define-flags cairo-content (color 4096) (alpha 8192) (color-alpha 12288)) (define-enumeration* cairo-format (argb-32 rgb-24 a-8 a-1 rgb-16-565 rgb-30)) (define cairo-format-invalid -1) (define-ftype cairo-write-func-t (function (ptr (* unsigned-8) unsigned-int) cairo-status-t)) (define-ftype cairo-read-func-t (function (ptr (* unsigned-8) unsigned-int) cairo-status-t)) (define-ftype cairo-rectangle-int-t (struct [x int] [y int] [width int] [height int])) (define-ftype-allocator cairo-rectangle-int-create cairo-rectangle-int-t) (define-enumeration* cairo-operator (clear source over in out atop dest dest-over dest-in dest-out dest-atop xor add saturate multiply screen overlay darken lighten color-dodge color-burn hard-light soft-light difference exclusion hsl-hue hsl-saturation hsl-color hsl-luminosity)) (define-enumeration* cairo-antialias (default none gray subpixel fast good best)) (define-enumeration* cairo-fill-rule (winding even-odd)) (define-enumeration* cairo-line-cap (butt round square)) (define-enumeration* cairo-line-join (miter round bevel)) (define-ftype double-array (array 0 double)) (define-ftype-array-allocator double-array-create double-array double) (define (double-array-create-from-vector l) (let* ([ls (vector->list l)] [size (vector-length l)] [array (double-array-create size)]) (do ([i 0 (fx1+ i)]) ((fx>= i size)) (let ([x (vector-ref l i)] [r (ftype-&ref double-array (i) array)]) (ftype-set! double () r x))) array)) (define-ftype cairo-rectangle-t (struct [x double] [y double] [width double] [height double])) (define-ftype-allocator cairo-rectangle-create cairo-rectangle-t) (define-ftype cairo-rectangle-list-t (struct [status cairo-status-t] [rectangles (* cairo-rectangle-t)] [num-rectangles int])) (define-ftype-allocator cairo-rectangle-list-create cairo-rectangle-list-t) (define-ftype cairo-scaled-font-t void*) (define-ftype cairo-font-face-t void*) (define-ftype cairo-glyph-t (struct [index unsigned-long] [x double] [y double])) (define-ftype-allocator cairo-glyph-create cairo-glyph-t) (define-ftype cairo-glyph-t* (* cairo-glyph-t)) (define-ftype-allocator cairo-glyph*-create cairo-glyph-t*) (define-ftype cairo-text-cluster-t (struct [num-bytes int] [num-glyphs int])) (define-ftype-allocator cairo-text-cluster-create cairo-text-cluster-t) (define-ftype cairo-text-cluster-t* (* cairo-text-cluster-t)) (define-ftype-allocator cairo-text-cluster*-create cairo-text-cluster-t*) (define-enumeration* cairo-text-cluster-flag (none backward)) (define-ftype cairo-text-cluster-flags-t int) (define-ftype-allocator cairo-text-cluster-flags-create cairo-text-cluster-flags-t) (define-ftype-allocator cairo-int-create int) (define-ftype-allocator cairo-void*-create void*) (define-ftype cairo-text-extents-t (struct [x-bearing double] [y-bearing double] [width double] [height double] [x-advance double] [y-advance double])) (define-ftype-allocator cairo-text-extents-create cairo-text-extents-t) (define-ftype cairo-font-extents-t (struct [ascent double] [descent double] [height double] [max-x-advance double] [max-y-advance double])) (define-ftype-allocator cairo-font-extents-create cairo-font-extents-t) ;(define-ftype cairo-font-extents-t int) (define-enumeration* cairo-font-slant (normal italic oblique)) (define-enumeration* cairo-font-weight (normal bold)) (define-enumeration* cairo-subpixel-order (default rgb bgr vrgb vbgr)) (define-enumeration* cairo-hint-style (default none slight medium full)) (define-enumeration* cairo-hint-metrics (default off on)) (define-ftype cairo-font-options-t void*) (define-enumeration* cairo-font-type (toy ft win32 quartz user)) (define-ftype cairo-user-scaled-font-init-func-t (function (cairo-scaled-font-t (* cairo-t) (* cairo-font-extents-t)) cairo-status-t)) (define-ftype cairo-user-scaled-font-render-glyph-func-t (function (cairo-scaled-font-t unsigned-long (* cairo-t) (* cairo-font-extents-t )) cairo-status-t)) (define-ftype cairo-user-scaled-font-text-to-glyphs-func-t (function (cairo-scaled-font-t string int (* cairo-glyph-t) int (* cairo-text-cluster-t) int (* cairo-text-cluster-flags-t)) cairo-status-t)) (define-ftype cairo-user-scaled-font-unicode-to-glyph-func-t (function (cairo-scaled-font-t unsigned-long (* unsigned-long)) cairo-status-t)) (define-enumeration* cairo-path-data-type (move-to line-to curve-to close-path)) (define-ftype cairo-path-data-t (union [header (struct [type cairo-path-data-type-t] [length int])] [point (struct [x double] [y double])])) (define-ftype cairo-path-t (struct [status cairo-status-t] [data (* cairo-path-data-t)] [num-data int])) (define-ftype-allocator cairo-path-create cairo-path-t) (define-enumeration* cairo-device-type (drm gl script xcb xlib xml cogl win32)) (define cairo-device-type-invalid -1) (define-enumeration* cairo-surface-observer-mode (normal record-operations)) (define-ftype cairo-surface-observer-callback-t (function ((* cairo-surface-t) (* cairo-surface-t) void*) void)) (define-enumeration* cairo-surface-type (image pdf ps xlib xcb gliz quartz win32 beos directfb svg os2 win32-printing quartz-image script qt recording vg gl drm tee xml skia subsurface cogl)) (define cairo-mime-types '((jpeg . "image/jpeg") (png . "image/png") (jp2 . "image/jp2") (uri . "text/x-uri") (unique-id . "application/x-cairo.uuid") (jbig2 . "application/x-cairo.jbig2") (jbig2-global . "application/x-cairo.jbig2-global") (jbig2-global-id . "application/x-cairo.jbig2-global-id"))) (define-ftype cairo-raster-source-acquire-func-t (function ((* cairo-pattern-t) void* (* cairo-surface-t) (* cairo-rectangle-int-t)) cairo-status-t)) (define-ftype cairo-raster-source-acquire-func-t* (* cairo-raster-source-acquire-func-t)) (define-ftype cairo-raster-source-release-func-t (function ((* cairo-pattern-t) void* (* cairo-surface-t)) cairo-status-t)) (define-ftype cairo-raster-source-release-func-t* (* cairo-raster-source-release-func-t)) (define-ftype cairo-raster-source-snapshot-func-t (function ((* cairo-pattern-t) void*) cairo-status-t)) (define-ftype cairo-raster-source-copy-func-t (function ((* cairo-pattern-t) void* (* cairo-pattern-t)) cairo-status-t)) (define-ftype cairo-raster-source-finish-func-t (function ((* cairo-pattern-t) void*) cairo-status-t)) (define-enumeration* cairo-pattern-type (solid surface linear radial mesh raster-source)) (define-enumeration* cairo-extend (none repeat reflect pad)) (define-enumeration* cairo-filter (fast good best nearest bilinear gaussian)) (define-ftype cairo-region-t void*) (define-enumeration* cairo-region-overlap (in out part)) (define-ftype cairo-pdf-version-t int) (define-ftype cairo-pdf-version-t* (* cairo-pdf-version-t)) (define-ftype cairo-pdf-version-t-const cairo-pdf-version-t)
false
34408e1e1743a2ce3d67f402683f0187bbb3fff3
4a1ff5a0f674ff41bd384301ab82b3197f5ca0c8
/problems/0021/main.scm
eea92899e6f7ebb4061dcf542fa00e4169c889e1
[]
no_license
MiyamonY/yukicoder
e0a323d68c4d3b41bdb42fb3ed6ab105619ca7e9
1bb8882ac76cc302428ab0417f90cfa94f7380c8
refs/heads/master
2020-05-09T12:13:31.627382
2019-10-06T17:01:45
2019-10-06T17:01:45
181,105,911
0
0
null
null
null
null
UTF-8
Scheme
false
false
272
scm
main.scm
(define (solve k arr) (define max (last arr)) (define min (car arr)) (- max min)) (let* ((n (string->number (read-line))) (k (string->number (read-line))) (arr (map (lambda (_) (string->number (read-line))) (iota n)))) (print (solve k (sort arr))))
false
fa83acb4226e21a32efe8bd6884b444aaacb0057
be571edfb28be8cc693048cdc7b674ae2404bf82
/my-stat.scm
9efe73a0d1c86b6793efe0015e1e0f2dcc8b8662
[]
no_license
h8gi/my-stat
af18275d158561a6d75327493e91a0655e76ebab
a33a46919e990c4cda0222e53db59d43b80ff72b
refs/heads/master
2020-05-21T12:23:49.345531
2017-02-11T10:27:00
2017-02-11T10:27:00
52,955,842
0
0
null
null
null
null
UTF-8
Scheme
false
false
89
scm
my-stat.scm
(module my-stat * (import scheme chicken srfi-1 extras) (include "main.scm") )
false
9bc897e16330a373bf849981a39ea7f9cebe26b5
2c291b7af5cd7679da3aa54fdc64dc006ee6ff9b
/ch3/exercise.3.17.scm
a66e7715095153f5df2444dc67730d1a0f47354f
[]
no_license
etscrivner/sicp
caff1b3738e308c7f8165fc65a3f1bc252ce625a
3b45aaf2b2846068dcec90ea0547fd72b28f8cdc
refs/heads/master
2021-01-10T12:08:38.212403
2015-08-22T20:01:44
2015-08-22T20:01:44
36,813,957
1
0
null
null
null
null
UTF-8
Scheme
false
false
644
scm
exercise.3.17.scm
(load "exercise.3.16.scm") (define (count-unique-pairs x) (define (iter x already-seen) (if (or (memq x already-seen) (not (pair? x))) (begin (length already-seen)) (let ((new-already-seen (cons x already-seen))) (max (iter (car x) new-already-seen) (iter (cdr x) new-already-seen))))) (iter x '())) (= 0 (count-unique-pairs '())) (= 1 (count-unique-pairs '(a))) (= 2 (count-unique-pairs '(a b))) (= 3 (count-unique-pairs '(((a))))) (count-unique-pairs '(a b c)) (count-unique-pairs (return-4)) (count-unique-pairs '((a b) (c d) e)) (count-unique-pairs (make-cycle '(a b c)))
false
5bcad0c48f4287403a7d22ea9fcdb00a6d32412e
569eb7a16d4cfb02c4fb5d92c7452aa13d22d7b8
/scheme/gui/gui05.scm
bbe1d2cf6e305ef240fca48437d98258e2992dcf
[]
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,256
scm
gui05.scm
#lang racket ;; Geoffrey Matthews ;; 2013 ;; Building gui's with racket (require racket/gui) (define frame (new frame% (label "Example") (min-width 120) (min-height 80) )) (send frame create-status-line) (send frame show #t) ;; Let's add lots of controls, laid out horizontally ;; and then vertically: (define h-panel (new horizontal-panel% (parent frame) (stretchable-height #f) (style '(border)) (border 2))) (let loop ((i 0)) (when (< i 10) (new button% (parent h-panel) (label (format "Button~a" i)) (callback (lambda (b e) (send frame set-status-text (format "You clicked horizontal button ~a!" i))))) (loop (add1 i)))) (define v-panel (new vertical-panel% (parent frame) (style '(border)) (border 2))) (let loop ((i 0)) (when (< i 10) (new button% (parent v-panel) (label (format "Button~a" i)) (callback (lambda (b e) (send frame set-status-text (format "You clicked vertical button ~a!" i))))) (loop (add1 i))))
false
7f525d20722ac4d046c0b20e6e5e53f637320666
41648be07e8803784690d9b4f6f08091e322b193
/core-box.ss
d51cde34da2c6ab52ce6a736cd2f7665ec28f872
[]
no_license
samth/not-a-box
dad25a9ea65debf318a14f2a5f5788b331b62a76
9fa61e07b278be52148612fb5a77f4058eca5a9f
refs/heads/master
2021-01-19T12:51:12.457049
2017-03-02T19:57:20
2017-03-03T19:59:37
82,343,642
0
0
null
2017-02-17T22:27:36
2017-02-17T22:27:36
null
UTF-8
Scheme
false
false
783
ss
core-box.ss
(define (box-immutable v) (let ([b (box v)]) (set-immutable! b) b)) (define (set-box! b v) (unless (and (box? b) (unsafe-mutable? b)) (raise-argument-error 'set-box! "(and/c box? (not/c immutable?))" b)) (chez:set-box! b v)) (define (box-cas! b v1 v2) (unless (and (box? b) (unsafe-mutable? b)) (raise-argument-error 'box-cas! "(and/c box? (not/c immutable?))" b)) (unsafe-box-cas! b v1 v2)) (define (unsafe-box-cas! b v1 v2) (and (eq? v1 (unbox b)) (chez:set-box! b v2) #t)) (define (make-weak-box v) (weak-cons v #t)) (define (weak-box? v) (weak-pair? v)) (define (weak-box-value v) (unless (weak-pair? v) (raise-argument-error 'weak-box-value "weak-box?" v)) (let ([c (car v)]) (if (eq? c #!bwp) #f c)))
false
a3a8182383129b6ebdb94cf89facf399e9e70668
3686e1a62c9668df4282e769220e2bb72e3f9902
/ex2.20.scm
e42ecd6cac1f02c109b4b3ffd410173a34e0e5de
[]
no_license
rasuldev/sicp
a4e4a79354495639ddfaa04ece3ddf42749276b5
71fe0554ea91994822db00521224b7e265235ff3
refs/heads/master
2020-05-21T17:43:00.967221
2017-05-02T20:32:06
2017-05-02T20:32:06
65,855,266
0
0
null
null
null
null
UTF-8
Scheme
false
false
292
scm
ex2.20.scm
(define (same-parity x . lst) (define (iter cand) (if (null? cand) '() (let ((y (car cand))) (if (= (remainder x 2) (remainder y 2)) (cons y (iter (cdr cand))) (iter (cdr cand)) ) ) ) ) (cons x (iter lst)) ) (same-parity 2 3 4 5 6 7)
false
5f1e4308da2d1b5ae99d0f70746354c5eff754c4
defeada37d39bca09ef76f66f38683754c0a6aa0
/mscorlib/system/member-access-exception.sls
09f0ab0833f970520e3074300df9f6f4f0e90619
[]
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
394
sls
member-access-exception.sls
(library (system member-access-exception) (export new is? member-access-exception?) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new System.MemberAccessException a ...))))) (define (is? a) (clr-is System.MemberAccessException a)) (define (member-access-exception? a) (clr-is System.MemberAccessException a)))
true
51940fd490f2b5ae123091a19019d4a59d3c145a
defeada37d39bca09ef76f66f38683754c0a6aa0
/UnityEngine/unity-engine/location-service.sls
a914b84d7f621c1476a9e9de74c5abfcf9e10598
[]
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,183
sls
location-service.sls
(library (unity-engine location-service) (export new is? location-service? stop start is-enabled-by-user? status last-data) (import (ironscheme-clr-port)) (define-syntax new (lambda (e) (syntax-case e () ((_ a ...) #'(clr-new UnityEngine.LocationService a ...))))) (define (is? a) (clr-is UnityEngine.LocationService a)) (define (location-service? a) (clr-is UnityEngine.LocationService a)) (define-method-port stop UnityEngine.LocationService Stop (System.Void)) (define-method-port start UnityEngine.LocationService Start (System.Void) (System.Void System.Single) (System.Void System.Single System.Single)) (define-field-port is-enabled-by-user? #f #f (property:) UnityEngine.LocationService isEnabledByUser System.Boolean) (define-field-port status #f #f (property:) UnityEngine.LocationService status UnityEngine.LocationServiceStatus) (define-field-port last-data #f #f (property:) UnityEngine.LocationService lastData UnityEngine.LocationInfo))
true
c1887ecd42285c2950a2764852e84061a50288ac
1f48fb14898799bf9ee1118bf691586b430c5e9e
/230.scm
11ae5d5ddb565fe5195c3f423d44294fac55cca5
[]
no_license
green-93-nope/sicp
0fa79dd59414808a9cdcbfa18bd3a1c7f0b8191c
59241b6c42621c2ef967efebdd281b845f98e923
refs/heads/master
2021-01-10T10:51:22.328123
2017-05-21T08:33:25
2017-05-21T08:33:25
48,210,972
0
0
null
null
null
null
UTF-8
Scheme
false
false
262
scm
230.scm
(define (scale-tree tree factor) (map (lambda (x) (if (pair? x) (scale-tree x factor) (* x factor))) tree)) (define (square-tree tree) (map (lambda (x) (if (pair? x) (square-tree x) (* x x))) tree))
false
b5cc8fb058912434001bbb9d1dd2f22c14b72f39
559934d76e760d2ac18121e9871f55199035c3e2
/chapter-1/fast-mult.scm
37a98a22e48bb0898c6ce9212b6864dd9da802c6
[ "MIT" ]
permissive
floyza/sicp-exersices
6ea930c83cabbecc509abf1e014f7419231481d6
ee82444b82f2b2fc130728e5ec9d35bdf73c24de
refs/heads/master
2023-06-16T11:51:43.794164
2021-07-14T16:47:44
2021-07-14T16:48:46
383,636,376
0
0
null
null
null
null
UTF-8
Scheme
false
false
413
scm
fast-mult.scm
(define (mult a b) (if (= b 0) 0 (+ a (mult a (1- b))))) (define (double x) (* x 2)) (define (half x) (/ x 2)) (define (fast-mult-helper a b) (cond ((= b 0) 0) ((even? b) (double (fast-mult-helper a (half b)))) (else (+ a (fast-mult-helper a (1- b)))))) (define (fast-mult a b) (if (< b 0) (fast-mult-helper (- a) (- b)) (fast-mult-helper a b))) (fast-mult 5 6)
false
a545f5d7f9c5437bf9502597d0a53fa1c57bacb8
bf6fad8f5227d0b0ef78598065c83b89b8f74bbc
/chapter02/scheme/make-counter.ss
0f4cc2b6e34722946fa065a163e5c05009f8381b
[]
no_license
e5pe0n/tspl
931d1245611280457094bd000e20b1790c3e2499
bc76cac2307fe9c5a3be2cea36ead986ca94be43
refs/heads/main
2023-08-18T08:21:29.222335
2021-09-28T11:04:54
2021-09-28T11:04:54
393,668,056
0
0
null
null
null
null
UTF-8
Scheme
false
false
412
ss
make-counter.ss
(define print (lambda (x) (for-each display `(,x "\n")) ) ) (define make-counter (lambda () (let ([next 0]) (lambda () (let ([v next]) (set! next (+ next 1)) v ) ) ) ) ) (define count1 (make-counter)) (define count2 (make-counter)) (print (count1)) ; 0 (print (count2)) ; 0 (print (count1)) ; 1 (print (count1)) ; 2 (print (count2)) ; 1
false
26596e10335236ea0310f041f3e709122f47564e
4b5dddfd00099e79cff58fcc05465b2243161094
/chapter_2/symbol_deriv.scm
3fa8b9ad55402b2f15be943a8df047aabe3a0eab
[ "MIT" ]
permissive
hjcapple/reading-sicp
c9b4ef99d75cc85b3758c269b246328122964edc
f54d54e4fc1448a8c52f0e4e07a7ff7356fc0bf0
refs/heads/master
2023-05-27T08:34:05.882703
2023-05-14T04:33:04
2023-05-14T04:33:04
198,552,668
269
41
MIT
2022-12-20T10:08:59
2019-07-24T03:37:47
Scheme
UTF-8
Scheme
false
false
1,513
scm
symbol_deriv.scm
#lang racket ;; P99 - [2.3.2 实例: 符号求导] (define (deriv exp var) (cond ((number? exp) 0) ((variable? exp) (if (same-variable? exp var) 1 0)) ((sum? exp) (make-sum (deriv (addend exp) var) (deriv (augend exp) var))) ((product? exp) (make-sum (make-product (multiplier exp) (deriv (multiplicand exp) var)) (make-product (deriv (multiplier exp) var) (multiplicand exp)))) (else (error "unknown expression type -- DERIV" exp)))) (define (variable? x) (symbol? x)) (define (same-variable? v1 v2) (and (variable? v1) (variable? v2) (eq? v1 v2))) (define (=number? exp num) (and (number? exp) (= exp num))) (define (make-sum a1 a2) (cond ((=number? a1 0) a2) ((=number? a2 0) a1) ((and (number? a1) (number? a2) (+ a1 a2))) (else (list '+ a1 a2)))) (define (make-product m1 m2) (cond ((or (=number? m1 0) (=number? m2 0)) 0) ((=number? m1 1) m2) ((=number? m2 1) m1) ((and (number? m1) (number? m2) (* m1 m2))) (else (list '* m1 m2)))) (define (sum? x) (and (pair? x) (eq? (car x) '+))) (define (addend s) (cadr s)) (define (augend s) (caddr s)) (define (product? x) (and (pair? x) (eq? (car x) '*))) (define (multiplier s) (cadr s)) (define (multiplicand s) (caddr s)) ;;;;;;;;;;;;;;;;;;;;; (deriv '(+ x 3) 'x) (deriv '(* x y) 'x) (deriv '(* (* x y) (+ x 3)) 'x)
false
e54111b87a225aec3f22a1c977d87c4178da7524
0b0b7987be5b118121b0d991bdcf8d573a3273c1
/ESSLLI2006/resources/arithmetic1.scm
903f388f20298b8193052f384ac75190a2f3bf88
[ "Apache-2.0" ]
permissive
dcavar/dcavar.github.io
d0a85ca7025b8e0fa190e0a9f0966ab115f3dbbb
af1a2ceefc5e46559a7e74f96230bf4dccf24344
refs/heads/master
2023-08-30T10:05:20.825342
2023-08-17T19:07:43
2023-08-17T19:07:43
87,249,109
4
1
Apache-2.0
2021-09-28T00:18:17
2017-04-05T00:44:19
HTML
UTF-8
Scheme
false
false
91
scm
arithmetic1.scm
(+ 3 2) (- 3 2) (* 3 2) (/ 4 2) (/ 3 2) (/ 3.0 2.0) (expt 2 3) (sqrt 4) (- 3) (/ 3) (/ 3.0)
false
bc0faa4215b0b3c6494251a139734fe0264f9ea4
ec5b4a92882f80b3f62eac8cbd059fb1f000cfd9
/imperative/old/!tests/fibonacci.ss
ab5392ce902c0eb4541550d1f155f7a91d17b516
[]
no_license
ggem/alpa
ee35ffc91d9f4b1d540ce8b2207595813e488e5f
4f53b888b5a5b4ffebd220c6e0458442325fbff2
refs/heads/master
2019-01-02T03:12:17.899768
2005-01-04T03:43:12
2005-01-04T03:43:12
42,612,681
0
0
null
null
null
null
UTF-8
Scheme
false
false
396
ss
fibonacci.ss
;; ;; (alpa-imp (vars) (definitions (define (fib n) (vars fn fn-1 fn-2) (if (< n 2) n (begin (set! fn 1) (set! fn-1 1) (set! fn-2 0) (set! n (- n 2)) (while (> n 0) (set! n (- n 1)) (set! fn-2 fn-1) (set! fn-1 fn) (set! fn (+ fn-1 fn-2))) fn)))) (pretty-print (map fib '(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20))))
false
b596571c6e42a3d37a822ceeec6a471aa4ea9044
be06d133af3757958ac6ca43321d0327e3e3d477
/combination/combination.scm
78a450f2c790b1816862779f7552cac788d5c176
[]
no_license
aoyama-val/scheme_practice
39ad90495c4122d27a5c67d032e4ab1501ef9c15
f133d9326699b80d56995cb4889ec2ee961ef564
refs/heads/master
2020-03-13T12:14:45.778707
2018-04-26T07:12:06
2018-04-26T07:12:06
131,115,150
0
0
null
null
null
null
UTF-8
Scheme
false
false
965
scm
combination.scm
(define (prepend-all lis x) (map (lambda (y) (cons x y)) lis)) (display (prepend-all '((1) (2) (3)) 4)) (newline) : nCrの組み合わせ ; (car lis)を含む場合と含まない場合に分けて再帰 (define (combination lis n) (cond ((= n 0) '(())) ((< (length lis) n) '()) (else (append (prepend-all (combination (cdr lis) (- n 1)) (car lis)) (combination (cdr lis) n))))) (display (combination '() 1)) (newline) (display (combination '(1) 1)) (newline) (display (combination '(1 2) 1)) (newline) (display (combination '(1 2) 2)) (newline) (display (combination '(1 2 3) 1)) (newline) (display (combination '(1 2 3) 2)) (newline) (display (combination '(1 2 3) 3)) (newline) (define lis4 (iota 4 1)) (display lis4) (newline) (display (combination lis4 1)) (newline) (display (combination lis4 2)) (newline) (display (combination lis4 3)) (newline) (display (combination lis4 4)) (newline)
false
f95a02524acbf9b1072517ff4d5f7209161b6656
6b5ba856c09084ff8d528d284dd82a2bf44e7e72
/trunk/camille/camille/addressbook.scm
1385b5646479fcf9c38a8dab3da952b845dae6a4
[ "BSD-2-Clause" ]
permissive
BackupTheBerlios/hooch-svn
54b395b0fbe56cacf19ba17f4e6b3e05d79efd7d
8afaebc43eccf27f3f43859f5cf5d6dc06026b7e
refs/heads/master
2021-01-18T13:47:18.211730
2005-03-17T15:21:58
2005-03-17T15:21:58
40,803,167
0
0
null
null
null
null
UTF-8
Scheme
false
false
6,129
scm
addressbook.scm
;;; ;;; $Id: addressbook.scm 153 2005-02-25 08:16:12Z sjamaan $ ;;; ;;; addressbook.scm - Addressbook datastructure & manipulation functionality ;;; ;;; Copyright (c) 2005 Peter Bex and Vincent Driessen ;;; All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; 3. Neither the names of Peter Bex or Vincent Driessen nor the names of any ;;; contributors may be used to endorse or promote products derived ;;; from this software without specific prior written permission. ;;; ;;; THIS SOFTWARE IS PROVIDED BY PETER BEX AND VINCENT DRIESSEN AND CONTRIBUTORS ;;; ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED ;;; TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR ;;; PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS ;;; BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ;;; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ;;; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ;;; CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ;;; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ;;; POSSIBILITY OF SUCH DAMAGE. (define-record-type addressbook (make-addressbook defaults contacts groups) addressbook? (defaults addressbook-defaults) ; Just settings (contacts addressbook-contacts) (groups addressbook-groups)) (define-record-type contact (make-contact name ids settings) contact? (name contact-name) (ids contact-ids) (settings contact-settings)) (define-record-type contact-id (make-contact-id name settings) contact-id? (name contact-id-name) (settings contact-id-settings)) (define-record-type group (make-group name members settings) group? (name group-name) (members group-members) (settings group-settings)) (define-record-type struct (make-struct name settings) struct? (name struct-name) (settings struct-settings)) ;; ;; This could be implemented a bit simpler, but for consistency we're using ;; a record type anyway. ;; (define-record-type option (make-option name value) option? (name option-name) (value option-value)) ;; ;; We could use inheritance to make this a bit more elegant. But that would ;; mean using a complicated OO system or something. I prefer this. ;; (define (setting-name setting) (if (option? setting) (option-name setting) (struct-name setting))) (define (setting? thing) (or (option? thing) (struct? thing))) (define defaults? list?) (define settings? list?) (define (struct-add-detail detail struct) (cond ((not detail) struct) ((setting? detail) (struct-add-setting detail struct)) (else (error "Struct detail type not recognised" detail)))) (define (struct-add-setting setting struct) (make-struct (struct-name struct) (alist-cons (setting-name setting) setting (struct-settings struct)))) (define (defaults-add-entry entry defaults) (if (not entry) defaults (cons entry defaults))) (define (contact-add-detail detail contact) (cond ((not detail) contact) ((contact-id? detail) (contact-add-id detail contact)) ((setting? detail) (contact-add-setting detail contact)) (else (error "Contact detail type not recognised" detail)))) (define (contact-id-add-detail detail id) (cond ((not detail) id) ((setting? detail) (contact-id-add-setting detail id)) (else (error "id detail type not recognised" detail)))) (define (group-add-members members group) (if (not members) group (make-group (append members (group-members group)) (group-settings group)))) (define (addressbook-add-entry entry book) (cond ((not entry) book) ((group? entry) (addressbook-add-group entry book)) ((contact? entry) (addressbook-add-contact entry book)) ((defaults? entry) (addressbook-add-defaults entry book)) (else (error "addressbook entry type not recognised")))) (define (addressbook-add-defaults defaults book) (if (not defaults) book (make-addressbook (append defaults (addressbook-defaults book)) (addressbook-contacts book) (addressbook-groups book)))) (define (addressbook-add-contact contact book) (if (not contact) book (make-addressbook (addressbook-defaults book) (alist-cons (contact-name contact) contact (addressbook-contacts book)) (addressbook-groups book)))) (define (addressbook-add-group group book) (if (not group) book (make-addressbook (addressbook-defaults book) (addressbook-contacts book) (alist-cons (group-name group) group (addressbook-groups book))))) (define (contact-add-id id contact) (if (not id) contact (make-contact (contact-name contact) (alist-cons (contact-id-name id) id (contact-ids contact)) (contact-settings contact)))) (define (contact-add-setting setting contact) (if (not setting) contact (make-contact (contact-name contact) (contact-ids contact) (alist-cons (setting-name setting) setting (contact-settings contact))))) (define (contact-id-add-setting setting id) (if (not setting) id (make-contact-id (contact-id-name id) (alist-cons (setting-name setting) setting (contact-id-settings id))))) ;; XXX These need to be looked at (define find-contact assq) (define find-group assq) (define find-contact-id assq) (define find-setting assq)
false