id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
20,199
password-prompt.lisp
alessiostalla_portofino-cli-lisp/src/password-prompt.lisp
(in-package :portofino-cli) ;; Credits go to Raymond Wiker for this #+sbcl (require :sb-posix) #-capi (defun prompt-for-value (prompt) (format t "~&~a " prompt) (force-output) (read-line)) #+capi (defun prompt-for-value (prompt) (capi:prompt-for-string prompt)) #+(and sbcl (not win32)) (defun echo-off () (let ((tm (sb-posix:tcgetattr sb-sys:*tty*))) (setf (sb-posix:termios-lflag tm) (logandc2 (sb-posix:termios-lflag tm) sb-posix:echo)) (sb-posix:tcsetattr sb-sys:*tty* sb-posix:tcsanow tm))) #+(and sbcl (not win32)) (defun echo-on () (let ((tm (sb-posix:tcgetattr sb-sys:*tty*))) (setf (sb-posix:termios-lflag tm) (logior (sb-posix:termios-lflag tm) sb-posix:echo)) (sb-posix:tcsetattr sb-sys:*tty* sb-posix:tcsanow tm))) #-capi (defun prompt-for-passphrase (prompt) (format t "~&~a " prompt) (force-output) #+(and sbcl (not win32)) (echo-off) (unwind-protect (read-line) #+(and sbcl (not win32)) (echo-on))) #+capi (defun prompt-for-passphrase (prompt) (capi:prompt-for-string prompt :pane-class 'capi:password-pane))
1,094
Common Lisp
.lisp
35
28.257143
66
0.677143
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f69f9dad4faa193f4bf0f9fea380b993beedd0332ad7e6e64e45efff9fff6345
20,199
[ -1 ]
20,200
packages.lisp
alessiostalla_portofino-cli-lisp/src/packages.lisp
(defpackage :portofino (:use :cl :split-sequence) (:export #:action-types #:add-database-schema #:authentication-required #:copy-or-move-action #:create-action #:create-application #:create-database #:*default-connection-timeout* #:*default-portofino-url* #:delete-action #:http-error-url #:*latest-portofino-version* #:login #:log-message #:log-message-received #:log-message-severity #:not-authorized #:not-found #:remove-database #:resolve-file #:resolve-directory #:synchronize-database #:update-database)) (defpackage :portofino-cli (:use :cl :portofino) (:shadow #:login #:delete) (:export #:main)) (defpackage :portofino-cli-actions (:export #:create #:delete)) (defpackage :portofino-cli-dbs (:export #:create #:delete))
779
Common Lisp
.lisp
22
32.136364
99
0.71618
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6f80f4107fb7afbeda24f67f009b01925b58ee004133de58adda6e184ac3152e
20,200
[ -1 ]
20,201
portofino-cli.asd
alessiostalla_portofino-cli-lisp/portofino-cli.asd
(in-package :asdf) (defsystem "portofino-cli" :version "0.1.0" :author "Alessio Stalla" :license "AGPL" :depends-on ("cl-json" "cl-semver" "clingon" "drakma" "split-sequence") :components ((:module "src" :components ((:file "packages") (:file "portofino") (:file "password-prompt") (:file "cli")))) :description "Command-line interface to a Portofino application" :in-order-to ((test-op (test-op "portofino-cli/tests")))) #+sbcl (defsystem "portofino-cli/executable" :version "0.1.0" :author "Alessio Stalla" :license "AGPL" :depends-on ("portofino-cli") :components ((:module "src" :components ((:file "binary-sbcl")))) :build-operation "program-op" :build-pathname "portofino" :entry-point "portofino-cli:main" :description "Command-line interface to a Portofino application") #-sbcl (error "Only SBCL is supported for now") (defsystem "portofino-cli/tests" :author "Alessio Stalla" :license "AGPL" :depends-on ("portofino-cli" "rove") :components ((:module "tests" :components ((:file "main")))) :description "Test system for portofino-cli" :perform (test-op (op c) (symbol-call :rove :run c)))
1,179
Common Lisp
.asd
31
34.419355
110
0.684164
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
576678aaf993cd8609e650f56b8a2f0e30faea8f616f5c249595113136887d9a
20,201
[ -1 ]
20,202
portofino-cli-osx-app.asd
alessiostalla_portofino-cli-lisp/portofino-cli-osx-app.asd
(asdf:defsystem "portofino-cli-osx-app" :defsystem-depends-on (:deploy) :build-operation "osx-app-deploy-op" :build-pathname "portofino" :entry-point "portofino-cli:main" :version "0.1.0" :author "Alessio Stalla" :license "AGPL" :depends-on ("portofino-cli") :description "Portofino CLI OSX app")
316
Common Lisp
.asd
10
28.7
39
0.72459
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c327889b1e845d00a0f561b0efff3679ef92489ef4c4e290833ab6f58ce79e9e
20,202
[ -1 ]
20,203
portofino-cli-deb.asd
alessiostalla_portofino-cli-lisp/portofino-cli-deb.asd
(asdf:defsystem "portofino-cli-deb" :defsystem-depends-on (:linux-packaging) :class "linux-packaging:deb" :build-operation "linux-packaging:build-op" :package-name "portofino-cli" :build-pathname "portofino-cli" :entry-point "portofino-cli:main" :version "0.1.0" :author "Alessio Stalla" :license "AGPL" :depends-on ("portofino-cli") :description "Portofino CLI Debian package")
401
Common Lisp
.asd
12
30.583333
46
0.74036
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f7a79b783114e6f46ebec3fcebc8a98028ab1d6aaaeb4344837f9b775f064c08
20,203
[ -1 ]
20,216
linux-ci.yaml
alessiostalla_portofino-cli-lisp/.github/workflows/linux-ci.yaml
name: Build Linux executable on: push: jobs: build-executable: name: Build Linux executable runs-on: ubuntu-latest env: LISP: sbcl steps: - uses: actions/checkout@v3 # Caching - see https://github.com/40ants/setup-lisp - name: Grant All Perms to Make Cache Restoring Possible run: | sudo mkdir -p /usr/local/etc/roswell sudo chown "${USER}" /usr/local/etc/roswell # Here the ros binary will be restored: sudo chown "${USER}" /usr/local/bin - name: Get Current Month id: current-month run: | echo "value=$(date -u "+%Y-%m")" >> $GITHUB_OUTPUT - name: Cache Roswell Setup id: cache uses: actions/cache@v3 env: cache-name: cache-roswell with: path: | /usr/local/bin/ros ~/.cache/common-lisp/ ~/.roswell /usr/local/etc/roswell .qlot key: "${{ steps.current-month.outputs.value }}-${{ env.cache-name }}-${{ runner.os }}-${{ hashFiles('qlfile.lock') }}" - name: Restore Path To Cached Files run: | echo $HOME/.roswell/bin >> $GITHUB_PATH echo .qlot/bin >> $GITHUB_PATH if: steps.cache.outputs.cache-hit == 'true' - uses: 40ants/setup-lisp@v2 if: steps.cache.outputs.cache-hit != 'true' with: asdf-system: portofino-cli qlfile-template: | dist ultralisp http://dist.ultralisp.org - name: Prepare system run: | sudo apt-get update -qq; sudo apt-get install -y rubygems sbcl; sudo gem install --no-document fpm; git clone --depth=1 --branch=sbcl-2.0.10 https://github.com/sbcl/sbcl.git ~/sbcl &> /dev/null; - name: Build executable run: | ros use sbcl/system; PATH=~/.roswell/bin:$PATH ros run -- --eval "(progn (asdf:load-asd \"`pwd`/portofino-cli.asd\") (ql:quickload :portofino-cli) (asdf:make :portofino-cli/executable) (quit))" chmod +x ./portofino - name: Upload artifact uses: actions/upload-artifact@v3 with: name: portofino-cli-linux path: portofino if-no-files-found: error
2,284
Common Lisp
.l
64
26.734375
156
0.571429
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
66262c05a159e0b8795bd6938e2d1292e5880603d36824360f916c8954950a98
20,216
[ -1 ]
20,217
osx-ci.yaml
alessiostalla_portofino-cli-lisp/.github/workflows/osx-ci.yaml
name: Build OSX Application on: push: jobs: build-executable: name: Build OSX Application runs-on: macOS-latest steps: - uses: actions/checkout@v3 - uses: 40ants/setup-lisp@v2 with: asdf-system: portofino-cli - name: Build executable run: | PATH="~/.roswell/bin:$PATH" ros run -- --eval "(progn (asdf:load-asd \"`pwd`/portofino-cli.asd\") (ql:quickload :portofino-cli) (asdf:make :portofino-cli/executable) (quit))" chmod +x ./portofino - name: Upload artifact uses: actions/upload-artifact@v3 with: name: portofino-cli-osx path: portofino if-no-files-found: error
708
Common Lisp
.l
23
23.565217
156
0.609649
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
277c9fd28fc4cf4ce2bf4ebab256a45c04ee405cbb7b4a09566e9b48c9173fbf
20,217
[ -1 ]
20,218
windows-ci.yml
alessiostalla_portofino-cli-lisp/.github/workflows/windows-ci.yml
name: CI (Windows) on: push: jobs: build-executable: name: Build Windows executable runs-on: windows-2019 steps: - uses: actions/checkout@v3 - name: Install Roswell env: LISP: sbcl-bin ROSWELL_INSTALL_DIR: /c/roswell shell: bash run: | PATH="/c/roswell/bin:$PATH" curl -L https://raw.githubusercontent.com/fukamachi/roswell/windows-source-registry-settings/scripts/install-for-ci.sh | sh - name: Build executable shell: bash run: | PATH="~/.roswell/bin:/c/roswell/bin:$PATH" ros run -- --eval "(progn (asdf:load-asd \"`pwd`/portofino-cli.asd\") (ql:quickload :portofino-cli) (asdf:make :portofino-cli/executable) (quit))" - name: Upload artifact uses: actions/upload-artifact@v3 with: name: portofino-cli-windows path: portofino.exe if-no-files-found: error
946
Common Lisp
.l
28
26.071429
156
0.615721
alessiostalla/portofino-cli-lisp
2
0
1
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
20a9bdf0a6c39c35487279cddfdb544f5fc3eb162f85294dc2e1b371f9cef128
20,218
[ -1 ]
20,233
4-4.lisp
LeZheng_l-lisp-demo/SICP_Exercise/4-4.lisp
;;; 4.55 ;;a) (supervisor ?p (Bitdiddle Ben)) ;;b) (job ?p (accounting . ?type)) ;;c) (address ?p (Slumerville . ?address)) ;;; 4.56 ;;a) (and (supervisor ?p (Bitdiddle Ben)) (address ?p ?where)) ;;b) (and (salary (Bitdiddle Ben) ?b-salary) (salary ?p ?salary) (lisp-value > ?b-salary ?salary)) ;;c) (and (supervisor ?p ?boss) (not (job ?boss (computer . ?type))) (job ?boss ?b-job)) ;;; 4.57 (rule (replace-dy ?a ?b) (and (job ?a ?s-job) (job ?b ?s-job) (not (same $a $b)))) ;;a) (replace-dy (D.Fect Cy) ?p) ;;b) (and (salary ?a ?a-salary) (salary ?b ?b-salary) (lisp-value > ?a-salary ?b-salary) (replace-dy ?a ?b)) ;;; 4.58 (rule (dawan ?a ?p) (and (job ?a (?p .)) (supervisor ?a ?boss) (job ?boss (?p .)))) ;;; 4.59 ;;a) (meeting ?p (Friday ?t)) ;;b) (rule (meeting-time ?person ?day-and-time) (or (meeting whole-company ?day-and-time) (job ?person (?p .)) (meeting ?p ?day-and-time))) ;;c) (meeting-time (Haccker Alyssa P) (Wednesday .)) ;;; 4.60 ;;因为两种都满足条件 ;;对名称进行字母排序 ;;; 4.61 ;; ((2 3) next-to 4 in (1 (2 3) 4)) ;; (1 next-to (2 3) in (1 (2 3) 4)) ;; (3 next-to 1 in (2 1 3 1)) ;; (2 next-to 1 in (2 1 3 1)) ;;; 4.62 (rule (last-pair (?x) (?x))) (rule (last-pair (?a . ?b) ?x) (last-pair ?v ?x)) ;;; 4.63 (rule (grand-son ?s ?g) (and (son ?s ?f) (son ?f ?g))) (rule (son ?s ?m) (and (wife ?w ?m) (son ?s ?w))) ;;; 4.64 ;; outranked-by 的递归不会终止 ;;; 4.65 ;; 因为这里有4种数据满足wheel的情况 ;;; 4.66 ;; 结果会重复累加,添加去重语句 ;;; 4.67 TODO ;;; 4.68 (rule (reverse () ())) (rule (reverse (?x . ?y) ?z) (and (reverse ?y ?u) (append-to-form ?u (?x) ?z))) ;;; 4.69 TODO ;;;; 4.4.4 (defparameter input-prompt ";;; Query input:") (defparameter output-prompt ";;; Query Result:") (defun query-driver-loop () (prompt-for-input input-prompt) (let ((q (query-syntax-process (read)))) (cond ((assertion-to-be-added? q) (add-rule-or-assertion! (add-assertion-body q)) (format t "Assertion added to data base.") (query-driver-loop)) (t (format t "~%~A" output-prompt) (display-stream (stream-map (lambda (frame) (instantiate q frame (lambda (v f) (contract-question-mark v)))) (qeval q (singleton-stream '())))) (query-driver-loop))))) (defun instantiate (exp frame unbound-var-handler) (labels ((inner-copy (exp) (cond ((var? exp) (let ((binding (binding-in-frame exp frame))) (if binding (inner-copy (binding-value binding)) (funcall unbound-var-handler exp frame)))) ((pair? exp) (cons (inner-copy (car exp)) (inner-copy (cdr exp)))) (t exp)))) (inner-copy exp))) (defun qeval (query frame-stream) (let ((qproc (get 'qeval (type query)))) (if qproc (funcall qproc (contents query) frame-stream) (simple-query query frame-stream)))) (defun simple-query (query-pattern frame-stream) (stream-flatmap (lambda (frame) (stream-append-delayed (find-assertions query-pattern frame) (delay (apply-rules query-pattern frame)))) frame-stream)) (defun conjoin (conjuncts frame-stream) (if (empty-conjunction? conjuncts) frame-stream (conjoin (rest-conjuncts conjuncts) (qeval (first-conjunct conjuncts) frame-stream)))) (setf (get 'qeval 'and) #'conjoin) (defun disjoin (disjuncts frame-stream) (if (empty-disjunction? disjuncts) the-empty-stream (interleave-delayed (qeval (first-disjunct disjuncts) frame-stream) (delay (disjoin (rest-disjuncts disjuncts) frame-stream))))) (setf (get 'qeval 'or) #'disjoin) (defun negate (operands frame-stream) (stream-flatmap (lambda (frame) (if (stream-null? (qeval (negated-query operands) (singleton-stream frame))) (singleton-stream frame) the-empty-stream)) frame-stream)) (setf (get 'qeval 'not) #'negate) (defun lisp-value (call frame-stream) (stream-flatmap (lambda (frame) (if (execute (instantiate call frame (lambda (v f) (error "Unknown pat var -- LISP-VALUE" v)))) (singleton-stream frame) the-empty-stream)) frame-stream)) (setf (get 'qeval 'lisp-value) #'lisp-value) (defun execute (exp) (apply (eval (predicate exp) user-initial-environment) (args exp))) (defun always-true (ignore frame-stream) frame-stream) (setf (get 'qeval 'always-true) #'always-true) (defun find-assertions (pattern frame) (stream-flatmap (lambda (datum) (check-an-assertion datum pattern frame)) (fetch-assertions pattern frame))) (defun check-an-assertion (assertion query-pat query-frame) (let ((match-result (pattern-match query-pat assertion query-frame))) (if (eql match-result 'failed) the-empty-stream (singleton-stream match-result)))) (defun pattern-match (pat dat frame) (cond ((eql frame 'failed) 'failed) ((equalp pat dat) frame) ((var? pat) (extend-if-consistent pat dat frame)) ((and (pair? pat) (pair? dat)) (pattern-match (cdr pat) (cdr dat) (pattern-match (car pat) (car dat) frarme))) (t 'failed))) (defun extend-if-consistent (var dat frame) (let ((binding (binding-in-frame var frame))) (if binding (pattern-match (binding-value binding) dat frame) (extend var dat frame)))) (defun apply-rules (pattern frame) (stream-flatmap (lambda (rule) (apply-a-rule rule pattern frame)) (fetch-rules pattern frame))) (defun apply-a-rule (rule query-pattern query-frame) (let ((clean-rule (rename-variables-in rule))) (let ((unify-result (unify-match query-pattern (conclusion clean-rule) query-frame))) (if (eql unify-result 'failed) the-empty-stream (qeval (rule-body clean-rule) (singleton-stream unify-result)))))) (defun rename-variables-in (rule) (let ((rule-application-id (new-rule-application-id))) (labels ((tree-walk (exp) (cond ((var? exp) (make-new-variable exp rule-application-id)) ((pair? exp) (cons (tree-walk (car exp)) (tree-walk (cdr exp)))) (t exp)))) (tree-walk rule)))) (defun unify-match (p1 p2 frame) (cond ((eql frame 'failed) 'failed) ((equalp p1 p2) frame) ((var? p1) (extend-if-possible p1 p2 frame)) ((var? p2) (extend-if-possible p2 p1 frame)) ((and (pair? p1) (pair? p2)) (unify-match (cdr p1) (cdr p2) (unify-match (car p1) (car p2) frame))) (t 'failed))) (defun extend-if-possible (var val frame) (let ((binding (binding-in-frame var frame))) (cond (binding (unify-match (binding-value binding) val frame)) ((var? val) (let ((binding (binding-in-frame val frame))) (if binding (unify-match var (binding-value binding) frame) (extend var val frame)))) ((depends-on? val var frame) 'failed) (t (extend var val frame))))) (defun depends-on? (exp var frame) (labels ((tree-walk (e) (cond ((var? e) (if (equalp var e) t (let ((b (binding-in-frame e frame))) (if b (tree-walk (binding-value b)) nil)))) ((pair? e) (or (tree-walk (car e)) (tree-walk (cdr e)))) (t nil)))) (tree-walk exp))) (defparameter THE-ASSERTIONS the-empty-stream) (defun fetch-assertions (pattern frame) (if (use-index? pattern) (get-indexed-assertions pattern) (get-all-assertions))) (defun get-all-assertions () THE-ASSERTIONS) (defun get-indexed-assertions (pattern) (get-stream (index-key-of pattern) 'assertion-stream)) (defun get-stream (key1 key2) (let ((s (get key1 key2))) (if s s the-empty-stream))) (defparameter THE-RULES the-empty-stream) (defun fetch-rules (pattern frame) (if (use-index? pattern) (get-indexed-rules pattern) (get-all-rules))) (defun get-all-rules () THE-RULES) (defun get-indexed-rules (pattern) (stream-append (get-stream (index-key-of pattern) 'rule-stream) (get-stream '? 'rule-stream))) (defun add-rule-or-assertion! (assertion) (if (rule? assertion) (add-rule! assertion) (add-assertion! assertion))) (defun add-assertion! (assertion) (store-assertion-in-index assertion) (let ((old-assertions THE-ASSERTIONS)) (setf THE-ASSERTIONS (cons-stream assertion old-assertions)) 'ok)) (defun add-rule! (rule) (store-rule-in-index rule) (let ((old-rules THE-RULES)) (setf THE-RULES (cons-stream rule old-rules)) 'ok)) (defun store-assertion-in-index (assertion) (if (indexable? assertion) (let ((key (index-key-of assertion))) (let ((current-assertion-stream (get-stream key 'assertion-stream))) (setf (get 'assertion-stream key) (cons-stream assertion current-assertion-stream)))))) (defun store-rule-in-index (rule) (let ((pattern (conclusion rule))) (if (indexable? pattern) (let ((current-rule-stream (get-stream key 'rule-stream))) (setf (get 'rule-stream key) (cons-stream rule current-rule-stream)))))) (defun indexable? (pat) (or (constant-symbol? (car pat)) (var? (car pat)))) (defun index-key-of (pat) (let ((key (car pat))) (if (var? key) '? key))) (defun use-index? (pat) (constant-symbol? (car pat))) ;;; 4.70 ;; 保存旧的值 TODO (defun stream-append-delayed (s1 delay-s2) (if (stream-null? s1) (force delay-s2) (cons-stream (stream-car s1) (stream-append-delayed (stream-cdr s1) delay-s2)))) (defun interleave-delayed (s1 delay-s2) (if (stream-null? s1) (force delay-s2) (cons-stream (stream-car s1) (stream-append-delayed (stream-cdr s1) (interleave-delayed (force delay-s2) (delay (stream-cdr s1))))))) (defun stream-flatmap (proc s) (flatten-stream (stream-map proc s))) (defun flatten-stream (stream) (if (stream-null? stream) the-empty-stream (interleave-delayed (stream-car stream) (delay (flatten-stream (stream-cdr stream)))))) (defun singleton-stream (x) (cons-stream x the-empty-stream)) (defun type (exp) (if (pair? exp) (car exp) (error "Unknown expression TYPE" exp))) (defun contents (exp) (if (pair? exp) (cdr exp) (error "Unknown expression CONTENTS" exp))) (defun assertion-to-be-added? (exp) (eql (type exp) 'assert!)) (defun add-assertion-body (exp) (car (contents exp))) (defun empty-conjunction? (exps) (null exps)) (defun first-conjunct (exps) (car exps)) (defun rest-conjuncts (exps) (cdr exps)) (defun empty-disjunction? (exps) (null exps)) (defun first-disjunct (exps) (car exps)) (defun rest-disjuncts (exps) (cdr exps)) (defun negated-query (exps) (car exps)) (defun predicate (exps) (car exps)) (defun args (exps) (cdr exps)) (defun rule? (statement) (tagged-list? statement 'rule)) (defun conclusion (rule) (cadr rule)) (defun rule-body (rule) (if (null (cddr rule)) '(always-true) (caddr rule))) (defun query-syntax-process (exp) (map-over-symbols #'expand-question-mark exp)) (defun (map-over-symbols proc exp) (cond ((pair? exp) (cons (map-over-symbols proc (car exp)) (map-over-symbols proc (cdr exp)))) ((symbolp exp) (proc exp)) (t exp))) (defun expand-question-mark (symbol) (let ((chars (symbol->string symbol))) (if (string= (substring chars 0 1) "?") (list '? (string->symbol (substring chars 1 (string-length chars)))) symbol))) (defun var? (exp) (tagged-list? exp '?)) (defun constant-symbol? (exp) (symbolp exp)) (defvar rule-counter 0) (defun new-rule-application-id () (setf rule-counter (+ 1 rule-counter)) rule-counter) (defun make-new-variable (var rule-application-id) (cons '? (cons rule-application-id (cdr var)))) (defun contract-question-mark (variable) (string->symbol (string-append "?" (if (numberp (cadr variable)) (string-append (symbol->string (caddr variable)) "-" (number->string (cadr variable))) (symbol->string (cadr variable)))))) (defun make-binding (variable value) (cons variable value)) (defun binding-variable (binding) (car binding)) (defun binding-value (binding) (cdr binding)) (defun binding-in-frame (variable frame) (assoc variable frame)) (defun extend (varialbe value frame) (cons (make-binding variable value) frame)) ;;; 剩余练习 TODO
12,269
Common Lisp
.lisp
374
28.534759
139
0.651701
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
23c8b103f82c489c92834b0470273c06ac23163a23263fd49e253e7cad82cda0
20,233
[ -1 ]
20,234
chapter-two.lisp
LeZheng_l-lisp-demo/SICP_Exercise/chapter-two.lisp
(defun make-rat (n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (defun numer (x) (car x)) (defun denom (x) (cdr x)) (defun add-rat (x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (defun sub-rat (x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (defun mul-rat (x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (defun div-rat (x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (defun equal-rat? (x y) (= (* (numer x) (denom y)) (* (numer y) (denom x)))) (defun print-rat (x) (format t "~A/~A" (numer x) (denom x))) ;;;exercice 2.1 (defun make-rat (n d) (let ((g (gcd n d))) (cond ((and (< n 0) (< d 0)) (cons (/ (- n) g) (/ (- d) g))) ((and (< n 0) (> d 0)) (cons (/ n g) (/ d g))) ((and (> n 0) (< d 0)) (cons (/ (- n) g) (/ (- d) g))) (t (cons (/ n g) (/ d g)))))) ;;;exercice 2.2 (defun make-point (x y) (cons x y)) (defun x-point (point) (car point)) (defun y-point (point) (cdr point)) (defun make-segment (start end) (cons start end)) (defun start-segment (segment) (car segment)) (defun end-segment (segment) (cdr segment)) (defun midpoint-segment (segment) (let ((start (start-segment segment)) (end (end-segment segment))) (make-point (/ (+ (x-point start) (x-point end)) 2) (/ (+ (y-point start) (y-point end)) 2)))) (defun print-point (point) (format t "(~A,~A)~%" (x-point point) (y-point point))) ;;;exercice 2.3 (defun make-rect (left-top-point right-bottom-point) (cons left-top-point right-bottom-point)) (defun left-top-rect (rect) (car rect)) (defun right-bottom-rect (rect) (cdr rect)) (defun width-rect (rect) (- (x-point (right-bottom-rect rect)) (x-point (left-top-rect rect)))) (defun height-rect (rect) (- (y-point (right-bottom-rect rect)) (y-point (left-top-rect rect)))) (defun perimeter-rect (rect) (+ (* 2 (width-rect rect)) (* 2 (height-rect rect)))) (defun area-rect (rect) (* (width-rect rect) (height-rect rect))) (defun make-rect (left-top-point width height) (cons left-top-point (cons width height))) (defun width-rect (rect) (car (cdr rect))) (defun height-rect (rect) (cdr (cdr rect))) ;;;exercice 2.4 (defun cons-1 (x y) (lambda (m) (funcall m x y))) (defun car-1 (z) (funcall z (lambda (p q) p))) (defun cdr-1 (z) (funcall z (lambda (p q) q))) ;;;exercice 2.5 (defun cons-2 (x y) (* (expt 2 x) (expt 3 y))) (defun car-2 (z) (if (= 0 (rem z 2)) (1+ (car-2 (/ z 2))) 0)) (defun cdr-2 (z) (if (= 0 (rem z 3)) (1+ (car-2 (/ z 3))) 0)) ;;;exercice 2.6 (defun zero () (lambda (f) (lambda (x) x))) (defun add-1 (n) (lambda (f) (lambda (x) (funcall f (funcall (funcall n f) x))))) (defun one () (lambda (f) (lambda (x) (funcall f x)))) (defun two () (lambda (f) (lambda (x) (funcall f (funcall f x))))) (defun add (x y) (lambda (f) (lambda (x) (funcall m f (funcall n f x))))) ;;;exercice 2.7 (defun add-interval (x y) (make-interval (+ (lower-bound x) (lower-bound y)) (+ (upper-bound x) (upper-bound y)))) (defun mul-interval (x y) (let ((p1 (* (lower-bound x) (lower-bound y))) (p2 (* (lower-bound x) (upper-bound y))) (p3 (* (upper-bound x) (lower-bound y))) (p4 (* (upper-bound x) (upper-bound y)))) (make-interval (min p1 p2 p3 p4) (max p1 p2 p3 p4)))) (defun div-interval (x y) (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y))))) (defun make-interval (x y) (cons x y)) (defun upper-bound (x) (cdr x)) (defun lower-bound (x) (car x)) ;;;exercice 2.8 (defun sub-interval (x y) (make-interval (- (lower-bound x) (upper-bound y)) (- (upper-bound x) (lower-bound y1)))) ;;;exercice 2.9 TODO ;;;exercice 2.10 (defun div-interval (x y) (if (and (>= (upper-bound y) 0) (<= (lower-bound y) 0)) (error "y's upper-bound and lower-bound contains 0") (mul-interval x (make-interval (/ 1.0 (upper-bound y)) (/ 1.0 (lower-bound y)))))) ;;;exercice 2.11 (defun mul-interval (x y) (cond ((and (plusp (lower-bound x)) (plusp (lower-bound y))) (make-interval (* (lower-bound x) (lower-bound y) (upper-bound x) (upper-bound y)))) ((and (minusp (upper-bound x)) (minusp (upper-bound y))) (make-interval (* (lower-bound x) (lower-bound y) (upper-bound x) (upper-bound y)))) ((and (plusp (lower-bound x)) (minusp (upper-bound y))) (make-interval (* (upper-bound x) (lower-bound y)) (* (lower-bound x) (upper-bound y)))) ((and (minusp (upper-bound x)) (plusp (lower-bound y))) (make-interval (* (lower-bound x) (upper-bound y)) (* (upper-bound x) (lower-bound y)))) ;;;TODO 剩余5种情况 )) ;;;exercice 2,12 (defun make-center-percent (c p) (make-interval (- c (* c p)) (+ c (* c p)))) (defun percent (i) (/ (/ (- (upper-bound i) (lower-bound i)) 2) (center i))) (defun center (i) (/ (+ (upper-bound i) (lower-bound i)) 2)) ;;;exercice 2.13 TODO ;;;exercice 2.14 TODO ;;;exercice 2.15 TODO ;;;exercice 2.16 TODO ;;;; 2.2 (defun list-ref (l n) (if (= n 0) (car l) (list-ref (cdr l) (- n 1)))) (defun my-length (l) (labels ((iter (l c) (if (null l) c (iter (cdr l) (1+ c))))) (iter l 0))) (defun my-append (l1 l2) (if (null l1) l2 (cons (car l1) (my-append (cdr l1) l2)))) ;;;exercice 2.17 (defun last-pair (l) (if (null (cdr l)) (car l) (last-pair (cdr l)))) ;;;exercice 2.18 (defun my-reverse (l) (labels ((iter (l r) (if (null l) r (iter (cdr l) (cons (car l) r))))) (iter l nil))) ;;;exercice 2.19 (defvar us-coins (list 50 25 10 5 1)) (defvar uk-coins (list 100 50 20 10 5 2 1 0.5)) (defun cc (amount coin-values) (cond ((= amount 0) 1) ((or (< amount 0) (no-more? coin-values)) 0) (t (+ (cc amount (exception-first-denomination coin-values)) (cc (- amount (first-denomination coin-values)) coin-values))))) (defun first-denomination (coins) (car coins)) (defun exception-first-denomination (coins) (cdr coins)) (defun no-more? (coins) (null coins)) ; 调换顺序不影响,因为这个程序在枚举所有币种的组合 ;;;exercice 2.20 (defun same-parity (&rest nums) (cond ((null nums) nil) (t (let ((first-odd? (oddp (first nums))) (result '())) (dolist (num (reverse nums) result);TODO dolist (if (equal first-odd? (oddp num)) (push num result))))))) ;;;exercice 2,21 (defun square-list (items) (if (null items) nil (cons (expt (car items) 2) (square-list (cdr items))))) (defun square-list (items) (mapcar (lambda (x) (expt x 2)) items)) ;;;exercice 2.22 ; cons 的构造决定了 ;;;exercice 2.23 (defun for-each (proc items) (when (not (null items)) (funcall proc (car items)) (for-each proc (cdr items)))) ;;;; 2.2.2 (defun count-leaves (tree) (cond ((null tree) 0) ((atom tree) 1) (t (+ (count-leaves (car tree)) (count-leaves (cdr tree)))))) ;;;exercice 2.24 ;略 ;;;exercice 2.25 (car (cdr (car (cdr (cdr '(1 3 (5 7) 9)))))) (car (car '((7)))) (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr (car (cdr '(1 (2 (3 (4 (5 (6 7)))))))))))))))))) ;;;exercice 2.26 (setf x (list 1 2 3)) (setf y (list 4 5 6)) (append x y) ; => (1 2 3 4 5 6) (cons x y) ; => ((1 2 3) 4 5 6) (list x y) ; => ((1 2 3) (4 5 6)) ;;;exercice 2.27 (defun deep-reverse (tree) (labels ((iter (l r) (cond ((null l) r) ((atom l) l) (t (iter (cdr l) (cons (iter (car l) nil) r)))))) (iter tree nil))) ;;;exercice 2.28 (defun fringe (tree) (cond ((null tree) nil) ((atom tree) (list tree)) (t (labels ((iter (l r) (cond ((null l) r) (t (iter (cdr l) (append r (fringe (car l)))))))) (iter tree nil))))) ;;;exercice 2.29 (defun make-mobile (left right) (list left right)) (defun make-branch (length struct) (list length struct)) (defun left-branch (mobile) (first mobile)) (defun right-branch (mobile) (second mobile)) (defun branch-length (branch) (first branch)) (defun branch-struct (branch) (second branch)) (defun total-weight (mobile) (labels ((branch-weight (branch) (if (numberp (branch-struct branch)) (branch-struct branch) (total-weight (branch-struct branch))))) (+ (branch-weight (left-branch mobile)) (branch-weight (right-branch mobile))))) (defun balancep (mobile) (and (= (* (branch-length (left-branch mobile)) (total-weight (left-branch mobile))) (* (branch-length (right-branch mobile)) (total-weight (right-branch mobile)))) (or (numberp (branch-struct (left-branch mobile))) (balancep (branch-struct (left-branch mobile)))) (or (numberp (branch-struct (right-branch mobile))) (balancep (branch-struct (right-branch)))))) (defun make-mobile (left right) (cons left right)) (defun make-branch (length struct) (cons length struct)) (defun left-branch (mobile) (car mobile)) (defun right-branch (mobile) (cdr mobile)) (defun branch-length (branch) (car branch)) (defun branch-struct (branch) (cdr branch)) ;;;exercice 2.30 (defun square-tree (tree) (cond ((null tree) nil) ((atom tree) (expt tree 2)) (t (cons (square-tree (car tree)) (square-tree (cdr tree)))))) (defun square-tree (tree) (mapcar (lambda (sub-tree) (if (atom sub-tree) (expt sub-tree 2) (square-tree sub-tree))) tree)) ;;;exercice 2.31 (defun tree-map (tree operator) (cond ((null tree) nil) ((atom tree) (funcall operator tree)) (t (cons (tree-map (car tree) operator) (tree-map (cdr tree) operator))))) ;;;exercice 2.32 (defun subsets (s) (if (null s) (list nil) (let ((rest (subsets (cdr s)))) (append rest (mapcar (lambda (x) (cons (car s) x)) rest))))) ;;;; 2.2.3 (defun filter (predicate seq) (cond ((null seq) nil) ((funcall predicate (car seq)) (cons (car seq) (filter predicate (cdr seq)))) (t (filter predicate (cdr seq))))) (defun accumulate (op initial sequence) (if (null sequence) initial (funcall op (car sequence) (accumulate op initial (cdr sequence))))) ;;;exercice 2.33 (defun my-map (p seq) (accumulate (lambda (x y) (cons (funcall p x) y)) nil seq)) (defun my-append (seq1 seq2) (accumulate #'cons seq2 seq1)) (defun my-length (seq) (accumulate (lambda (x y) (1+ y)) 0 seq)) ;;;exercice 2.34 (defun horner-eval (x seq) (accumulate (lambda (this-coeff higher-terms) (+ (* x higher-terms) this-coeff)) 0 seq)) ;;;exercice 2.35 (defun count-leaves (tree) (accumulate (lambda (x y) (+ x y)) 0 (my-map (lambda (x) (if (atom x) 1 (count-leaves x))) tree))) ;;;exercice 2.36 (defun accumulate-n (op initial seqs) (if (null (car seqs)) nil (cons (accumulate op initial (my-map #'car seqs)) (accumulate-n op initial (my-map #'cdr seqs))))) ;;;exercice 2.37 TODO 未消化 (defun dot-product (v w) (accumulate #'+ 0 (my-map #'* v w))) (defun matrix-*-vector (m v) (my-map (lambda (col) (dot-product col v)) m)) (defun transpose (m) (accumulate-n #'cons '() m)) (defun matrix-*-matrix (m n) (let ((trans-n (transpose n))) (my-map (lambda (col-of-m) (matrix-*-vector trans-n col-of-m)) m))) ;;;exercice 2.38 (defun fold-left (op initial seq) (labels ((iter (result rest) (if (null rest) result (iter (funcall op result (car rest)) (cdr rest))))) (iter initial seq))) (defun fold-right (op initial sequence) (if (null sequence) initial (funcall op (car sequence) (fold-right op initial (cdr sequence))))) (fold-right #'/ 1 (list 1 2 3)) ;=> 3/2 (fold-left #'/ 1 (list 1 2 3)) ;=> 1/6 (fold-right #'list nil (list 1 2 3)) ;=>(1 (2 (3 1))) (fold-left #'list nil (list 1 2 3)) ;=>(((1 1) 2) 3) ;;两个函数要产生一样的结果,那么op得符合结合率 ;;;exercice 2.39 (defun my-reverse-1 (seq) (fold-right (lambda (x y) (append y (list x))) nil seq)) (defun my-reverse-2 (seq) (fold-left (lambda (x y) (cons y x)) nil seq)) ;;;;嵌套映射 (defun enumerate-interval (i n) (if (> i n) nil (cons i (enumerate-interval (1+ i) n)))) (defun flatmap (proc seq) (accumulate #'append nil (my-map proc seq))) (load "chapter-one.lisp") (defun prime-sum? (pair) (prime? (+ (car pair) (cadr pair)))) (defun make-pair-sum (pair) (list (car pair) (cadr pair) (+ (car pair) (cadr pair)))) (defun prime-pair-sum (n) (my-map #'make-pair-sum (filter #'prime-sum? (flatmap (lambda (i) (my-map (lambda (j) (list i j)) (enumerate-interval 1 (- i 1)))) (enumerate-interval 1 n))))) (defun permutations (s) (if (null s) (list nil) (flatmap (lambda (x) (my-map (lambda (p) (cons x p)) (permutations (remove x s)))) s))) ;;;exercice 2.40 (defun unique-pairs (n) (flatmap (lambda (x) (my-map (lambda (i) (list x i)) (enumerate-interval 1 (- x 1)))) (enumerate-interval 1 n))) (defun prime-pair-sum (n) (my-map #'make-pair-sum (filter #'prime-sum? (unique-pairs n)))) ;;;exercice 2.41 (defun unique-triple (n) (flatmap (lambda (x) (my-map (lambda (i) (cons x i)) (unique-pairs (- x 1)))) (enumerate-interval 1 n))) (defun enum-3-tuple (n s &optional (index 0)) (filter (lambda (a) (= s (+ (first a) (second a) (third a)))) (unique-triple n))) ;;;exercice 2.42 (defvar empty-board '()) (defun adjoin-position (new-row k rest-of-queens) (if (null rest-of-queens) (list new-row) (append rest-of-queens (list new-row)))) (defun safe? (k positions) (let ((x (elt positions (1- k)))) (dotimes (i (length positions)) (if (and (/= i (1- k)) (equal x (elt positions i))) (return-from safe? nil))) t)) (defun queens (board-size) (labels ((queen-cols (k) (if (= k 0) (list empty-board) (filter (lambda (pos) (safe? k pos)) (flatmap (lambda (rest-of-queens) (my-map (lambda (new-row) (adjoin-position new-row k rest-of-queens)) (enumerate-interval 1 board-size))) (queen-cols (- k 1))))))) (queen-cols board-size))) ;;;exercice 2.43 (defun queens (board-size) (labels ((queen-cols (k) (if (= k 0) (list empty-board) (filter (lambda (pos) (safe? k pos)) (flatmap (lambda (new-row) (format t "~A~%" new-row) (my-map (lambda (rest-of-queens) (adjoin-position new-row k rest-of-queens)) (queen-cols (- k 1)))) (enumerate-interval 1 board-size)))))) (queen-cols board-size))) ;;;;example 2.2.4 (defun transform-painter (painter origin corner1 corner2) (lambda (frame) (let ((m (frame-coord-map frame))) (let ((new-origin (m origin))) (funcall painter (make-frame new-origin (sub-vert (funcall m corner1) new-origin) (sub-vert (funcall m corner2) new origin))))))) (defun beside (p1 p2) (let ((split-point (make-vert 0.5 0.0))) (let ((paint-left (transform-painter p1 (make-vert 0.0 0.0) split-point (make-vert 0.0 1.0))) (paint-right (transform-painter p2 split-point (make-vert 1.0 0.0) (make-vert 0.5 1.0)))) (lambda (frame) (funcall paint-left frame) (funcall paint-right frame))))) (defun below (p1 p2)) ;not implement (defun flip-vert (painter) (transform-painter painter (make-vert 0.0 1.0) (make-vert 1.0 1.0) (make-vert 0.0 0.0))) (defun flip-horiz (painter) (transform-painter painter (make-vert 1.0 0.0) (make-vert 0.0 0.0) (make-vert 1.0 1.0))) ;;;exercice 2.44 (defun right-split (painter n) (if (= n 0) painter (let ((smaller (right-split painter (- n 1)))) (beside painter (below smaller smaller))))) (defun up-split (painter n) (if (= n 0) painter (let ((smaller (up-split painter (- n 1)))) (below painter (beside smaller smaller))))) (defun corner-split (painter n) (if (= n 0) painter (let ((up (up-split painter (- n 1))) (right (right-split painter (- n 1)))) (let ((top-left (beside up up)) (bottom-right (below right right)) (corner (corner-split painter (- n 1)))) (beside (below painter top-left) (below bottom-right corner)))))) (defun square-of-four (tl tr bl br) (lambda (painter) (let ((top (beside (funcall tl painter) (funcall tr painter))) (bottom (beside (funcall bl painter) (funcall br painter)))) (below top bottom)))) (defun flipped-pairs (painter) (let ((combine4 (square-of-four #'identity #'flip-vert #'identity #'flip-vert))) (funcall combine4 painter))) (defun rotate180 (painter) (flip-vert (flip-horiz painter))) (defun squire-limit (painter n) (let ((combine4 (square-of-four #'flip-horiz #'identity #'rotate180 #'flip-vert))) (funcall combine4 (corner-split painter n)))) ;;;exercice 2.45 (defun split (split-op combine-op) (labels ((new-split (painter n) (if (= n 0) painter (let ((smaller (new-split painter (- n 1)))) (combine-op painter (split-op smaller smaller)))))))) (defun right-split () (split #'beside #'below)) (defun up-split () (split #'below #'beside)) ;;;exercice 2.46 (defun frame-coord-map (frame) (lambda (v) (add-vert (origin-frame frame) (add-vert (scale-vert (xcor-vert v) (edge1-frame frame)) (scale-vert (ycor-vert v) (edge2-frame frame)))))) (defun make-vert (x y) (cons x y)) (defun xcor-vert (v) (car v)) (defun ycor-vert (v) (cdr v)) (defun add-vert (v1 v2) (make-vert (+ (xcor-vert v1) (xcor-vert v2)) (+ (ycor-vert v1) (ycor-vert v2)))) (defun sub-vert (v1 v2) (make-vert (- (xcor-vert v1) (xcor-vert v2)) (- (ycor-vert v1) (ycor-vert v2)))) (defun scale-vert (v s) (make-vert (* s (xcor-vert v)) (* (ycor-vert v)))) ;;;exercice 2.47 (defun make-frame (origin edge1 edge2) (list origin edge1 edge2)) (defun origin-frame (f) (first f)) (defun origin-frame (f) (second f)) (defun origin-frame (f) (third f)) (defun make-frame (origin edge1 edge2) (cons origin (cons edge1 edge2))) (defun origin-frame (f) (car f)) (defun edge1-frame (f) (cadr f)) (defun edge2-frame (f) (caddr f)) ;;;exercice 2.48 (defun make-segment (start-v end-v) (cons start-v end-v)) (defun start-segment (s) (car s)) (defun end-segment (s) (cdr s)) ;;;exercice 2.49 (defun draw-line ()) ;not implement (defun segment->painter (segment-list) (lambda (frame) (mapcar (lambda (segment) (draw-line (funcall (frame-coord-map frame) (start-segment segment)) (funcall (frame-coord-map frame) (end-segment segment)))) segment-list))) (defun draw-frame-painter () (lambda (frame) (let ((segment-list (list (make-segment (make-vert 0 0) (sub-vert (edge1-frame frame) (origin-frame frame))) (make-segment (make-vert 0 0) (sub-vert (edge2-frame frame) (origin-frame frame))) (make-segment (sub-vert (edge1-frame frame) (origin-frame frame)) (sub-vert (add-vert (edge1-frame frame) (edge2-frame frame)) (origin-frame frame))) (make-segment (sub-vert (edge2-frame frame) (origin-frame frame)) (sub-vert (add-vert (edge1-frame frame) (edge2-frame frame)) (origin-frame frame)))))) (funcall (segment->painter segment-list) frame)))) (defun draw-opposite-angle-painter () (lambda (frame) (let ((segment-list (list (make-segment (make-vert 0 0) (sub-vert (add-vert (edge1-frame frame) (edge2-frame frame)) (origin-frame frame))) (make-segment (edge1-frame frame) (edge2-frame frame))))) (funcall (segment->painter segment-list) frame)))) (defun draw-middle-point-painter () (lambda (frame) (let ((segment-list (list (make-segment (scale-vert (sub-vert (edge1-frame frame) (origin-frame frame)) 0.5) (scale-vert (sub-vert (edge2-frame frame) (origin-frame frame)) 0.5)) (make-segment (scale-vert (sub-vert (edge1-frame frame) (origin-frame frame)) 0.5) (sub-vert (add-vert (edge1-frame frame) (scale-vert (sub-vert (edge2-frame frame)) 0.5)) (origin-frame frame))) (make-segment (scale-vert (sub-vert (edge2-frame frame) (origin-frame frame)) 0.5) (sub-vert (add-vert (edge2-frame frame) (scale-vert (sub-vert (edge1-frame frame)) 0.5)) (origin-frame frame))) (make-segment (sub-vert (add-vert (edge1-frame frame) (scale-vert (sub-vert (edge2-frame frame)) 0.5)) (origin-frame frame)) (sub-vert (add-vert (edge2-frame frame) (scale-vert (sub-vert (edge1-frame frame)) 0.5)) (origin-frame frame)))))) (funcall (segment->painter segment-list) frame)))) (defun draw-wave-painter () );not implement ;;;exercice 2.50 ;flip-horiz 见上方 (defun rotate180 (painter) (transform-painter painter (make-vert 1.0 1.0) (make-vert 0.0 1.0) (make-vert 1.0 0.0))) (defun rotate270 (painter) (transform-painter painter (make-vert 0.0 1.0) (make-vert 0.0 0.0) (make-vert 1.0 1.0))) ;;;exercice 2.51 (defun below (p1 p2) (let ((split-point (make-vert 0.0 0.5))) (let ((paint-bottom (transform-painter p1 (make-vert 0.0 0.0) (make-vert 1.0 0.0) split-point)) (paint-top (transform-painter p2 split-point (make-vert 1.0 0.5) (make-vert 0.0 1.0)))) (lambda (frame) (funcall paint-top frame) (funcall paint-bottom frame))))) (defun rotate90 (painter) (transform-painter painter (make-vert 1.0 0.0) (make-vert 1.0 1.0) (make-vert 0.0 0.0))) (defun below (p1 p2) (rotate90 (beside p1 p2))) ;;;exercice 2.52 ;TODO ;;;exercice 2.53 (defun memq (s symbols) (cond ((null symbols) nil) ((equal s (car symbols)) symbols) (t (memq s (cdr symbols))))) (list 'a 'b 'c) ;=> (A B C) (list (list 'george)) ;=> ((george)) (cdr '((x1 x2) (y1 y2))) ;=> ((Y1 Y2)) (cadr '((x1 x2) (y1 y2))) ;=> (Y1 Y2) (memq 'red '((red shoes) (blue socks))) ;=> nil (memq 'red '(red shoes blue socks)) ;=>(RED SHOES BLUE SOCKS) ;;;exercice 2.54 (defun equal? (s1 s2) (cond ((and (symbolp s1) (symbolp s2) (equal s1 s2)) t) ((and (listp s1) (listp s2) (equal (car s1) (car s2)) (equal? (cdr s1) (cdr s2))) t) (t nil))) ;;;exercice 2.55 ; ''abracadabra => (quote (quote abracadabra)) ;;;;exercice 2.3.2 (defun variable? (x) (symbolp x)) (defun same-variable? (v1 v2) (and (variable? v1) (variable? v2) (eql v1 v2))) (defun make-sum (a1 a2) (list '+ a1 a2)) (defun make-product (m1 m2) (list '* m1 m2)) (defun sum? (x) (and (consp x) (eql (car x) '+))) (defun addend (s) (cadr s)) (defun augend (s) (caddr s)) (defun product? (x) (and (consp x) (eql (car x) '*))) (defun multiplier (p) (cadr p)) (defun multiplicand (p) (caddr p)) (defun deriv (expr var) (cond ((numberp expr) 0) ((variable? expr) (if (same-variable? expr var) 1 0)) ((sum? expr) (make-sum (deriv (addend expr) var) (deriv (augend expr) var))) ((product? expr) (make-sum (make-product (multiplier expr) (deriv (multiplicand expr) var)) (make-product (deriv (multiplier expr) var) (multiplicand expr)))) (t (error "unknown expression type -- DERIV" expr)))) (defun make-sum (a1 a2) (cond ((equal a1 0) a2) ((equal a2 0) a1) ((and (numberp a1) (numberp a2)) (+ a1 a2)) (t (list '+ a1 a2)))) (defun make-product (a1 a2) (cond ((or (equal a1 0) (equal a2 0)) 0) ((equal a1 1) a2) ((equal a2 1) a1) ((and (numberp a1) (numberp a2)) (* a1 a2)) (t (list '* a1 a2)))) ;;;exercice 2.56 (defun make-exponentiation (b e) (cond ((equal e 0) 1) ((equal e 1) b) (t (list '** b e)))) (defun base (expr) (cadr expr)) (defun exponent (expr) (caddr expr)) (defun exponentiation? (expr) (and (consp expr) (eql (car expr) '**))) (defun deriv (expr var) (cond ((numberp expr) 0) ((variable? expr) (if (same-variable? expr var) 1 0)) ((sum? expr) (make-sum (deriv (addend expr) var) (deriv (augend expr) var))) ((product? expr) (make-sum (make-product (multiplier expr) (deriv (multiplicand expr) var)) (make-product (deriv (multiplier expr) var) (multiplicand expr)))) ((exponentiation? expr) (make-product (exponent expr) (make-product (make-exponentiation (base expr) (- (exponent expr) 1)) (deriv (base expr) var)))) (t (error "unknown expression type -- DERIV" expr)))) ;;;exercice 2.57 (defun make-sum (&rest as) (let ((sum-list '()) (num-sum 0)) (dolist (num as) (if (numberp num) (incf num-sum num) (push num sum-list))) (cond ((= num-sum 0) (if (= 1 (length sum-list)) (car sum-list) (cons '+ sum-list))) ((null sum-list) num-sum) (t (append (list '+ num-sum) sum-list))))) (defun addend (expr) (cadr expr)) (defun augend (expr) (if (= 3 (length expr)) (caddr expr) (cons '+ (cddr expr)))) (defun make-product (&rest ms) (let ((product-list '()) (num-product 1)) (dolist (num ms) (if (numberp num) (setf num-product (* num-product num)) (push num product-list))) (cond ((= num-product 0) 0) ((= num-product 1) (if (= 1 (length product-list)) (car product-list) (cons '* product-list))) ((null product-list) num-product) (t (append (list '* num-product) product-list))))) (defun multiplier (expr) (cadr expr)) (defun multiplicand (expr) (if (= 3 (length expr)) (caddr expr) (cons '* (cddr expr)))) ;;;exercice 2.58 ;;a) (defun make-sum (a1 a2) (cond ((equal a1 0) a2) ((equal a2 0) a1) ((and (numberp a1) (numberp a2)) (+ a1 a2)) (t (list a1 '+ a2)))) (defun addend (expr) (car expr)) (defun augend (expr) (caddr expr)) (defun sum? (expr) (equal (cadr expr) '+)) (defun make-product (m1 m2) (cond ((or (equal m1 0) (equal m2 0)) 0) ((equal m1 1) m2) ((equal m2 1) m1) ((and (numberp m1) (numberp m2)) (* m1 m2)) (t (list m1 '* m2)))) (defun multiplier (expr) (car expr)) (defun multiplicand (expr) (caddr expr)) (defun product? (expr) (equal (cadr expr) '*)) ;;b) (defun sum? (expr) (not (null (member '+ expr)))) (defun addend (expr) (let ((add-pos (position '+ expr))) (if (equal 1 add-pos) (first expr) (subseq expr 0 add-pos)))) (defun augend (expr) (let ((add-pos (position '+ expr))) (if (equal (- (length expr) 2) add-pos) (car (last expr)) (subseq expr (1+ add-pos))))) (defun make-sum (&rest as) (let ((sum-expr (list (car as)))) (dolist (num (subseq as 1) sum-expr) (push '+ sum-expr) (push num sum-expr)))) (defun product? (expr) (and (null (member '+ expr)) (some (lambda (x) (equal '* x)) expr))) (defun multiplier (expr) (car expr)) (defun multiplicand (expr) (if (= (length expr) 3) (car (last expr)) (subseq expr 2))) (defun make-product (&rest ms) (let ((product-expr (list (car ms)))) (dolist (num (subseq ms 1) product-expr) (push '* product-expr) (push num product-expr)))) ;;;;2.3.3 (defun element-of-set? (x set) (cond ((null set) nil) ((equal (car set) x) t) (t (element-of-set? x (cdr set))))) (defun adjoin-set (x set) (if (element-of-set? x set) set (cons x set))) (defun intersection-set (set1 set2) (cond ((or (null set1) (null set2)) '()) ((element-of-set? (car set1) set2) (cons (car set1) (intersection-set (cdr set1) set2))) (t (intersection-set (cdr set1) set2)))) ;;;exercice 2.59 (defun union-set (set1 set2) (cond ((null set1) set2) ((null set2) set1) ((element-of-set? (car set1) set2) (union-set (cdr set1) set2)) (t (cons (car set1) (union-set (cdr set1) set2))))) ;;;exercice 2.60 ;element-of-set? adjoin-set intersection-set 同上 (defun union-set (set1 set2) (append set1 set2)) ;;;有序集合 (defun element-of-set? (x set) (cond ((null set) nil) ((= x (car set)) t) ((< x (car set)) nil) (t (element-of-set? x (cdr set))))) (defun intersection-set (set1 set2) (if (or (null set1) (null set2)) '() (let ((x1 (car set1)) (x2 (car set2))) (cond ((= x1 x2) (cons x1 (intersection-set (cdr set1) (cdr set2)))) ((< x1 x2) (intersection-set (cdr set1) set2)) ((> x1 x2) (intersection-set set1 (cdr set2))))))) ;;;exercice 2.61 (defun adjoin-set (x set) (cond ((null set) (list x)) ((= x (car set)) set) ((< x (car set)) (cons x set)) ((> x (car set)) (cons (car set) (adjoin-set x (cdr set)))))) ;;;exercice 2.62 (defun union-set (set1 set2) (cond ((null set1) set2) ((null set2) set1) (t (let ((x1 (car set1)) (x2 (car set2))) (cond ((= x1 x2) (cons x1 (union-set (cdr set1) (cdr set2)))) ((< x1 x2) (cons x1 (union-set (cdr set1) set2))) ((> x1 x2) (cons x2 (union-set set1 (cdr set2))))))))) ;;;;集合作为二叉树 (defun entry (tree) (car tree)) (defun left-branch (tree) (cadr tree)) (defun right-branch (tree) (caddr tree)) (defun make-tree (entry left right) (list entry left right)) (defun element-of-set? (x set) (cond ((null set) nil) ((= x (entry set)) t) ((< x (entry set)) (element-of-set? x (left-branch set))) ((> x (entry set)) (element-of-set? x (right-branch set))))) (defun adjoin-set (x set) (cond ((null set) (make-tree x nil nil)) ((= x (car set) set)) ((< x (car set)) (make-tree (car set) (adjoin-set x (left-branch set)) (right-branch set))) ((> x (car set)) (make-tree (car set) (left-branch set) (adjoin-set x (right-branch set)))))) ;;;exercice 2.63 (defun tree->list-1 (tree) (if (null tree) '() (append (tree->list-1 (left-branch tree)) (cons (entry tree) (tree->list-1 (right-branch tree)))))) (defun tree->list-2 (tree) (labels ((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) 相同 ;b) 不同 1是On2,而2是On ;;;exercice 2.64 (defun list->tree (elements) (car (partial-tree elements (length elements)))) (defun partial-tree (elts n) (if (= n 0) (cons '() elts) (let ((left-size (floor (- n 1) 2))) (let ((left-result (partial-tree elts left-size))) (let ((left-tree (car left-result)) (non-left-tree (cdr left-result)) (right-size (- n (1+ left-size)))) (let ((this-entry (car non-left-tree)) (right-result (partial-tree (cdr non-left-tree) right-size))) (let ((right-tree (car right-result)) (remaining-elts (cdr right-result))) (cons (make-tree this-entry left-tree right-tree) remaining-elts)))))))) ;a)结果为(5 (1 NIL (3 NIL NIL)) (9 (7 NIL NIL) (11 NIL NIL))) ;b)复杂度O(n) ;;;exercice 2.65 (defun union-tree (set1 set2) (list->tree (union-set (tree->list-2 set1) (tree->list-2 set2)))) (defun intersection-set (set1 set2) (list->tree (intersection-set (tree->list-2 set1) (tree->list-2 set2)))) ;;;exercice 2.66 (defun lookup (given-key set-of-records) (cond ((null set-of-records) nil) ((= given-key (key (entry set-of-records))) (entry set-of-records)) ((< given-key (key (entry set-of-records))) (lookup given-key (left-branch set-of-records))) (t (lookup given-key (right-branch set-of-records))))) ;;;;2.3.4 (defun make-leaf (symbol weight) (list 'leaf symbol weight)) (defun leaf? (obj) (eq (car obj) 'leaf)) (defun symbol-leaf (x) (cadr x)) (defun weight-leaf (x) (caddr x)) (defun make-code-tree (left right) (list left right (append (symbols left) (symbols right)) (+ (weight left) (weight right)))) (defun left-branch (tree) (car tree)) (defun right-branch (tree) (cadr tree)) (defun symbols (tree) (if (leaf? tree) (list (symbol-leaf tree)) (caddr tree))) (defun weight (tree) (if (leaf? tree) (weight-leaf tree) (cadddr tree))) (defun decode (bits tree) (labels ((decode-1 (bits current-branch) (if (null bits) nil (let ((next-branch (choose-branch (car bits) current-branch))) (if (leaf? next-branch) (cons (symbol-leaf next-branch) (decode-1 (cdr bits) tree)) (decode-1 (cdr bits) next-branch)))))) (decode-1 bits tree))) (defun choose-branch (bit branch) (cond ((= bit 0) (left-branch branch)) ((= bit 1) (right-branch branch)) (t (error "bad bit -- CHOOSE-BRANCH" bit)))) (defun adjoin-set (x set) (cond ((null set) (list x)) ((< (weight x) (weight (car set))) (cons x set)) (t (cons (car set) (adjoin-set x (cdr set)))))) (defun make-leaf-set (pairs) (if (null pairs) nil (let ((pair (car pairs))) (adjoin-set (make-leaf (car pair) (cadr pair)) (make-leaf-set (cdr pairs)))))) ;;;exercice 2.67 (defvar sample-tree (make-code-tree (make-leaf 'A 4) (make-code-tree (make-leaf 'B 2) (make-code-tree (make-leaf 'D 1) (make-leaf 'C 1))))) (defvar sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0)) ;=> (A D A B B C A) ;;;exercice 2.68 (defun encode (message tree) (if (null message) nil (append (encode-symbol (car message) tree) (encode (cdr message) tree)))) (defun encode-symbol (symbol tree) (if (leaf? tree) (if (equal (symbol-leaf tree) symbol) nil (error "symbol not support")) (if (position symbol (symbols (left-branch tree))) (cons 0 (encode-symbol symbol (left-branch tree))) (cons 1 (encode-symbol symbol (right-branch tree)))))) ;;;exercice 2.69 (defun generate-huffman-tree (pairs) (successive-merge (make-leaf-set pairs))) (defun successive-merge (leaf-set &optional (code-tree nil)) (cond ((null leaf-set) nil) ((= 1 (length leaf-set)) (make-code-tree (car leaf-set) code-tree)) (t (successive-merge (cdr leaf-set) (if (null code-tree) (car leaf-set) (make-code-tree (car leaf-set) code-tree)))))) ;;;exercice 2.70 (defvar rock-tree (generate-huffman-tree '((a 2) (na 16) (boom 1) (sha 3) (get 2) (yip 9) (job 2) (wah 1)))) ;(encode '(get a job sha na na na na na na na na get a job sha na na na na na na na na wah yip yip yip yip yip yip yip yip yip sha boom) rock-tree ) ; => length 87 ,如果用定长编码,需要108个二进制位 ;;;exercice 2.71 ;最频繁的用1个二进制位 ;最不频繁的用n-1个 ;;;exercice 2.72 ;最频繁的符号是n ;最不频繁 (1+n) * n / 2 + n ;;;;2.4 (defun add-complex (z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (defun sub-complex (z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (real-part z2)))) (defun mul-complex (z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (defun div-complex (z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (defun real-part (z) (car z)) (defun imag-part (z) (cdr z)) (defun magnitude (z) (sqrt (+ (expt (real-part z) 2) (expt (imag-part z) 2)))) (defun angle (z) (atan (imag-part z) (real-part z))) (defun make-from-real-imag (x y) (cons x y)) (defun make-from-mag-ang (r a) (cons (* r (cos a)) (* r (sin a)))) (defun real-part (z) (* (magnitude z) (cos (angle z)))) (defun imag-part (z) (* (magnitude z) (sin (angle z)))) (defun magnitude (z) (car z)) (defun angle (z) (cdr z)) (defun make-from-real-imag (x y) (cons (sqrt (+ (expt x 2) (expt y 2))) (atan y x))) (defun make-from-mag-ang (r a) (cons r a)) (defun attach-tag (type-tag contents) (cons type-tag contents)) (defun type-tag (datum) (if (consp datum) (car datum) (error "bad tagged datum -- TYPE-TAG" datum))) (defun contents (datum) (if (consp datum) (cdr datum) (error "bad tagged datum -- TYPE-TAG" datum))) (defun rectangular? (z) (eql (type-tag z) 'rectangular)) (defun polar? (z) (eql (type-tag z) 'polar)) (defun real-part-rectangular (z) (car z)) (defun imag-part-rectangular (z) (cdr z)) (defun magnitude-rectangular (z) (sqrt (+ (expt (real-part-rectangular z) 2) (expt (imag-part-rectangular z) 2)))) (defun angle-rectangular (z) (atan (imag-part-rectangular z) (real-part-rectangular z))) (defun make-from-real-imag-rectangular (x y) (attach-tag 'rectangular (cons x y))) (defun make-from-mag-ang-rectangular (r a) (attach-tag 'rectangular (cons (* r (cos a)) (* r (sin a))))) (defun real-part-polar (z) (* (magnitude-polar z) (cos (angle-polar z)))) (defun imag-part-polar (z) (* (magnitude-polar z) (sin (angle-polar z)))) (defun magnitude-polar (z) (car z)) (defun angle-polar (z) (cdr z)) (defun make-from-real-imag-polar (x y) (attach-tag 'polar (cons (sqrt (+ (expt x 2) (expt y 2))) (atan y x)))) (defun make-from-mag-ang-polar (r a) (attach-tag 'polar (cons r a))) (defun real-part (z) (cond ((rectangular? z) (real-part-rectangular (contents z))) ((polar? z) (real-part-polar (contents z))) (t (error "Unknown type -- REAL-TYPE" z)))) (defun imag-part (z) (cond ((rectangular? z) (imag-part-rectangular (contents z))) ((polar? z) (imag-part-polar (contents z))) (t (error "Unknown type -- REAL-TYPE" z)))) (defun magnitude (z) (cond ((rectangular? z) (magnitude-rectangular (contents z))) ((polar? z) (magnitude-polar (contents z))) (t (error "Unknown type -- MAGNITUDE" z)))) (defun angle (z) (cond ((rectangular? z) (angle-rectangular (contents z))) ((polar? z) (angle-polar (contents z))) (t (error "Unknown type -- ANGLE" z)))) (defun make-from-real-imag (x y) (make-from-real-imag-rectangular x y)) (defun make-from-mag-ang (r a) (make-from-mag-ang-polar r a)) (defun install-rectangular-package () (flet ((real-part (z) (car z)) (imag-part (z) (cdr z)) (make-from-real-imag (x y) (cons x y)) (magnitude (z) (sqrt (+ (expt (real-part z) 2) (expt (imag-part z) 2)))) (angle (z) (atan (imag-part z) (real-part z))) (make-from-mag-ang (r a) (cons (* r (cos a)) (* (sin a)))) (tag (x) (attach-tag 'rectangular x))) (put 'real-part '(rectangular) real-part) (put 'imag-part '(rectangular) imag-part) (put 'magnitude '(rectangular) magnitude) (put 'angle '(rectangular) angle) (put 'make-from-real-imag 'rectangular (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'rectangular (lambda (r a) (tag (make-from-mag-ang r a)))) 'done)) (defun install-polar-package () (flet ((magnitude (z) (car z)) (angle (z) (cdr z)) (make-from-mag-ang (r a) (cons r a)) (real-part (z) (* (magnitude z) (cos (angle z)))) (imag-part (z) (* (magnitude z) (sin (angle z)))) (make-from-real-imag (x y) (cons (sqrt (+ (expt x 2) (expt x 2))) (atan y x))) (tag (x) (attach-tag 'polar x))) (put 'real-part '(polar) real-part) (put 'imag-part '(polar) imag-part) (put 'magnitude '(polar) magnitude) (put 'angle '(polar) angle) (put 'make-from-real-imag 'polar (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'polar (lambda (r a) (tag (make-from-mag-ang r a)))) 'done)) (defun apply-generic (op &rest args) (let ((type-tags (mapcar #'type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (mapcar #'contents args)) (error "No method for these types -- APPLY-GENERIC" (list op type-tags)))))) (defun real-part (z) (apply-generic 'real-part z)) (defun imag-part (z) (apply-generic 'imag-part z)) (defun magnitude (z) (apply-generic 'magnitude z)) (defun angle (z) (apply-generic 'angle z)) (defun make-from-real-imag (x y) (funcall (get 'make-from-real-imag 'rectangular) x y)) (defun make-from-mag-ang (r a) (funcall (get 'make-from-mag-ang 'polar) r a)) ;;;exercice 2.73 ;a) 根据代数运算符的类型找到对应的操作,将其应用到操作的参数上。因为数字和变量是一类符号,不能应用数据导向分派。 (defun deriv-1 (exp var) (cond ((numberp exp) 0) ((variable? exp) (if (equal exp var) 1 0)) (t (funcall (get 'deriv (operator exp)) (operands exp) var)))) (defun operator (exp) (car exp)) (defun operands (exp) (cdr exp)) (defun install-sum () (labels ((deriv-add (args var) (make-sum (deriv-1 (first args) var) (deriv-1 (second args) var)))) (put 'deriv '+ deriv-add))) (defun install-product () (labels ((deriv-product (args var) (make-sum (make-product (first args) (deriv-1 (second exp) var)) (make-product (deriv-1 (first exp) var) (second exp))))) (put 'deriv '* deriv-product))) ;c) 略 ;d) 在安装的时候就是 (put '* 'deriv deriv-add) 这样了。 ;;;exercice 2.74 TODO ;;;exercice 2.75 (defun make-from-mag-ang-1 (r a) (Lambda (op) (cond ((eql op 'real-part) (* r (cos a))) ((eql op 'imag-part) (* r (sin a))) ((eql op 'magnitude) r) ((eql op 'angle) a) (t (error "Unknown op -- MAKE-FROM-REAL-IMAG" op))))) ;;;exercice 2.76 ;数据导向适合经常加入操作的系统 ;消息传递适合经常加入类型的系统 ;;;;2.5 (defun add (x y) (apply-generic 'add x y)) (defun sub (x y) (apply-generic 'sub x y)) (defun mul (x y) (apply-generic 'mul x y)) (defun div (x y) (apply-generic 'div x y)) (defun install-scheme-number-package () (flet ((tag (x) (attach-tag 'scheme-number x))) (put 'add '(scheme-number scheme-number) (lambda (x y)(tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make 'scheme-number (lambda (x) (tag x))) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (= x y))) (put '=zero? 'scheme-number (lambda (x) (= x 0))) 'done)) (defun make-scheme-number (n) (funcall (get 'make 'scheme-number) n)) (defun install-rational-package () (flet ((numer (x) (car x)) (denom (x) (cdr x)) (make-rat (n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (add-rat (x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (sub-rat (x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (mul-rat (x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (div-rat (x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (tag (x) (attach-tag 'rational x))) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put 'equ? '(rational rational) (lambda (x y) (and (= (numer x) (numer y)) (= (denom x) (denom y))))) (put '=zero? 'rational (lambda (x) (and (= (numer x) 0) (= (denom y) 0)))) 'done)) (defun make-rational (n d) (funcall (get 'make 'rational) n d)) (defun install-complex-package () (flet ((make-from-real-imag (x y) (funcall (get 'make-from-real-imag 'rectangular) x y)) (make-from-mag-ang (r a) (funcall (get 'make-from-mag-ang 'polar) r a)) (add-complex (z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (sub-complex (z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (real-part z2)))) (mul-complex (z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (div-complex (z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (tag (z) (attach-tag 'complex z))) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (pub 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(complex complex) (lambda (x y) (and (= (real-part x) (real-part y)) (= (imag-part x) (imag-part y))))) (put '=zero? 'complex (lambda (x y) (and (= (real-part x) 0) (= (imag-part x) 0)))) 'done)) (defun make-complex-from-real-imag (x y) (funcall (get 'make-from-real-imag 'complex) x y)) (defun make-complex-from-mag-ang (r a) (funcall (get 'make-from-mag-ang 'complex) r a)) ;;;exercice 2.77 ; 因为这样会脱去最外层的complex,用rectangular 去调用magnitude ; 过程 TODO ;;;exercice 2.78 (defun attach-tag (type-tag contents) (if (numberp contents) contents (cons type-tag contents))) (defun type-tag (datum) (if (consp datum) (car datum) datum)) (defun contents (datum) (if (consp datum) (car datum) datum)) ;;;exercice 2.79 ;安装见上方 (defun equ? (x y) (apply-generic 'equ? x y)) ;;;exercice 2.80 ;安装见上方 (defun equ? (x) (apply-generic '=zero? x)) ;;;; 2.5.2 (defun apply-generic (op &rest args) (let ((type-tags (mapcar #'type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map #'contents args)) (if (= (length args) 2) (let ((type1 (car type-tags)) (type2 (cadr type-tags)) (a1 (car args)) (a2 (cadr args))) (let ((t1->t2 (get-coercion type1 type2)) (t2->t1 (get-coercion type2 type1))) (cond (t1->t2 (apply-generic op (t1->t2 a1) a2)) (t2->t1 (apply-generic op a1 (t2->t1 a2))) (t (error "No method for these types" (list op type-tags)))))) (error "No method for these types" (list op type-tags)))))) ;;;exercice 2.81 ;a) 找不到相应操作时会出现无限递归 ;b) 没有纠正,不能像原来那样正常工作 ;c) (defun apply-generic (op &rest args) (let ((type-tags (mapcar #'type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (mapcar #'contents args)) (if (= (length args) 2) (let ((type1 (car type-tags)) (type2 (cadr type-tags)) (a1 (car args)) (a2 (cadr args))) (if (equal type1 type2) (error "No method for these types" (list op type-tags)) (let ((t1->t2 (get-coercion type1 type2)) (t2->t1 (get-coercion type2 type1))) (cond (t1->t2 (apply-generic op (funcall t1->t2 a1) a2)) (t2->t1 (apply-generic op a1 (funcall t2->t1 a2))) (t (error "No method for these types" (list op type-tags))))))) (error "No method for these types" (list op type-tags)))))) ;;;exercice 2.82 (defun apply-generic-n (op &rest args) (labels ((apply-inner (op i &rest args) (let ((n-args (mapcar (lambda (arg) (let ((t->tn (get-coercion (type-tag arg) (type-tag (elt args i))))) (if t->tn (apply t->tn arg) nil))) args))) (let ((type-tags (mapcar #'type-tag n-args) (let ((proc (get op type-tags))) (if proc (apply proc (mapcar #'contents n-args)) (if (= i (length args)) (error "No Method for these type" (list op type-tags)) (apply-inner op (1+ i) args)))))))))) (apply-inner op 0 args))) ;;TODO 例外情况 ;;;exercice 2.83 (defun install-raise () (put-coercion 'scheme-number 'rational (lambda (n) (make-rat (contents n) 1))) (put-coercion 'rational 'complex (lambda (n) (make-complex-from-real-imag (/ (numer (contents n)) (denom (contents n))) 0)))) ;;TODO raise ;;;exercice 2.84 TODO ;;;exercice 2.85 TODO ;;;exercice 2.86 TODO ;;;;2.5.3 (defun add-poly (p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (add-terms (term-list p1) (term-list p2))) (error "polys not in same var -- ADD-POLY" (list p1 p2)))) (defun mul-poly (p1 p2) (if (same-variable? (variable p1) (variable p2)) (make-poly (variable p1) (mul-terms (term-list p1) (term-list p2))) (error "polys not in same var -- MUL-POLY" (list p1 p2)))) (defun install-polyunomial-package () (labels ((make-poly (var term-list) (cons var term-list)) (variable (p) (car p)) (term-list (p) (cdr p)) (tag (p) (attach-tag 'polynomial p)) (put 'add '(polynomial polynomial) (lambda (a b) (tag (add-poly a b)))) (put 'mul '(polynomial polynomial) (lambda (a b) (tag (mul-poly a b)))) (put '=zero? 'polynomial (lambda (p) )) (put 'make 'polynomial (lambda (var terms) (tag (make-poly var terms))))))) (defun add-terms (l1 l2) (cond ((empty-termlist? l1) l2) ((empty-termlist? l2) l1) (t (let ((t1 (first-term l1)) (t2 (second-term l2))) (cond ((> (order t1) (order t2)) (adjoin-term t1 (add-terms (rest-terms l1) l2))) ((< (order t1) (order t2)) (adjoin-term t2 (add-terms l1 (rest-terms l2)))) (t (adjoin-term (make-term (order t1) (add (coeff t1) (coeff t2))) (add-terms (rest-terms l1) (rest-terms l2))))))))) (defun mul-terms (l1 l2) (if (empty-termlist? l1) (the-empty-termlist) (add-terms (mul-term-by-all-terms (first-term l1) l2) (mul-terms (rest-terms l1) l2)))) (defun mul-term-by-all-terms (t1 l) (if (empty-termlist? l) (the-empty-termlist) (let ((t2 (first-term l))) (adjoin-term (make-term (+ (order t1) (order t2)) (mul (coeff t1) (coeff t2))) (mul-term-by-all-terms t1 (rest-terms l)))))) (defun adjoin-term (term term-list) (if (=zero? (coeff term)) term-list (const term term-list))) (defun the-empty-termlist '()) (defun first-term (term-list) (car term-list)) (defun rest-terms (term-list) (cdr term-list)) (defun empty-termlist? (term-list) (null term-list)) (defun make-term (order coeff) (list order coeff)) (defun order (term) (car term)) (defun coeff (term) (cadr term)) ;;;exercice 2.87 TODO ;;;exercice 2.88 TODO ;;;exercice 2.89 TODO ;;;exercice 2.90 TODO ;;;exercice 2.91 TODO ;;;exercice 2.92 TODO ;;;exercice 2.93 TODO ;;;exercice 2.94 TODO ;;;exercice 2.95 TODO ;;;exercice 2.96 TODO ;;;exercice 2.97 TODO
57,157
Common Lisp
.lisp
1,549
28.34603
148
0.535522
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a6bd5448007d2d02fb9fe2ae3102a87e88e602e056eefe008bde69f2facddfc4
20,234
[ -1 ]
20,235
5-5.lisp
LeZheng_l-lisp-demo/SICP_Exercise/5-5.lisp
(defvar all-regs '(exp env val continue proc argl unev)) (defvar label-count 0) (defun make-label (symbol) (intern (string-concat (symbol-name symbol) (format nil "~A" label-count)))) (defun l-compile (exp target linkage) (cond ((self-evaluating? exp) (compile-self-evaluating exp target linkage)) ((quoted? exp) (compile-quoted exp target linkage)) ((variable? exp) (compile-variable exp target linkage)) ((assignment? exp) (compile-assignment exp target linkage)) ((definition? exp) (compile-definition exp target linkage)) ((if? exp) (compile-if exp target linkage)) ((lambda? exp) (compile-lambda exp target linkage)) ((begin? exp) (compile-sequence (begin-actions exp) target linkage)) ((cond? exp) (l-compile (cond->if exp) target linkage)) ((application? exp) (compile-application exp target linkage)) (t (error "Unknown expression type -- COMPILE" exp)))) (defun make-instruction-sequence (needs modifies statements) (list needs modifies statements)) (defun empty-instruction-sequence () (make-instruction-sequence '() '() '())) (defun compile-linkage (linkage) (case linkage ('return (make-instruction-sequence '(continue) '() '((goto (reg continue))))) ('next (empty-instruction-sequence)) (otherwise (make-instruction-sequence '() '() `((goto (label ,linkage))))))) (defun end-with-linkage (linkage instruction-sequence) (preserving '(continue) instruction-sequence (compile-linkage linkage))) (defun compile-self-evaluating (exp target linkage) (end-with-linkage linkage (make-instruction-sequence '() (list target) `((assign ,target (const ,exp)))))) (defun compile-quoted (exp target linkage) (end-with-linkage linkage (make-instruction-sequence '() (list target) `((assign ,target (const ,(text-of-quotation exp))))))) (defun compile-variable (exp target linkage) (end-with-linkage linkage (make-instruction-sequence '(env) (list target) `((assign ,target (op lookup-variable-value) (const ,exp) (reg env)))))) (defun compile-assignment (exp target linkage) (let ((var (assignment-variable exp)) (get-value-code (l-compile (assignment-value exp) 'val 'next))) (end-with-linkage linkage (preserving '(env) get-value-code (make-instruction-sequence '(env val) (list target) `((perform (op set-variable-value) (const ,var) (reg val) (reg env)) (assign ,target (const ok)))))))) (defun compile-definition (exp target linkage) (let ((var (definition-variable exp)) (get-value-code (l-compile (definition-value exp) 'val 'next))) (end-with-linkage linkage (preserving '(env) get-value-code (make-instruction-sequence '(env val) (list target) `((perform (op define-variable) (const ,var) (reg val) (reg env)) (assign ,target (const ok)))))))) (defun compile-if (exp target linkage) (let ((t-branch (make-label 'true-branch)) (f-branch (make-label 'false-brance)) (after-if (make-label 'after-if))) (let ((consequent-linkage (if (eq linkage 'next) after-if linkage))) (let ((p-code (l-compile (if-predicate exp) 'val 'next)) (c-code (l-compile (if-consequent exp) target consequent-linkage)) (a-code (l-compile (if-alternative exp) target linkage))) (preserving '(env continue) p-code (append-instruction-sequences (make-instruction-sequence '(val) '() `((test (op false?) (reg val)) (brance (label ,f-branch)))) (parallel-instruction-sequences (append-instruction-sequences t-branch c-code) (append-instruction-sequences f-branch a-code)) after-if)))))) (defun compile-sequence (seq target linkage) (if (last-exp? seq) (l-compile (first-exp seq) target linkage) (preserving '(env continue) (l-compile (first-exp seq) target 'next) (compile-sequence (rest-exps seq) target linkage)))) (defun compile-lambda (exp target linkage) (let ((proc-entry (make-label 'entry)) (after-lambda (make-label 'after-lambda))) (let ((lambda-linkage (if (eq linkage 'next) after-lambda linkage))) (append-instruction-sequences (tack-on-instruction-sequence (end-with-linkage lambda-linkage (make-instruction-sequence '(env) (list target) `((assign ,target (op make-compiled-procedure) (label ,proc-entry) (reg env))))) (compile-lambda-body exp proc-entry)) after-lambda)))) (defun compile-lambda-body (exp proc-entry) (let ((formals (lambda-parameters exp))) (append-instruction-sequences (make-instruction-sequence '(env proc argl) '(env) `(,proc-entry (assign env (op compiled-procedure-env) (env proc)) (assign env (op extend-environment) (const ,formals) (reg argl) (reg env)))) (compile-sequence (lambda-body exp) 'val 'return)))) (defun compile-application (exp target linkage) (let ((proc-code (l-compile (operator exp) 'proc 'next)) (operand-codes (mapcar (lambda (operand) (l-compile operand 'val 'next)) (operands exp)))) (preserving '(env continue) proc-code (preserving '(proc continue) (construct-arglist operand-codes) (compile-procedure-call target linkage))))) (defun construct-arglist (operand-codes) (let ((operand-codes (reverse operand-codes))) (if (null operand-codes) (make-instruction-sequence '() '(argl) `((assign argl (const ())))) (let ((code-to-get-last-arg (append-instruction-sequences (car operand-codes) (make-instruction-sequence '(val) '(argl) '((assign argl (op list) (reg val))))))) (if (null (cdr operand-codes)) code-to-get-last-arg (preserving '(env) code-to-get-last-arg (code-to-get-rest-args (cdr operand-codes)))))))) (defun code-to-get-rest-args (operand-codes) (let ((code-for-next-arg (preserving '(argl) (car operand-codes) (make-instruction-sequence '(val argl) '(argl) `((assign argl (op cons) (reg val) (reg argl))))))) (if (null (cdr operand-codes)) code-for-next-arg (preserving '(env) code-for-next-arg (code-to-get-rest-args (cdr operand-codes)))))) (defun compile-procedure-call (target linkage) (let ((primitive-branch (make-label 'primitive-branch)) (compiled-branch (make-label 'compiled-branch)) (after-call (make-label 'after-call))) (let ((compiled-linkage (if (eq linkage 'next) after-call linkage))) (append-instruction-sequences (make-instruction-sequence '(proc) '() `((test (op primitive-procedure) (reg proc)) (branch (label ,primitive-branch)))) (parallel-instruction-sequences (append-instruction-sequences compiled-branch (compile-proc-appl target compiled-linkage)) (append-instruction-sequences primitive-branch (end-with-linkage linkage (make-instruction-sequence '(proc argl) (list target) `((assign ,target (op apply-primitive-procedure) (reg proc) (reg argl))))))) after-call)))) (defun compile-proc-appl (target linkage) (cond ((and (eq target 'val) (not (eq linkage 'return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,linkage)) (assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val))))) ((and (not (eq target 'val)) (not (eq linkage 'return))) (let ((proc-return (make-label 'proc-return))) (make-instruction-sequence '(proc) all-regs `((assign continue (label ,proc-return)) (assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val)) ,proc-return (assign ,target (reg val)) (goto (label ,linkage)))))) ((and (eq target 'val) (eq linkage 'return)) (make-instruction-sequence '(proc continue) all-regs '((assign val (op compiled-procedure-entry) (reg proc)) (goto (reg val))))) ((and (not (eq tatget val)) (eq linkage 'return)) (error "return linkage, target not val -- COMPILE" target)))) (defun statements (s) (if (symbolp s) '() (caddr s))) (defun registers-needed (s) (if (symbolp s) '() (car s))) (defun registers-modified (s) (if (symbolp s) '() (cadr s))) (defun needs-register? (seq reg) (member reg (registers-needed seq))) (defun modifies-register? (seq reg) (member reg (registers-modified seq))) (defun append-instruction-sequences (&rest seqs) (labels ((append-2-sequences (seq1 seq2) (make-instruction-sequence (list-union (registers-needed seq1) (list-difference (registers-needed seq2) (registers-modified seq1))) (list-union (registers-modified seq1) (registers-modified seq2)) (append (statements seq1) (statements seq2))))) (labels ((append-seq-list (seqs) (if (null seqs) (empty-instruction-sequence) (append-2-sequences (car seqs) (append-seq-list (cdr seqs)))))) (append-seq-list seqs)))) (defun list-union (s1 s2) (cond ((null s1) s2) ((member (car s1) s2) (list-union (cdr s1) s2)) (t (cons (car s1) (list-union (cdr s1) s2))))) (defun list-difference (s1 s2) (cond ((null s1) '()) ((member (car s1) s2) (list-difference (cdr s1) s2)) (t (cons (car s1) (list-difference (cdr s1) s2))))) (defun preserving (regs seq1 seq2) (if (null regs) (append-instruction-sequences seq1 seq2) (let ((first-reg (car regs))) (if (and (needs-register? seq2 first-reg) (modifies-register? seq1 first-reg)) (preserving (cdr regs) (make-instruction-sequence (list-union (list first-reg) (registers-needed seq1)) (list-difference (registers-modified seq1) (list first-reg)) (append `((save ,first-reg)) (statements seq1) `((resotore ,first-reg)))) seq2) (preserving (cdr regs) seq1 seq2))))) (defun tack-on-instruction-sequence (seq body-seq) (make-instruction-sequence (registers-needed seq) (registers-modified seq) (append (statements seq) (statements body-seq)))) (defun parallel-instruction-sequences (seq1 seq2) (make-instruction-sequence (list-union (registers-needed seq1) (registers-needed seq2)) (list-union (registers-modified seq1) (registers-modified seq2)) (append (statements seq1) (statements seq2)))) (l-compile `(define (factorial n) (if (= n 1) 1 (* (factorial (- n 1)) n))) 'val 'next)
10,491
Common Lisp
.lisp
325
27.713846
79
0.663441
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fb61b1bda4d6387d91049b90441a5c8c0dbb5d68e4aee2473f4bb13798c1d8b9
20,235
[ -1 ]
20,236
4-3.lisp
LeZheng_l-lisp-demo/SICP_Exercise/4-3.lisp
(defun l-require (p) (if (not p) (amb))) (defun an-element-of (items) (l-require (not (null items))) (amb (car items) (an-element-of (cdr items)))) ;;; 4.35 (defun an-integer-between (a b) (if (> a b) (amb) (amb a (an-integer-between (+ a 1) b)))) ;;; 4.36 ;;使用 an-integer-starting-from 会产生无尽的选择,导致程序无法正常继续下去 (defun a-pythagorean-triple-from (low) (let ((k (an-integer-starting-from low))) (let ((j (an-integer-between low k))) (let ((i (an-integer-between low j))) (l-require (= (+ (* i i) (* j j)) (* k k))) (list i j k))))) ; (a-pythagorean-triple-from 0) ;;; 4.37 ;; 本题的方法高,少了一个搜索分支 ;;;; 4.3.2 (defun multiple-dwelling () (let ((baker (amb 1 2 3 4 5)) (cooper (amb 1 2 3 4 5)) (fletcher (amb 1 2 3 4 5)) (miller (amb 1 2 3 4 5)) (smith (amb 1 2 3 4 5))) (l-require (distinctp (list baker cooper fletcher miller smith))) (l-require (not (= baker 5))) (l-require (not (= cooper 1))) (l-require (not (= fletcher 5))) (l-require (not (= fletcher 1))) (l-require (> miller cooper)) (l-require (not (= (abs (- smith fletcher)) 1))) (l-require (not (= (abs (- fletcher cooper)) 1))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith)))) ;;; 4.38 ;; (l-require (> (abs (- fletcher smith)) 1)) ;;; 4.39 ;;约束条件的顺序不会影响答案,会影响找到答案的时间 ;; distinct 放最后 ;;; 4.40 (defun multiple-dwelling-2 () (let ((fletcher (amb 1 2 3 4 5))) (l-require (not (= fletcher 5))) (l-require (not (= fletcher 1))) (let ((cooper (amb 1 2 3 4 5))) (l-require (not (= cooper 1))) (l-require (not (= (abs (- fletcher cooper)) 1))) (let ((smith (amb 1 2 3 4 5))) (l-require (not (= (abs (- smith fletcher)) 1))) (let ((miller (amb 1 2 3 4 5))) (l-require (> miller cooper)) (let ((baker (amb 1 2 3 4 5))) (l-require (not (= baker 5))) (l-require (distinctp (list baker cooper fletcher miller smith))) (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith)))))))) ;;; 4.41 (defun multiple-dwelling-cl () (let ((result '()) (level-list '(1 2 3 4 5))) (dolist (baker level-list) (dolist (cooper level-list) (dolist (fletcher level-list) (dolist (miller level-list) (dolist (smith level-list) (if (and (distinctp (list baker cooper fletcher miller smith)) (not (= baker 5)) (not (= cooper 1)) (not (= fletcher 5)) (not (= fletcher 1)) (> miller cooper) (not (= (abs (- smith fletcher)) 1)) (not (= (abs (- fletcher cooper)) 1))) (push (list (list 'baker baker) (list 'cooper cooper) (list 'fletcher fletcher) (list 'miller miller) (list 'smith smith)) result))))))))) ;;; 4.42 (defun require-half-truth (p1 p2) (l-require (or (and p1 (not p2)) (and (not p1) p2)))) (defun (liars-puzzle) (let ((betty (amb 1 2 3 4 5)) (ethel (amb 1 2 3 4 5)) (joan (amb 1 2 3 4 5)) (kitty (amb 1 2 3 4 5)) (mary (amb 1 2 3 4 5))) (require-half-truth (= kitty 2) (= betty 3)) (require-half-truth (= ethel 1) (= joan 2)) (require-half-truth (= joan 1) (= ethel 5)) (require-half-truth (= kitty 2) (= mary 4)) (require-half-truth (= mary 4) (= betty 1)) (l-require (distinctp (list betty ethel joan kitty mary))) (list (list 'betty betty) (list 'ethel ethel) (list 'joan joan) (list 'kitty kitty) (list 'mary mary)))) ;;; 4.43 TODO ;;; 4.44 (defun safe-position (pos positions) (if (notany #'(lambda (p) (= pos p)) positions) (let ((len (length positions))) (dotimes (i len) (let ((p (elt positions i))) (if (= (- len i) (abs (- pos p))) (return nil)))) (return t)))) (defun eight-queen (size) (labels ((next-pos (col postions) (let ((pos (an-integer-between 1 8))) (l-require (safe-position pos positions)) (push pos positions) (if (= col size) positions (next-pos (+ col 1) positions))))) (next-pos 1 '()))) ;;;自然语言的语法分析 (setf nouns '(noun student professor cat class)) (setf verbs '(verb studies lectures eats sleeps)) (setf articles '(article the a)) (setf prepositions '(prep for to in by with)) (defun parse-sentence () (list 'sentence (parse-noun-phrase) (parse-word verbs))) (defun parse-noun-phrase () (list 'noun-phrase (parse-word articles) (parse-word nouns))) (defun parse-word (word-list) (l-require (not (null *unparsed*))) (l-require (memq (car *unparsed*) (cdr word-list))) (let ((found-word (car *unparsed*))) (setf *unparsed* (cdr *unparsed*)) (list (car word-list) found-word))) (setf *unparsed* '()) (defun parse (input) (setf *unparsed* input) (let ((sent (parse-sentence))) (l-require (null unparsed*)) sent)) (defun parse-prepositional-phrase () (list 'prep-phrase (parse-word prepositions) (parse-noun-phrase))) (defun parse-sentence () (list 'sentence (parse-noun-phrase) (parse-verb-phrase))) (defun parse-verb-phrase () (labels ((maybe-extend (verb-phrase) (amb verb-phrase (maybe-extend (list 'verb-phrase verb-phrase (parse-prepositional-phrase)))))) (maybe-extend (parse-word verbs)))) (defun parse-simple-noun-phrase () (list 'simple-noun-phrase (parse-word articles) (parse-word nouns))) (defun parse-noun-phrase () (labels ((maybe-extend (noun-phrase) (amb noun-phrase (maybe-extend (list 'noun-phrase noun-phrase (parse-prepositional-phrase)))))) (maybe-extend (parse-simple-noun-phrase)))) ;;;4.45 略 ;;;4.46 句子是从左到右开始解析的 ;;; 4.47 行不通,会导致死循环,改变求值顺序,还是会有这种现象 ;;; 4.48 TODO ;;; 4.49 (defun (amb-list lst) (if (null lst) (amb) (amb (car lst) (amb-list (cdr lst))))) (defun parse-word-create (word-list) (l-require (not (null *unparsed*))) (l-require (memq (car *unparsed*) (cdr word-list))) (let ((found-word (amb-list (cdr word-list)))) (setf *unparsed* (cdr *unparsed*)) (list (car word-list) found-word))) ;;;;4.3.3 (defun amb? (exp) (tagged-list? exp 'amb)) (define amb-choices (exp) (cdr exp)) (defun ambeval (exp env succeed fail) (funcall (analyze exp) env succeed fail)) (defun analyze-self-evaluating (exp) (lambda (env succeed fail) (funcall succeed exp fail))) (defun analyze-quoted (exp) (let ((qval (text-of-quotation exp))) (lambda (env succeed fail) (funcall succeed qval fail)))) (defun analyze-variable (exp) (lambda (env succeed fail) (funcall succeed (lookup-variable-value exp env) fail))) (defun analyze-lambda (exp) (let ((vars (lambda-parameters exp)) (bproc (analyze-sequence (lambda-body exp)))) (lambda (env succeed fail) (funcall succeed (make-procedure vars bproc env) fail)))) (defun analyze-if (exp) (let ((pproc (analyze (if-predicate exp))) (cproc (analyze (if-consequent exp))) (aproc (analyze (if-alternative exp)))) (lambda (env succeed fail) (funcall pproc env (lambda (pred-value fail2) (if (true? pred-value) (funcall cproc env succeed fail2) (funcall aproc env succeed fail2))) fail)))) (defun analyze-sequence (exps) (labels ((sequentially (a b) (lambda (env succeed fail) (funcall a env (lambda (a-value fail2) (funcall b env succeed fail2)) fail)))) (labels ((l-loop (first-proc rest-procs) (if (null rest-procs) first-proc (l-loop (sequentially first-proc (car rest-procs)) (cdr rest-procs))))) (let ((procs (mapcar #'analyze exps))) (if (null procs) (error "Empty sequence -- ANALYZE")) (l-loop (car procs) (cdr procs)))))) (defun analyze-defination (exp) (let ((var (definition-variable exp)) (vproc (analyze (definition-value exp)))) (lambda (env succeed fail) (funcall vproc env (lambda (val fail2) (define-variable! var val env) (funcall succeed 'ok fail2)) fail)))) (defun analyze-assignment (exp) (let ((var (assignment-variable exp)) (vproc (analyze (assignment-value exp)))) (lambda (env succeed fail) (funcall vproc env (lambda (val fail2) (let ((old-value (lookup-variable-value var env))) (set-variable-value! var val env) (funcall succeed 'ok (lambda () (set-variable-value! var old-value env) (funcall fail2))))) fail)))) (defun analyze-application (exp) (let ((fproc (analyze (operator exp))) (aprocs (mapcar #'analyze (operands exp)))) (lambda (env succeed fail) (funcall fproc env (lambda (proc fail2) (get-args aprocs env (lambda (args fail3) (execute-application proc args succeed fail3)) fail2)) fail)))) (defun get-args (aprocs env succeed fail) (if (null aprocs) (succeed '() fail) (funcall (car aprocs) env (lambda (arg fail2) (get-args (cdr aprocs) env (lambda (args fail3) (funcall succeed (cons arg args) fail3)) fail2)) fail))) (defun execute-application (proc args succeed fail) (cond ((primitive-procedure? proc) (funcall succeed (apply-primitive-procedure proc args) fail)) ((compound-procedure? proc) (funcall (procedure-body proc) (extend-environment (procedure-parameters proc) args (procedure-environment proc)) succeed fail)) (t (error "Unknown procedure type -- EXECUTE-APPLICATION")))) (defun analyze-amb (exp) (let ((cprocs (mapcar #'analyze (amb-choices exp)))) (lambda (env succeed fail) (labels ((try-next (choices) (if (null choices) (fail) (funcall (car choices) env succeed (lambda () (try-next (cdr choices))))))) (try-next cprocs))))) (setf input-prompt ";;; Amb-Eval input:") (setf output-prompt ";;; Amb-Eval value:") (defun driver-loop () (labels ((internal-loop (try-again) (prompt-for-input input-prompt) (let ((input (read))) (if (eql input 'try-again) (funcall try-again) (begin (format "~%;;; Starting a new problem ") (ambeval input the-global-environment (lambda (val next-alternative) (announce-output output-prompt) (user-print val) (internal-loop next-alternative)) (lambda () (announce-output ";;; There are no more values of") (user-print input) (driver-loop)))))))) (internal-loop (lambda () (format ";;; There is no current problem") (driver-loop))))) ;;; 4.50 TODO ;;; 4.51 TODO ;;; 4.52 TODO ;;; 4.53 TODO ;;; 4.54 TODO
10,949
Common Lisp
.lisp
340
26.723529
70
0.615839
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7d133badd2f9f6992ea4e9ff734b54f920d53c3676428a16e3638b99d9b91813
20,236
[ -1 ]
20,237
chapter-one.lisp
LeZheng_l-lisp-demo/SICP_Exercise/chapter-one.lisp
;;; exercise 1.1 10 ;; => 10 (+ 5 3 4) ;; => 12 (- 9 1) ;; => 8 (/ 6 2) ;; => 3 (+ (* 2 4) (- 4 6)) ;; => 6 (setf a 3) ;; => 3 (setf b (+ a 1)) ;; => 4 (+ a b (* a b)) ;; => 19 (= a b) ;; => nil (if (and (> b a) (< b (* a b))) b a);; => 4 (cond ((= a 4) 6) ((= b 4) (+ 6 7 a)) (t 25)) ; => 16 (+ 2 (if (> b a) b a)) ;; => 6 (* (cond ((> a b) a) ((< a b) b) (t -1)) (+ a 1)) ;; => 16 ;;;exercise 1.2 (/ (+ 5 4 (- 2 (- 3 (+ 6 (/ 4 5))))) (* 3 (- 6 2) (- 2 7))) ;;;exercise 1.3 (defun max3 (a b c) (+ (if (> a b) a b) (if (> b c) b c))) ;;;exercise 1.4 (defun a-plus-abs-b (a b) (funcall (if (> b 0) #'+ #'-) a b)) ;; => a 加上 b 的绝对值 ;;;exercise 1.5 ;如果是应用序求值,test调用前对 (p) 求值会进入死循环 ;如果是正则序求值,则返回0,这个过程中 (p) 没有被求值 ;;;example 1.1.7 (defun good-enough? (guess x) (< (abs (- (* guess guess) x)) 0.0001)) (defun sqrt-iter (guess x) (if (good-enough? guess x) guess (sqrt-iter (float (/ (+ guess (/ x guess)) 2)) x))) (defun my-sqrt (x) (sqrt-iter 1 x)) ;;;exercise 1.6 ;;cond 是应用序求值的情况下,new-if调用展开前then和else子句都会先求值 ;;;exercise 1.7 (defun sqrt-iter-x (guess x &optional (last-guess 0)) (format t "~A~%" guess) (if (< (abs (- guess last-guess)) 0.001) guess (sqrt-iter-x (float (/ (+ guess (/ x guess)) 2)) x guess))) (defun my-sqrt-x (x) (sqrt-iter-x 1 x)) ;过小的数不能检测,例如:(my-sqrt 0.00000000000001) ;过大的数不能检测,例如: (my-sqrt 1000000001) ;my-sqrt-x 可以,TODO 待检验 ;;;exercise 1.8 (defun good-enough?3 (guess x) (< (abs (- (* guess guess guess) x)) 0.001)) (defun cube-iter (guess x) (if (good-enough?3 guess x) guess (cube-iter (/ (+ (/ x (* guess guess)) (* 2 guess)) 3) x))) (defun my-cube (x) (cube-iter 1 x)) ;;;exercise 1.9 ; (+ 4 5) ; (inc (+ 3 5)) ; (inc (inc (+ 2 5))) ; (inc (inc (inc (+ 1 5)))) ; (inc (inc (inc (inc (+ 0 5))))) ; (inc (inc (inc (inc 5)))) ; ... ; (+ 4 5) ; (+ 3 6) ; (+ 2 7) ; (+ 1 8) ; (+ 0 9) ; 9 ;;第一个加法是递归,第二个加法是迭代 ;;;exercise 1.10 (defun aa (x y) (cond ((= y 0) 0) ((= x 0) (* 2 y)) ((= y 1) 2) (t (aa (- x 1) (aa x (- y 1)))))) (aa 1 10);; => 1024 (aa 2 4) ;; => 65535 (aa 3 3) ;; => 65535 ;;(f n) => 2n ;;(g n) => 2^(n^1) ;;(h n) => 2^(n^2) ;;;exercise 1.11 (defun fn-rec (n) (if (< n 3) n (+ (fn-rec (- n 1)) (* 2 (fn-rec (- n 2))) (* 3 (fn-rec (- n 3)))))) (defun fn-iter (n &optional (x 0) (y 1) (z 2)) (cond ((< n 3) n) ((= n 3) (+ (* 3 x) (* 2 y) z)) (t (fn-iter (- n 1) y z (+ (* 3 x) (* 2 y) z))))) ;;;exercise 1.12 (defun pascal-triangle (x y) (cond ((= x 1) 1) ((= x y) 1) (t (+ (pascal-triangle (- x 1) (- y 1)) (pascal-triangle x (- y 1)))))) ;;;exercise 1.13 TODO 证明 (defun fib (n &optional (x 0) (y 1)) (cond ((< n 2) n) ((= n 2) (+ x y)) (t (fib (- n 1) y (+ x y))))) ;;;exercise 1.14 (defun count-change (amount) (labels ((cc (rest-amount kinds-of-coins) (cond ((= rest-amount 0) 1) ((or (< rest-amount 0) (= kinds-of-coins 0)) 0) (t (+ (cc rest-amount (1- kinds-of-coins)) (cc (- rest-amount (case kinds-of-coins (1 1) (2 5) (3 10) (4 25) (t 50))) kinds-of-coins)))))) (cc amount 5))) ;(cc 11 5) ;(cc 11 4) (cc -39 5) ;(cc 11 3) (cc -14 4) 0 ;(cc 11 2) (cc 1 3) 0 ;(cc 11 1) (cc 6 2) (cc 1 2) (cc -9 3) ;(cc 11 0) (cc 10 1) (cc 6 1) (cc 1 2) (cc 1 1) (cc -4 2) 0 ;0 (cc 10 0) (cc 9 1) (cc 6 0) (cc 5 1) (cc 1 1) (cc -4 2) (cc 1 0) (cc 0 1) 0 ;0 (cc 9 0) (cc 8 1) 0 (cc 5 0) (cc 4 1) (cc 1 0) (cc 0 1) 0 0 1 ;0 (cc 8 0) (cc 7 1) 0 (cc 4 0) (cc 3 1) 0 1 1 ;0 (cc 7 0) (cc 6 1) 0 (cc 3 0) (cc 2 1) 1 1 ;0 (cc 6 0) (cc 5 1) 0 (cc 2 0) (cc 1 1) 1 1 ;0 (cc 5 0) (cc 4 1) 0 (cc 1 0) (cc 0 1) 1 1 ;0 (cc 4 0) (cc 3 1) 0 1 1 1 ;0 (cc 3 0) (cc 2 1) 1 1 1 ;0 (cc 2 0) (cc 1 1) 1 1 1 ;0 (cc 1 0) (cc 0 1) 1 1 1 ;0 1 1 1 1 ;4 ;空间 TODO ;增长的阶 TODO ;;;exercise 1.15 (defun sine (angle) (flet ((p (x) (- (* 3 x) (* 4 x x x)))) (if (not (> (abs angle) 0.1)) angle (p (sine (/ angle 3.0)))))) ;a) p 被使用了5次 ;b) 增长的阶都是 O(log a) ;;;exercise 1.16 (defun fast-expt-iter (b n &optional (a 1)) (cond ((= n 0) a) ((evenp n) (fast-expt-iter (* b b) (/ n 2) a)) (t (fast-expt-iter b (1- n) (* a b))))) ;;;exercise 1.17 (defun fast-* (a b) (labels ((double (x) (* x 2)) (halve (x) (/ x 2))) (cond ((= b 1) a) ((= b 0) 0) ((evenp b) (fast-* (double a) (halve b))) (t (+ a (fast-* a (1- b))))))) ;;;exercise 1.18 (defun fast-*-2 (a b &optional (product 0)) (labels ((double (x) (* x 2)) (halve (x) (/ x 2))) (cond ((= b 1) (+ a product)) ((= b 0) product) ((evenp b) (fast-*-2 (double a) (halve b) product)) (t (fast-*-2 a (1- b) (+ a product)))))) ;;;exercise 1.19 (defun fib-19 (n &optional (a 1) (b 0) (p 0) (q 1)) (cond ((= n 0) b) ((evenp n) (fib-19 (/ n 2) a b (+ (* p p) (* q q)) (+ (* 2 p q) (* q q)))) (t (fib-19 (1- n) (+ (* b q) (* a q) (* a p)) (+ (* b p) (* a q)) p q)))) ;;;exercise 1.20 (defun my-gcd (a b) (if (= b 0) a (my-gcd b (rem a b)))) ;;1.正则序 ; (my-gcd 206 40) ; (my-gcd 40 (rem 206 40)) ; (if (= (rem 206 40) 0) 40 (my-gcd 40 (rem 40 (rem 206 40))))TODO ;;2.应用序 ; (my-gcd 206 40) ; (my-gcd 40 6) ; (my-gcd 6 4) ; (my-gcd 4 2) ; (my-gcd 2 0) ; 执行四次 rem 操作 ;;; exercise 1.21 (defun prime? (n) (= n (smallest-divisor n))) (defun find-divisor (n test-divisor) (cond ((> (expt test-divisor 2) n) n) ((= (rem n test-divisor) 0) test-divisor) (t (find-divisor n (1+ test-divisor))))) (defun smallest-divisor (n) (find-divisor n 2)) ; 199 => 199 ; 1999 => 1999 ; 19999 => 19999 ;;; exercise 1.22 (defun timed-prime-test (n) (format t "~%~A" n) (start-prime-test n (get-internal-real-time))) (defun start-prime-test (n start-time) (if (prime? n) (progn (report-prime (- (get-internal-real-time) start-time)) n) nil)) (defun report-prime (elapsed-time) (format t " *** ~A" elapsed-time)) (defun search-for-primes (min-value) (loop for i from min-value with c = 0 when (timed-prime-test i) do (incf c) until (= c 3))) ; 耗时并非是10的平方根,100000和1000000的情况也不是如此,时间正比于计算步数?? TODO ;;; exercise 1.23 (defun next-div (n) (if (= n 2) 3 (+ n 2))) (defun find-divisor (n test-div) (cond ((> (expt test-div 2) n) n) ((= (rem n test-div) 0) test-div) (t (find-divisor n (next-div test-div))))) ; 事实情况并没有加快一倍,原因?? TODO ;;; exercise 1.24 (defun expmod (base exp m) (cond ((= exp 0) 1) ((evenp exp) (rem (expt (expmod base (/ exp 2) m) 2) m)) (t (rem (* base (expmod base (- exp 1) m)) m)))) (defun fermat-test (n) (let ((a (+ 1 (random (- n 1))))) (= (expmod a n n) a))) (defun fast-prime? (n &optional (times 10)) (cond ((= times 0) t) ((fermat-test n) (fast-prime? n (- times 1))) (t nil))) (defun timed-prime-test-2 (n) (format t "~%~A" n) (start-prime-test-2 n (get-internal-real-time))) (defun start-prime-test-2 (n start-time) (if (fast-prime? n) (progn (report-prime (- (get-internal-real-time) start-time)) n) nil)) ;;TODO 验证结果并解答 ;;;exercise 1.25 TODO ;;;exercise 1.26 TODO ;;;exercise 1.27 TODO ;;;exercise 1.28 TODO ;;;exercise 1.29 TODO ;;;exercise 1.30 (defun my-sum (term a next b) (labels ((iter (a result) (if (> a b) result (iter (funcall next a) (+ result (funcall term a)))))) (iter a 0))) ;;;exercise 1.31 (defun my-product (term a next b) (labels ((iter (a result) (if (> a b) result (iter (funcall next a) (* result (funcall term a)))))) (iter a 1))) (defun my-product-2 (term a next b) (if (> a b) 1 (* (funcall term a) (my-product-2 term (funcall next a) next b)))) (defun factorial (n) (my-product #'identity 1 #'1+ n)) (defun cal-pi () (float (* 4 (my-product (lambda (n) (/ (* n (+ n 2)) (expt (1+ n) 2))) 2 (lambda (n) (+ n 2)) 1000)))) ;;exercise 1.32 (defun accumulate-1 (combiner null-value term a next b) (if (> a b) null-value (funcall combiner (funcall term a) (accumulate-1 combiner null-value term (funcall next a) next b)))) (defun acc-sum (term a next b) (accumulate-1 #'+ 0 term a next b)) (defun acc-product (term a next b) (accumulate-1 #'* 1 term a next b)) (defun accumulate-2 (combiner null-value term a next b) (labels ((iter (a result) (if (> a b) result (iter (funcall next a) (funcall combiner result (funcall term a)))))) (iter a null-value))) ;;;exercise 1.33 (defun filtered-accumulate (combiner null-value predicte term a next b) (if (> a b) null-value (if (funcall predicte (funcall term a)) (funcall combiner (funcall term a) (filtered-accumulate combiner null-value predicte term (funcall next a) next b)) (filtered-accumulate combiner null-value predicte term (funcall next a) next b)))) (defun acc-prime (a b) (filtered-accumulate #'+ 0 #'prime? #'identity a #'1+ b)) ;;;exercise 1.34 ; 最后出现(2 2) 调用,而2不是一个过程,因此出错 ;;;exercise 1.35 (defun fixed-point (f first-guess) (labels ((close-enough? (v1 v2) (< (abs (- v1 v2)) 0.00001)) (try (guess) (let ((next (funcall f guess))) (if (close-enough? guess next) next (try next))))) (try first-guess))) ;(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0) => 1.6180328 ;;;exercise 1.36 (defun fixed-point-2 (f first-guess) (labels ((close-enough? (v1 v2) (< (abs (- v1 v2)) 0.00001)) (try (guess) (format t "guess: ~A~%" guess) (let ((next (funcall f guess))) (if (close-enough? guess next) next (try next))))) (try first-guess))) ;使用平均阻尼前后计算步数大概是 4:1 ;;;exercise 1.37 (defun cont-frac (n d k &optional (i 1)) (if (< i k) (/ (funcall n i) (+ (funcall d i) (cont-frac n d k (1+ i)))) (/ (funcall n i) (funcall d i)))) ; 具有4位精度时k为11 (defun cont-frac-2 (n d k) (labels ((iter (r i) (if (> i 1) (iter (/ (funcall n i) (+ (funcall d i) r)) (- i 1)) r))) (iter (/ (funcall n k) (funcall d k)) (- k 1)))) ;;;exercise 1.38 TODO 结果不对 (cont-frac-2 (lambda (i) 1.0) (lambda (i) (if (< i 3) i (if (= (mod (- i 2) 3) 0) (* 2 (+ 1 (/ (- i 2) 3))) 1))) 12) ;;;exercise 1.39 (defun tan-cf (x k) (cont-frac-2 (lambda (n) (if (> n 1) (* x x) x)) (lambda (d) (- (* d 2) 1)) k)) ;;;exercise 1.40 (defparameter dx 0.00001) (defun deriv (g) (lambda (x) (/ (- (funcall g (+ x dx)) (funcall g x)) dx))) (defun newtons-transform (g) (lambda (x) (- x (/ (funcall g x) (funcall (deriv g) x))))) (defun newtons-method (g guess) (fixed-point (newtons-transform g) guess)) (defun cubix (a b c) (lambda (x) (+ (* x x x) (* a x x) (* b x) c))) ;;;exercise 1.41 (defun double (f) (lambda (x) (funcall f (funcall f x)))) ;(funcall (funcall (double (double #'double)) #'1+) 5) => 21 ;;;exercise 1.42 (defun compose (f g) (lambda (x) (funcall f (funcall g x)))) ;;;exercise 1.43 (defun repeated (f n) (if (> n 1) (let ((cf f)) (dotimes (i (- n 1) cf) (setf cf (compose cf f)))) f)) ;;;exercise 1.44 (defun smooth (f) (lambda (x) (/ (+ (funcall f (- x dx)) (funcall f x) (funcall f (+ x dx))) 3))) ;;;exercise 1.45 TODO ;;;exercise 1.46 TODO
12,808
Common Lisp
.lisp
412
23.978155
95
0.484736
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
301ada6bb59e31c2f5917e441bbcf838affc2f98354db1d4b29faa2fa82ad307
20,237
[ -1 ]
20,238
4-2.lisp
LeZheng_l-lisp-demo/SICP_Exercise/4-2.lisp
(defun list-of-values (exps env) (if (no-operands? exps) '() (cons (l-eval (first-operand exps) env) (list-of-values (rest-operands exps) env)))) (defun eval-if (exp env) (if (true? (l-eval (if-predicate exp) env)) (l-eval (if-consequent exp) env) (l-eval (if-alternative exp) env))) (defun eval-sequence (exps env) (cond ((last-exp? exps) (l-eval (first-exp exps) env)) (t (l-eval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (defun eval-assignment (exp env) (set-variable-value! (assignment-variable exp) (l-eval (assignment-value exp) env) env) 'ok) (defun eval-definition (exp env) (define-variable! (definition-variable exp) (l-eval (definition-value exp) env) env) 'ok) (defun l-eval (exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (l-eval (cond->if exp) env)) ((application? exp) (l-apply (l-eval (operator exp) env) (list-of-values (operands exp) env))) (t (error "Unknown expression type -- EVAL" exp)))) (defun l-apply (procedure arguments) ;(format t "l-apply:~A~%" procedure) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (t (error "Unknown procedure type -- APPLY" procedure)))) (defun l->r-list-of-values (exps env) (if (no-operands? exps) '() (let ((left (l-eval (first-operand exps) env))) (let ((right (list-of-values (rest-operands exps) env))) (cons left right))))) (defun r->l-list-of-values (exps env) (if (no-operands? exps) '() (let ((rigth (list-of-values (rest-operands exps) env))) (let (left (l-eval (first-operand exps) env)) (cons left right))))) (defun self-evaluating? (exp) (cond ((numberp exp) t) ((stringp exp) t) (t nil))) (defun variable? (exp) (symbolp exp)) (defun tagged-list? (exp tag) (if (consp exp) (eql (car exp) tag) nil)) (defun quoted? (exp) (tagged-list? exp 'quote)) (defun text-of-quotation (exp) (cadr exp)) (defun assignment? (exp) (tagged-list? exp 'set!)) (defun assignment-variable (exp) (cadr exp)) (defun assignment-value (exp) (caddr exp)) (defun definition? (exp) (tagged-list? exp 'define)) (defun definition-variable (exp) (if (symbolp (cadr exp)) (cadr exp) (caadr exp))) (defun definition-value (exp) (if (symbolp (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) (defun lambda? (exp) (tagged-list? exp 'lambda)) (defun lambda-parameters (exp) (cadr exp)) (defun lambda-body (exp) (cddr exp)) (defun make-lambda (parameters body) (cons 'lambda (cons parameters body))) (defun if? (exp) (tagged-list? exp 'if)) (defun if-predicate (exp) (cadr exp)) (defun if-consequent (exp) (caddr exp)) (defun if-alternative (exp) (if (not (null (cdddr exp))) (cadddr exp) nil)) (defun make-if (predicate consequent alternative) (list 'if predicate consequent alternative)) (defun begin? (exp) (tagged-list? exp 'begin)) (defun begin-actions (exp) (cdr exp)) (defun last-exp? (seq) (null (cdr seq))) (defun first-exp (seq) (car seq)) (defun rest-exps (seq) (cdr seq)) (defun sequence-exp (seq) (cond ((null seq) seq) ((last-exp? seq) (first-exp seq)) (t (make-begin seq)))) (defun make-begin (seq) (cons 'begin seq)) (defun application? (exp) (consp exp)) (defun operator (exp) (car exp)) (defun operands (exp) (cdr exp)) (defun no-operands? (ops) (null ops)) (defun first-operand (ops) (car ops)) (defun rest-operands (ops) (cdr ops)) (defun cond? (exp) (tagged-list? exp 'cond)) (defun cond-clauses (exp) (cdr exp)) (defun cond-else-clause? (clause) (eql (cond-predicate clause) 'else)) (defun cond-predicate (clause) (car clause)) (defun cond-actions (clause) (cdr clause)) (defun cond->if (exp) (expand-clauses (cond-clauses exp))) (defun expand-clauses (clauses) (if (null clauses) 'nil (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null rest) (sequence-exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF" clauses)) (make-if (cond-predicate first) (sequence-exp (cond-actions first)) (expand-clauses rest)))))) (defun true? (x) (not (eql x nil))) (defun false? (x) (eql x nil)) (defun make-procedure (parameters body env) (list 'procedure parameters body env)) (defun compound-procedure? (p) (tagged-list? p 'procedure)) (defun procedure-parameters (p) (cadr p)) (defun procedure-body (p) (caddr p)) (defun procedure-environment (p) (cadddr p)) (defun enclosing-environment (env) (cdr env)) (defun first-frame (env) (car env)) (defvar the-empty-environment '()) (defun make-frame (variables values) (cons variables values)) (defun frame-variables (frame) (car frame)) (defun frame-values (frame) (cdr frame)) (defun add-binding-to-frame! (var val frame) (setf (car frame) (cons var (car frame))) (setf (cdr frame) (cons val (cdr frame)))) (defun extend-environment (vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals)))) (defun lookup-variable-value (var env) (labels ((env-loop (env) ;(format t "env-loop:~A - ~A~%" var env) (labels ((scan (vars vals) (cond ((null vars) (env-loop (enclosing-environment env))) ((eql var (car vars)) (car vals)) (t (scan (cdr vars) (cdr vals)))))) (if (eql env the-empty-environment) (error "Unbound variable:~A" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))))) (env-loop env))) (defun set-variable-value! (var val env) (labels ((env-loop (env) (labels ((scan (vars vals) (cond ((null vars) (env-loop (enclosing-environment env))) ((eql var (car vars)) (setf (car vals) val)) (t (scan (cdr vars) (cdr vals)))))) (if (eql env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env))))) (defun define-variable! (var val env) (let ((frame (first-frame env))) (labels ((scan (vars vals) (cond ((null vars) (add-binding-to-frame! var val frame)) ((eql var (car vars)) (setf (car vals) val)) (t (scan (cdr vars) (cdr vals)))))) (scan (frame-variables frame) (frame-values frame))))) (defun l-make-frame (variables values) (if (or (null variables) (null values)) nil (cons (cons (car variables) (car values)) (make-frame (cdr variables) (cdr values))))) (defun l-frame-variables (frame) (if (null frame) nil (cons (caar frame) (frame-variables (cdr frame))))) (defun l-frame-values (frame) (if (null frame) nil (cons (cdar frame) (frame-values (cdr frame))))) (defun l-add-binding-to-frame! (var val frame) (setf (cdr frame) frame) (setf (car frame) (cons var val))) (defun scan-map (vars vals found-action no-action) (cond ((null vars) (funcall no-action)) ((eql var (car vars)) (funcall found-action vars vals)) (t (scan-map (cdr vars) (cdr vals))))) (setf primitive-procedures (list (list 'car #'car) (list 'cdr #'cdr) (list 'cons #'cons) (list 'null #'null) )) (defun primitive-procedure-names () (mapcar #'car primitive-procedures)) (defun primitive-procedure-objects () (mapcar (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures)) (defun setup-environment () (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true t initial-env) (define-variable! 'false nil initial-env) initial-env)) (setf the-global-environment (setup-environment)) (defun primitive-procedure? (proc) (tagged-list? proc 'primitive)) (defun primitive-implementation (proc) (cadr proc)) (setf (symbol-function 'apply-in-underlying-scheme) #'apply) (defun apply-primitive-procedure (proc args) (apply-in-underlying-scheme (primitive-implementation proc) args)) (setf input-prompt ";;; M-Eval input:") (setf output-prompt ";;; M-Eval value:") (defun driver-loop () (prompt-for-input input-prompt) (let ((input (read))) (let ((output (l-eval input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (defun prompt-for-input (string) (format t "~%~%~A~%" string)) (defun announce-output (string) (format t "~%~A~%" string)) (defun user-print (object) (if (compound-procedure? object) (format t "~A" (list 'compound-procedure (procedure-parameters object) (procedure-body object) )) (format t "~A" object))) ;;;;4-2 ;;;4.2.2 (defun l-eval (exp env) (format t "l-eval: ~A <=> ~%" exp) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (l-eval (cond->if exp) env)) ((application? exp) (l-apply (actual-value (operator exp) env) (operands exp) env)) (t (error "Unknown expression type -- EVAL" exp)))) (defun actual-value (exp env) (format t "actual-value:~A <=>~%" exp) (force-it (l-eval exp env))) (defun l-apply (procedure arguments env) ;(format t "l-apply:~A~%" procedure) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure (list-of-arg-values arguments env))) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) (list-of-delayed-args arguments env) (procedure-environment procedure)))) (t (error "Unknown procedure type -- APPLY" procedure)))) (defun list-of-arg-values (exps env) (if (no-operands? exps) '() (cons (actual-value (first-operand exps) env) (list-of-arg-values (rest-operands exp) env)))) (defun list-of-delayed-args (exps env) (if (no-operands? exps) '() (cons (delay-it (first-operand exps) env) (list-of-delayed-args (rest-operands exps) env)))) (defun eval-if (exp env) (if (true? (actual-value (if-predicate exp) env)) (l-eval (if-consequent exp) env) (l-eval (if-alternative exp) env))) (setf input-prompt ";;; L-Eval input:") (setf output-prompt ";;; L-Eval output:") (defun driver-loop () (prompt-for-input input-prompt) (let ((input (read))) (let ((output (actual-value input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (defun force-it (obj) (if (thunk? obj) (actual-value (thunk-exp obj) (thunk-env obj)) obj)) (defun delay-it (exp env) (list 'thunk exp env)) (defun thunk? (obj) (tagged-list? obj 'thunk)) (defun thunk-exp (thunk) (cadr thunk)) (defun thunk-env (thunk) (caddr thunk)) (defun evaluated-thunk? (obj) (tagged-list? obj 'evaluated-thunk)) (defun thunk-value (evaluated-thunk) (cadr evaluated-thunk)) (defun force-it (obj) (cond ((thunk? obj) (let ((result (actual-value (thunk-exp obj) (thunk-env boj)))) (setf (car obj) 'evaluated-thunk) (setf (car (cdr obj)) result) (setf (cdr (cdr obj)) '()) result)) ((evaluated-thunk? obj) (thunk-value obj)) (t obj))) ;;;4.27 ;;0 ;;10 ;;2 ;;;4.28 ;;TODO 未知 ;;;4.29 ;;略 ;;100 ;;count => 1或2 ;;;4.30 TODO ;;;4.31 TODO important ;;;;4.2.3 TODO 待定
12,480
Common Lisp
.lisp
398
27.648241
68
0.660722
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a832f07d7faf7b1fadad853eedeb788c5e1c9eb024641c60963e3bf510ed942f
20,238
[ -1 ]
20,239
chapter-three.lisp
LeZheng_l-lisp-demo/SICP_Exercise/chapter-three.lisp
;;;;3.1 ;;;exercise 3.1 (defun make-accumulator (num) (lambda (x) (setf num (+ num x)) num)) ;;;exercise 3.2 (defun make-monitored (f) (let ((count 0)) (lambda (x) (if (equal 'how-many-calls x) count (progn (incf count) (funcall f x)))))) ;;;exercise 3.3 3.4 (defun make-account (balance psd) (labels ((withdraw (amount) (if (>= balance amount) (progn (setf balance (- balance amount)) balance) (warn "Insufficient Funds"))) (deposit (amount) (setf balance (+ balance amount)) balance) (call-the-cops () (error "Call the cops"))) (let ((error-count 0)) (lambda (password m) (if (equal password psd) (progn (setf error-count 0) (cond ((equal m 'withdraw) #'withdraw) ((equal m 'deposit) #'deposit) ((equal m 'check-password) t) (t (error "Unknown request -- MAKE_ACCOUNT" m)))) (progn (incf error-count) (if (>= error-count 7) (call-the-cops) "Incorrect Password"))))))) ;;;exercise 3.5 (defun cesaro-test () (= (gcd (random 1000) (random 1000)) 1)) (defun estimate-po (trials) (sqrt (/ 6 (monte-carlo trials #'cesaro-test)))) (defun monte-carlo (trials experiment) (labels ((iter (trials-remaining trials-passwd) (cond ((= trials-remaining 0) (/ trials-passwd trials)) ((experiment) (iter (- trials-remaining 1) (+ trials-passwd 1))) (t (iter (- trials-remaining 1) trials-passwd))))) (iter trials 0))) (defun random-in-range (low high) (+ low (random (- high low)))) (defun estimate-integral (trials p x1 x2 y1 y2) (* 4 (monte-carlo trials (lambda () (funcall p (random-in-range x1 x2) (random-in-range y1 y2)))))) ;;;exercise 3.6 (defvar random-init 1008611) (defun rand () (let ((state random-init)) (lambda (mode) (cond ((equal mode 'generate) (random state)) ((equal mode 'rest) (lambda (new-value) (setf state new-value) state)) (t (error "Unknown mode --RAND" mode)))))) ;;;exercise 3.7 (defun make-joint (acc psd new-password) (if (equal t (funcall acc psd 'check-password)) (lambda (password m) (if (equal password new-password) (funcall acc psd m) (error "Incorrect Password"))) (error "Origin Incorrect Password"))) ;;;exercise 3.8 (defvar last-n 0) (defun f (n) (let ((r last-n)) (setf last-n n) r)) ;;;exercise 3.9 3.10 3.11 ;;略 ;;;exercise 3.12 (defun last-pair (x) (if (null (cdr x)) x (last-pair (cdr x)))) (defun append! (x y) (setf (cdr (last-pair x)) y) x) ;;第一个是(B) ;;第二个是(B C D) ;;;exercise 3.13 (defun make-cycle (x) (setf (cdr (last-pair x)) x) x) ;;死循环 ;;;exercise 3.14 (defun mystery (x) (labels ((my-loop (x y) (if (null x) y (let ((temp (cdr x))) (setf (cdr x) y) (my-loop temp x))))) (my-loop x '()))) ;;w => (d c b a) ;;v => (a) ;;exercise 3.15 略 ;;;exercise 3.16 ;没有考虑共享和循环的情况,因此是错误的 ; '((1 3) 2 3) => 4 其中3共享 ; '((1 2 3) 2 3) => 7 其中 2 3 共享 ;;;exercise 3.17 (defun count-pairs (x) (let ((pairs '())) (labels ((count-p (x) (if (position x pairs) 0 (progn (push x pairs) (if (consp x) (1+ (count-p (cdr x))) 0))))) (count-p x)))) ;;;exercise 3.18 (defun is-loop (x) (let ((pairs '())) (labels ((has-loop? (x) (cond ((null x) nil) ((position x pairs) t) (t (progn (push x pairs) (has-loop? (cdr x))))))) (has-loop? x)))) ;;;exercise 3.19 (defun is-loop-1 (x) (labels ((iter (x1 x2) (if (and (not (null x1)) (eq x1 x2)) t (if (null x2) nil (iter (cdr x1) (cddr x2)))))) (iter x (cdr x)))) ;;;exercise 3.20 略 ;;;;3.3.2 (defun front-ptr (queue) (car queue)) (defun rear-ptr (queue) (cdr queue)) (defun set-front-ptr! (queue item) (setf (car queue) item)) (defun set-rear-ptr! (queue item) (setf (cdr queue) item)) (defun empty-queue? (queue) (null (front-ptr queue))) (defun make-queue () (cons '() '())) (defun front-queue (queue) (if (empty-queue? queue) (error "FRONT called with an empty queue" queue) (car (front-ptr queue)))) (defun insert-queue! (queue item) (let ((new-pair (cons item '()))) (cond ((empty-queue? queue) (set-front-ptr! queue new-pair) (set-rear-ptr! queue new-pair) queue) (t (setf (cdr (rear-ptr queue)) new-pair) (set-rear-ptr! queue new-pair) queue)))) (defun delete-queue! (queue) (if (empty-queue? queue) (error "DELETE called with an empty queue" queue) (progn (set-front-ptr! queue (cdr (front-ptr queue))) queue))) ;;;exercise 3.21 ;front-ptr开始的都清空了,但是rear-ptr没有清空 (defun print-queue (queue) (format t "~A~%" (front-ptr queue))) ;;;exercise 3.22 (defun make-queue () (let ((front-ptr '()) (rear-ptr '())) (labels ((empty-queue? () (null front-ptr)) ) (lambda (m) (case m ('front-ptr front-ptr) ('rear-ptr rear-ptr) ('empty-queue? (empty-queue?)) ('insert-queue! (lambda (item) (let ((new-pair (cons item '()))) (cond ((empty-queue?) (setf front-ptr new-pair) (setf rear-ptr new-pair) front-ptr) (t (setf (cdr rear-ptr) new-pair) (setf rear-ptr new-pair) front-ptr))))) ('delete-queue! (if (empty-queue?) (error "DELETE called with an empty queue") (progn (setf front-ptr (cdr front-ptr)) front-ptr)))))))) ;;;exercise 3.23 (defun make-deque () (let ((front-ptr '()) (rear-ptr '())) (labels ((empty-deque? () (null front-ptr))) (lambda (m) (case m ('front-deque front-ptr) ('rear-deque rear-ptr) ('empty-deque? (empty-deque?)) ('front-insert-deque! (lambda (item) (let ((new-pair (cons item (cons nil front-ptr)))) (cond ((empty-deque?) (setf front-ptr new-pair) (setf rear-ptr new-pair) (setf (cadr rear-ptr) new-pair) (setf (cddr front-ptr) new-pair) front-ptr) (t (setf (cadr front-ptr) new-pair) (setf front-ptr new-pair) front-ptr))))) ('rear-insert-deque! (lambda (item) (let ((new-pair (cons item (cons rear-ptr nil)))) (cond ((empty-deque?) (setf front-ptr new-pair) (setf rear-ptr new-pair) (setf (cadr rear-ptr) new-pair) (setf (cddr front-ptr) new-pair) front-ptr) (t (setf (cddr rear-ptr) new-pair) (setf rear-ptr new-pair) front-ptr))))) ('front-delete-deque! (when (not (empty-deque?)) (setf front-ptr (cddr front-ptr)) (setf (cadr front-ptr) nil) front-ptr)) ('rear-delete-deque! (when (not (empty-deque?)) (setf rear-ptr (cadr rear-ptr)) (setf (cddr rear-ptr) nil) front-ptr))))))) ;;;;3.3.3 (defun lookup (key table) (let ((record (my-assoc key (cdr table)))) (if record (cdr record) nil))) (defun my-assoc (key records) (cond ((null records) nil) ((equal key (caar records)) (car records)) (t (my-assoc key (cdr records))))) (defun insert! (key value table) (let ((record (my-assoc key (cdr table)))) (if record (setf (cdr record) value) (setf (cdr table) (cons (cons key value) (cdr table)))))) (defun make-table () (list '*table*)) (defun lookup (key-1 key-2 table) (let ((subtable (my-assoc key-1 (cdr table)))) (if subtable (let ((record (my-assoc key-2 (cdr subtable)))) (if record (cdr record) nil)) nil))) (defun insert! (key-1 key-2 value table) (let ((subtable (my-assoc key-1 (cdr table)))) (if subtable (let ((record (my-assoc key-2 (cdr subtable)))) (if record (setf (cdr record) value) (setf (cdr subtable) (cons (cons key-2 value) (cdr subtable))))) (setf (cdr table) (cons (list key-1 (cons key-2 value)) (cdr table)))))) (defun make-table () (let ((local-table (list '*table*))) (labels ((lookup (key-1 key-2) (let ((subtable (my-assoc key-1 (cdr local-table)))) (if subtable (let ((record (my-assoc key-2 (cdr subtable)))) (if record (cdr record) nil)) nil))) (insert! (key-1 key-2 value) (let ((subtable (my-assoc key-1 (cdr local-table)))) (if subtable (let ((record (my-assoc key-2 (cdr subtable)))) (if record (setf (cdr record) value) (setf (cdr subtable) (cons (cons key-2 value) (cdr subtable))))) (setf (cdr local-table) (cons (list key-1 (cons key-2 value)) (cdr local-table))))))) (lambda (m) (cond ((eq m 'lookup-proc) #'lookup) ((eq m 'insert-proc) #'insert!) (t (error "Unknown operation -- TABLE" m))))))) ;;;exercise3.24 (defun make-table-1 (same-key?) (let ((local-table (list '*table*))) (labels ((my-assoc (key records) (cond ((null records) nil) ((funcall same-key? key (caar records)) (car records)) (t (my-assoc key (cdr records)))))) (labels ((lookup (key-1 key-2) (let ((subtable (my-assoc key-1 (cdr local-table)))) (if subtable (let ((record (my-assoc key-2 (cdr subtable)))) (if record (cdr record) nil)) nil))) (insert! (key-1 key-2 value) (let ((subtable (my-assoc key-1 (cdr local-table)))) (if subtable (let ((record (my-assoc key-2 (cdr subtable)))) (if record (setf (cdr record) value) (setf (cdr subtable) (cons (cons key-2 value) (cdr subtable))))) (setf (cdr local-table) (cons (list key-1 (cons key-2 value)) (cdr local-table))))))) (lambda (m) (cond ((eq m 'lookup-proc) #'lookup) ((eq m 'insert-proc) #'insert!) (t (error "Unknown operation -- TABLE" m)))))))) ;;;exercise 3.25 (defun make-table-n () (let ((local-table (list '*table*))) (labels ((lookup (keys table) (let ((record (my-assoc (car keys) (cdr table)))) (if record (if (null (cdr keys)) record (lookup (cdr keys) record)) nil))) (insert! (keys value table) (let ((record (my-assoc (car keys) (cdr table)))) (if record (insert! (cdr keys) value (cdr record)) (if (null (cdr keys)) (setf (cdr table) (cons (cons (car keys) value) (cdr table))) (setf (cdr table) (cons (cons (car keys) (insert! (cdr keys) value (cdr table))) (cdr table)))))))) (lambda (m) (cond ((eq m 'lookup-proc) #'lookup) ((eq m 'insert-proc) #'insert!) (t (error "Unknown operation -- TABLE" m))))))) ;;;exercise 3.26 ;TODO ;;;exercise 3.27 ;对于每个n只计算一次 ;不能正常工作因为调用的是fib ;;;;3.3.4 (defun make-wire () (let ((signal-value 0) (action-procedures '())) (labels ((set-my-signal! (new-value) (if (not (= signal-value new-value)) (progn (setf signal-value new-value) (call-each action-procedures)) 'done)) (accept-action-procedure! (proc) (setf action-procedures (cons proc action-procedures)) (funcall proc)) (dispatch (m) (cond ((eql m 'get-signal) #'signal-value) ((eql m 'set-signal) #'set-my-signal!) ((eql m 'add-action!) #'accept-action-procedure!) (t (error "Unknown operation -- WIRE" m))))) #'dispatch))) (defun call-each (procedures) (if (null procedures) 'done (progn (funcall (car procedures) (call-each (cdr procedures)))))) (defun get-signal (wire) (funcall wire 'get-signal)) (defun set-signal! (wire new-value) (funcall (funcall wire 'set-signal!) new-value)) (defun add-action! (wire action-procedure) (funcall (funcall wire 'add-action!) action-procedure)) (defun logical-or (a1 a2) (cond ((or (= a1 1) (= a2 1)) 1) ((and (= a1 0) (= a2 0)) 0) (t (error "Invalid signal" a1 a2)))) (defun logical-and (a1 a2) (cond ((and (= a1 1) (= a2 1) 1)) ((or (= a1 0) (= a2 0)) 0) (t (error "Invalid signal" a1 a2)))) (defun logical-not (s) (cond ((= s 0) 1) ((= s 1) 0) (t (error "Invalid signal" s)))) (defun inverter (input output) (labels ((invert-input () (let ((new-value (logical-not (get-signal input)))) (after-delay inverter-delay (lambda () (set-signal! output new-value)))))) (add-action! input invert-input) 'ok)) (defun and-gate (a1 a2 output) (labels ((and-action-procedure () (let ((new-value (logical-and (get-signal a1) (get-signal a2)))) (after-delay and-gate-delay (lambda () (set-signal! output new-value)))))) (add-action! a1 and-action-procedure) (add-action! a2 and-action-procedure) 'ok)) ;;;exercise 3.28 (defun or-gate (a1 a2 output) (labels ((or-action-procedure () (let ((new-value (logical-or (get-signal a1) (get-signal a2)))) (after-delay or-gate-delay (lambda () (set-signal! output new-value)))))) (add-action! a1 or-action-procedure) (add-action! a2 or-action-procedure) 'or)) ;;;exercise 3.29 (defun or-gate-1 (a1 a2 output) (let ((invert-1 (make-wire)) (invert-2 (make-wire)) (and-invert-1-invert-2 (make-wire))) (inverter a1 invert-1) (inverter a2 invert-2) (and-gate a1 a2 and-invert-1-invert-2) (inverter and-invert-1-invert-2)) 'ok) ;时间为 3*invert-delay + and-gate-delay ;;;exercise 3.30 (defun half-adder (a b s c) (let ((d (make-wire)) (e (make-wire))) (or-gate a b d) (and-gate a b c) (inverter c e) (and-gate d e s) 'ok)) (defun full-adder (a b c-in sum c-out) (let ((s (make-wire)) (c1 (make-wire)) (c2 (make-wire))) (half-adder b c-in s c1) (half-adder a s sum c2) (or-gate c1 c2 c-out) 'ok)) (defun ripple-carry-adder (as bs ss c) (let ((c-out (make-wire))) (full-adder (car as) (car bs) c (car ss) c-out) (if (null (cdr as)) 'ok (ripple-carry-adder (cdr as) (cdr bs) (cdr ss) c-out)))) (defun after-delay (delay action) (add-to-agenda! (+ delay (current-time the-agenda)) action the-agenda)) (defun propagate () (if (empty-agenda? the-agenda) 'done (let ((first-item (first-agenda-item the-agenda))) (first-item) (remove-first-agenda-item! the-agenda) (propagate)))) (defun probe (name wire) (add-action! wire (lambda () (format t "~% ~A ~A New-value = ~A" name (l-current-time the-agenda) (get-signal wire))))) (defun make-time-segment (time queue) (cons time queue)) (defun segment-time (s) (car s)) (defun segment-queue (s) (cdr s)) (defun make-agenda () (list 0)) (defun l-current-time (agenda) (car agenda)) (defun set-current-time! (agenda time) (setf (car agenda) time)) (defun segments (agenda) (cdr agenda)) (defun set-segments! (agenda segments) (setf (cdr agenda) segments)) (defun first-segment (agenda) (car (segments agenda))) (defun rest-segments (agenda) (cdr (segments agenda))) (defun empty-agenda? (agenda) (null (segments agenda))) ;TODO uncomplete labels (defun add-to-agenda! (time action agenda) (labels ((belongs-before? (segments) (or (null segments) (< time (segment-time (car (segments)))))) (make-new-time-segment (time action) (let ((q (make-queue))) (insert-queue! q action) (make-time-segment time q))) (add-to-segments! (segments) (if (= (segment-time (car segments)) time) (insert-queue! (segment-queue (car segments)) action) (let ((rest (cdr segments))) (if (belongs-before? rest) (setf (cdr segments) (cons (make-new-time-segment time action) (cdr segments))) (add-to-segments! rest)))))) (let ((segments (segments agenda))) (if (belongs-before? segments) (set-segments! agenda (cons (make-new-time-segment time action) segments)) (add-to-segments! segments))))) (defun remove-first-agenda-item! (agenda) (let ((q (segment-queue (first-segment agenda)))) (delete-queue! q) (if (empty-queue? q) (set-segments! agenda (rest-segments agenda))))) (defun first-agenda-item (agenda) (if (empty-agenda? agenda) (error "agenda is empty -- FIRST-AGENDA-ITEM") (let ((first-seg (first-segment agenda))) (set-current-time! agenda (segment-time first-seg)) (front-queue (segment-queue first-seg))))) ;;;exercise 3.32 TODO ;;;;3.3.5 (defun celsius-fahrenheit-conerter (c f) (let ((u (make-connector)) (v (make-connector)) (w (make-connector)) (x (make-connector)) (y (make-connector))) (multiplier c w u) (multiplier v x u) (adder v y f) (constant 9 w) (constant 5 x) (constant 32 y) 'ok)) (defun adder (a1 a2 sum) (let ((me nil)) (labels ((process-new-value () (cond ((and (has-value? a1) (has-value? a2)) (set-value! sum (+ (get-value a1) (get-value a2)) me)) ((and (has-value? a1) (has-value? sum)) (set-value! a2 (- (get-value sum) (get-value a1)) me)) ((and (has-value? a2) (has-value? sum)) (set-value! a1 (- (get-value sum) (get-value a2)) me))))) (labels ((process-forget-value () (forget-value! sum me) (forget-value! a1 me) (forget-value! a2 me) (process-new-value))) (setf me (lambda (request) (cond ((eql request 'I-have-a-value) (process-new-value)) ((eql request 'I-lost-my-value) (process-forget-value)) (t (error "Unknown request -- ADDER" request))))) (connect a1 me) (connect a2 me) (connect sum me) me)))) (defun inform-about-value (constraint) (funcall constraint 'I-have-a-vlaue)) (defun inform-about-no-value (constraint) (funcall constraint 'I-lost-my-value)) (defun multiplier (m1 m2 product) (let ((me nil)) (labels ((process-new-value () (cond ((or (and (has-value? m1) (= (get-value m1) 0)) (and (has-value? m2) (= (get-value m2) 0))) (set-value! product 0 me)) ((and (has-value? m1) (has-value? m2)) (set-value! product (* (get-value m1) (get-value m2)) me)) ((and (has-value? product) (has-value? m1)) (set-value! m2 (/ (get-value product) (get-value m1)) me)) ((and (has-value? product) (has-value? m2)) (set-value! m1 (/ (get-value product) (get-value m2)) m2))))) (labels ((process-forget-value () (forget-value! product me) (forget-value! m1 me) (forget-value! m2 me) (process-new-value))) (setf me (lambda (request) (cond ((eql request 'I-have-a-vlaue) (process-new-value)) ((eql request 'I-lost-my-value) (process-forget-value)) (t (error "Unknown request -- MULTIPLIER" request))))) (connect m1 me) (connect m2 me) (connect product me) me)))) (defun constraint (value connector) (let ((me (lambda (request) (error "Unknown request -- CONSTANT" request)))) (connect connector me) (set-value! connector value me) me)) (defun probe (name connector) (labels ((print-probe (value) (format t "~% Probe:~A = ~A" name value))) (let ((me nil)) (labels ((process-new-value () (print-probe (get-value connector))) (process-forget-value () (print-probe "?"))) (setf me (lambda (request) (cond ((eql request 'I-have-a-vlaue) (process-new-value)) ((eql request 'I-lost-my-value) (process-forget-value)) (t (error "Unknown request -- PROBE" request))))) (connect connector me) me)))) (defun make-connector () (let ((value false) (informant false) (constraints '()) (me nil)) (labels ((set-my-value (newval setter) (cond ((not (has-value? me)) (setf value newval) (setf informant setter) (for-each-except setter #'inform-about-value constraints)) ((not (- value newval)) (error "Contradiction" (list value newval))) (t 'ignored))) (forget-my-value (retractor) (if (eql retractor informant) (progn (setf informant nil) (for-each-except retractor #'inform-about-no-value constraints)) 'ignored)) (connect (new-constraint) (if (not (member new-constraint constraints)) ;member memq ? (setf constraints (cons new-constraint constraints))) (if (has-value? me) (inform-about-value new-constraint)) 'done)) (setf me (lambda (request) (cond ((eql request 'has-value?) (if informant t nil)) ((eql request 'value) value) ((eql request 'set-value!) (lambda (n s) (set-my-value n s))) ((eql request 'forget) (lambda (r) (forget-my-value r))) ((eql request 'connect) (lambda (n) (connect n))) (t (error "Unknown operation -- CONNECTOR" request))))) me))) (defun for-each-except (exception procedure list) (labels ((inner-loop (items) (cond ((null items) 'done) ((eql (car items) exception) (inner-loop (cdr items))) ((t (funcall procedure (car items)) (inner-loop (cdr items))))))) (inner-loop list))) (defun has-value? (connector) (funcall connector 'has-value?)) (defun get-value (connector) (funcall connector 'value)) (defun set-value! (connector new-value informant) (funcall (funcall connector 'set-value!) new-value informant)) (defun forget-value! (connector retractor) (funcall (funcall connector 'forget) retractor)) (defun connect (connector new-constraint) (funcall (funcall connector 'connect) new-constraint)) ;;;exercise 3.33 (defun averager (a b c) (let ((sum (make-connector)) (d (make-connector))) (adder a b sum) (multiplier sum d c) (constant (/ 1 2) d) 'ok)) ;;;exercise 3.34 ;可以从a得到b,但是无法从b得到a,只有b有值的情况下,multiplier无法得到它的两个a引线的值。 ;;;exercise 3.35 (defun squarer (a b) (let ((me nil)) (labels ((process-new-value () (if (has-value? b) (if (< (get-value b) 0) (error "square less than 0 -- SQUARER" (get-value b)) (set-value! a (sqrt (get-value b)) me)) (if (has-value? a) (set-value! b (expt (get-value a) 2) me) (error "Neither a nor b has value")))) (process-forget-value () (forget-value! a me) (forget-value! b me))) (setf me (lambda (request) (cond ((eql request 'I-have-a-vlaue) (process-new-value)) ((eql request 'I-lost-my-value) (process-forget-value)) (t (error "Unknown request -- MULTIPLIER" request))))) (connect a me) (connect b me) me))) ;;;exercise 3.36 3.37 TODO ;;;;3.4 ;;;exercise 3.38 ;a 60 35 50 45 ;b 略 ;;;exercise 3.39 ;100还会出现 ;;;exercise 3.40 ;;a) 1000000 100000 10000 ;;b) 1000000 ;;;exercise 3.41 ;;不同意,不存在 ;;;exercise 3.42-3.49 ;;TODO ;;;;3.5 (defparameter the-empty-stream '()) (defun memo-proc (proc) (let ((already-run? nil) (result nil)) (lambda () (if (not already-run?) (progn (setf result (funcall proc)) (setf already-run? t) result) result)))) (defun stream-null? (stream) (null stream)) (defmacro delay (exp) `(memo-proc (lambda () ,exp))) (defun force (delayed-object) (funcall delayed-object)) (defmacro cons-stream (a b) `(cons ,a (delay ,b))) (defun stream-car (stream) (car stream)) (defun stream-cdr (stream) (force (cdr stream))) (defun stream-ref (s n) (if (= n 0) (stream-car s) (stream-ref (stream-cdr s) (- n 1)))) (defun stream-filter (pred stream) (cond ((stream-null? stream) the-empty-stream) ((funcall pred (stream-car stream)) (cons-stream (stream-car stream) (stream-filter pred (stream-cdr stream)))) (t (stream-filter pred (stream-cdr stream))))) (defun stream-for-each (proc s) (if (stream-null? s) 'done (progn (funcall proc (stream-car s)) (stream-for-each proc (stream-cdr s))))) (defun display-stream (s) (stream-for-each #'print s)) (defun stream-enumerate-interval (low high) (if (> low high) the-empty-stream (cons-stream low (stream-enumerate-interval (+ low 1) high)))) ;;;exercise 3.50 (defun stream-map (proc &rest argstreams) (if (null (car argstreams)) the-empty-stream (cons-stream (apply proc (mapcar #'stream-car argstreams)) (apply #'stream-map (cons proc (mapcar #'stream-cdr argstreams)))))) ;;;exercise 3.51 ;;0 1 2 3 4 5 6 7 8 9 10 ;;5 ;;7 ;;;exercise 3.52 ;;seq执行完是 210 ;;y 执行完是 210 ;;z 执行完是 210 ;;stream-ref 执行完是210 ,执行打印136 ;;display-stream 打印 10 15 45 55 105 120 190 210 DONE ;;并不总是210 ;;;exercise 3.53 ;;1 2 4 8 16 ... (defun add-streams (s1 s2) (stream-map #'+ s1 s2)) (defun mul-streams (s1 s2) (stream-map #'* s1 s2)) (setf ones (cons-stream 1 ones)) (setf integers (cons-stream 1 (add-streams ones integers))) ;;;exercise 3.54 (setf factorials (cons-stream 1 (mul-streams (stream-cdr integers) factorials))) ;;;exercise 3.55 (defun partial-sums (s) (cons-stream (stream-car s) (add-streams (partial-sums s) (stream-cdr s)))) ;;;exercise 3.56 (defun scale-stream (s factor) (stream-map (lambda (x) (* x factor)) s)) (defun merge-stream (s1 s2) (cond ((stream-null? s1) s2) ((stream-null? s2) s1) (t (let ((s1car (stream-car s1)) (s2car (stream-car s2))) (cond ((< s1car s2car) (cons-stream s1car (merge-stream (stream-cdr s1) s2))) ((> s1car s2car) (cons-stream s2car (merge-stream s1 (stream-cdr s2)))) (t (cons-stream s1car (merge-stream (stream-cdr s1) (stream-cdr s2))))))))) (setf S (cons-stream 1 (merge-stream (scale-stream S 2) (merge-stream (scale-stream S 3) (scale-stream S 5))))) ;;;exercise 3.57 ;;带有记忆过程,所以是n次加法。不带记忆过程的时候就是指数。 ;;;exercise 3.58 (defun expand (num den radix) (cons-stream (floor (* num radix) den) (expand (mod (* num radix) den) den radix))) ;;expand 1 7 10 => 1 4 2 8 5 7 ... ;;expand 3 8 10 => 7 5 0 0 0 0 ... ;;;exercise 3.59 ;;a) (defun integrate-series (a) (mul-streams a (stream-map #'/ ones integers))) ;;b) TODO ;;;exercise 3.60 3.61 3.62 TODO ;;;;3.5.3 (defun average (a b) (/ (+ a b) 2)) (defun sqrt-improve (guess x) (average guess (/ x guess))) (defun sqrt-stream (x) (let ((guesses nil)) (setf guesses (cons-stream 1.0 (stream-map (lambda (guess) (sqrt-improve guess x)) guesses))) guesses)) (defun pi-summands (n) (cons-stream (/ 1.0 n) (stream-map #'- (pi-summands (+ n 2))))) (setf pi-stream (scale-stream (partial-sums (pi-summands 1)) 4)) ;;;exercise 3.63 ;;一个是沿用前面的结果来计算流的下一个元素,而另一个是每次都是新的流,复杂度分别为O(n)和O(n^2) ;;不带memo-proc的话效率一样。 ;;;exercise 3.64 (defun stream-limit (s tolerance) (let ((a (stream-car s)) (b (stream-car (stream-cdr s)))) (if (< (abs (- x y)) tolerance) b (stream-limit (stream-cdr s) tolerance)))) ;;;exercise 3.65 (defun ln2-stream (n) (cons-stream (/ 1 n) (stream-map #'- (ln2-stream (+ n 1))))) (setf ln2 (partial-sums (ln2-stream 1))) ;;;; (defun interleave (s1 s2) (if (stream-null? s1) s2 (cons-stream (stream-car s1) (interleave s2 (stream-cdr s1))))) (defun pairs (s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (pairs (stream-cdr s) (stream-cdr t))))) ;;;exercise 3.66 TODO ;;;exercise 3.67 (defun pairs-2 (s t) (cons-stream (list (stream-car s) (stream-car t)) (interleave (interleave (stream-map (lambda (x) (list (stream-car s) x)) (stream-cdr t)) (stream-map (lambda (x) (list (stream-car t) x)) (stream-cdr s))) (pairs (stream-cdr s) (stream-cdr t))))) ;;;exercise 3.68 TODO ;;;exercise 3.69 (defun triples (s t u) (cons-stream (list (stream-car s) (stream-car t) (stream-car u)) (interleave (stream-map (lambda (x) (list (stream-car s) (car x) (cadr x))) (pairs (stream-cdr t) (stream-cdr u))) (triples (stream-cdr s) (stream-cdr t) (stream-cdr u))))) ;;TODO 毕达哥拉斯三元组 ;;;exercise 3.70 TODO ;;;exercise 3.71 TODO ;;;exercise 3.72 TODO ;;;exercise 3.73 (defun integral (integrand initial-value dt) (let ((int nil)) (setf int (cons-stream initial-value (add-streams (scale-stream integrand dt) int))) int)) (defun rc (r c dt) ;;TODO ) ;;;exercise 3.74 ;;(setf zero-crossings (stream-map #'sign-change-detector sense-data (cons-stream 0 sense-data))) ;;;exercise 3.75 TODO ;;;exercise 3.76 TODO ;;;exercise 3.77 (defun integral-1 (delay-integrand initial-value dt) (cons-stream initial-value (if (stream-null? (force delay-integrand)) the-empty-stream (integral-1 (stream-cdr (force delay-integrand)) (+ (* dt (stream-car (force delay-integrand))) initial-value) dt)))) ;;;exercise 3.78 (defun solve-2nd (a b dt y0 dyo dydt) ;;TODO ) ;;;exercise 3.79 TODO ;;;exercise 3.80 TODO ;;;exercise 3.81 TODO ;;;exercise 3.82 TODO
33,660
Common Lisp
.lisp
938
25.901919
114
0.522753
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a29a0603643e71668715d1f6d93ef70f28f02063185790fda508ea946c457d52
20,239
[ -1 ]
20,240
5-2.lisp
LeZheng_l-lisp-demo/SICP_Exercise/5-2.lisp
(defun test-demo-1 () (let ((gcd-machine (make-machine '(a b t) (list (list 'rem #'rem) (list '= #'=)) '(test-b (test (op =) (reg b) (const 0)) (branch (label gcd-done)) (assign t (op rem) (reg a) (reg b)) (assign a (reg b)) (assign b (reg t)) (goto (label test-b)) gcd-done)))) (set-register-contents gcd-machine 'a 206) (set-register-contents gcd-machine 'b 40) (set-breakpoint gcd-machine 'test-b 4) (set-breakpoint gcd-machine 'test-b 3) (cancel-breakpoint gcd-machine 'test-b 4) ;(cancel-all-breakpoints gcd-machine) (start gcd-machine) (get-register-contents gcd-machine 'a))) (defun tagged-list? (exp tag) (if (consp exp) (eql (car exp) tag) nil)) (defun make-machine (register-names ops controller-text) (let ((machine (make-new-machine))) (dolist (register-name register-names) (funcall (funcall machine 'allocate-register) register-name)) (funcall (funcall machine 'install-operations) ops) (funcall (funcall machine 'install-instruction-sequence) (assemble controller-text machine)) machine)) (defun make-register (name) (let ((contents '*unassigned*) (trace-flag nil)) (lambda (message) (case message ('trace-on (setf trace-flag t)) ('trace-off (setf trace-flag nil)) ('get contents) ('set (lambda (v) (if trace-flag (format t "set register ~A from ~A to ~A~%" name contents v));;寄存器跟踪 (setf contents v))) (otherwise (error "Unknown request -- REGISTER" message)))))) (defun get-contents (register) (funcall register 'get)) (defun set-contents (register value) (funcall (funcall register 'set) value)) (defun make-stack () (let ((s '()) (number-pushes 0) (max-depth 0) (current-depth 0)) (labels ((s-push (x) (setf s (cons x s)) (setf number-pushes (1+ number-pushes)) (setf current-depth (1+ current-depth)) (setf max-depth (max current-depth max-depth))) (s-pop () (if (null s) (error "Empty stack -- POP") (let ((top (car s))) (setf s (cdr s)) (setf current-depth (- current-depth 1)) top))) (initialize () (setf s '()) (setf number-pushes 0) (setf max-depth 0) (setf current-depth 0) 'done) (print-statistics () (format t "~% total-pushes = ~A~% maximum-depth = ~A" number-pushes max-depth))) (lambda (message) (case message ('push #'s-push) ('pop (s-pop)) ('print-statistics (print-statistics)) ('initialize (initialize))))))) (defun s-pop (stack) (funcall stack 'pop)) (defun s-push (stack value) (funcall (funcall stack 'push) value)) (defun make-new-machine () (let ((execute-count 0) (trace-flag t) (pc (make-register 'pc)) (flag (make-register 'flag)) (stack (make-stack)) (the-instruction-sequence '())) (let ((the-ops (list (list 'initialize-stack (lambda () (funcall stack 'initialize))) (list 'print-stack-statistics (lambda () (funcall stack 'print-statistics))))) (register-table (list (list 'pc pc) (list 'flag flag)))) (labels ((allocate-register (name) (if (assoc name register-table) (error "Multiply defined register:" name) (setf register-table (cons (list name (make-register name)) register-table))) 'register-allocated) (lookup-register (name) (let ((val (assoc name register-table))) (if val (cadr val) nil))) (execute () (let ((insts (get-contents pc))) (if (null insts) 'done (if (instruction-breakpoint (car insts)) 'break (progn (if trace-flag (format t "execute : ~A~%" (caar insts)));;指令追踪 (funcall (instruction-execution-proc (car insts))) (setf execute-count (1+ execute-count));;指令计数 (execute))))))) (lambda (message) (case message ('start (set-contents pc the-instruction-sequence) (execute)) ('install-instruction-sequence (lambda (seq) (setf the-instruction-sequence seq))) ('allocate-register #'allocate-register) ('get-register #'lookup-register) ('install-operations (lambda (ops) (setf the-ops (append the-ops ops)))) ('stack stack) ('operations the-ops) ('instructions the-instruction-sequence) ('trace-on (setf trace-flag t)) ('trace-off (setf trace-flag nil)) ('print-execute-count (lambda () (format t "execute-count: ~A~%" execute-count) (setf execute-count 0))) ('continue-break (let ((insts (get-contents pc))) (if (null insts) 'done (progn (if trace-flag (format t "execute : ~A~%" (caar insts)));;指令追踪 (funcall (instruction-execution-proc (car insts))) (setf execute-count (1+ execute-count));;指令计数 (execute))))) (otherwise (error "Unknown request -- MACHINE" message)))))))) (defun start (machine) (funcall machine 'start)) (defun get-register-contents (machine register-name) (get-contents (get-register machine register-name))) (defun set-register-contents (machine register-name value) (set-contents (get-register machine register-name) value) 'done) (defun get-register (machine reg-name) (funcall (funcall machine 'get-register) reg-name)) (defun get-or-allocate-register (machine reg-name) (let ((register (get-register machine reg-name))) (if (null register) (progn (funcall (funcall machine 'allocate-register) reg-name) (get-register machine reg-name)) register))) (defun assemble (controller-text machine) (extract-labels controller-text (lambda (insts labels) (update-insts insts labels machine) insts))) (defun extract-labels (text receive) (if (null text) (funcall receive '() '()) (extract-labels (cdr text) (lambda (insts labels) (let ((next-inst (car text))) (if (symbolp next-inst) (if (find-if (lambda (l) (equal l next-inst)) labels :key #'car) (error "label is existed") (funcall receive insts (cons (make-label-entry next-inst insts) labels))) (funcall receive (cons (make-instruction next-inst) insts) labels))))))) (defun update-insts (insts labels machine) (let ((pc (get-register machine 'pc)) (flag (get-register machine 'flag)) (stack (funcall machine 'stack)) (ops (funcall machine 'operations))) (dolist (label labels) (dolist (inst (cdr label)) (set-instruction-label inst (car label)))) (dolist (inst insts) (set-instruction-execution-proc inst (make-execution-procedure (instruction-text inst) labels machine pc flag stack ops))))) (defun make-instruction (text) (cons (list nil nil text) '())) (defun instruction-text (inst) (nth 2 (car inst))) (defun instruction-label (inst) (nth 0 (car inst))) (defun instruction-execution-proc (inst) (cdr inst)) (defun set-instruction-label (inst label-name) (setf (nth 0 (car inst)) label-name)) (defun set-instruction-breakpoint (inst break-on) (setf (nth 1 (car inst)) break-on)) (defun instruction-breakpoint (inst) (nth 1 (car inst))) (defun set-instruction-execution-proc (inst proc) (setf (cdr inst) proc)) (defun make-label-entry (label-name insts) (cons label-name insts)) (defun lookup-label (label-table label-name) (let ((val (assoc label-name label-table))) (if val (cdr val) (error "Undefined label label -- ASSEMBLE" label-name)))) (defun make-execution-procedure (inst labels machine pc flag stack ops) (case (car inst) ('assign (make-assign inst machine labels ops pc)) ('test (make-test inst machine labels ops flag pc)) ('branch (make-branch inst machine labels flag pc)) ('goto (make-goto inst machine labels pc)) ('save (make-save inst machine stack pc)) ('restore (make-restore inst machine stack pc)) ('perform (make-perform inst machine labels ops pc)) ('init-stack (make-init-stack inst machine stack ops pc)) ('print-statistics (make-print-statistics inst machine stack ops pc)) (otherwise (error "Unknown instruction type -- ASSEMBLE" inst)))) (defun make-assign (inst machine labels operations pc) (let ((target (get-or-allocate-register machine (assign-reg-name inst))) (value-exp (assign-value-exp inst))) (let ((value-proc (if (operation-exp? value-exp) (make-operation-exp value-exp machine labels operations) (make-primitive-exp (car value-exp) machine labels)))) (lambda () (set-contents target (funcall value-proc)) (advance-pc pc))))) (defun assign-reg-name (assign-instruction) (cadr assign-instruction)) (defun assign-value-exp (assign-instruction) (cddr assign-instruction)) (defun advance-pc (pc) (set-contents pc (cdr (get-contents pc)))) (defun make-test (inst machine labels operations flag pc) (let ((condition (test-condition inst))) (if (operation-exp? condition) (let ((condition-proc (make-operation-exp condition machine labels operations))) (lambda () (set-contents flag (funcall condition-proc)) (advance-pc pc))) (error "Bad TEST instruction -- ASSEMBLE" inst)))) (defun test-condition (test-instruction) (cdr test-instruction)) (defun make-branch (inst machine labels flag pc) (let ((dest (branch-dest inst))) (if (label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (if (get-contents flag) (set-contents pc insts) (advance-pc pc)))) (error "Bad BRANCH instruction -- ASSEMBLE" inst)))) (defun branch-dest (branch-instruction) (cadr branch-instruction)) (defun make-goto (inst machine labels pc) (let ((dest (goto-dest inst))) (cond ((label-exp? dest) (let ((insts (lookup-label labels (label-exp-label dest)))) (lambda () (set-contents pc insts)))) ((register-exp? dest) (let ((reg (get-or-allocate-register machine (register-exp-reg dest)))) (lambda () (set-contents pc (get-contents reg))))) (otherwise (error "Bad GOTO instruction -- ASSEMBLE" inst))))) (defun goto-dest (goto-instruction) (cadr goto-instruction)) (defun make-init-stack (inst machine stack operations pc) (lambda () (let ((op (lookup-prim 'initialize-stack operations))) (funcall op)) (advance-pc pc))) (defun make-print-statistics (inst machine stack operations pc) (lambda () (let ((op (lookup-prim 'print-stack-statistics operations))) (funcall op)) (advance-pc pc))) (defun make-save (inst machine stack pc) (let ((reg (get-or-allocate-register machine (stack-inst-reg-name inst)))) (lambda () (s-push stack (get-contents reg)) (advance-pc pc)))) (defun make-restore (inst machine stack pc) (let ((reg (get-or-allocate-register machine (stack-inst-reg-name inst)))) (lambda () (set-contents reg (s-pop stack)) (advance-pc pc)))) (defun stack-inst-reg-name (stack-instruction) (cadr stack-instruction)) (defun make-perform (inst machine labels operations pc) (let ((action (perform-action inst))) (if (operation-exp? action) (let ((action-proc (make-operation-exp action machine labels operations))) (lambda () (funcall action-proc) (advance-pc pc))) (error "Bad PERFORM instruction -- ASSEMBLE" inst)))) (defun perform-action (inst) (cdr inst)) (defun make-primitive-exp (exp machine labels) (cond ((constant-exp? exp) (let ((c (constant-exp-value exp))) (lambda () c))) ((label-exp? exp) (let ((insts (lookup-label labels (label-exp-label exp)))) (lambda () insts))) ((register-exp? exp) (let ((r (get-or-allocate-register machine (register-exp-reg exp)))) (lambda () (get-contents r)))) (otherwise (error "Unknown expression type -- ASSEMBLE" exp)))) (defun register-exp? (exp) (tagged-list? exp 'reg)) (defun register-exp-reg (exp) (cadr exp)) (defun constant-exp? (exp) (tagged-list? exp 'const)) (defun constant-exp-value (exp) (cadr exp)) (defun label-exp? (exp) (tagged-list? exp 'label)) (defun label-exp-label (exp) (cadr exp)) (defun make-operation-exp (exp machine labels operations) (let ((op (lookup-prim (operation-exp-op exp) operations)) (aprocs (mapcar (lambda (e) (make-primitive-exp e machine labels)) (operation-exp-operands exp)))) (lambda () (apply op (mapcar (lambda (p) (funcall p)) aprocs))))) (defun operation-exp? (exp) (and (consp exp) (tagged-list? (car exp) 'op))) (defun operation-exp-op (operation-exp) (cadr (car operation-exp))) (defun operation-exp-operands (operation-exp) (cdr operation-exp)) (defun lookup-prim (symbol operations) (let ((val (assoc symbol operations))) (if val (cadr val) (error "Unknown operation ~A ASSEMBLE" symbol)))) (defun test-demo-2 () (let ((gcd-machine (make-machine '();;这里不传递所需要的寄存器,而是汇编程序直接根据指令添加寄存器 (list (list 'rem #'rem) (list '= #'=)) '(test-b (test (op =) (reg b) (const 0)) (branch (label gcd-done)) (assign t (op rem) (reg a) (reg b)) (assign a (reg b)) (assign b (reg t)) (goto (label test-b)) gcd-done)))) (set-register-contents gcd-machine 'a 206) (set-register-contents gcd-machine 'b 40) (funcall gcd-machine 'trace-on);;测试指令追踪 (funcall (get-register gcd-machine 'a) 'trace-on);;测试寄存器跟踪 (start gcd-machine) (funcall (funcall gcd-machine 'print-execute-count));;测试指令计数 (get-register-contents gcd-machine 'a))) (defun test-demo-3 () (let ((n-machine (make-machine '() (list (list '= #'=) (list '- #'-) (list '* #'*) (list 'read (lambda () (print "Please input:") (read))) (list 'print (lambda (v) (print v)))) '( start (init-stack) (assign n (op read)) (assign continue (label fact-done)) fact-loop (test (op =) (reg n) (const 1)) (branch (label base-case)) (save continue) (save n) (assign n (op -) (reg n) (const 1)) (assign continue (label after-fact)) (goto (label fact-loop)) after-fact (restore n) (restore continue) (assign val (op *) (reg n) (reg val)) (goto (reg continue)) base-case (assign val (const 1)) (goto (reg continue)) fact-done (perform (op print) (reg val)) (print-statistics) (goto (label start)))))) (start n-machine))) (defun set-breakpoint (machine label n) (labels ((iter (insts) (cond ((null insts) nil) ((equal label (instruction-label (car insts))) (set-instruction-breakpoint (nth (- n 1) insts) t)) (t (iter (cdr insts)))))) (iter (funcall machine 'instructions)))) (defun proceed-machine (machine) (funcall machine 'continue-break)) (defun cancel-breakpoint (machine label n) (labels ((iter (insts) (cond ((null insts) nil) ((equal label (instruction-label (car insts))) (set-instruction-breakpoint (nth (- n 1) insts) nil)) (t (iter (cdr insts)))))) (iter (funcall machine 'instructions)))) (defun cancel-all-breakpoints (machine) (dolist (inst (funcall machine 'instructions)) (set-instruction-breakpoint inst nil)))
15,301
Common Lisp
.lisp
416
31.521635
97
0.651685
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d6ec1d6d8d8640ae04bdf33b4b681ddac8c00c33719ef466531abb795fe7b712
20,240
[ -1 ]
20,241
chapter-four.lisp
LeZheng_l-lisp-demo/SICP_Exercise/chapter-four.lisp
;;;;4.1.1 (defun list-of-values (exps env) (if (no-operands? exps) '() (cons (l-eval (first-operand exps) env) (list-of-values (rest-operands exps) env)))) (defun eval-if (exp env) (if (true? (l-eval (if-predicate exp) env)) (l-eval (if-consequent exp) env) (l-eval (if-alternative exp) env))) (defun eval-sequence (exps env) (cond ((last-exp? exps) (l-eval (first-exp exps) env)) (t (l-eval (first-exp exps) env) (eval-sequence (rest-exps exps) env)))) (defun eval-assignment (exp env) (set-variable-value! (assignment-variable exp) (l-eval (assignment-value exp) env) env) 'ok) (defun eval-definition (exp env) (define-variable! (definition-variable exp) (l-eval (definition-value exp) env) env) 'ok) (defun l-eval (exp env) (cond ((self-evaluating? exp) exp) ((variable? exp) (lookup-variable-value exp env)) ((quoted? exp) (text-of-quotation exp)) ((assignment? exp) (eval-assignment exp env)) ((definition? exp) (eval-definition exp env)) ((if? exp) (eval-if exp env)) ((lambda? exp) (make-procedure (lambda-parameters exp) (lambda-body exp) env)) ((begin? exp) (eval-sequence (begin-actions exp) env)) ((cond? exp) (l-eval (cond->if exp) env)) ((application? exp) (l-apply (l-eval (operator exp) env) (list-of-values (operands exp) env))) (t (error "Unknown expression type -- EVAL" exp)))) (defun l-apply (procedure arguments) (format t "l-apply:~A~%" procedure) (cond ((primitive-procedure? procedure) (apply-primitive-procedure procedure arguments)) ((compound-procedure? procedure) (eval-sequence (procedure-body procedure) (extend-environment (procedure-parameters procedure) arguments (procedure-environment procedure)))) (t (error "Unknown procedure type -- APPLY" procedure)))) ;;;exercise 4.1 (defun l->r-list-of-values (exps env) (if (no-operands? exps) '() (let ((left (l-eval (first-operand exps) env))) (let ((right (list-of-values (rest-operands exps) env))) (cons left right))))) (defun r->l-list-of-values (exps env) (if (no-operands? exps) '() (let ((rigth (list-of-values (rest-operands exps) env))) (let (left (l-eval (first-operand exps) env)) (cons left right))))) (defun self-evaluating? (exp) (cond ((numberp exp) t) ((stringp exp) t) (t nil))) (defun variable? (exp) (symbolp exp)) (defun tagged-list? (exp tag) (if (consp exp) (eql (car exp) tag) nil)) (defun quoted? (exp) (tagged-list? exp 'quote)) (defun text-of-quotation (exp) (cadr exp)) (defun assignment? (exp) (tagged-list? exp 'set!)) (defun assignment-variable (exp) (cadr exp)) (defun assignment-value (exp) (caddr exp)) (defun definition? (exp) (tagged-list? exp 'define)) (defun definition-variable (exp) (if (symbolp (cadr exp)) (cadr exp) (caadr exp))) (defun definition-value (exp) (if (symbolp (cadr exp)) (caddr exp) (make-lambda (cdadr exp) (cddr exp)))) (defun lambda? (exp) (tagged-list? exp 'lambda)) (defun lambda-parameters (exp) (cadr exp)) (defun lambda-body (exp) (cddr exp)) (defun make-lambda (parameters body) (cons 'lambda (cons parameters body))) (defun if? (exp) (tagged-list? exp 'if)) (defun if-predicate (exp) (cadr exp)) (defun if-consequent (exp) (caddr exp)) (defun if-alternative (exp) (if (not (null (cdddr exp))) (cadddr exp) nil)) (defun make-if (predicate consequent alternative) (list 'if predicate consequent alternative)) (defun begin? (exp) (tagged-list? exp 'begin)) (defun begin-actions (exp) (cdr exp)) (defun last-exp? (seq) (null (cdr seq))) (defun first-exp (seq) (car seq)) (defun rest-exps (seq) (cdr seq)) (defun sequence-exp (seq) (cond ((null seq) seq) ((last-exp? seq) (first-exp seq)) (t (make-begin seq)))) (defun make-begin (seq) (cons 'begin seq)) (defun application? (exp) (consp exp)) (defun operator (exp) (car exp)) (defun operands (exp) (cdr exp)) (defun no-operands? (ops) (null ops)) (defun first-operand (ops) (car ops)) (defun rest-operands (ops) (cdr ops)) (defun cond? (exp) (tagged-list? exp 'cond)) (defun cond-clauses (exp) (cdr exp)) (defun cond-else-clause? (clause) (eql (cond-predicate clause) 'else)) (defun cond-predicate (clause) (car clause)) (defun cond-actions (clause) (cdr clause)) (defun cond->if (exp) (expand-clauses (cond-clauses exp))) (defun expand-clauses (clauses) (if (null clauses) 'nil (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null rest) (sequence-exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF" clauses)) (make-if (cond-predicate first) (sequence-exp (cond-actions first)) (expand-clauses rest)))))) ;;;exercise 4.2 ;;后续的if cond 之类的表达式都被当成过程应用处理了。 (defun application?-2 (exp) (eql (car exp) 'call)) ;;;exercise 4.3 (defun d-eval (exp env) (let ((eval-proc (get 'eval (expression-type exp)))) (if (null eval-proc) (error "Unknown expression type -- EVAL" exp) (funcall eval-proc exp env)))) (defun expression-type (exp) (cond ((self-evaluating? exp) 'self-evaluating) ((variable? exp) 'variable) ((quoted? exp) 'quote) ((assignment? exp) 'assignment) ((definition? exp) 'definition) ((if? exp) 'if) ((lambda? exp) 'lambda) ((begin? exp) 'begin) ((cond? exp) 'cond) ((let? exp) 'let) ((application? exp) 'application) (t (error "Unknown expression type -- EXPRESSION-TYPE" exp)))) (defun install-eval () (setf (get 'eval 'self-evaluating) (lambda (exp env) exp)) (setf (get 'eval 'variable) #'lookup-variable-value) (setf (get 'eval 'quote) (lambda (exp env) (text-of-quotation exp))) (setf (get 'eval 'assignment) (lambda (exp env) (set-variable-value! (assignment-variable exp) (d-eval (assignment-value exp) env) env) 'ok)) (setf (get 'eval 'definition) (lambda (exp env) (define-variable! (definition-variable exp) (d-eval (definition-value exp) env) env) 'ok)) (setf (get 'eval 'if) (lambda (exp env) (if (true? (d-eval (if-predicate exp) env)) (d-eval (if-consequent exp) env) (d-eval (if-alternative exp) env)))) (setf (get 'eval 'lambda) (lambda (exp env) (make-procedure (lambda-parameters exp) (scan-out-defines (lambda-body exp)) ;;这里的 scan-out-defines 来自练习4.16 env))) (setf (get 'eval 'begin) (lambda (exp env) (eval-sequence (begin-actions exp) env))) (setf (get 'eval 'cond) (lambda (exp env) (d-eval (cond->if exp) env))) (setf (get 'eval 'application) (lambda (exp env) (l-apply (d-eval (operator exp) env) (list-of-values (operands exp) env))))) ;(install-eval) ;;;exercise 4.4 (defun eval-and (exps env) (let ((r (d-eval (car exps) env))) (cond ((null r) nil) ((null (cdr exps)) r) (t (eval-and (cdr exps) env))))) (setf (get 'eval '(and)) (lambda (exp env) (eval-and (cdr exp) env))) (defun eval-or (exps env) (let ((r (d-eval (car exps) env))) (cond ((not (null r)) r) ((not (null (cdr exps))) (eval-or (cdr exps) env)) (t nil)))) (setf (get 'eval '(or)) (lambda (exp env) (eval-or (cdr exp) env))) ;;TODO and or 实现为派生表达式 ;;;exercise 4.5 (defun test-recipient? (exp) (and (= 3 (length exp)) (eql '=> (cadr exp)))) (defun expand-clauses (clauses) (if (null clauses) 'nil (let ((first (car clauses)) (rest (cdr clauses))) (if (cond-else-clause? first) (if (null rest) (sequence-exp (cond-actions first)) (error "ELSE clause isn't last -- COND->IF" clauses)) (if (test-recipient? first) (let ((value (car first)) (proc (caddr first))) (make-if value (list 'd-eval (list proc value)) (expand-clauses rest))) ;这里的value会求值2次,会有问题 (make-if (cond-predicate first) (sequence-exp (cond-actions first)) (expand-clauses rest))))))) ;;;exercise 4.6 (defun let? (exp) (tagged-list? exp 'let)) (defun let-variables (exp) (let ((vars '())) (dolist (item (cadr exp)) (push (car item) vars)) (reverse vars))) (defun let-exps (exp) (let ((exps '())) (dolist (item (cadr exp)) (push (cadr item) exps)) (reverse exps))) (defun let-body (exp) (caddr exp)) (defun let->combination (exp) (cons (list 'lambda (let-variables exp) (let-body exp)) (let-exps exp))) (setf (get 'eval '(let)) (lambda (exp env) (d-eval (let->combination exp) env))) ;;;exercise 4.7 (defun let*->nested-lets (exp) (labels ((iter (vars) (list 'let (cons (car vars) nil) (if (null (cdr cars)) (let-body exp) (iter (cdr vars)))))) (iter (cadr exp)))) (defun let*? (exp) (tagged-list? exp '(let*))) (setf (get 'eval '(let*)) (lambda (exp env) (d-eval (let*->nested-lets exp) env))) ;;不必以非派生方式来扩充 ;;;exercise 4.8 ;;TODO ;;;exercise 4.9 ;;TODO do for while until ;;;exercise 4.10 ;;修改选择函数和构造函数即可 TODO 不是很理解? ;;;; 4.1.3 (defun true? (x) (not (eql x nil))) (defun false? (x) (eql x nil)) (defun make-procedure (parameters body env) (list 'procedure parameters body env)) (defun compound-procedure? (p) (tagged-list? p 'procedure)) (defun procedure-parameters (p) (cadr p)) (defun procedure-body (p) (caddr p)) (defun procedure-environment (p) (cadddr p)) (defun enclosing-environment (env) (cdr env)) (defun first-frame (env) (car env)) (defvar the-empty-environment '()) (defun make-frame (variables values) (cons variables values)) (defun frame-variables (frame) (car frame)) (defun frame-values (frame) (cdr frame)) (defun add-binding-to-frame! (var val frame) (setf (car frame) (cons var (car frame))) (setf (cdr frame) (cons val (cdr frame)))) (defun extend-environment (vars vals base-env) (if (= (length vars) (length vals)) (cons (make-frame vars vals) base-env) (if (< (length vars) (length vals)) (error "Too many arguments supplied" vars vals) (error "Too few arguments supplied" vars vals)))) (defun lookup-variable-value (var env) (labels ((env-loop (env) (format t "env-loop:~A - ~A~%" var env) (labels ((scan (vars vals) (cond ((null vars) (env-loop (enclosing-environment env))) ((eql var (car vars)) (car vals)) (t (scan (cdr vars) (cdr vals)))))) (if (eql env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))))) (env-loop env))) (defun set-variable-value! (var val env) (labels ((env-loop (env) (labels ((scan (vars vals) (cond ((null vars) (env-loop (enclosing-environment env))) ((eql var (car vars)) (setf (car vals) val)) (t (scan (cdr vars) (cdr vals)))))) (if (eql env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))) (env-loop env))))) (defun define-variable! (var val env) (let ((frame (first-frame env))) (labels ((scan (vars vals) (cond ((null vars) (add-binding-to-frame! var val frame)) ((eql var (car vars)) (setf (car vals) val)) (t (scan (cdr vars) (cdr vals)))))) (scan (frame-variables frame) (frame-values frame))))) ;;;exercise 4.11 (defun l-make-frame (variables values) (if (or (null variables) (null values)) nil (cons (cons (car variables) (car values)) (make-frame (cdr variables) (cdr values))))) (defun l-frame-variables (frame) (if (null frame) nil (cons (caar frame) (frame-variables (cdr frame))))) (defun l-frame-values (frame) (if (null frame) nil (cons (cdar frame) (frame-values (cdr frame))))) (defun l-add-binding-to-frame! (var val frame) (setf (cdr frame) frame) (setf (car frame) (cons var val))) ;;;exercise 4.12 (defun scan-map (vars vals found-action no-action) (cond ((null vars) (funcall no-action)) ((eql var (car vars)) (funcall found-action vars vals)) (t (scan-map (cdr vars) (cdr vals))))) ;;;exercise 4.13 TODO ;;;;4.1.4 (setf primitive-procedures (list (list 'car #'car) (list 'cdr #'cdr) (list 'cons #'cons) (list 'null #'null) )) (defun primitive-procedure-names () (mapcar #'car primitive-procedures)) (defun primitive-procedure-objects () (mapcar (lambda (proc) (list 'primitive (cadr proc))) primitive-procedures)) (defun setup-environment () (let ((initial-env (extend-environment (primitive-procedure-names) (primitive-procedure-objects) the-empty-environment))) (define-variable! 'true t initial-env) (define-variable! 'false nil initial-env) initial-env)) (setf the-global-environment (setup-environment)) (defun primitive-procedure? (proc) (tagged-list? proc 'primitive)) (defun primitive-implementation (proc) (cadr proc)) (setf (symbol-function 'apply-in-underlying-scheme) #'apply) (defun apply-primitive-procedure (proc args) (apply-in-underlying-scheme (primitive-implementation proc) args)) (setf input-prompt ";;; M-Eval input:") (setf output-prompt ";;; M-Eval value:") (defun driver-loop () (prompt-for-input input-prompt) (let ((input (read))) (let ((output (d-eval input the-global-environment))) (announce-output output-prompt) (user-print output))) (driver-loop)) (defun prompt-for-input (string) (format t "~%~%~A~%" string)) (defun announce-output (string) (format t "~%~A~%" string)) (defun user-print (object) (if (compound-procedure? object) (format t "~A" (list 'compound-procedure (procedure-parameters object) (procedure-body object) )) (format t "~A" object))) ;;;exercise 4.14 ;;运行环境不同 ;;;exercise 4.15 略 ;;;exercise 4.16 (defun lookup-variable-value (var env) (labels ((env-loop (env) (format t "env-loop:~A - ~A~%" var env) (labels ((scan (vars vals) (cond ((null vars) (env-loop (enclosing-environment env))) ((eql (car vals) '*unassigned*) (error "value is *unassigned*")) ((eql var (car vars)) (car vals)) (t (scan (cdr vars) (cdr vals)))))) (if (eql env the-empty-environment) (error "Unbound variable" var) (let ((frame (first-frame env))) (scan (frame-variables frame) (frame-values frame))))))) (env-loop env))) (defun scan-out-defines (body) (let ((bindings '()) (result-body '())) (dolist (item body) (if (definition? item) (progn (push (list (definition-variable item) '*unassigned*) bindings) (push (list 'setf (definition-variable item) (definition-value item)) result-body)) (push item result-body))) (cons 'let (cons bindings (reverse result-body))))) ;;;exercise 4.17 ;;1. 因为变换之后的程序多了一个let,这个时候引入了新的frame。 ;;2. 因为e3求值的时候访问的是同样的定义,尽管环境不同。 ;;3. TODO ;;;exercise 4.18 ;;1. 不能正常工作,因为这里面的dy的定义依赖于之前y的定义,或者说,y的定义必须在dy的定义前。 ;;;exercise 4.19 ;;支持eva的方式 ;;实现 TODO ;;;exercise 4.20 (defun trans-letrec (exp) (let ((bindings '()) (result-body '())) (dolist (binding (cadr exp)) (format t "~A~%" binding) (push (cons (car binding) '*unassigned*) bindings) (format t "1~%") (push (list 'setf (car binding) (cadr binding)) result-body)) (cons 'let (cons bindings (append result-body (cddr exp)))))) ;;b) 环境层数不一样 ;;;exercise 4.21 ;;a)确实可以 (defun test-fib () (funcall (lambda (n) (funcall (lambda (f) (funcall f f (1- n))) (lambda (f i) (cond ((= i 0) 1) ((= i 1) 1) (t (+ (funcall f f (- i 1)) (funcall f f (- i 2)))))))) 10)) ;;b) (defun f (x) (funcall (lambda (even? odd?) (funcall even? even? odd? x)) (lambda (ev? od? n) (if (= n 0) t (funcall od? ev? od? (- n 1)))) (lambda (ev? od? n) (if (= n 0) nil (funcall ev? ev? od? (- n 1)))))) ;;;;4.1.7 (defun c-eval (exp env) (funcall (analyze exp) env)) (defun analyze (exp) (cond ((self-evaluating? exp) (analyze-self-evaluating exp)) ((quoted? exp) (analyze-quoted exp)) ((variable? exp) (analyze-variable exp)) ((assignment? exp) (analyze-assignment exp)) ((definition? exp) (analyze-definition exp)) ((if? exp) (analyze-if exp)) ((lambda? exp) (analyze-lambda exp)) ((begin? exp) (analyze-sequence (begin-actions exp))) ((cond? exp) (analyze (cond->if exp))) ((let? exp) (analyze-let exp)) ((application? exp) (analyze-application exp)) (t (error "Unknown expression type -- ANALYZE" exp)))) (defun analyze-self-evaluating (exp) (lambda (env) exp)) (defun analyze-quoted (exp) (let ((qval (text-of-quotation exp))) (lambda (env) qval))) (defun analyze-variable (exp) (lambda (env) (lookup-variable-value exp env))) (defun analyze-assignment (exp) (let ((var (assignment-variable exp)) (vproc (analyze (assignment-value exp)))) (lambda (env) (set-variable-value! var (funcall vproc env) env) 'ok))) (defun analyze-definition (exp) (let ((var (definition-variable exp)) (vproc (analyze (definition-value exp)))) (lambda (env) (define-variable! var (vproc env) env) 'ok))) (defun analyze-if (exp) (let ((pproc (analyze (if-predicate exp))) (cproc (analyze (if-consequent exp))) (aproc (analyze (if-alternative exp)))) (lambda (env) (if (true? (pproc env)) (funcall cproc env) (funcall aproc env))))) (defun analyze-lambda (exp) (let ((vars (lambda-parameters exp)) (bproc (analyze-sequence (lambda-body exp)))) (lambda (env) (make-procedure vars bproc env)))) (defun analyze-sequence (exps) (labels ((sequentially (proc1 proc2) (lambda (env) (funcall proc1 env) (funcall proc2 env)))) (labels ((loop (first-proc rest-procs) (if (null rest-procs) first-proc (loop (sequentially first-proc (car rest-procs)) (cdr rest-procs))))) (let ((procs (mapcar #'analyze exps))) (if (null procs) (error "Empty sequence -- ANALYZE")) (loop (car procs) (cdr procs)))))) (defun analyze-application (exp) (let ((fproc (analyze (operator exp))) (aprocs (mapcar #'analyze (operands exp)))) (lambda (env) (execute-application (funcall fproc env) (mapcar (lambda (aproc) (funcall aproc env)) aprocs))))) (defun execute-application (proc args) (cond ((primitive-procedure? proc) (apply-primitive-procedure proc args)) ((compound-procedure? proc) (funcall (procedure-body proc) (extend-environment (procedure-parameters proc) args (procedure-environment proc)))) (t (error "Unknown procedure type -- EXECUTE-APPLICATION" proc)))) ;;;exercise 4.22 (defun analyze-let (exp) (lambda (env) (c-eval (let->combination exp) env))) ;;;exercise 4.23 判断是否为最后一个过程的操作,正文中的在分析阶段就完成了 ;;;exercise 4.24 TODO ;;;; 4.2 ;;; exercise 4.25 ;;在应用序的Scheme里会出现死循环,在正则序的语言里能正常工作 ;;;exercise 4.26 ;;实现可以参考if,把条件反过来。 ;;情况举例不出来
19,415
Common Lisp
.lisp
593
28.05059
95
0.647847
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8894949fd9924853610e6336120b3ef23a670fe22b983a2e865104ff60c499f2
20,241
[ -1 ]
20,242
os-environment.lisp
LeZheng_l-lisp-demo/32_Platform_Specific_Extensions/os-environment.lisp
;;; (EXT:GETENV) ;;;get all environment variables (EXT:GETENV "PATH") ;;get PATH environment variable (SETF (EXT:GETENV "TIME") (format nil "~A" (get-universal-time))) (EXT:GETENV "TIME")
192
Common Lisp
.lisp
5
36.6
65
0.706522
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
01eb2cddef0a0878c0bb5b4c7d9164fa3e192992056750cf0efe40ba4fe9c4c8
20,242
[ -1 ]
20,243
socket-demo.lisp
LeZheng_l-lisp-demo/32_Platform_Specific_Extensions/socket-demo.lisp
;;;There are some socket examples (defun start-read-tcp-server (port) (LET ((server (SOCKET:SOCKET-SERVER port))) (FORMAT t "~&Waiting for a connection on ~S:~D~%" (SOCKET:SOCKET-SERVER-HOST server) (SOCKET:SOCKET-SERVER-PORT server)) (UNWIND-PROTECT (LOOP (WITH-OPEN-STREAM (socket (SOCKET:SOCKET-ACCEPT server)) (MULTIPLE-VALUE-BIND (local-host local-port) (SOCKET:SOCKET-STREAM-LOCAL socket) (MULTIPLE-VALUE-BIND (remote-host remote-port) (SOCKET:SOCKET-STREAM-PEER socket) (FORMAT T "~&Connection: ~S:~D -- ~S:~D~%" remote-host remote-port local-host local-port))) (LOOP (WHEN (EQ :eof (SOCKET:SOCKET-STATUS (cons socket :input))) (RETURN)) (format t "~A~%" (read-line socket))))) (SOCKET:SOCKET-SERVER-CLOSE server)))) (DEFUN wget-text (host page file &OPTIONAL (port 80)) "This function is to get a page from host/page:port,and output to file,like:(wget-text \"www.baidu.com\" \"/\" \"a.txt\")" (WITH-OPEN-STREAM (socket (SOCKET:SOCKET-CONNECT port host :EXTERNAL-FORMAT :DOS)) (FORMAT socket "GET ~A HTTP/1.0~2%" page) (WITH-OPEN-FILE (out file :direction :output) (LOOP :for line = (READ-LINE socket nil nil) :while line :do (WRITE-LINE line out))))) (DEFUN wget-binary (host page file &OPTIONAL (port 80)) "This function is to get a binary file from host/page:port,and output to file" (WITH-OPEN-STREAM (socket (SOCKET:SOCKET-CONNECT port host :EXTERNAL-FORMAT :DOS)) (FORMAT socket "GET ~A HTTP/1.0~2%" page) (LOOP :with content-length :for line = (READ-LINE socket nil nil) :until (ZEROP (LENGTH line)) :do (WHEN (STRING= line #1="Content-length: " :end1 #2=#.(LENGTH #1#)) (SETQ content-length (PARSE-INTEGER line :start #2#)) :finally (RETURN (LET ((data (MAKE-ARRAY content-length :element-type '(UNSIGNED-BYTE 8)))) (SETF (STREAM-ELEMENT-TYPE socket) '(UNSIGNED-BYTE 8)) (EXT:READ-BYTE-SEQUENCE data socket) (WITH-OPEN-FILE (out file :direction :output :ELEMENT-TYPE '(UNSIGNED-BYTE 8)) (EXT:WRITE-BYTE-SEQUENCE data out)) data)))))) (DEFUN wput (host page file &OPTIONAL (port 80)) "This function is to put a file to host/page:port" (WITH-OPEN-STREAM (socket (SOCKET:SOCKET-CONNECT port host :EXTERNAL-FORMAT :DOS)) (WITH-OPEN-FILE (in file :direction :inptut :ELEMENT-TYPE '(UNSIGNED-BYTE 8)) (LET* ((length (FILE-LENGTH in)) (data (MAKE-ARRAY length :element-type '(UNSIGNED-BYTE 8)))) (FORMAT socket "PUT ~A HTTP/1.0~%Content-length: ~D~2%" page length) (SETF (STREAM-ELEMENT-TYPE socket) '(UNSIGNED-BYTE 8)) (EXT:READ-BYTE-SEQUENCE data in) (EXT:WRITE-BYTE-SEQUENCE data socket))) (SOCKET:SOCKET-STREAM-SHUTDOWN socket :output) (LOOP :for line = (READ-LINE socket nil nil) :while line :collect line)))
3,777
Common Lisp
.lisp
52
49.423077
135
0.505911
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
893d98a2f87386929a2c287a061c824a74e2343cfd43e76b7b73314e36186d12
20,243
[ -1 ]
20,244
foreign-fun.lisp
LeZheng_l-lisp-demo/32_Platform_Specific_Extensions/foreign-fun.lisp
;;; (FFI:OPEN-FOREIGN-LIBRARY "libpthread.so.0");;open a shared library (FFI:DEF-C-STRUCT foo ;;define a c struct (a ffi:int) (b (ffi:c-array (ffi:c-ptr foo) 100))) (declare (type foo f)) (foo-a (aref (foo-b f) 7)) (FFI:DEF-C-STRUCT bar (x ffi:short) (y ffi:short) (a ffi:char) (b ffi:char) ; or (b character) if it represents a character, not a number (z ffi:int) (n (ffi:c-ptr bar))) (FFI:DEF-C-VAR my_struct (:type (ffi:c-ptr bar))) (setq my_struct (let ((s my_struct)) (incf (slot-value s 'x)) s)) ; or (incf (slot my_struct 'x)) (setq my_struct (let ((s my_struct)) (setf (slot-value s 'a) 5) s)) ; or (setf (slot my_struct 'a) 5) (setq my_struct (slot-value my_struct 'n)) ; or (setq my_struct (deref (slot my_struct 'n)))
799
Common Lisp
.lisp
21
34.47619
80
0.606727
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7d8a1d57c5d87e726b4198d6de0485dea3892d15b110bca9ea8940f391a0daaf
20,244
[ -1 ]
20,245
llgen-tool.lisp
LeZheng_l-lisp-demo/EOPL_Exercise/llgen-tool.lisp
;;Scanner-spec ::= ({Regexp-and-action }∗ ) ;;Regexp-and-action ::= (Name ({Regexp}∗ ) Action) ;;Name ::= Symbol ;;Regexp ::= String | letter | digit | whitespace | any ;; ::= (not Character) | (or {Regexp}∗ ) ;; ::= (arbno Regexp) | (concat {Regexp} ∗ ) ;;Action ::= skip | symbol | number | string (defun make-string-scanner (scanner-spec) (format t "lexical spec:~A~%" scanner-spec) (labels ((concat-reducer (reducer c) (lambda (s) (funcall reducer (cons c s)))) (result-length (r) (length (if (vectorp r) (svref r 1) r))) (re-read (scanner remain-chars) (if remain-chars (if (functionp scanner) (re-read (funcall scanner (car remain-chars)) (cdr remain-chars)) (cons (car scanner) (append (cdr scanner) remain-chars))) scanner)) (regexp->scanner (regexp reducer next-cont) (if (null regexp) (funcall next-cont (funcall reducer nil) nil) (lambda (c) (if (null c) (funcall next-cont (funcall reducer nil) nil) (labels ((handle-single-char-with (predicate) (if (funcall predicate c) (regexp->scanner (cdr regexp) (concat-reducer reducer c) next-cont) (funcall next-cont nil (funcall reducer `(,c)))))) (let ((exp (car regexp))) (etypecase exp (cons (funcall (regexp->scanner exp #'identity (lambda (token-chars remain-chars) (if (or token-chars (equal (car exp) 'arbno)) (re-read (regexp->scanner (cdr regexp) (lambda (s) (funcall reducer (append token-chars s))) next-cont) remain-chars) (funcall next-cont nil (funcall reducer remain-chars))))) c)) (string (funcall (regexp->scanner `((concat ,@(coerce exp 'list)) ,@(cdr regexp)) reducer next-cont) c)) (character (handle-single-char-with (lambda (c) (equal exp c)))) (symbol (ecase exp (letter (handle-single-char-with #'alpha-char-p)) (digit (handle-single-char-with #'digit-char-p)) (whitespace (funcall (regexp->scanner (cons '(concat (or #\Space #\NewLine) (arbno (or #\Space #\NewLine))) (cdr regexp)) reducer next-cont) c)) (any (handle-single-char-with (lambda (c) t))) (not (if (not (equal c (cadr regexp))) (funcall next-cont (funcall reducer `(,c)) nil) (funcall next-cont nil (funcall reducer `(,c))))) (or (labels ((apply-scanners (scanners c) (let ((scanners (mapcar (lambda (scanner) (if (functionp scanner) (funcall scanner c) (append scanner `(,c))));;append need optimize scanners))) (if (some #'functionp scanners) (lambda (c) (apply-scanners scanners c)) (let ((result (reduce (lambda (&optional a b) (if (and a b) (if (>= (result-length (car a)) (result-length (car b))) a b))) scanners))) (funcall next-cont (car result) (cdr result))))))) (apply-scanners (mapcar (if (eql scanner-spec (cdr regexp)) (lambda (spec) (regexp->scanner (cadr spec) #'identity (lambda (token-chars remain-chars) (cons (vector (car spec) token-chars (caddr spec)) remain-chars)))) (lambda (sub-exp) (regexp->scanner (if (consp sub-exp) sub-exp (cons sub-exp nil)) #'identity #'cons))) (cdr regexp)) c))) (arbno (funcall (regexp->scanner (cdr regexp) #'identity (lambda (token-chars remain-chars) (if token-chars (re-read (regexp->scanner regexp #'identity (lambda (tc2 rc2) (if tc2 (funcall next-cont (funcall reducer (append token-chars tc2)) rc2) (funcall next-cont (funcall reducer token-chars) rc2)))) remain-chars) (funcall next-cont (funcall reducer nil) remain-chars)))) c)) (concat (funcall (regexp->scanner (cdr regexp) reducer next-cont) c)))))))))))) (lambda (text) (let ((src-scanner (regexp->scanner (cons 'or scanner-spec) #'identity #'cons))) (labels ((iter-char (chars scanner tokens) (if chars (let ((r (funcall scanner (car chars)))) (if (functionp r) (iter-char (cdr chars) r tokens) (progn ;;(format t "iter token: ~A~%" r) (if (svref (car r) 1) (iter-char (append (cdr r) (cdr chars)) src-scanner (cons (car r) tokens)) (reverse tokens))))) (mapcan (lambda (r) (destructuring-bind (name chars action) (coerce r 'list) (let ((token (coerce chars 'string))) (ecase action (symbol (list (make-symbol token))) (number (list (read-from-string token))) (string (list token)) (skip nil))))) (reverse (cons (car (funcall scanner nil)) tokens)))))) (iter-char (coerce text 'list) src-scanner nil)))))) ;;Grammar ::= ({Production}∗ ) ;;Production ::= (Lhs ({Rhs-item}∗ ) Prod-name) ;;Lhs ::= Symbol ;;Rhs-item ::= Symbol | String ;; ::= (arbno {Rhs-item}∗ ) ;; ::= (separated-list {Rhs-item}∗ String) ;;Prod-name ::= Symbol (defun make-token-parser (grammar-spec) (let ((parser-table (make-hash-table))) (labels ((try-call-parser (parser token) (if (functionp parser) (funcall parser token) (append parser `(,token))));;append need optimize (re-read (parser tokens) (if (null tokens) parser (if (functionp parser) (re-read (funcall parser (car tokens)) (cdr tokens)) (cons (car parser) (append (cdr parser) tokens))))) (rhs->parser (rhs-items reducer next-cont) (if (null rhs-items) (funcall next-cont (funcall reducer nil) nil) (let ((rhs-item (car rhs-items))) (labels ((parse-string (token) (if (equal token rhs-item) (rhs->parser (cdr rhs-items) (lambda (tokens) (funcall reducer (cons token tokens))) next-cont) (funcall next-cont nil (funcall reducer `(,token))))) (parse-symbol (token) (case rhs-item (number (if (numberp token) (rhs->parser (cdr rhs-items) (lambda (tokens) (funcall reducer (cons token tokens))) next-cont) (funcall next-cont nil (funcall reducer `(,token))))) (identifier (if (not (numberp token)) (rhs->parser (cdr rhs-items) (lambda (tokens) (funcall reducer (cons token tokens))) next-cont) (funcall next-cont nil (funcall reducer `(,token))))) (otherwise (let ((parser-list (gethash rhs-item parser-table))) (if (null parser-list) (error "unsupported symbol: ~A" rhs-item) (labels ((apply-parsers (token parsers) (let ((parsers (mapcar (lambda (p) (try-call-parser p token)) parsers))) (if (some #'functionp parsers) (lambda (token) (apply-parsers token parsers)) (let ((result (reduce (lambda (&optional a b) (cond ((null a) b) ((null b) a) (t (if (< (length (cdr a)) (length (cdr b))) a b)))) parsers))) (re-read (rhs->parser (cdr rhs-items) (lambda (tokens) (funcall reducer (cons (car result) tokens))) next-cont) (cdr result))))))) (apply-parsers token parser-list))))))) (parse-arbno (token) (labels ((next-parser (arbno-cont) (rhs->parser (cdr rhs-items) #'identity (lambda (pt rt) (if (null pt) (funcall arbno-cont nil rt) (re-read (next-parser (lambda (pt2 rt2) (funcall arbno-cont (cons pt pt2) rt2))) rt)))))) (funcall (next-parser next-cont) token))) (parse-separated-list (token) (labels ((next-parser (cont) (rhs->parser (butlast (cdr rhs-items)) #'identity (lambda (pt rt) (if (null pt) (funcall cont nil rt) (re-read (rhs->parser (last rhs-items) #'identity (lambda (s srt) (if (null s) (funcall cont pt srt) (re-read (next-parser (lambda (pt2 rt2) (funcall cont (cons pt (cons (car s) pt2)) rt2))) srt)))) rt)))))) (funcall (next-parser next-cont) token)))) (lambda (token) (if (null token) (funcall next-cont nil (funcall reducer nil)) (let ((rhs-item (car rhs-items))) (etypecase rhs-item (simple-vector (funcall (rhs->parser (cons (svref rhs-item 1) (cdr rhs-items)) reducer next-cont) token)) (string (parse-string token)) (symbol (case rhs-item (arbno (parse-arbno token)) (separated-list (parse-separated-list token)) (otherwise (parse-symbol token)))) (cons (funcall (rhs->parser rhs-item #'identity (lambda (pt rt) (re-read (rhs->parser (cdr rhs-items) (lambda (tokens) (funcall reducer (cons pt tokens))) next-cont) rt))) token) )))))))))) (lambda (token-list) (let ((parser-list (mapcar (lambda (spec) (destructuring-bind (lhs rhs-items prod-name) spec (let ((parser (rhs->parser rhs-items #'identity (lambda (tokens rt) (if tokens (cons (cons prod-name tokens) rt))))) (prev-parsers (gethash lhs parser-table))) (setf (gethash lhs parser-table) (cons parser prev-parsers));;side effect parser))) grammar-spec))) (labels ((iter-token (tokens parsers reducer) (if (some #'functionp parsers) (iter-token (cdr tokens) (mapcar (lambda (parser) (try-call-parser parser (car tokens))) parsers) reducer) (let ((r (reduce (lambda (&optional a b) (cond ((null a) b) ((null b) a) (t (if (< (length (cdr a)) (length (cdr b))) a b)))) parsers))) (if r (iter-token (if (cdr r) (append (cdr r) tokens) tokens) parser-list (lambda (rs) (funcall reducer (cons (car r) rs)))) (funcall reducer nil)))))) (iter-token token-list parser-list #'identity))))))) (defun make-string-parser (lexical-spec grammar) (labels ((walk (l) (let ((value (car l))) (cond ((simple-vector-p value) (append (walk (cons (svref value 1) nil)) (walk (cdr l)))) ((stringp value) (cons value (walk (cdr l)))) ((consp value) (append (walk value) (walk (cdr l)))) ((null value) '()) (t (walk (cdr l))))))) (let ((keywords '())) (mapcar (lambda (k) (pushnew k keywords)) (walk grammar)) (format t "keywords: ~A~%" keywords) (let ((scanner (make-string-scanner (cons (list 'keyword (cons 'or keywords) 'string) lexical-spec))) (parser (make-token-parser grammar))) (lambda (text) (let ((tokens (funcall scanner text))) (format t "parsed tokens: ~A~%" tokens) (funcall parser tokens))))))) ;;(defstruct (person (:constructor make-person (name age sex)) (:predicate person?)) name age sex) ;;(defstruct (student (:constructor make-student (name age sex school)) (:include person)) school) (defmacro define-datatype (type-name predicate-name &rest variants) `(labels ((list-of (pred) (lambda (val) (or (null val) (and (consp val) (funcall pred (car val)) (funcall (list-of pred) (cdr val))))))) (defstruct (,type-name (:predicate ,predicate-name))) ,@(mapcar (lambda (variant) (destructuring-bind (variant-name &rest variant-slots) variant `(defstruct (,variant-name) ,@(mapcar (lambda (slot) (destructuring-bind (field-name predicate) slot field-name ;;todo handle slot )) variant-slots))) ) variants))) (defun grammar->def-datatype (grammar) (let ((lhs-variants-map (make-hash-table)) (lhs-list '())) (labels ((rhs-items->fields (rhs-items &optional (type-wrapper #'identity) (cont #'identity)) (if (null rhs-items) (funcall cont nil) (let ((rhs-item (car rhs-items))) (typecase rhs-item (simple-vector (rhs-items->fields (cdr rhs-items) type-wrapper (lambda (fields) (funcall cont (cons (list (svref rhs-item 0) (funcall type-wrapper (svref rhs-item 1))) fields))))) (cons (rhs-items->fields rhs-item (lambda (field) (funcall type-wrapper `(list-of ,field))) (lambda (fields) (rhs-items->fields (cdr rhs-items) type-wrapper (lambda (fields2) (funcall cont (append fields fields2))))))) (otherwise (rhs-items->fields (cdr rhs-items) type-wrapper cont))))))) (dolist (prod grammar) (let ((lhs (car prod))) (pushnew lhs lhs-list) (setf (gethash lhs lhs-variants-map) (cons prod (gethash lhs lhs-variants-map))))) `(progn ,@(mapcar (lambda (lhs) (let ((variant-productions (gethash lhs lhs-variants-map))) `(define-datatype ,lhs ,(intern (concatenate 'string (symbol-name lhs) "-P")) ,@(mapcar (lambda (production) (destructuring-bind (lhs rhs-items prod-name) production `(,prod-name ,@(rhs-items->fields rhs-items)))) variant-productions)))) lhs-list))))) (defmacro def-datatype-from-grammar (grammar) (grammar->def-datatype grammar)) (defun ast->make-data (ast grammar) (let ((builder-map (make-hash-table))) (labels ((rhs-items->builder (rhs-items &optional (data-wrapper #'identity)) (if (null rhs-items) (lambda (ast) (funcall data-wrapper nil)) (lambda (ast) (let ((rhs-item (car rhs-items))) (etypecase rhs-item ;;todo (cons (if (consp (car ast)) (append (funcall (rhs-items->builder rhs-item (lambda (args) (cons 'list-of args)));;TODO list-of ?? (car ast)) (funcall (rhs-items->builder (cdr rhs-items) data-wrapper) (cdr ast))) (error "ast's head is not a cons ~A" ast))) (symbol (if (or (equal rhs-item 'arbno) (equal rhs-item 'separated-list)) (mapcar #'(lambda (item) (funcall (rhs-items->builder (cdr rhs-items) ) item)) ;;type-wrapper ?? ast) (error "unexpected condition in make-datatype-from-ast"))) (simple-vector (let* ((prod-type (svref rhs-item 1)) (token-name (svref rhs-item 0)) (builder (if (consp (car ast)) (gethash (caar ast) builder-map)))) (if (null builder) (ecase prod-type ((identifier number) (cons (list token-name (car ast)) (funcall (rhs-items->builder (cdr rhs-items) data-wrapper) (cdr ast))))) (cons (intern (symbol-name (svref rhs-item 0)) 'keyword) (cons (funcall builder (cdar ast)) (funcall (rhs-items->builder (cdr rhs-items) data-wrapper) (cdr ast))))))) (string (if (equal rhs-item (car ast)) (funcall (rhs-items->builder (cdr rhs-items) data-wrapper) (cdr ast)) (error "string is not equal:'~A' and '~A'" (car ast) rhs-item))))))))) (dolist (production grammar) (destructuring-bind (lhs rhs-items prod-name) production (format t "register builder for ~A~%" prod-name) (setf (gethash prod-name builder-map) (rhs-items->builder rhs-items)))) (let* ((prod-name (car ast)) (builder (gethash prod-name builder-map))) (if (null builder) (error "Can not find builder for production: ~A~%" prod-name) (cons prod-name (funcall builder (cdr ast)))))))) (defmacro make-datatype-from-ast (ast grammar) (ast->make-data ast grammar)) (setf scanner-spec-a '((white-sp (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit))) symbol) (number (digit (arbno digit)) number))) (setf the-lexical-spec '((whitespace (concat (or #\Space #\NewLine) (arbno (or #\Space #\NewLine))) skip) (comment ("//" (arbno (not #\Newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number))) (setf the-grammar '((program (expression) a-program) (expression (number) const-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression ("[" (separated-list expression ",") "]") array-exp) (expression (identifier) var-exp) (expression ("let" (arbno identifier "=" expression) "in" expression) let-exp))) (setf the-grammar '((program (#(content expression)) a-program) (expression (#(expr number)) const-exp) (expression ("-" "(" #(minuend expression) "," #(subtrahend expression) ")") diff-exp) (expression ("zero?" "(" #(expr expression) ")") zero?-exp) (expression ("if" #(condition expression) "then" #(then-expr expression) "else" #(else-expr expression)) if-exp) (expression ("[" (separated-list #(exprs expression) ",") "]") array-exp) (expression (#(identifier identifier)) var-exp) (expression ("let" (arbno #(vars identifier) "=" #(exprs expression)) "in" #(body expression)) let-exp))) (defun test-scan () (format t "---------------------- test scan --------------------------~%") (funcall (make-string-scanner the-lexical-spec) "123 asdf -432 iuo3u //asdf ")) (defun test-parse () (format t "---------------------- test parse --------------------------~%") (let ((p (make-token-parser the-grammar))) (format t "~A~%" (funcall p (list "-" "(" 1 "," 2 ")"))) (format t "~A~%" (funcall p (list "zero?" "(" 1 ")"))) (format t "~A~%" (funcall p (list "let" 'x "=" 'y 'u1 "=" 321 'a "=" 33 "in" 'z))) (format t "~A~%" (funcall p (list "[" 'x "," 'y "," 1 "]"))) )) (defun scan1 (s) (funcall (make-string-scanner the-lexical-spec) s)) (defun scan&parse1 (s) (funcall (make-string-parser the-lexical-spec the-grammar) s)) (defun test-scan-parse () (scan&parse1 "let x = y u1 = 321 in z "))
18,103
Common Lisp
.lisp
468
31.871795
124
0.586483
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f3fbc1d598809056d427c0f765855bda29c2a04ebdc134a024064578cccf234b
20,245
[ -1 ]
20,246
chapter1.lisp
LeZheng_l-lisp-demo/EOPL_Exercise/chapter1.lisp
;;LcExp ::= Identifier ;; ::= (lambda (Identifier) LcExp) ;; ::= (LcExp LcExp) ;;;1.1 ;;TODO ;;;1.2 ;;TODO ;;;1.3 ;;TODO ;;;1.4 ;; List-of-Int ;; => (Int . List-of-Int) ;; => (-7 . List-of-Int) ;; => (-7 . (Int . List-of-Int)) ;; => (-7 . (3 . List-of-Int)) ;; => (-7 . (3 . (Int . List-of-Int))) ;; => (-7 . (3 . (14 . List-of-Int))) ;; => (-7 . (3 . (14 . ()))) ;;;1.5 ;;如果LcExp是一个Identifier,那么左括号数和有括号数都是0,相等。 ;;如果LcExp是(lambda (Identifier) LcExp),左边和右边括号数都是 LcExp 的括号数+2,相等。 ;;如果LcExp是(LcExp LcExp),左边的和右边的括号数都是 两个LcExp的括号数+1,相等。 (defun list-length (l) (if (null l) 0 (+ 1 (list-length (cdr l))))) (defun report-list-too-short (n) (error "List to short by ~A elements.~%" (+ n 1))) (defun nth-element (lst n) (if (null lst) (report-list-too-short n) (if (zerop n) (car lst) (nth-element (cdr lst) (- n 1))))) (defun remove-first (s los) (if (null los) '() (if (eql s (car los)) (cdr los) (cons (car los) (remove-first s (cdr los)))))) (defun occurs-free? (s lcexp) (cond ((atom lcexp) (eql s lcexp)) ((eql 'lambda (car lcexp)) (and (not (eql s (caadr lcexp))) (occurs-free? s (caddr lcexp)))) (t (or (occurs-free? s (car lcexp)) (occurs-free? s (cadr lcexp)))))) ;;;1.10 ;;TODO ;;eopl subst (defun subst-in-s-list (new old slist) (if (null slist) '() (cons (subst-in-s-exp new old (car slist)) (subst-in-s-list new old (cdr slist))))) (defun subst-in-s-exp (new old sexp) (cond ((atom sexp) (if (eql sexp old) new sexp)) (t (subst-in-s-list new old sexp)))) ;;;1.11 ;;因为 subst 在调用 subst 或 subst-in-s-exp 时都在缩小结构 ;;;1.12 (defun subst-without-s-exp (new old slist) (if (null slist) '() (cons (cond ((atom (car slist)) (if (eql (car slist) old) new (car slist))) (t (subst-without-s-exp new old (car slist)))) (subst-without-s-exp new old (cdr slist))))) ;;;1.13 (defun subst-with-map (new old slist) (mapcar (lambda (s-exp) (cond ((atom s-exp) (if (eql s-exp old) new s-exp) (t (subst-with-map new old s-exp))))) slist)) (defun number-elements-from (lst n) (if (null lst) '() (cons (list n (car lst)) (number-elements-from (cdr lst) (+ 1 n))))) (defun number-elements (lst) (number-elements-from lst 0)) (defun list-sum (loi) (if (null loi) 0 (+ (car loi) (list-sum (cdr loi))))) (defun partial-vector-sum (v n) (if (zerop n) (svref v 0) (+ (svref v n) (partial-vector-sum v (- n 1))))) (defun vector-sum (v) (let ((n (length v))) (if (zerop n) 0 (partial-vector-sum v (- n 1))))) ;;;1.14 ;;如果向量没有元素,那么它的和为0; ;;如果向量只有一个元素,那么它的和就是该元素; ;;如果向量不止一个元素,那么它的和就是最后一个元素加上其他元素的和。 ;;;1.15 (defun duple (n x) (if (zerop n 0) '() (cons x (duple (- n 1) x)))) ;;;1.16 (defun invert (lst) (if (null lst) '() (cons (list (cadar lst) (caar lst)) (invert (cdr lst))))) ;;;1.17 (defun down (lst) (if (null lst) '() (cons (cons (car lst) nil) (down (cdr lst))))) ;;;1.18 (defun swapper (s1 s2 slist) (cond ((null slist) '()) ((atom (car slist)) (cons (cond ((eql s1 (car slist)) s2) ((eql s2 (car slist)) s1) (t (car slist))) (swapper s1 s2 (cdr slist)))) (t (cons (swapper s1 s2 (car slist)) (swapper s1 s2 (cdr slist)))))) ;;;1.19 (defun list-set (lst n x) (if (null lst) '() (if (zerop n) (cons x (cdr lst)) (cons (car lst) (list-set (cdr lst) (- n 1) x))))) ;;;1.20 (defun count-occurrences (s slist) (cond ((null slist) 0) ((atom (car slist)) (+ (if (eql s (car slist)) 1 0) (count-occurrences s (cdr slist)))) (t (+ (count-occurrences s (car slist)) (count-occurrences s (cdr slist)))))) ;;;1.21 (defun product-s (s sos) (if (null sos) '() (cons (list s (car sos)) (product-s s (cdr sos))))) (defun product (sos1 sos2) (cond ((or (null sos1) (null sos2)) '()) (t (append (product-s (car sos1) sos2) (product (cdr sos1) sos2))))) ;;;1.22 (defun filter-in (pred lst) (if (null lst) '() (if (funcall pred (car lst)) (cons (car lst) (filter-in pred (cdr lst))) (filter-in pred (cdr lst))))) ;;;1.23 (defun list-index-from (n pred lst) (if (null lst) nil (if (funcall pred (car lst)) n (list-index-from (+ n 1) pred (cdr lst))))) (defun list-index (pred lst) (list-index-from 0 pred lst)) ;;;1.24 (defun every? (pred lst) (if (null lst) t (if (funcall pred (car lst)) (every? pred (cdr lst)) nil))) ;;;1.25 (defun exists? (pred lst) (if (null lst) nil (if (funcall pred (car lst)) t (exist? pred (cdr lst))))) ;;;1.26 (defun up (lst) (if (null lst) '() (if (atom (car lst)) (cons (car lst) (up (cdr lst))) (append (car lst) (up (cdr lst)))))) ;;;1.27 (defun flatten (slist) (cond ((null slist) nil) ((null (car slist)) (flatten (cdr slist))) ((atom (car slist)) (cons (car slist) (flatten (cdr slist)))) (t (append (flatten (car slist)) (flatten (cdr slist)))))) ;;;1.28 (defun loi-merge (loi1 loi2) (cond ((null loi1) loi2) ((null loi2) loi1) (t (if (> (car loi1) (car loi2)) (cons (car loi2) (loi-merge loi1 (cdr loi2))) (cons (car loi1) (loi-merge (cdr loi1) loi2)))))) ;;;1.29 (defun insert (i loi) (if (null loi) (cons i nil) (if (> i (car loi)) (cons (car loi) (insert i (cdr loi))) (cons i loi)))) (defun loi-sort (loi) (if (null loi) '() (insert (car loi) (loi-sort (cdr loi))))) ;;;1.30 (defun insert-predicate (pred i loi) (if (null loi) (cons i nil) (if (funcall pred i (car loi)) (cons i loi) (cons (car loi) (insert-predicate pred i (cdr loi)))))) (defun sort-predicate (pred loi) (if (null loi) '() (insert-predicate pred (car loi) (sort-predicate pred (cdr loi))))) ;;;1.31 (defun leaf (i) (cons i nil)) (defun interior-node (s t1 t2) (cons s (cons t1 (cons t2 nil)))) (defun leaf? (tree) (null (cdr tree))) (defun lson (tree) (cadr tree)) (defun rson (tree) (caddr tree)) (defun contents-of (tree) (car tree)) ;;;1.32 (defun double-tree (tree) (cond ((null tree) '()) ((leaf? tree) (leaf (* (contents-of tree) (contents-of tree)))) (t (interior-node (contents-of tree) (double-tree (lson tree)) (double-tree (rson tree)))))) ;;;1.33 (defun mark-leaves-with-n (n tree) (cond ((null tree) '()) ((leaf? tree) (leaf n)) (t (if (eql 'red (contents-of tree)) (interior-node (contents-of tree) (mark-leaves-with-n (+ n 1) (lson tree)) (mark-leaves-with-n (+ n 1) (rson tree))) (interior-node (contents-of tree) (mark-leaves-with-n n (lson tree)) (mark-leaves-with-n n (rson tree))))))) (defun mark-leaves-with-red-depth (tree) (if (null tree) '() (mark-leaves-with-n 0 tree))) ;;;1.34 (defun tree-path (n bst) (if (null bst) 'not-found (cond ((> n (car bst)) (cons 'right (tree-path n (caddr bst)))) ((< n (car bst)) (cons 'left (tree-path n (cadr bst)))) (t '())))) ;;;1.35 (defun number-tree (n tree) (cond ((leaf? tree) (cons (+ n 1) (leaf n))) (t (let ((l-temp (number-tree n (lson tree)))) (let ((r-temp (number-tree (car l-temp) (rson tree)))) (cons (car r-temp) (interior-node (contents-of tree) (cdr l-temp) (cdr r-temp)))))))) (defun number-leaves (tree) (cond ((null tree) '()) (t (cdr (number-tree 0 tree))))) ;;;1.36 (defun number-elements (lst) (if (null lst) '() (g (list 0 (car lst)) (number-elements (cdr lst))))) (defun g (l lst) (cons l (mapcar #'(lambda (l) (list (+ 1 (car l)) (cadr l))) lst)))
8,091
Common Lisp
.lisp
307
21.576547
69
0.568807
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c9b9f1a6313ef947f85a276a4a09dd3f8ce9b885ff4b5631908a1ff84c76ec5f
20,246
[ -1 ]
20,247
let-lang.lisp
LeZheng_l-lisp-demo/EOPL_Exercise/let-lang.lisp
(defun empty-env () (list 'empty-env)) (defun extend-env (var val env) (list 'extend-env var val env)) (defun apply-env (env search-var) (cond ((eql (car env) 'empty-env) (report-no-binding-found search-var)) ((eql (car env) 'extend-env) (let ((saved-var (cadr env)) (saved-val (caddr env)) (saved-env (cadddr env))) (if (equal search-var saved-var) saved-val (apply-env saved-env search-var)))) (t (report-invalid-env env)))) (defun report-no-binding-found (search-var) (error "No binding for ~s" search-var)) (defun report-invalid-env (env) (error "Bad environment: ~s" env)) (defmacro define-datatype (type-name type-predicate-name &rest variants) (let ((variant-pred-list (mapcar (lambda (v) (intern (concatenate 'string (symbol-name (car v)) "?"))) variants))) `(progn (defun ,type-predicate-name (e) (some (lambda (p) funcall p e) ,variant-pred-list)) ,@(mapcar (lambda (variant-exp) (let* ((variant-name (car variant-exp)) (variant-fields (cdr variant-exp)) (variant-pred (intern (concatenate 'string (symbol-name variant-name) "?")))) `(progn (defun ,variant-name (&rest fields) (cons ',variant-name (mapcar (lambda (pred field) (if (funcall pred field) field (error "field[~s] init field." field))) (mapcar #'cadr ',variant-fields) fields))) (defun ,variant-pred (e) (eql (car e) ',variant-name)) ,@(loop for i from 0 below (length variant-fields) for field in variant-fields collect `(let ((index (+ 1 ,i))) (defun ,(intern (concatenate 'string (symbol-name variant-name) "->" (symbol-name (car field)))) (e) (nth index e))))))) variants)))) (defmacro cases (type-name expression &rest clauses) (let ((exp-sym (gensym))) `(let ((,exp-sym ,expression)) (cond ,@(mapcar (lambda (c) (let ((variant-name (car c))) (if (eql variant-name 'else) `(t ,(cadr c)) (let ((var-pred (intern (concatenate 'string (symbol-name variant-name) "?"))) (bound-var-list (cadr c))) (format t "var-pred:~A~%" var-pred) `((,var-pred ,exp-sym) (let ,(loop for i from 0 below (length bound-var-list) for var in bound-var-list collect (list var `(nth (1+ ,i) ,exp-sym))) ,@(cddr c))))))) clauses))))) (defun number? (n) (numberp n)) (defun identifier? (e) (and (atom e) (not (eql e 'lambda)))) (defun boolean? (b) (typep b 'boolean)) (define-datatype expval expval? (num-val (num number?)) (bool-val (bool boolean?))) (defun expval->num (val) (cases expval val (num-val (num) num) (else (error "expval->num extract error ~A~%" val)))) (defun expval->bool (val) (cases expval val (bool-val (bool) bool) (else (error "expval->bool extract error ~A~%" val)))) (define-datatype program program? (a-program (exp1 expression?))) (define-datatype expression expression? (const-exp (num number?)) (diff-exp (exp1 expression?) (exp2 expression?)) (zero?-exp (exp1 expression?)) (if-exp (exp1 expression?) (exp2 expression?) (exp3 expression?)) (var-exp (var identifier?)) (let-exp (var identifier?) (exp1 expression?) (body expression?)) (minus-exp (num number?)) (add-exp (exp1 expression?) (exp2 expression?)) (mul-exp (exp1 expression?) (exp2 expression?)) (div-exp (exp1 expression?) (exp2 expression?)) (equal-exp (exp1 expression?) (exp2 expression?)) (greater-exp (exp1 expression?) (exp2 expression?)) (less-exp (exp1 expression?) (exp2 expression?))) (defun init-env () (extend-env 'i (num-val 1) (extend-env 'v (num-val 5) (extend-env 'x (num-val 10) (empty-env))))) (defvar let-lexical-spec '((whitespace (whitespace) skip) (comment ("%" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number) )) (defvar let-grammar '((program (expression) a-program) (expression (number) const-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression (identifier) var-exp) (expression ("let" identifier "=" expression "in" expression) let-exp) )) (defun scan&parse (s) (funcall (make-string-parser let-lexical-spec let-grammar) s)) (defun run (string) (value-of-program (cons 'a-program (scan&parse string)))) (defun value-of-program (pgm) (format t "program:~A~%" pgm) (cases program pgm (a-program (exp1) (value-of exp1 (init-env))))) (defun value-of (exp env) (format t "value-of:~A <= ~A~%" exp env) (cases expression exp (const-exp (num) (num-val num)) (var-exp (var) (apply-env env var)) (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zerop num1) (bool-val t) (bool-val nil))))) (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) (let-exp (var exp1 body) (let ((val1 (value-of exp1 env))) (value-of body (extend-env var val1 env)))) (minus-exp (num) (num-val (- num))) (add-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (+ num1 num2))))) (mul-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (* num1 num2))))) (div-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (/ num1 num2))))) (equal-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (bool-val (= num1 num2))))) (greater-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (bool-val (> num1 num2))))) (less-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (bool-val (< num1 num2)))))))
7,083
Common Lisp
.lisp
247
23.380567
88
0.588123
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0b127a9dc2886db034785dd8e59ee70fb3c9787be151a2bfe843e4576c965b31
20,247
[ -1 ]
20,248
cl-llgen.lisp
LeZheng_l-lisp-demo/EOPL_Exercise/cl-llgen.lisp
(defun make-token (class-name data) (list class-name data)) (defun make-string-scanner (scanner-spec) (lambda (str) (with-input-from-string (stream str) (scan-stream stream scanner-spec)))) (defun make-stream-scanner (scanner-spec) (lambda (stream) (scan-stream stream scanner-spec))) (defun re-read (v) (if (vectorp v) (let ((buffer (svref v 1)) (fun (svref v 0))) (if buffer (cond ((functionp fun) (re-read (vector (funcall fun (car buffer)) (cdr buffer)))) ((vectorp fun) (vector (svref fun 0) (append (svref fun 1) buffer))) (t v)) fun)) v)) (defun scan-stream (stream scanner-spac) (let ((scanner-list (mapcar #'token-spec->scanner scanner-spac))) (labels ((iter (stream scanners token-list &optional buffer) (let ((c (read-char stream nil 'end-of-stream))) (if (not (characterp c)) (reverse token-list) (let ((temp (mapcar #'(lambda (s) (etypecase s (function (funcall s c)) (cons (vector s (cons c nil))) (vector (vector (svref s 0) (cons c (svref s 1)))))) scanners))) (if (some #'functionp temp) (iter stream temp token-list (cons c buffer)) (let* ((scan-result (car (sort temp #'< :key (lambda (s) (if (vectorp s) (if (svref s 0) (length (svref s 1)) most-positive-fixnum) 0))))) (r (if (vectorp scan-result) (svref scan-result 0) scan-result)) (unuse-buffer (if (vectorp scan-result) (reverse (svref scan-result 1))))) (if (null r) (error "scan error:~A not match any scanner~%" (reverse buffer)) (destructuring-bind (token-string name action) r (iter (if unuse-buffer (make-concatenated-stream (make-string-input-stream (coerce unuse-buffer 'string)) stream) stream) scanner-list (ecase action (skip token-list) (symbol (cons (make-token name (make-symbol token-string)) token-list)) (number (cons (make-token name (read-from-string token-string)) token-list)) (string (cons (make-token name token-string) token-list))))))))))))) (iter stream scanner-list nil)))) (defun token-spec->scanner (raa) (destructuring-bind (name regexp action) raa (labels ((make-concat-receiver (regexp receiver backouter) (lambda (char-seq) (if (cdr regexp) (regexp->scanner (cdr regexp) (lambda (char-seq2) (funcall receiver (append char-seq char-seq2))) (lambda (char-seq2) (funcall backouter (append char-seq char-seq2)))) (funcall receiver char-seq)))) (make-single-char-scanner (regexp receiver char-tester backouter) (lambda (c) (if (funcall char-tester c) (if (cdr regexp) (regexp->scanner (cdr regexp) (lambda (s) (funcall receiver (cons c s))) (lambda (s) (funcall backouter (cons c s)))) (funcall receiver (cons c nil))) (vector nil (cons c nil))))) (regexp->scanner (regexp receiver backouter) (let ((exp (car regexp))) (cond ((stringp exp) (regexp->scanner (cons (cons 'concat (coerce exp 'list)) (cdr regexp)) receiver backouter)) ((consp exp) (regexp->scanner exp (make-concat-receiver regexp receiver backouter) backouter)) ((characterp exp) (make-single-char-scanner regexp receiver (lambda (c) (eql c exp)) backouter)) ((eql exp 'letter) (make-single-char-scanner regexp receiver #'alpha-char-p backouter)) ((eql exp 'digit) (make-single-char-scanner regexp receiver #'digit-char-p backouter)) ((eql exp 'any) (make-single-char-scanner regexp receiver (constantly t) backouter)) ((eql exp 'not) (lambda (c) (if (not (eql c (cadr regexp))) (funcall receiver (cons c nil)) (vector nil (cons c nil))))) ((eql exp 'whitespace) (regexp->scanner '((or #\Space #\NewLine) (arbno (or #\Space #\NewLine))) (make-concat-receiver regexp receiver backouter) backouter)) ((eql exp 'or) (labels ((make-or-scan (or-scanners &optional buffer) (labels ((or-scan (c) (let ((temp (mapcar (lambda (s) (etypecase s (function (funcall s c)) (cons (vector s (cons c nil))) (vector (vector (svref s 0) (cons c (svref s 1)))))) or-scanners))) (if (some #'functionp temp) (make-or-scan temp (cons c nil)) (let ((r (car (sort temp #'< :key (lambda (s) (if (vectorp s) (length (svref s 1)) 0)))))) (etypecase r (cons (funcall receiver r)) (vector (re-read (vector (funcall receiver (svref r 0)) (reverse (svref r 1))))) (null (vector nil (funcall backouter (reverse (cons c buffer))))))))))) #'or-scan))) (make-or-scan (mapcar (lambda (e) (regexp->scanner (cons e nil) #'identity #'identity)) (cdr regexp))))) ((eql exp 'arbno) (lambda (c) (let ((r (funcall (regexp->scanner (cdr regexp) #'identity #'identity) c))) (labels ((handle-result (r buffer) (etypecase r (cons (regexp->scanner regexp (lambda (s) (funcall receiver (append r s))) (lambda (s) (funcall backouter (append (reverse buffer) s))))) (vector (re-read (vector (funcall receiver (svref r 0)) (svref r 1)))) (function (lambda (c) (handle-result (funcall r c) (cons c buffer)))) (null (re-read (vector (funcall receiver nil) (reverse buffer))))))) (handle-result r (cons c nil)))))) ((eql exp 'concat) (regexp->scanner (cdr regexp) receiver backouter)) (t (error "Unknown expression:~A~%" exp)))))) (regexp->scanner regexp (lambda (s) (if s (list (coerce s 'string) name action))) #'identity)))) (defun parse-token (grammar-spec token-list) (let ((prod-parser-table (make-hash-table))) (dolist (production grammar-spec) (destructuring-bind (lhs rhs-list prod-name) production (push (production->parser production prod-parser-table) (gethash lhs prod-parser-table)))) (let ((parser-list '())) (maphash (lambda (k v) (setf parser-list (append parser-list v))) prod-parser-table) (labels ((iter (token-list parsers receiver) (if (null token-list) (funcall receiver nil) (let ((temps (mapcan (lambda (r) (and (or (functionp r) (consp r) (and (vectorp r) (consp (svref r 0)))) (list r))) (mapcar (lambda (p) (etypecase p (function (funcall p (car token-list))) (cons (vector p (cons (car token-list) nil))) (vector (vector (svref p 0) (nconc (svref p 1) (cons (car token-list) nil)))))) parsers)))) (if (some #'functionp temps) (iter (cdr token-list) temps receiver) (let ((r (car (sort temps #'< :key (lambda (p) (etypecase p (cons 0) (vector (length (svref p 1))))))))) (etypecase r (cons (iter (cdr token-list) parser-list (lambda (gs) (cons r gs)))) (vector (iter (append (svref r 1) (cdr token-list)) parser-list (lambda (gs) (cons (svref r 0) gs))))))))))) (iter token-list parser-list #'identity))))) (defun production->parser (production parser-table) (destructuring-bind (lhs rhs-list prod-name) production (labels ((rhs->parser (remain-rhs receiver backouter) (let ((rhs (car remain-rhs))) (cond ((and (symbolp rhs) (not (equal rhs 'arbno)) (not (equal rhs 'separated-list))) (labels ((parse-lhs (parsers buffer) (lambda (token) (if (null parsers) (if (equal rhs (car token)) (if (cdr remain-rhs) (rhs->parser (cdr remain-rhs) (lambda (p) (funcall receiver (cons (cadr token) p))) (lambda (ts) (funcall backouter (append (reverse (cons token buffer)) ts)))) (funcall receiver (cons (cadr token) nil))) (vector nil (funcall backouter (reverse (cons token buffer))))) (let* ((temps (mapcar (lambda (parser) (if (functionp parser) (funcall parser token) parser)) parsers)) (r (find-if #'consp temps))) (if (some #'functionp temps) (parse-lhs temps (cons token buffer)) (let ((r (car (sort temps #'< :key (lambda (p) (etypecase p (cons 0) (vector (length (svref p 1))))))))) (etypecase r (cons (if (cdr remain-rhs) (rhs->parser (cdr remain-rhs) (lambda (p) (funcall receiver (cons r p))) (lambda (ts) (funcall backouter (append (reverse (cons token buffer)) ts)))) (funcall receiver (cons r nil)))) (vector (if (cdr remain-rhs) (rhs->parser (cdr remain-rhs) (lambda (p) (funcall receiver (cons (svref r 0) p))) (lambda (ts) (funcall backouter (append (reverse (cons token buffer)) ts)))) (funcall receiver (cons (svref r 0) nil)))))))))))) (parse-lhs (gethash rhs parser-table) nil))) ((stringp rhs) (lambda (token) (if (equal rhs (cadr token)) (if (cdr remain-rhs) (rhs->parser (cdr remain-rhs) receiver (lambda (ts) (funcall backouter (cons token ts)))) (funcall receiver nil)) (vector nil (cons token nil))))) ((consp rhs) (lambda (token) (funcall (rhs->parser rhs (lambda (r1) (if (cdr remain-rhs) (rhs->parser (cdr remain-rhs) (lambda (r2) (funcall receiver (cons r1 r2))) (lambda (ts) (funcall backouter (cons token ts)))) (funcall receiver r1))) backouter) token))) ((eql 'arbno rhs) (lambda (token) (let ((r (funcall (rhs->parser (cdr remain-rhs) #'identity #'identity) token))) (labels ((handle-result (r buffer) (etypecase r (cons (rhs->parser remain-rhs (lambda (r2) (funcall receiver (if r2 (mapcar #'list r r2) r))) (lambda (ts) (funcall backouter (append (reverse buffer) ts))))) (function (lambda (token) (handle-result (funcall r token) (cons token buffer)))) (vector (re-read (vector (funcall receiver (svref r 0)) (svref r 1)))) (null (re-read (vector (funcall receiver nil) (reverse buffer))))))) (handle-result r (cons token nil)))))) ((eql 'separated-list rhs) (lambda (token) (let ((r (funcall (rhs-parser (butlast (cdr remain-rhs)) #'identity backouter) token))) (labels ((handle-result (r buffer) (etypecase r (cons (lambda (token) (if (string-equal (cadr token) (car (last remain-rhs))) (rhs->parser remain-rhs (lambda (r2) (funcall receiver (mapcar #'cons r r2))) (lambda (ts) (funcall backouter (append (reverse (cons token buffer)) ts)))) (re-read (vector (funcall receiver nil) (funcall backouter (append (reverse (cons token buffer)) ts))))))) (function (lambda (token) (handle-result (funcall r token) (cons token buffer)))) (vector (re-read (vector (funcall receiver (svref r 0)) (svref r 1)))) (null (re-read (vector (funcall receiver nil) (funcall backouter (reverse buffer)))))))) (handle-result r (cons token nil)))))) (t (error "Unexpected rhs:~A~%" rhs)))))) (rhs->parser rhs-list (lambda (r) (cons prod-name r)) #'identity)))) (defun make-string-parser (the-lexical-spec the-grammar) (labels ((find-keywords (rhs-items receiver) (if (null rhs-items) (funcall receiver nil) (etypecase (car rhs-items) (string (find-keywords (cdr rhs-items) (lambda (ks) (funcall receiver (cons (car rhs-items) ks))))) (symbol (find-keywords (cdr rhs-items) receiver)) (cons (let ((cks (find-keywords (car rhs-items) #'identity))) (find-keywords (cdr rhs-items) (lambda (ks) (funcall receiver (append cks ks)))))))))) (let* ((ext-lexical-spec `((keyword ((or ,@(reduce (lambda (l1 l2) (union l1 l2 :test #'equal)) (mapcar (lambda (production) (find-keywords (cadr production) #'identity)) the-grammar)))) string) ,@the-lexical-spec)) (scanner (make-string-scanner ext-lexical-spec))) (lambda (s) (let ((token-list (funcall scanner s))) (format t "token-list:~A~%" token-list) (parse-token the-grammar token-list)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; test ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (setf the-lexical-spec '((whitespace ((or #\Space #\NewLine) (arbno (or #\Space #\NewLine))) skip) (comment ("//" (arbno (not #\newline))) skip) (identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol) (number (digit (arbno digit)) number) (number ("-" digit (arbno digit)) number))) (setf the-grammar '((program (expression) a-program) (expression (number) const-exp) (expression ("-" "(" expression "," expression ")") diff-exp) (expression ("zero?" "(" expression ")") zero?-exp) (expression ("if" expression "then" expression "else" expression) if-exp) (expression (identifier) var-exp) (expression ("let" (arbno identifier "=" expression) "in" expression) let-exp))) (defun test-scan () (funcall (make-string-scanner the-lexical-spec) "asdf 1234 -4321 // skdlajf")) (defun scan1 (s) (funcall (make-string-scanner the-lexical-spec) s)) (defun scan&parse1 (s) (funcall (make-string-parser the-lexical-spec the-grammar) s)) (defun test-parse () (scan&parse1 "let x = y u1 = 321 in z "))
13,494
Common Lisp
.lisp
322
35
114
0.600167
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6b77d31fe1bef43110fd47ef712daef0b060b8b30b1d809b88bf5aec4284c2b9
20,248
[ -1 ]
20,249
chapter2.lisp
LeZheng_l-lisp-demo/EOPL_Exercise/chapter2.lisp
;;;exercise 2.1 (defvar bigit-base-n 16) (defun bigit-zero () '()) (defun bigit-is-zero? (n) (cond ((null n) t) ((zerop (car n)) (bigit-is-zero? (cdr n))) (t nil))) (defun bigit-successor (n) (cond ((bigit-is-zero? n) (list 1)) ((= (+ 1 (car n)) bigit-base-n) (cons 0 (bigit-successor (cdr n)))) (t (cons (+ 1 (car n)) (cdr n))))) (defun bigit-predecessor (n) (cond ((bigit-is-zero? n) (error "Zero is not support")) ((> (car n) 0) (cons (- (car n) 1) (cdr n))) (t (cons (- bigit-base-n 1) (bigit-predecessor (cdr n)))))) (defun bigit-number (num) (if (= 0 num) (bigit-zero) (bigit-successor (bigit-number (- num 1))))) (defun bigit-plus (a b) (if (bigit-is-zero? a) b (bigit-plus (bigit-predecessor a) (bigit-successor b)))) (defun bigit-factorial (n) ;;TODO ) ;;;exercise 2.2 ;;TODO ;;;exercise 2.3 ;;1. 对于任意的 n,使得n = n1 - n2,其中n1可以为任何数,因此n的表示是无穷的。 ;;2. (defun dt-number (n) (cond ((= n 1) '(one)) ((< n 1) (list 'diff (dt-number (+ n 1)) '(one))) ((> n 1) (list 'diff (dt-number (- n 1)) '(diff (diff (one) (one)) (one)))))) (defun dt-value (n) (if (equal 'one (car n)) 1 (- (dt-value (cadr n)) (dt-value (caddr n))))) (defun dt-zero () '(diff (one) (one))) (defun dt-is-zero? (n) (= 0 (dt-value n))) (defun dt-successor (n) (if (equal 'one (car n)) '(diff (one) (diff (diff (one) (one)) (one))) (list 'diff (cadr n) (list 'diff (caddr n) (one))))) (defun dt-predecessor (n) (if (equal 'one (car n)) '(diff (one) (one)) (list 'diff (list 'diff (cadr n) (one)) (caddr n)))) (defun diff-tree-plus (a b) ; (n1 - n2) + (n3 - n4) = (n1 - n2) - (n4 - n3) (list 'diff a (cond ((equal 'one (car b)) '(diff (diff (one) (one)) (one))) (t (list 'diff (caddr b) (cadr b)))))) (defun empty-env () (list 'empty-env)) (defun extend-env (var val env) (list 'extend-env var val env)) (defun apply-env (env search-var) (cond ((eql (car env) 'empty-env) (report-no-binding-found search-var)) ((eql (car env) 'extend-env) (let ((saved-var (cadr env)) (saved-val (caddr env)) (saved-env (cadddr env))) (if (eql search-var saved-var) saved-val (apply-env saved-env search-var)))) (t (report-invalid-env env)))) (defun report-no-binding-found (search-var) (error "No binding for ~s" search-var)) (defun report-invalid-env (env) (error "Bad environment: ~s" env)) ;;;exercise 2.4 ;;TODO ;;;exercise 2.5 (defun al-empty-env () '()) (defun al-extend-env (var val env) (cons (cons var val) env)) (defun al-apply-env (env search-var) (cond ((null env) (report-no-binding-found search-var)) (t (let ((saved-var (caar env)) (saved-val (cdar env)) (saved-env (cdr env))) (if (eql search-var saved-var) saved-val (al-apply-env saved-env search-var)))))) ;;;exercise 2.6 ;;1. hash表表示法:key为var,value为val ;;2. 2维动态数组表示法:a[i][0]为var,a[i][1]为val ;;3. 向量表示法:v[0]为var,v[1]为val,以此类推 ;;;exercise 2.7 ;;TODO ;;;exercise 2.8 (defun al-empty-env (env) (null env)) ;;;exercise 2.9 (defun has-binding (env s) (cond ((null env) nil) (t (let ((saved-var (caar env)) (saved-val (cdar env)) (saved-env (cdr env))) (if (eql s saved-var) t (has-binding saved-env s)))))) ;;;exercise 2.10 (defun extend-env* (var-list val-list env) (cond ((null var-list) env) (t (extend-env* (cdr var-list) (cdr val-list) (extend-env (car var-list) (car val-list) env))))) ;;;exercise 2.11 (defun r-empty-env () '()) (defun r-extend-env (var val env) (cons (cons (cons var nil) (cons val nil)) env)) (defun r-find-var (vars vals search-var) (if (null vars) nil (if (eql (car vars) search-var) (cons (car vars) (car vals)) (r-find-var (cdr vars) (cdr vals) search-var)))) (defun r-apply-env (env search-var) (cond ((null env) (report-no-binding-found search-var)) (t (let ((saved-vars (caar env)) (saved-vals (cdar env)) (saved-env (cdr env))) (let ((r (r-find-var saved-vars saved-vals search-var))) (if (null r) (r-apply-env saved-env search-var) (cdr r))))))) (defun extend-env* (vars vals env) (cons (cons vars vals) env)) ;;;exercise 2.12 (defun empty-stack () (lambda (op) (case op (is-empty t) (otherwise (error "The stack is empty"))))) (defun stack-push (n stack) (lambda (op) (case op (is-empty nil) (pop stack) (top n) (otherwise (error "operation[~A] is not support" op))))) (defun stack-pop (stack) (funcall stack 'pop)) (defun stack-top (stack) (funcall stack 'top)) (defun emtpy-stack? (stack) (funcall stack 'is-empty)) ;;;exercise 2.13 (defun p-empty-env () (list (lambda (search-var) (report-no-binding-found search-var)) (lambda () t))) (defun p-extend-env (saved-var saved-val saved-env) (list (lambda (search-var) (if (eql search-var saved-var) saved-val (p-apply-env saved-env search-var))) (lambda () nil))) (defun p-apply-env (env search-var) (funcall (car env) search-var)) ;;;exercise 2.14 (defun p-empty-env () (list (lambda (search-var) (report-no-binding-found search-var)) (lambda () t) (lambda (search-var) nil))) (defun p-extend-env (saved-var saved-val saved-env) (list (lambda (search-var) (if (eql search-var saved-var) saved-val (p-apply-env saved-env search-var))) (lambda () nil) (lambda (search-var) (if (eql search-var saved-val) t (funcall (caddr saved-env) search-var))))) (defun p-is-empty-env? (env) (funcall (cadr env))) (defun p-has-binding? (env search-var) (funcall (caddr saved-env) search-var)) ;;;;2.3 ;;;exercise 2.15 (defun var-exp (var) var) (defun lambda-exp (var lc-exp) `(lambda (,var) ,lc-exp)) (defun app-exp (lc-exp1 lc-exp2) (list lc-exp1 lc-exp2)) (defun var-exp? (lc-exp) (atom lc-exp)) (defun lambda-exp? (lc-exp) (eql 'lambda (car lc-exp))) (defun app-exp? (lc-exp) (and (lc-exp? (car lc-exp)) (lc-exp? (cadr lc-exp)))) (defun lc-exp? (exp) (or (var-exp? exp) (lambda-exp? exp) (app-exp? exp))) (defun var-exp->var (exp) exp) (defun lambda-exp->bound-var (lc-exp) (caadr lc-exp)) (defun lambda-exp->body (lc-exp) (cddr lc-exp)) (defun app-exp->rator (lc-exp) (car lc-exp)) (defun app-exp->rand (lc-exp) (cadr lc-exp)) ;;;exercise 2.16 (defun lambda-exp-2 (var lc-exp) `(lambda ,var ,lc-exp)) (defun lambda-exp->bound-var (lc-exp) (cadr lc-exp)) ;;其余不变 ;;;exercise 2.17 ;;1. (identifier -> lc-exp) ;;2. (identifier => lc-exp) ;;实现略 TODO ;;;exercise 2.18 (defun number->sequence (n) (list n '() '())) (defun current-element (s) (car s)) (defun move-to-left (s) (if (not (null (cadr s))) (list (car (cadr s)) (cdr (cadr s)) (cons (car s) (caddr s))))) (defun move-to-right (s) (if (not (null (caddr s))) (list (car (caddr s)) (cons (car s) (cadr s)) (cdr (caddr s))))) (defun insert-to-left (n s) (list (car s) (cons n (cadr s)) (caddr s))) (defun insert-to-right (n s) (list (car s) (cadr s) (cons n (caddr s)))) ;;;exercise 2.19 (defun number->bintree (n) (list n '() '())) (defun current-element (tree) (car tree)) (defun insert-to-left (n tree) (list (current-element tree) (list n (cadr tree) nil) (caddr tree))) (defun insert-to-right (n tree) (list (current-element tree) (cadr tree) (list n (caddr tree) nil))) (defun move-to-left (tree) (cadr tree)) (defun move-to-right (tree) (caddr tree)) (defun at-leaf? (tree) (null tree)) ;;;exercise 2.20 ;;TODO ;;;;2.4 (defmacro define-datatype (type-name type-predicate-name &rest variants) (let ((variant-pred-list (mapcar (lambda (v) (intern (concatenate 'string (symbol-name (car v)) "?"))) variants))) `(progn (defun ,type-predicate-name (e) (some (lambda (p) funcall p e) ,variant-pred-list)) ,@(mapcar (lambda (variant-exp) (let* ((variant-name (car variant-exp)) (variant-fields (cdr variant-exp)) (variant-pred (intern (concatenate 'string (symbol-name variant-name) "?")))) `(progn (defun ,variant-name (&rest fields) (cons ',variant-name (mapcar (lambda (pred field) (if (funcall pred field) field (error "field[~s] init field." field))) (mapcar #'cadr ',variant-fields) fields))) (defun ,variant-pred (e) (eql (car e) ',variant-name)) ,@(loop for i from 0 below (length variant-fields) for field in variant-fields collect `(let ((index (+ 1 ,i))) (defun ,(intern (concatenate 'string (symbol-name variant-name) "->" (symbol-name (car field)))) (e) (nth index e))))))) variants)))) (defmacro cases (type-name expression &rest clauses) (let ((exp-sym (gensym))) `(let ((,exp-sym ,expression)) (cond ,@(mapcar (lambda (c) (let ((variant-name (car c))) (if (eql variant-name 'else) `(t ,(cdr c)) (let ((var-pred (intern (concatenate 'string (symbol-name variant-name) "?"))) (bound-var-list (cadr c))) `((,var-pred ,exp-sym) (let ,(loop for i from 0 below (length bound-var-list) for var in bound-var-list collect (list var `(nth (1+ ,i) ,exp-sym))) ,@(cddr c))))))) clauses))))) ;;;exercise 2.21 (define-datatype env env? (empty-env) (extend-env (var identifier?) (val identity) (env env?))) ;;;exercise 2.22 ;;TODO ;;;exercise 2.23 (defun identifier? (e) (and (atom e) (not (eql e 'lambda)))) ;;;exercise 2.24 (define-datatype bintree bintree? (leaf-node (num integer?)) (interior-node (key symbol?) (left bintree?) (right bintree?))) (defun bintree-to-list (t) (if (null t) nil (if (leaf-node? t) (list 'leaf-node (leaf-node->num t)) (list 'interior-node (interior-node->key t) (interior-node->left t) (interior-node->right t))))) ;;;exercise 2.25 (defun max-interior-1 (t) (cases bintree t (leaf-node (num) (cons nil num)) (interior-node (key left right) (let ((lr (max-interior-1 left)) (rr (max-interior-1 right))) (let ((l (cdr lr)) (r (cdr rr)) (c (+ (cdr lr) (cdr rr)))) (cond ((and (car lr) (>= l c)) lr) ((and (car rr) (>= r c)) rr) (t (cons key c)))))))) (defun max-interior (t) (car (max-interior-1 t))) ;;;exercise 2.26 (define-datatype red-blue-tree red-blue-tree? (red-blue-subtree)) (define-datatype red-blue-subtree red-blue-subtree? (red-node (left-node red-blue-subtree?) (right-node red-blue-subtree?)) (blue-node (nodes)) (leaf-node (value integer?))) (defun proc1 (t num) (cases red-blue-sub t (red-node (left-node right-node) (red-node (proc1 left-node (+ num 1)) (proc1 right-node (+ num1)))) (blue-node (nodes) (blue-node (mapcar (lambda (node) (proc1 node num)) nodes))) (leaf-node (leaf-node num)))) (defun proc (t) (proc1 t 0)) ;;;;2.5 ;;;exercise 2.27 ;;TODO ;;;exercise 2.28 ;;Lc-exp ::= Identifier ;; ::= proc Identifier => Lc-exp ;; ::= Lc-exp(Lc-exp) (defun unparse-lc-exp-2 (exp) (cases lc-exp exp (var-exp (var) var) (lambda-exp (bound-var body) (list proc bound-var '=> (unparse-lc-exp-2 body))) (app-exp (rator rand) (list (unparse-lc-exp-2 rator) (unparse-lc-exp-2 rand))))) ;;;exercise 2.29 (define-datatype lc-exp lc-exp? (var-exp (var identifier?)) (lambda-exp (bound-vars (list-of identifier?)) (body lc-exp?)) (app-exp (rator lc-exp?) (rands (list-of lc-exp?)))) ;;;exercise 2.30 (defun parse-expression (datum) (cond ((symbolp datum) (var-exp datum)) ((consp datum) (if (eql (car datum) 'lambda) (if (lambda-exp? datum) (lambda-exp (car (cadr datum)) (parse-expression (caddr datum))) (error "parse lambda-exp failed")) (if (app-exp? datum) (app-exp (parse-expression (car datum)) (parse-expression (cadr datum))) (error "parse app-exp failed")))) (t (error "invalid concrete syntax: ~A" datum)))) ;;;exercise 2.31 (define-datatype prefix-exp prefix-exp? (const-exp (num integer?)) (diff-exp (operand1 prefix-exp?) (operand2 prefix-exp?))) (defun parse-prefix-exp-1 (datum) (if (eql (car datum) '-) (let ((temp (parse-prefix-exp-1 (cdr datum)))) (let ((temp2 (parse-prefix-exp-1 (cdr temp)))) (cons (diff-exp (car temp) (car temp2)) (cdr temp2)))) (cons (const-exp (car datum)) (cdr datum)))) (defun parse-prefix-exp (datum) (car (parse-prefix-exp-1 datum)))
12,800
Common Lisp
.lisp
467
23.344754
82
0.607432
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8c3e33e5dc400559528d62659ec33cf7cedca3652fd31df0408da30de86d0261
20,249
[ -1 ]
20,250
chapter3.lisp
LeZheng_l-lisp-demo/EOPL_Exercise/chapter3.lisp
;;;;0.0 parser start ;;;TODO 这个解析器需要重写,把词法分析和语法分析分开 (defun subseq-and-trim (&rest s) (string-trim '(#\Space #\Tab #\NewLine) (apply #'subseq s))) (defun start-with (s prefix) (= (string/= s prefix) (length prefix))) (defun skip-prefix (s prefix) (let ((start (string/= s prefix))) (if (= start (length prefix)) (subseq-and-trim s start) (error "skip failed:~A" prefix)))) (defun scan&parse (s) (list 'a-program (parse-expression s))) (defun parse-expression (s) (cond ((start-with s "zero? ") (parse-zero?-exp s)) ((start-with s "if ") (parse-if-exp s)) ((start-with s "let ") (parse-let-exp s)) ((or (start-with s "- ") (start-with s "-(")) (parse-diff-exp s)) ((numberp (read-from-string s)) (parse-const-exp s)) ((symbolp (read-from-string s)) (parse-var-exp s)) (t (error "unknown expression:~A~%" s)))) (defun parse-zero?-exp (s) (let ((exp1-start (1+ (or (position #\( s) (error "parse-zero?-exp:position #\( error"))))) (multiple-value-bind (exp1 s) (parse-expression (subseq-and-trim s exp1-start)) (let ((exp-end (1+ (or (position #\) s) (error "parse-zero?-exp:position #\) error"))))) (values (list 'zero?-exp exp1) (subseq-and-trim s exp-end)))))) (defun parse-const-exp (s) (multiple-value-bind (num exp-end) (read-from-string s) (values (list 'const-exp num) (subseq-and-trim s exp-end)))) (defun parse-var-exp (s) (multiple-value-bind (var exp-end) (read-from-string s) (values (list 'var-exp var) (subseq-and-trim s exp-end)))) (defun parse-diff-exp (s) (multiple-value-bind (exp1 s) (parse-expression (subseq-and-trim s (1+ (or (position #\( s) (error "parse-diff-exp:position #\( error"))))) (multiple-value-bind (exp2 s) (parse-expression (subseq-and-trim s (1+ (or (position #\, s) (error "parse-diff-exp:position #\, error"))))) (values (list 'diff-exp exp1 exp2) s)))) (defun parse-if-exp (s) (multiple-value-bind (exp1 s) (parse-expression (skip-prefix "if")) (multiple-value-bind (exp2 s) (parse-expression (skip-prefix "then")) (multiple-value-bind (exp3 s) (parse-expression (skip-prefix "else")) (values (list 'if-exp exp1 exp2 exp3) s))))) (defun parse-let-exp (s) (multiple-value-bind (var s) (parse-expression (skip-prefix "let")) (multiple-value-bind (exp1 s) (parse-expression (skip-prefix "=")) (multiple-value-bind (body s) (parse-expression (skip-prefix "in")) (values (list 'let-exp var exp1 body) s))))) ;;;;0.0 parser end (defun empty-env () (list 'empty-env)) (defun extend-env (var val env) (list 'extend-env var val env)) (defun apply-env (env search-var) (cond ((eql (car env) 'empty-env) (report-no-binding-found search-var)) ((eql (car env) 'extend-env) (let ((saved-var (cadr env)) (saved-val (caddr env)) (saved-env (cadddr env))) (if (eql search-var saved-var) saved-val (apply-env saved-env search-var)))) (t (report-invalid-env env)))) (defun report-no-binding-found (search-var) (error "No binding for ~s" search-var)) (defun report-invalid-env (env) (error "Bad environment: ~s" env)) (defmacro define-datatype (type-name type-predicate-name &rest variants) (let ((variant-pred-list (mapcar (lambda (v) (intern (concatenate 'string (symbol-name (car v)) "?"))) variants))) `(progn (defun ,type-predicate-name (e) (some (lambda (p) funcall p e) ,variant-pred-list)) ,@(mapcar (lambda (variant-exp) (let* ((variant-name (car variant-exp)) (variant-fields (cdr variant-exp)) (variant-pred (intern (concatenate 'string (symbol-name variant-name) "?")))) `(progn (defun ,variant-name (&rest fields) (cons ',variant-name (mapcar (lambda (pred field) (if (funcall pred field) field (error "field[~s] init field." field))) (mapcar #'cadr ',variant-fields) fields))) (defun ,variant-pred (e) (eql (car e) ',variant-name)) ,@(loop for i from 0 below (length variant-fields) for field in variant-fields collect `(let ((index (+ 1 ,i))) (defun ,(intern (concatenate 'string (symbol-name variant-name) "->" (symbol-name (car field)))) (e) (nth index e))))))) variants)))) (defmacro cases (type-name expression &rest clauses) (let ((exp-sym (gensym))) `(let ((,exp-sym ,expression)) (cond ,@(mapcar (lambda (c) (let ((variant-name (car c))) (if (eql variant-name 'else) `(t ,(cdr c)) (let ((var-pred (intern (concatenate 'string (symbol-name variant-name) "?"))) (bound-var-list (cadr c))) `((,var-pred ,exp-sym) (let ,(loop for i from 0 below (length bound-var-list) for var in bound-var-list collect (list var `(nth (1+ ,i) ,exp-sym))) ,@(cddr c))))))) clauses))))) (defun split-symbol-p (c) (case c (#\( t) (#\) t) (#\Space t) (#\, t) (otherwise nil))) (defun parse-let-exp (s c) (let* ((eql-pos (position #\= s)) (var (string-trim " " (subseq s 3 position)))) (scan&parse (subseq s (+ position 1)) (lambda (exp1 res-str) (scan&parse (subseq (string-trim " " res-str) 2) (lambda (body res-str) (funcall c (let-exp var exp1 body) res-str))))))) (defun parse-if-exp (s c) (let ((exp1-start (+ (position #\Space s) 1))) (scan&parse (subseq s exp1-start) (lambda (exp1 res-str) (scan&parse (subseq (string-trim " " res-str) 4) (lambda (exp2 res-str) (scan&parse (subseq (string-trim " " res-str) 4) (lambda (exp3 res-str) (funcall c (if-exp exp1 exp2 exp3) res-str))))))))) (defun parse-op-exp (s c) (let* ((op-end (position #\Space s)) (op (subseq s 0 op-end)) (arg-start (position #\( s)) (arg-list nil)) (labels ((arg-collector (exp res-str) (setf arg-list (cons exp arg-list)) (let ((res-str (string-trim " " res-str))) (ecase (svref res-str 0) (#\, (scan&parse (subseq res-str 1) #'arg-collector)) (#\) (funcall c (create-op-exp op (reverse arg-list)) (subseq res-str 1))))))) (scan&parse (subseq s (+ arg-start 1)) #'arg-collector)))) (defun create-op-exp (op arg-list) (ecase op ("-" (apply #'diff-exp arg-list)) ("zero?" (apply #'zero?-exp arg-list)))) (defun scan&parse (s c) (if (> (length s) 0) (let* ((str (string-trim "\n " s)) (split-index (position-if #'split-symbol-p str)) (token (subseq str 0 split-index))) (case token ("-" (parse-diff-exp str (lambda (exp res-str) (funcall c exp res-str)))) ("let" (parse-let-exp str (lambda (exp res-str) (funcall c exp res-str)))) ("zero?" (parse-zerop-exp str (lambda (exp res-str) (funcall c exp res-str)))) ("if" (parse-if-exp str (lambda (exp res-str) (funcall c exp res-str)))) (otherwise (parse-var-const-exp str (lambda (exp res-str) (funcall c exp res-str)))))))) (defun number? (n) (numberp n)) (defun identifier? (e) (and (atom e) (not (eql e 'lambda)))) (defun boolean? (b) (typep b 'boolean)) ;;;;3.2 ;;;exercise 3.1 ;;翻译成人话:n的表达式的值为n ;;x 3 v i 都用到了这个事实 ;;;exercise 3.2 ;;-0 (define-datatype program program? (a-program (exp1 expression?))) (define-datatype expression expression? (const-exp (num number?)) (diff-exp (exp1 expression?) (exp2 expression?)) (zero?-exp (exp1 expression?)) (if-exp (exp1 expression?) (exp2 expression?) (exp3 expression?)) (var-exp (var identifier?)) (let-exp (var identifier?) (exp1 expression?) (body expression?)) (minus-exp (num number?)) (add-exp (exp1 expression?) (exp2 expression?)) (mul-exp (exp1 expression?) (exp2 expression?)) (div-exp (exp1 expression?) (exp2 expression?)) (equal-exp (exp1 expression?) (exp2 expression?)) (greater-exp (exp1 expression?) (exp2 expression?)) (less-exp (exp1 expression?) (exp2 expression?))) (defun init-env () (extend-env 'i (num-val 1) (extend-env 'v (num-val 5) (extend-env 'x (num-val 10) (empty-env))))) (define-datatype expval expval? (num-val (num number?)) (bool-val (bool boolean?))) (defun expval->num (val) (cases expval val (num-val (num) num) (else (error "expval->num extract error ~A~%" val)))) (defun expval->bool (val) (cases expval val (bool-val (bool) bool) (else (error "expval->bool extract error ~A~%" val)))) (defun run (string) (value-of-program (scan&parse string))) (defun value-of-program (pgm) (cases (pgm) (a-program (exp1) (value-of exp1 (init-env))))) (defun value-of (exp env) (cases expression exp (const-exp (num) (num-val num)) (var-exp (var) (apply-env env var)) (diff-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (- num1 num2))))) (zero?-exp (exp1) (let ((val1 (value-of exp1 env))) (let ((num1 (expval->num val1))) (if (zero? num) (bool-val t) (bool-val nil))))) (if-exp (exp1 exp2 exp3) (let ((val1 (value-of exp1 env))) (if (expval->bool val1) (value-of exp2 env) (value-of exp3 env)))) (let-exp (var exp1 body) (let ((val1 (value-of exp1 env))) (value-of body (extend-env var val1 env)))) (minus-exp (num) (num-val (- num))) (add-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (+ num1 num2))))) (mul-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (* num1 num2))))) (div-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (num-val (/ num1 num2))))) (equal-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (bool-val (= num1 num2))))) (greater-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (bool-val (> num1 num2))))) (less-exp (exp1 exp2) (let ((val1 (value-of exp1 env)) (val2 (value-of exp2 env))) (let ((num1 (expval->num val1)) (num2 (expval->num val2))) (bool-val (< num1 num2))))))) ;;;exercise 3.3 ;;因为减法用一个操作符就可以表示加减法,而加法需要两个。 ;;exercise 3.4 ;;TODO ;;exercise 3.5 ;;TODO ;;exercise 3.6 ;;见value-of和expression的定义中对minus的处理 ;;解析器的调整 TODO ;;;exercise 3.7 ;;见上方对add、mul和div的处理 ;;解析器的调整 TODO ;;;exercise 3.8 ;;见上方对equal、greater和less的处理 ;;解析器的调整 TODO ;;;exercise 3.9 ;;TODO ;;;exercise 3.10 ;;TODO ;;;exercise 3.11 ;;添加一个统一的 op-exp,TODO ;;;exercise 3.12 ;;TODO ;;;exercise 3.13 ;;把if表达式处理中 expval->bool 改为 (/= 0 (expval->num ...)) 实现:TODO ;;;exercise 3.14 ;;TODO ;;;exercise 3.15 ;;实现:TODO ;;不可表达的原因是这个操作符具有打印控制台的副作用,无法用函数形式表达。 ;;;exercise 3.16 ;;需要修改let的定义 ;;实现:TODO ;;;exercise 3.17 ;;TODO 展开成多级let ;;exercise 3.18 ;;TODO
11,971
Common Lisp
.lisp
406
23.889163
86
0.598186
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b5a6e52cd5ed82dcb6f20b987d4368529a5b8af337039eba6cf323bfb7c02052
20,250
[ -1 ]
20,251
cogf-llgen.lisp
LeZheng_l-lisp-demo/EOPL_Exercise/cogf-llgen.lisp
(defclass lc-exp () ()) (defclass var-exp (lc-exp) ((var :type symbol))) (defclass lambda-exp (lc-exp) ((bound-var :type symbol) (body :type lc-exp))) (defclass app-exp (lc-exp) ((rator :type lc-exp) (rand :type lc-exp))) (define-datatype lc-exp (var-exp (var symbol)) (lambda-exp (bound-var symbol) (body lc-exp)) (app-exp (rator lc-exp) (rand lc-exp))) (defmacro define-datatype (type-name &rest variants) (flet ((field-reader-name (type-sym field-sym) (concatenate 'string (symbol-name type-sym) "->" (symbol-name field-sym)))) `(progn (defclass ,type-name () ()) ,@(mapcar (lambda (variant) (let ((name (car variant)) (fields (cdr variant))) `(defclass ,name () ,(mapcar (lambda (field) (list (car field) :type (cadr field) :initarg (intern (symbol-name (car field)) 'keyword) :accessor (intern (field-reader-name name (car field))))) fields)))) variants)))) (defmacro cases (exp &rest clauses) (let ((exp-sym (gensym))) `(let ((,exp-sym ,exp)) (ctypecase ,exp-sym ,@(mapcar #'(lambda (clause) `(,(car clause) (with-slots ,(cadr clause) ,exp-sym ,@(cddr clause)))) clauses))))) (defun test1 () (define-datatype lc-exp (var-exp (var symbol)) (lambda-exp (bound-var symbol) (body lc-exp)) (app-exp (rator lc-exp) (rand lc-exp))) (let ((v1 (make-instance 'var-exp :var 'int)) (a1 (make-instance 'app-exp :rator '+ :rand '1)) (l1 (make-instance 'lambda-exp :bound-var 'x :body '(+ 1 x)))) (dolist (i (list v1 a1 l1)) (cases i (var-exp (var) (format t "var-exp var:~A~%" var)) (lambda-exp (bound-var body) (format t "lambda-exp bound-var[~A] body[~A]~%" bound-var body)) (app-exp (rator rand) (format t "app-exp rator[~A] rand[~A]~%" rator rand))))))
1,913
Common Lisp
.lisp
67
23.626866
99
0.590289
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0d93d1ee2b63ecb3665da2152be649c8a9f40e183f8ac09bf9b9d9c5029b5425
20,251
[ -1 ]
20,252
chapter-11.lisp
LeZheng_l-lisp-demo/CLHS-Demo/chapter-11.lisp
(make-package 'temp :use nil) (use-package 'temp) (intern "TEMP-SYM" 'temp) (find-symbol "TEMP-SYM") (export (find-symbol "TEMP-SYM" 'temp) 'temp) (find-symbol "TEMP-SYM") (find-package "COMMON-LISP") (find-package 'common-lisp) (find-all-symbols 'car) (intern "CAR" 'temp) (find-all-symbols 'car) (import 'common-lisp::car 'temp) (find-symbol "CAR" 'temp) (find-symbol "CDR" 'temp) (delete-package 'temp) (make-package 'temporary :nicknames '("TEMP")) (rename-package 'temp 'ephemeral '("ephe")) (make-package 'temp) (package-shadowing-symbols 'temp) (shadow 'car 'temp) (find-symbol "CAR" 'temp) (package-shadowing-symbols 'temp) (in-package "COMMON-LISP-USER") ;=> #<PACKAGE "COMMON-LISP-USER"> (setq sym (intern "CONFLICT")) ;=> CONFLICT (intern "CONFLICT" (make-package 'temp)) ;=> TEMP::CONFLICT, NIL (package-shadowing-symbols 'temp) ; => NIL (shadowing-import sym 'temp); => T (package-shadowing-symbols 'temp) ;=> (CONFLICT) (make-package 'temporary :nicknames '("TEMP1" "temp1") :use "CL-USER") (defun print-all-symbols (package) (with-package-iterator (next-symbol (list package) :internal :external) (loop (multiple-value-bind (more? symbol) (next-symbol) (if more? (print symbol) (return)))))) (export (intern "CONTRABAND" 'temp) 'temp) (unexport 'contraband 'temp) (setq temps-unpack (intern "UNPACK" 'temp)) (unintern temps-unpack 'temp) (find-symbol "UNPACK" 'temp) (defpackage "MY-PACKAGE" (:nicknames "MYPKG" "MY-PKG") (:use "COMMON-LISP") (:shadow "CAR" "CDR") ; (:shadowing-import-from "VENDOR-COMMON-LISP" "CONS") ; (:import-from "VENDOR-COMMON-LISP" "GC") (:export "EQ" "CONS" "FROBOLA")) (let ((lst ())) (do-symbols (s (find-package "MY-PACKAGE")) (push s lst)) lst) (let ((lst ())) (do-external-symbols (s (find-package 'my-package) lst) (push s lst)) lst) (let ((lst ())) (do-all-symbols (s lst) (when (eq (find-package 'my-package) (symbol-package s)) (push s lst))) lst)
2,073
Common Lisp
.lisp
59
31.338983
75
0.648148
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1135ce72af4ed05ad9239991b6b553f80de0371f4b5efaaa774cf8f8e92ecbc6
20,252
[ -1 ]
20,253
chapter-5.lisp
LeZheng_l-lisp-demo/CLHS-Demo/chapter-5.lisp
;;apply (apply '+ '(1 2)) (apply #'+ '(1 2)) (apply (lambda (a b) (+ a b)) (list 1 2)) ;;defun (defun fun1 (a b &optional c) "this is fun1, contains optional." (list a b c)) (defun fun2 (a b &rest r) "this is fun2, contains rest." (list a b r)) (defun fun3 (a b &key name (age 0)) (declare (number age)) (list a b name age)); -> (fun3 1 2 :name "asdf" :age 2) (defun fun4 (a b c) (check-type a integer) (locally (declare (integer a)) (list (1+ a) b c))) ;;fdefinition (fdefinition '+) (setf (fdefinition 'fun5) (lambda (a) (list a 1))) ;;fboundp (fboundp 'fun5) ;;fmakunbound (fmakunbound 'fun5) ;;flet (flet ((add (a &rest r) "flet add" (apply '+ (cons a r)))) (add 1 2 3)) ;;labels (labels ((add (numbers) "label add" (if (null numbers) 0 (+ (car numbers) (add (cdr numbers)))))) (print (documentation #'add 'function)) (add (list 1 2 3))) ;;macrolet (defun foo (x flag) (macrolet ((fudge (z) `(if flag (* ,z x) ,z))) (fudge 2))) ;;funcall (funcall #'+ 1 2 3 4) (flet ((cons (x y) (list 'fcons x y))) (funcall #'cons 1 2)) ;;function (flet ((cons (x y) (list 'fcons x y))) (function cons)) ;;function-lambda-expression (function-lambda-expression #'fun1) (funcall (eval (function-lambda-expression #'fun2)) 1 2 3) ;;functionp (functionp #'+) ;;compiled-function-p (compiled-function-p #'+) ;;defconstant (defconstant CONST-VAR 123 "this is a const variable") ;;defparameter (defparameter *param-var* "pvarx" "This is a parameter") ;;defvar (defvar *var-var* 123 "This is a var") ;;destructuring-bind (destructuring-bind ((a) one two three) (list '(1000) 1 2 3) (list a one two three)) ;;let let* (let ((i 10) (j 11)) (list i j)) (let* ((i 10) (j (1+ i))) (list i j)) ;;progv (progv '(a b c) '(1 2 3) (list a b c)) ;;setq psetq (let ((a 1) (b 1) (c 1)) (setq a (1+ a) b (1+ a) c (1+ b)) (list a b c)) (let ((a 1) (b 1) (c 1)) (psetq a (1+ a) b (1+ a) c (1+ b)) (list a b c)) ;;block (block b1 (print 1) (print 2) (return-from b1 "return b1")) ;;catch throw (catch 'dummy-tag 1 2 (throw 'dummy-tag 3) 4) (catch 'dummy-tag 1 2 (throw 'dummy-tagx 3) 4) (catch 'c (flet ((c1 () (throw 'c 1))) (catch 'c (c1) (print 'unreachable)) 2)) ;;go tagbody (tagbody (setf f 1) t1 (print "1") (incf f) (print "2") t2 (print "3") (if (> f 5) (go end) (go t1)) end (print "end")) ;;return-from return (block b1 (return-from b1 1)) (block nil (return 1)) ;;unwind-protect (block nil (unwind-protect (return 1) (print "asdf"))) ;;eq (eq 3 3.0) (eql 3 3.0) (eql "asdf" "asdf") (equal "asdf" "asdf") (equal 3 3.0) (equalp 3 3.0) ;;complement constantly (funcall (complement #'evenp) 1) (funcall (constantly 1) 1 2 3 4) ;;every some notevery notany (every #'evenp '(2 4 6)) (some #'evenp '(1 2 3)) (notevery #'evenp '(1 2 3)) (notany #'evenp '(1 2 3)) ;;and (and (atom p) (numberp p)) ;;or (or (evenp i) (oddp i)) ;;cond (let ((i 0)) (cond ((evenp i) (print i) "even") ((oddp i) "odd") ((zerop i) "0") (t "else"))) ;;if (if (evenp i) "even" "odd") ;;when unless (when (oddp i) (print "odd")) (unless (evenp i) (print "odd")) ;;case ccase ecase (case i ((1 2) "1-2") ((3 4) "3-4") (5 "5") (t "else")) ;;typecase ctypecase etypecase (defun what-is-it (x) (format t "~&~S is ~A.~%" x (typecase x (float "a float") (null "a symbol, boolean false, or the empty list") (list "a list") (t (format nil "a(n) ~(~A~)" (type-of x)))))) ;;multiple-value-bind (multiple-value-bind (f r) (floor 130 11) (list f r)) ;;multiple-value-call (multiple-value-call #'+ 1 (values 2 3)) (multiple-value-call #'list 1 (values 2 3 4) 0) ;;multiple-value-list (multiple-value-list (floor 9 2)) ;;multiple-value-prog1 (multiple-value-prog1 (values 1 2 3) (print 1) "asdf") ;;multiple-value-setq (multiple-value-setq (a b) (values 1 2)) ;;values (values) (values 1 2 3) ;;values-list (values-list '(1 2 3)) ;;nth-value (nth-value 3 (values 1 2 3 4)) ;;progn prog prog* (progn (print 1) (print 2)) (prog (print 1) (print 2)) (prog ((a 1) (b 2)) (print a) (print b)) (prog ((a 1) (b 2)) t1 (print a) t2 (print b) (incf a) (cond ((> a 3) a) (t (go t1)))) ;;define-modify-macro (define-modify-macro my-cons (&rest args) cons "my cons") ;;shiftf (let ((a 1) (b 2) (c 3)) (shiftf a b c 99) (list a b c)) ;;rotatef (let ((a 1) (b 2) (c 3)) (rotatef a b c) (list a b c))
4,606
Common Lisp
.lisp
212
18.882075
65
0.583409
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
46422fb08608e05e3c443b41a2946040d9cfe6d80e6a6c0f39fe9bac17a1d911
20,253
[ -1 ]
20,254
chapter-7.lisp
LeZheng_l-lisp-demo/CLHS-Demo/chapter-7.lisp
;;function-keywords (defmethod gf1 ((a integer) &optional (b 2) &key (c 3) ((:dee d) 4) e ((eff f))) (list a b c d e f)) (function-keywords (find-method #'gf1 '() (list (find-class 'integer)))) ;;change-class (defclass my-position() ()) (defclass x-y-position (my-position) ((x :initform 0 :initarg :x) (y :initform 0 :initarg :y))) (defclass r-t-position (my-position) ((rho :initform 0) (theta :initform 0))) (defmethod update-instance-for-different-class :before ((old x-y-position) (new r-t-position) &key) (let ((x (slot-value old 'x)) (y (slot-value old 'y))) (setf (slot-value new 'rho) (sqrt (+ (* x x) (* y y))) (slot-value new 'theta) (atan y x)))) (setq p1 (make-instance 'x-y-position :x 2 :y 0)) (change-class p1 'rho-theta-position) ;;slot-boundp (slot-boundp p1 'rho) ;;slot-exists-p (slot-exists-p p1 'rhoxxx) ;;slot-makunbound (slot-makunbound p1 'rho) ;;slot-value (setf (slot-value p1 'rho) 33) (print (slot-value p1 'rho)) ;;make-instance (defclass person () ((name :initform "" :initarg :name) (age :initform 0 :initarg :age))) (make-instance 'person :name "colin" :age 11) ;;make-load-form (defclass pos () ((x :initarg :x :accessor pos-x) (y :initarg :y :accessor pos-y))) (defmethod make-load-form ((self pos) &optional env) (declare (ignore env)) `(make-instance ',(class-of self) :x ',(pos-x self) :y ',(pos-y self))) (setf p1 (make-instance 'pos :x 3 :y 4)) (make-load-form p1) ;;with-accessors (with-accessors ((x pos-x) (y pos-y)) p1 (setf x 6 y 8) (list x y)) ;;with-slots (with-slots (x y) p1 (setf x 33 y 44) (list x y)) ;;defclass (defclass point () ((x :initarg :x :accessor p-x :documentation "This is x of point" :allocation :instance :type number) (y :initarg :y :accessor p-y :initform 0 :documentation "This is y of point" :allocation :instance :type number) (name :initarg :name :initform "unknown" :reader get-name :writer set-name) (count :initform 0 :accessor p-count :allocation :class)) (:documentation "This is a point") (:default-initargs . (:x 0 :y 0 :name "default"))) (defmethod initialize-instance :after ((instance point) &rest initargs &key &allow-other-keys) (with-slots (count) instance (incf count)))
2,259
Common Lisp
.lisp
68
30.720588
94
0.6621
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
89f508a7591456b5c5aacf7ecdd55695d3fd73bb59d231b98b2924e81fd5c973
20,254
[ -1 ]
20,255
chapter-7.lisp~
LeZheng_l-lisp-demo/CLHS-Demo/chapter-7.lisp~
;;function-keywords (defmethod gf1 ((a integer) &optional (b 2) &key (c 3) ((:dee d) 4) e ((eff f))) (list a b c d e f)) (function-keywords (find-method #'gf1 '() (list (find-class 'integer)))) ;;change-class (defclass my-position() ()) (defclass x-y-position (my-position) ((x :initform 0 :initarg :x) (y :initform 0 :initarg :y))) (defclass r-t-position (my-position) ((rho :initform 0) (theta :initform 0))) (defmethod update-instance-for-different-class :before ((old x-y-position) (new r-t-position) &key) (let ((x (slot-value old 'x)) (y (slot-value old 'y))) (setf (slot-value new 'rho) (sqrt (+ (* x x) (* y y))) (slot-value new 'theta) (atan y x)))) (setq p1 (make-instance 'x-y-position :x 2 :y 0)) (change-class p1 'rho-theta-position) ;;slot-boundp (slot-boundp p1 'rho) ;;slot-exists-p (slot-exists-p p1 'rhoxxx) ;;slot-makunbound (slot-makunbound p1 'rho) ;;slot-value (setf (slot-value p1 'rho) 33) (print (slot-value p1 'rho)) ;;make-instance (defclass person () ((name :initform "" :initarg :name) (age :initform 0 :initarg :age))) (make-instance 'person :name "colin" :age 11)
1,141
Common Lisp
.lisp
37
28.594595
74
0.655485
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
36225319ea2e732792557bb3ee9e5361e9e8c8a4eb37c7a349746bbb8bbd6f06
20,255
[ -1 ]
20,256
sort.lisp
LeZheng_l-lisp-demo/Data_Structure_and_Algorithms/sort.lisp
;;1,冒泡排序 (defun bubble-sort (arr) (dotimes (i (1- (length arr)) arr) (dotimes (j (- (length arr) i 1)) (if (> (svref arr j) (svref arr (1+ j))) (rotatef (svref arr j) (svref arr (1+ j))))))) (defun bubble-sort-2 (arr &optional (start 0)) (if (>= start (1- (length arr))) arr (loop for i from (1- (length arr)) above start when (< (svref arr i) (svref arr (1- i))) do (rotatef (svref arr i) (svref arr (1- i))) finally (return (bubble-sort-2 arr (1+ start)))))) ;;2,插入排序 (defun insert-sort (arr) (dotimes (i (1- (length arr)) arr) (loop for j from (1+ i) downto 1 do (if (< (svref arr j) (svref arr (1- j))) (rotatef (svref arr j) (svref arr (1- j))) (return))))) (defun insert-sort-2 (arr &optional (start 0)) (if (= start (length arr)) arr (loop for i from start downto 1 until (> (svref arr i) (svref arr (1- i))) do (rotatef (svref arr i) (svref arr (1- i))) finally (return (insert-sort-2 arr (1+ start)))))) ;;3,选择排序 (defun select-sort (arr) (dotimes (i (1- (length arr)) arr) (let ((min-index i)) (loop for j from i to (1- (length arr)) do (if (< (svref arr j) (svref arr min-index)) (setf min-index j))) (rotatef (svref arr i) (svref arr min-index))))) (defun select-sort-2 (arr &optional (start 0)) (if (>= start (1- (length arr))) arr (loop with min-index = start for i from start to (1- (length arr)) do (if (< (svref arr i) (svref arr min-index)) (setf min-index i)) finally (progn (rotatef (svref arr min-index) (svref arr start)) (return (select-sort-2 arr (1+ start))))))) ;;4,希尔排序 (defun shell-sort (arr) (do ((gap (floor (length arr) 2) (floor gap 2))) ((< gap 1) arr) (dotimes (i gap) (dotimes (k (1- (floor (length arr) gap))) (loop for j from (+ i (* gap k)) downto 0 by gap do (if (< (svref arr (+ j gap)) (svref arr j)) (rotatef (svref arr j) (svref arr (+ j gap))) (return))))))) ;;5,归并排序 (defun merge-sort (arr) (if (< (length arr) 2) arr (let ((arr-1 (merge-sort (subseq arr 0 (floor (length arr) 2)))) (arr-2 (merge-sort (subseq arr (floor (length arr) 2))))) (merge 'vector arr-1 arr-2 #'<)))) ;;6,快速排序 (defun quick-sort (arr) (labels ((q-sort (vec l r) (let ((i l) (j r) (p (svref vec (round (+ l r) 2)))) (loop while (<= i j) do (progn (loop while (< (svref vec i) p) do (incf i)) (loop while (> (svref vec j) p) do (decf j)) (when (<= i j) (rotatef (svref vec i) (svref vec j)) (incf i) (decf j)))) (if (>= (- j l) 1) (q-sort vec l j)) (if (>= (- r i) 1) (q-sort vec i r))) vec)) (q-sort arr 0 (1- (length arr))))) ;;7,基数排序 (defun radix-sort (arr &optional (radix 0) (max-radix nil)) (let ((bucket (make-array 16 :initial-element nil)) (max-radix (or max-radix (reduce #'max arr :key #'integer-length)))) (loop for e across arr do (push e (aref bucket (ldb (byte 4 (* radix 4)) e)))) (let ((bucket-seq (coerce (reduce #'nconc bucket :key #'reverse) 'vector))) (if (<= max-radix radix) bucket-seq (radix-sort bucket-seq (1+ radix) max-radix))))) ;;8,堆排序 (defun heap-sort (arr) (labels ((heapify (seq current-index size) (let ((left (+ (* 2 current-index) 1)) (right (+ (* 2 current-index) 2)) (max-index current-index)) (if (and (< left size) (> (svref seq left) (svref seq max-index))) (setf max-index left)) (if (and (< right size) (> (svref seq right) (svref seq max-index))) (setf max-index right)) (when (/= current-index max-index) (rotatef (svref seq max-index) (svref seq current-index)) (heapify seq max-index size))))) (loop for i from (1- (floor (length arr) 2)) downto 0 do (heapify arr i (length arr))) (loop for j from (1- (length arr)) above 0 do (progn (rotatef (svref arr 0) (svref arr j)) (heapify arr 0 j)) finally (return arr)))) (defvar *test-seq* #(1 4 0 2 3 8 5 3 33 77 88 9 11)) (defun test-correctness () (let ((funs (list 'bubble-sort 'bubble-sort-2 'insert-sort 'insert-sort-2 'select-sort 'select-sort-2 'quick-sort 'heap-sort 'radix-sort 'shell-sort 'merge-sort))) (dolist (fun funs) (if (equalp (sort (copy-seq *test-seq*) #'<) (funcall (symbol-function fun) (copy-seq *test-seq*))) (format t "~A test ok~%" (symbol-name fun)) (format t "~A test failed~%" (symbol-name fun)))))) (defun test-random () (let ((funs (list 'bubble-sort 'bubble-sort-2 'insert-sort 'insert-sort-2 'select-sort 'select-sort-2 'quick-sort 'heap-sort 'radix-sort 'shell-sort 'merge-sort)) (random-seq (coerce (loop for i from 1 to 10000 collect (random 10000)) 'vector))) (dolist (fun funs) (if (not (typep (symbol-function fun) 'compiled-function)) (compile fun)) (format t "-----------------~%test ~A ...~%" (symbol-name fun)) (if (equalp (sort (copy-seq random-seq) #'<) (time (funcall (symbol-function fun) (copy-seq random-seq)))) (format t "~A test ok~%" (symbol-name fun)) (format t "~A test failed~%" (symbol-name fun)))))) ;(test-random)
5,983
Common Lisp
.lisp
115
39.695652
137
0.508805
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6ed6cca6a8ef3bd5acfa4f0c8869728933f0eba64aa90a46b6852647bcb86efc
20,256
[ -1 ]
20,257
kmp.lisp
LeZheng_l-lisp-demo/Data_Structure_and_Algorithms/kmp.lisp
(defun index-kmp (str p) (let ((next (loop for i from 1 below (length p) with arr = (make-array (length p) :initial-element 0) with j = 0 do (cond ((= i 1) (setf (aref arr i) 1)) ((equal (elt p (1- i)) (elt p j)) (psetf j (1+ j) (aref arr i) (1+ (aref arr (1- i))))) (t (setf j 0 (aref arr i) 1))) finally (return arr)))) (loop with i = 0 and j = 0 while (and (< i (length str)) (< j (length next))) when (equal (elt str i) (elt p j)) do (if (= j (1- (length next))) (return (- i j)) (progn (incf i) (incf j))) else do (setf i (1+ i) j (max 0 (1- (aref next j)))))))
865
Common Lisp
.lisp
15
36.8
112
0.376471
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7fec5a65724337f7087b0506f6f298af35c8d54e6ac38e4225cf822d4e8399e1
20,257
[ -1 ]
20,258
fib-cps.lisp
LeZheng_l-lisp-demo/Data_Structure_and_Algorithms/fib-cps.lisp
(defun fib (n) (labels ((iter (n f) (if (= n 1) (funcall f 0 1) (iter (- n 1) (lambda (a b) (funcall f b (+ a b))))))) (iter n (lambda (n1 n0) n0)))) (defun fib (n) (labels ((rec (n f) (if (<= n 2) (funcall f 1) (rec (- n 1) (lambda (a) (rec (- n 2) (lambda (b) (funcall f (+ a b))))))))) (rec n #'identity)))
390
Common Lisp
.lisp
18
16.222222
36
0.421622
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1c1bc7786486e39e078eac33d30603312f127a4017de47c23a9746664f7d9957
20,258
[ -1 ]
20,259
init-and-fini-hooks.lisp
LeZheng_l-lisp-demo/31_Platform_Independent_Extensions/init-and-fini-hooks.lisp
;;;31.1. Customizing CLISP Process Initialization and Termination demo (defun start () (format t "start...~%")) (defun end () (format t "end...~%")) (push #'start CUSTOM:*INIT-HOOKS*) (push #'end CUSTOM:*FINI-HOOKS*) (format t "hello~%") (ext:saveinitmem "init-fini.mem" :executable t) ;;this file can be loaded in clisp to create init-fini.mem,and do ./init-fini.mem to test start and end
416
Common Lisp
.lisp
11
34.454545
103
0.673317
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
48023386565e100f147755e4d2a165672d958682486b3e73b07050e5757dc36e
20,259
[ -1 ]
20,260
prompt-demo.lisp
LeZheng_l-lisp-demo/31_Platform_Independent_Extensions/prompt-demo.lisp
;;;clisp prompt demo ;;;Please load this file in clisp to create memory file,then use ./prompt-demo.mem to start it (setf CUSTOM:*PROMPT-START* "admin") (setf CUSTOM:*PROMPT-FINISH* "->") (setf CUSTOM:*PROMPT-BODY* #'(lambda () (format nil "[~A]" (get-internal-real-time)))) (ext:saveinitmem "prompt-demo.mem" :executable t) (exit)
335
Common Lisp
.lisp
7
46.428571
94
0.713846
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
069f9d7adb4ab0a1636271c51c90418d391e8e9f4bf66235845ce49f2d85dce9
20,260
[ -1 ]
20,261
additional-macro-and-fun.lisp
LeZheng_l-lisp-demo/31_Platform_Independent_Extensions/additional-macro-and-fun.lisp
;;;This file show some additional fancy macros and functions examples (EXT:ETHE number (+ 1 2)) ;;=> 3 ;this will check the return value of form:(+ 1 2) (EXT:ETHE number "This is string") ;; ERROR ,becase form is a string
226
Common Lisp
.lisp
5
43.4
69
0.720183
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
717297e41983a37ab48d74f9287dafdc9dfd5b7e96e791b051aee80b15b7ddea
20,261
[ -1 ]
20,262
run-shell-demo.lisp
LeZheng_l-lisp-demo/31_Platform_Independent_Extensions/run-shell-demo.lisp
;;;This demo is to run a shell command and get result to string (defun sh (cmd) (let ((res-str nil) (res-code nil) (buf-stream (ext:run-shell-command cmd :output :stream))) (loop for c = (read-char buf-stream nil) while c do (push c res-str)) (values (concatenate 'string (reverse res-str)) res-code)))
330
Common Lisp
.lisp
7
42.285714
73
0.656347
LeZheng/l-lisp-demo
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a2e725a080d3ecb07db41bd058ff1c0c2a04b45cdaf860bc356aef7367d273bc
20,262
[ -1 ]
20,310
PROJECT_LANG_1.lisp
seanpm2001_Learn-CommonLisp/PROJECT_LANG_1.lisp
; Start of script ; Project language file 1 ; For: seanpm2001/Learn-CommonLisp ; About: ; I decided to make Common Lisp the main project language file for this project (Seanpm2001/Learn-CommonLisp) as Common Lisp is the language this project is dedicated to, because this project is about learning the Common Lisp programming language. It only makes sense to Common Lisp the official language for this project. It is getting its own project language file, starting here. (defun plangone () (format t "Project language file 1") (format t "For: seanpm2001/Learn-CommonLisp") (format t "About:") (format t "I decided to make Common Lisp the main project language file for this project (Seanpm2001/Learn-CommonLisp) as Common Lisp is the language this project is dedicated to, because this project is about learning the Common Lisp programming language. It only makes sense to Common Lisp the official language for this project. It is getting its own project language file, starting here.") ) ; File info ; File type: CommonLisp source file (*.lisp) ; File version: 1 (2022, Wednesday, October 12th at 9:30 pm PST) ; Line count (including blank lines and compiler line): 21 ; End of script
1,194
Common Lisp
.lisp
16
73.125
394
0.788756
seanpm2001/Learn-CommonLisp
2
1
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f9aca752e27dad926be0b303d04d23c12d2a5fe515837393f155bb3e04c63212
20,310
[ -1 ]
20,353
mem.lisp
njm64_lzm/mem.lisp
(in-package #:lzm) (defvar *memory*) (defun read-u8 (addr) (aref *memory* addr)) (defun read-u16 (addr) (logior (ash (read-u8 addr) 8) (read-u8 (1+ addr)))) (defun read-word-addr (addr) (* 2 (read-u16 addr))) (defun write-u8 (addr value) (assert (< addr *static-memory-offset*)) (setf (aref *memory* addr) value)) (defun write-u16 (addr value) (assert (< (1+ addr) *static-memory-offset*)) (setf (aref *memory* addr) (ash value -8) (aref *memory* (1+ addr)) (logand value #xff))) (defun u16->s16 (n) (if (logbitp 15 n) (- n #x10000) n)) (defun s16->u16 (n) (logand #xffff n))
622
Common Lisp
.lisp
21
26.428571
55
0.620573
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1a97eb803415a8b4c83811f6250331d6bd65ed010a58fb4a1acbab699730789d
20,353
[ -1 ]
20,354
obj.lisp
njm64_lzm/obj.lisp
(in-package #:lzm) (defun obj-property-default (property) (read-u16 (+ *object-table-offset* (* (1- property) 2)))) (defun obj-address (obj) (assert (plusp obj)) (+ *object-table-offset* 62 (* (1- obj) 9))) (defun obj-attr-address (obj attr) (multiple-value-bind (byte bit) (floor attr 8) (values (+ (obj-address obj) byte) (- 7 bit)))) (defun obj-attr (obj attr) (multiple-value-bind (addr bit) (obj-attr-address obj attr) (logbitp bit (read-u8 addr)))) (defun (setf obj-attr) (val obj attr) (multiple-value-bind (addr bit) (obj-attr-address obj attr) (write-u8 addr (dpb (if val 1 0) (byte 1 bit) (read-u8 addr))))) (defun obj-parent (obj) (read-u8 (+ (obj-address obj) 4))) (defun (setf obj-parent) (val obj) (write-u8 (+ (obj-address obj) 4) val)) (defun obj-sibling (obj) (read-u8 (+ (obj-address obj) 5))) (defun (setf obj-sibling) (val obj) (write-u8 (+ (obj-address obj) 5) val)) (defun obj-child (obj) (read-u8 (+ (obj-address obj) 6))) (defun (setf obj-child) (val obj) (write-u8 (+ (obj-address obj) 6) val)) (defun obj-prev-sibling (obj) (let ((parent (obj-parent obj))) (if (zerop parent) 0 (loop for s = (obj-child parent) then (obj-sibling s) and prev = 0 then s finally (return 0) when (= s obj) do (return prev))))) (defun obj-name-addr (obj) (read-u16 (+ (obj-address obj) 7))) (defun obj-name-byte-len (obj) (* 2 (read-u8 (obj-name-addr obj)))) (defun obj-name (obj) (decode-text (+ 1 (obj-name-addr obj)))) (defun obj-properties-addr (obj) (+ (obj-name-addr obj) (obj-name-byte-len obj) 1)) ;; Return a list of (prop, addr, size) tuples (defun obj-property-list (obj) (loop with addr = (obj-properties-addr obj) for size-byte = (read-u8 addr) for prop = (logand size-byte #b11111) for size = (1+ (ash size-byte -5)) until (zerop prop) collect (list prop (1+ addr) size) do (incf addr (1+ size)))) (defun obj-first-prop (obj) (caar (obj-property-list obj))) (defun obj-next-prop (obj prop) (let ((plist (obj-property-list obj))) (when-let (i (position prop plist :key #'first)) (first (nth (1+ i) plist))))) (defun obj-prop-addr (obj prop) (when-let (p (find prop (obj-property-list obj) :key #'first)) (second p))) (defun obj-prop-len (prop-addr) (if (zerop prop-addr) 0 (let ((b (read-u8 (1- prop-addr)))) (1+ (ash b -5))))) (defun obj-prop (obj prop) (if-let (p (find prop (obj-property-list obj) :key #'first)) (destructuring-bind (prop addr size) p (declare (ignore prop)) (ecase size (1 (read-u8 addr)) (2 (read-u16 addr)) (t (error "invalid property size")))) (obj-property-default prop))) (defun (setf obj-prop) (val obj prop) (let ((p (find prop (obj-property-list obj) :key #'first))) (unless p (error "put to invalid property")) (destructuring-bind (prop addr size) p (declare (ignore prop)) (ecase size (1 (write-u8 addr val)) (2 (write-u16 addr val)) (t (error "invalid property size")))))) (defun obj-remove (obj) (let ((parent (obj-parent obj)) (sibling (obj-sibling obj)) (prev-sibling (obj-prev-sibling obj))) (when (plusp parent) (if (zerop prev-sibling) (setf (obj-child parent) sibling) (setf (obj-sibling prev-sibling) sibling)) (setf (obj-sibling obj) 0) (setf (obj-parent obj) 0)))) (defun obj-insert (obj dst) (obj-remove obj) ;; (format t "Moving ~a to ~a~%" (obj-name obj) (obj-name dst)) (setf (obj-sibling obj) (obj-child dst)) (setf (obj-child dst) obj) (setf (obj-parent obj) dst))
3,777
Common Lisp
.lisp
103
31.339806
64
0.605645
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
63008a6781375cd3de99567fcf93c1b9e77362d46e2ccb99d70ba50eda9d7319
20,354
[ -1 ]
20,355
decode.lisp
njm64_lzm/decode.lisp
(in-package #:lzm) (defconstant +operand-type-word+ 0) (defconstant +operand-type-byte+ 1) (defconstant +operand-type-var+ 2) (defconstant +operand-type-none+ 3) (defun read-operand (operand-type) (ecase operand-type (0 (fetch-u16)) (1 (fetch-u8)) (2 (read-var (fetch-u8))))) (defun decode-operand-types (b) (loop for pos from 6 downto 0 by 2 for type = (ldb (byte 2 pos) b) until (= type +operand-type-none+) collect type)) (defun opcode-type (b) (cond ((and (= b #xbe) (>= *version* 5)) :opcode-type-ext) ((not (logbitp 7 b)) :opcode-type-long) ((logbitp 6 b) :opcode-type-var) (t :opcode-type-short))) (defun decode-instruction () (let ((b (fetch-u8))) (ecase (opcode-type b) (:opcode-type-ext nil) (:opcode-type-long (list :2op (logand b #b11111) (if (logbitp 6 b) +operand-type-var+ +operand-type-byte+) (if (logbitp 5 b) +operand-type-var+ +operand-type-byte+))) (:opcode-type-var (list* (if (logbitp 5 b) :var :2op) (logand b #b11111) (decode-operand-types (fetch-u8)))) (:opcode-type-short (let ((opcode (ldb (byte 4 0) b)) (operand-type (ldb (byte 2 4) b))) (if (= operand-type +operand-type-none+) (list :0op opcode) (list :1op opcode operand-type))))))) (defun next-instruction () (let ((pc *pc*)) (destructuring-bind (arity opcode &rest optypes) (decode-instruction) (let ((operands (mapcar #'read-operand optypes))) (if-let (handler (find-handler arity opcode)) (progn ;; (format t "PC $~x: ~a ~a ~%" pc handler operands) (apply handler operands)) (progn (format t "No handler for ~a $~x at PC $~x" arity opcode pc) (setf *break* t)))))))
1,875
Common Lisp
.lisp
51
29.509804
73
0.573635
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
de4eee0f9f0d5eb3c59041d86c624b95ad5e414ea0b803208db5b22d15169c4c
20,355
[ -1 ]
20,356
main.lisp
njm64_lzm/main.lisp
(in-package #:lzm) (defun read-data (filename) (with-open-file (f filename :element-type '(unsigned-byte 8)) (let ((data (make-array (file-length f) :element-type '(unsigned-byte 8)))) (read-sequence data f) data))) (defun init (filename) (setf *memory* (read-data filename)) (read-header) ;; TODO: Validate header (init-dictionary) (setf *pc* *initial-pc*) (setf *frame* 0) (setf *break* nil) (setf *rand-seed* nil) (setf *stack* (make-array 0 :fill-pointer 0 :adjustable t :element-type '(unsigned-byte 32)))) (defun run (filename) (init filename) (loop until *break* do ;; (format t "PC: $~x~%" *pc*) (next-instruction))) (defun run-hitch () (run "/Users/nickm/infocom/hitchhiker-r60-s861002.z3")) (defun run-zork () (run "/Users/nickm/infocom/zork1-r88-s840726.z3")) (defun run-czech () (run "/Users/nickm/infocom/czech_0_8/czech.z3")) (defun log-czech () (with-open-file (*standard-output* "czech.log" :direction :output :if-does-not-exist :create :if-exists :overwrite) (run-czech)))
1,252
Common Lisp
.lisp
33
29.090909
75
0.563067
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d21dafbeb102879fe45fd66777d61fa397a36968a8c8c1b582db1cc8b343e987
20,356
[ -1 ]
20,357
header.lisp
njm64_lzm/header.lisp
(in-package #:lzm) (defvar *version*) (defvar *high-memory-offset*) (defvar *initial-pc*) (defvar *dictionary-offset*) (defvar *object-table-offset*) (defvar *global-table-offset*) (defvar *static-memory-offset*) (defvar *abbrev-table-offset*) (defun read-header () (setf *version* (read-u8 #x00) *high-memory-offset* (read-u16 #x04) *initial-pc* (read-u16 #x06) *dictionary-offset* (read-u16 #x08) *object-table-offset* (read-u16 #x0a) *global-table-offset* (read-u16 #x0c) *static-memory-offset* (read-u16 #x0e) *abbrev-table-offset* (read-u16 #x18))) (defun print-header () (format t "Version: ~d~%" *version*) (format t "High memory offset: ~4,'0x~%" *high-memory-offset*) (format t "Initial PC: ~4,'0x~%" *initial-pc*) (format t "Dictionary offset: ~4,'0x~%" *dictionary-offset*) (format t "Object table offset: ~4,'0x~%" *object-table-offset*) (format t "Global table offset: ~4,'0x~%" *global-table-offset*) (format t "Static memory offset: ~4,'0x~%" *static-memory-offset*) (format t "Abbrev table offset: ~4,'0x~%" *abbrev-table-offset*))
1,191
Common Lisp
.lisp
27
40.259259
68
0.620155
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f05a726279758dfa49c0abb3f88debadc71f8fdff708bd098ce6f05bc04df38e
20,357
[ -1 ]
20,358
var.lisp
njm64_lzm/var.lisp
(in-package #:lzm) (defun local (i) (aref *stack* (+ *frame* i))) (defun (setf local) (val i) (setf (aref *stack* (+ *frame* i)) val)) (defun global (i) (read-u16 (+ *global-table-offset* (* i 2)))) (defun (setf global) (val i) (write-u16 (+ *global-table-offset* (* i 2)) val)) (defun read-var (n) (cond ((zerop n) (stack-pop)) ((< n #x10) (local (1- n))) ((< n #x100) (global (- n #x10))))) (defun read-signed-var (n) (u16->s16 (read-var n))) (defun write-var (n val) (let ((uval (logand #xffff val))) (cond ((zerop n) (stack-push uval)) ((< n #x10) (setf (local (1- n)) uval)) ((< n #x100) (setf (global (- n #x10)) uval)))))
685
Common Lisp
.lisp
22
27.590909
54
0.545732
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
65d3b6f4602fddccc121bb16ac33236fdfdcd1af6a822bcb9cbe48d79d615664
20,358
[ -1 ]
20,359
op.lisp
njm64_lzm/op.lisp
(in-package #:lzm) (defparameter *op-table* (make-array 128 :initial-element nil)) (eval-when (:compile-toplevel :load-toplevel) (defun op-table-index (arity opcode) (+ opcode (ecase arity (:0op 0) (:1op 32) (:2op 64) (:var 96))))) (defun find-handler (arity opcode) (aref *op-table* (op-table-index arity opcode))) (defmacro def-op ((arity opcode name &key store) args &body body) (let ((i (op-table-index arity opcode)) (sym (intern (concatenate 'string "OP-" (string-upcase name))))) (when store (setf body `((write-var (fetch-u8) (progn ,@body))))) `(progn (defun ,sym ,args ,@body) (setf (aref *op-table* ,i) (function ,sym))))) ;;;;------------------------------------------------------------------------ ;;;; 2OP opcodes ;;;;------------------------------------------------------------------------ (def-op (:2op #x01 "je") (a &rest args) (branch (member a args))) (def-op (:2op #x02 "jl") (a b) (branch (< (u16->s16 a) (u16->s16 b)))) (def-op (:2op #x03 "jg") (a b) (branch (> (u16->s16 a) (u16->s16 b)))) (def-op (:2op #x04 "dec-chk") (var limit) (let ((val (1- (read-signed-var var)))) (write-var var val) (branch (< val (u16->s16 limit))))) (def-op (:2op #x05 "inc-chk") (var limit) (let ((val (1+ (read-signed-var var)))) (write-var var val) (branch (> val (u16->s16 limit))))) (def-op (:2op #x06 "jin") (a b) (branch (= (obj-parent a) b))) (def-op (:2op #x07 "test") (bitmap flags) (branch (= (logand bitmap flags) flags))) (def-op (:2op #x08 "or" :store t) (a b) (logior a b)) (def-op (:2op #x09 "and" :store t) (a b) (logand a b)) (def-op (:2op #x0a "test-attr") (obj attr) (branch (obj-attr obj attr))) (def-op (:2op #x0b "set-attr") (obj attr) (setf (obj-attr obj attr) t)) (def-op (:2op #x0c "clear-attr") (obj attr) (setf (obj-attr obj attr) nil)) (def-op (:2op #x0d "store") (variable value) (when (zerop variable) (stack-pop)) ; 6.3.4 (write-var variable value)) (def-op (:2op #x0e "insert-obj") (obj dst) (obj-insert obj dst)) (def-op (:2op #x0f "loadw" :store t) (array word-index) (read-u16 (+ array (* 2 word-index)))) (def-op (:2op #x10 "loadb" :store t) (array byte-index) (read-u8 (+ array byte-index))) (def-op (:2op #x11 "get-prop" :store t) (obj prop) (obj-prop obj prop)) (def-op (:2op #x12 "get-prop-addr" :store t) (obj prop) (or (obj-prop-addr obj prop) 0)) (def-op (:2op #x13 "get-next-prop" :store t) (obj prop) (or (if (zerop prop) (obj-first-prop obj) (obj-next-prop obj prop)) 0)) (def-op (:2op #x14 "add" :store t) (a b) (+ a b)) (def-op (:2op #x15 "sub" :store t) (a b) (- a b)) (def-op (:2op #x16 "mul" :store t) (a b) (* a b)) (def-op (:2op #x17 "div" :store t) (a b) (truncate (u16->s16 a) (u16->s16 b))) (def-op (:2op #x18 "mod" :store t) (a b) (rem (u16->s16 a) (u16->s16 b))) ;;;;------------------------------------------------------------------------ ;;;; 1OP opcodes ;;;;------------------------------------------------------------------------ (def-op (:1op #x00 "jz") (a) (branch (zerop a))) (def-op (:1op #x01 "get-sibling" :store t) (obj) (let ((sibling (obj-sibling obj))) (branch (plusp sibling)) sibling)) (def-op (:1op #x02 "get-child" :store t) (obj) (let ((child (obj-child obj))) (branch (plusp child)) child)) (def-op (:1op #x03 "get-parent" :store t) (obj) (obj-parent obj)) (def-op (:1op #x04 "get-prop-len" :store t) (prop-addr) (obj-prop-len prop-addr)) (def-op (:1op #x05 "inc") (var) (write-var var (1+ (read-signed-var var)))) (def-op (:1op #x06 "dec") (var) (write-var var (1- (read-signed-var var)))) (def-op (:1op #x07 "print-addr") (addr) (let ((s (decode-text addr))) (write-sequence s *standard-output*))) (def-op (:1op #x09 "remove-obj") (obj) (obj-remove obj)) (def-op (:1op #x0a "print-obj") (obj) (princ (obj-name obj))) (def-op (:1op #x0b "ret") (val) (ret val)) (def-op (:1op #x0c "jump") (offset) (incf *pc* (- (u16->s16 offset) 2))) (def-op (:1op #x0d "print-paddr") (addr) (let ((s (decode-text (* addr 2)))) (write-sequence s *standard-output*))) (def-op (:1op #x0e "load" :store t) (var) (when (zerop var) (stack-push (stack-top))) ; 6.3.4 (read-var var)) (def-op (:1op #x0f "not" :store t) (val) (logxor val #xffff)) ;;;;------------------------------------------------------------------------ ;;;; 0OP opcodes ;;;;------------------------------------------------------------------------ (def-op (:0op #x00 "true") () (ret 1)) (def-op (:0op #x01 "false") () (ret 0)) (def-op (:0op #x02 "print") () (multiple-value-bind (s byte-len) (decode-text *pc*) (write-sequence s *standard-output*) (incf *pc* byte-len))) (def-op (:0op #x03 "print-ret") () (op-print) (terpri) (ret 1)) (def-op (:0op #x08 "ret-popped") () (ret (stack-pop))) (def-op (:0op #x09 "pop") () (stack-pop)) (def-op (:0op #x0b "new-line") () (terpri)) (def-op (:0op #x0a "quit") () (setf *break* t)) (def-op (:0op #x0d "verify") () ;; Is there any point implementing this? (branch t)) ;;;;------------------------------------------------------------------------ ;;;; Variable opcodes ;;;;------------------------------------------------------------------------ (def-op (:var #x00 "call") (routine &rest args) (let ((ret-var (fetch-u8))) (if (zerop routine) (write-var ret-var 0) (progn (stack-push ret-var) ;; Return variable (stack-push *pc*) ;; Return address (stack-push *frame*) ;; Frame pointer (setf *frame* (fill-pointer *stack*) *pc* (* routine 2)) (let ((num-locals (fetch-u8))) (dotimes (i num-locals) (let* ((default (fetch-u16)) (local (or (nth i args) default))) (stack-push local)))))))) (def-op (:var #x01 "storew") (array word-index value) (write-u16 (+ array (* 2 word-index)) value)) (def-op (:var #x02 "storeb") (array byte-index value) (write-u8 (+ array byte-index) value)) (def-op (:var #x03 "put-prop") (obj prop val) (setf (obj-prop obj prop) val)) (def-op (:var #x04 "read") (text-buf parse-buf) (let* ((max-chars (1- (read-u8 text-buf))) (max-tokens (read-u8 parse-buf)) (text (truncate-seq (string-downcase (read-line)) max-chars))) (loop for c across text for dst = (1+ text-buf) then (1+ dst) do (write-u8 dst (char-code c))) (write-u8 (+ text-buf (length text) 1) 0) (let ((tokens (truncate-seq (tokenise text) max-tokens))) (write-u8 (1+ parse-buf) (length tokens)) (loop for (addr len offset) in tokens for dst = (+ parse-buf 2) then (+ dst 4) do (write-u16 dst addr) (write-u8 (+ dst 2) len) (write-u8 (+ dst 3) (1+ offset)))))) (def-op (:var #x05 "print-char") (n) (princ (code-char n))) (def-op (:var #x06 "print-num") (n) (princ (u16->s16 n))) (def-op (:var #x07 "random" :store t) (n) (setf n (u16->s16 n)) (if (plusp n) (rand-next n) (rand-seed (- n)))) (def-op (:var #x08 "push") (n) (stack-push n)) (def-op (:var #x09 "pull") (dst) (let ((val (stack-pop))) (when (zerop dst) (stack-pop)) ; 6.3.4 (write-var dst val)))
7,321
Common Lisp
.lisp
197
33.050761
76
0.527703
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
874c3fa60b95c5e1e9f320df3a1f92561dbbd239a6627c4d88d3fe01056766ca
20,359
[ -1 ]
20,360
cpu.lisp
njm64_lzm/cpu.lisp
(in-package #:lzm) (defvar *stack*) (defvar *frame*) (defvar *pc*) (defvar *break*) (defun fetch-u8 () (prog1 (read-u8 *pc*) (incf *pc*))) (defun fetch-u16 () (prog1 (read-u16 *pc*) (incf *pc* 2))) (defun stack-push (value) (vector-push-extend value *stack*)) (defun stack-pop () (vector-pop *stack*)) (defun stack-top () (aref *stack* (1- (length *stack*)))) (defun ret (val) (setf (fill-pointer *stack*) *frame* *frame* (stack-pop) *pc* (stack-pop)) (write-var (stack-pop) val)) (defun branch (condition) (setf condition (not (not condition))) (let* ((b (fetch-u8)) (offset (ldb (byte 6 0) b))) (unless (logbitp 6 b) (let ((b2 (fetch-u8))) (setf offset (logior (ash offset 8) b2)))) (when (logbitp 13 offset) ;; Handle negative branch (decf offset #x4000)) (when (eql condition (logbitp 7 b)) (case offset (0 (ret 0)) (1 (ret 1)) (otherwise (incf *pc* (- offset 2)))))))
1,003
Common Lisp
.lisp
37
22.621622
50
0.577244
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
edd5374038cacfee1d638bc674def9d2e7a589f27d489cd31f294724db73321f
20,360
[ -1 ]
20,361
text.lisp
njm64_lzm/text.lisp
(in-package #:lzm) (defparameter *A0* "abcdefghijklmnopqrstuvwxyz") (defparameter *A1* "ABCDEFGHIJKLMNOPQRSTUVWXYZ") (defparameter *A2* #(#\Space #\Newline #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\. #\, #\! #\? #\_ #\# #\' #\" #\/ #\\ #\- #\: #\( #\) )) (defun abbrev-addr (table-index i) (read-word-addr (+ *abbrev-table-offset* (* table-index 64) (* i 2)))) (defun collect-chars (addr) (loop for p = addr then (+ 2 p) for w = (read-u16 p) collect (ldb (byte 5 10) w) into cs collect (ldb (byte 5 5) w) into cs collect (ldb (byte 5 0) w) into cs until (logbitp 15 w) finally (return (values cs (+ 2 (- p addr)))))) (defun decode-chars (chars) (with-output-to-string (s) (loop with charset = *A0* with abbrev = nil with esc = nil with esc-code = 0 for c in chars do (cond ((eql esc 0) (setf esc-code (ash c 5)) (incf esc)) ((eql esc 1) (setf esc-code (logior esc-code c)) (princ (code-char esc-code) s) (setf esc nil)) (abbrev (princ (decode-text (abbrev-addr abbrev c)) s) (setf abbrev nil)) ((= c 0) (princ " " s)) ((= c 1) (setf abbrev 0)) ((= c 2) (setf abbrev 1)) ((= c 3) (setf abbrev 2)) ((= c 4) (setf charset *A1*)) ((= c 5) (setf charset *A2*)) ((and (= c 6) (eql charset *A2*)) (setf esc 0 charset *A0*)) (t (princ (elt charset (- c 6)) s) (setf charset *A0*)))))) (defun decode-text (addr) (multiple-value-bind (chars byte-len) (collect-chars addr) (let ((s (decode-chars chars))) (values s byte-len))))
1,855
Common Lisp
.lisp
49
27.918367
72
0.474736
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
658a37731ace8a8bab92c7826896c6bf76580cac851045f29b96d2edf0900207
20,361
[ -1 ]
20,362
rand.lisp
njm64_lzm/rand.lisp
(in-package #:lzm) (defvar *rand-seed* nil) (defvar *rand-next* 0) (defun rand-seed (n) (if (zerop n) (setf *rand-seed* nil *rand-next* 0) (setf *rand-seed* n *rand-next* 0))) (defun rand-next-predictable () (assert *rand-seed*) (prog1 (mod *rand-next* *rand-seed*) (incf *rand-next*))) (defun rand-next-random () (get-internal-real-time)) (defun rand-next (n) (let ((raw (if *rand-seed* (rand-next-predictable) (rand-next-random)))) (1+ (mod raw n))))
522
Common Lisp
.lisp
18
24.166667
42
0.591182
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
092e028e3c5a8513d4738f11b15a861e2cc01ed822a2b0b052e0516ed0e4bc1a
20,362
[ -1 ]
20,363
tok.lisp
njm64_lzm/tok.lisp
(in-package #:lzm) (defvar *dict-separators*) (defvar *dict-words*) (defvar *dict-word-length*) (defun read-separators () (let ((num-separators (fetch-u8))) (loop repeat num-separators collect (code-char (fetch-u8))))) (defun read-words () (let ((entry-length (fetch-u8)) (num-entries (fetch-u16))) (loop repeat num-entries collect (cons (decode-text *pc*) *pc*) do (incf *pc* entry-length)))) (defun init-dictionary () (let ((*pc* *dictionary-offset*)) (setf *dict-separators* (read-separators)) (setf *dict-words* (read-words)) (setf *dict-word-length* 6) ;; This varies by version nil)) (defun truncate-seq (s max-length) (if (> (length s) max-length) (subseq s 0 max-length) s)) (defun find-dict-word (word) (let ((key (truncate-seq word *dict-word-length*))) (if-let (dict-entry (assoc key *dict-words* :test #'equal)) (cdr dict-entry) 0))) (defun is-split-point (a b) "Split points are before/after spaces, and before/after separator chars" (or (char= a #\Space) (char= b #\space) (member a *dict-separators*) (member b *dict-separators*))) (defun split-text (text) "Split text into a list of words at split points, preserving whitespace" (loop for c across text and prev = c for i = 0 then (1+ i) with prev-split = 0 with words = nil do (when (and prev (is-split-point c prev)) (push (subseq text prev-split i) words) (setf prev-split i)) finally (return (nreverse (cons (subseq text prev-split) words))))) (defun tokenise (text) "Tokenise text into a list of (dict-address, length, offset) tuples" (loop for word in (split-text text) and offset = 0 then (+ offset (length word)) unless (string= word " ") collect (list (find-dict-word word) (length word) offset)))
1,904
Common Lisp
.lisp
51
31.803922
75
0.631236
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
23b5b1a1509b4fd2791d14e00a6bf2a9917eb64a046d3574a2780a0f42ac685b
20,363
[ -1 ]
20,364
lzm.asd
njm64_lzm/lzm.asd
(defsystem :lzm :author "Nick Maher" :description "Lisp Z-Machine" :depends-on (:alexandria) :components ((:file "packages") (:file "mem") (:file "header") (:file "text") (:file "var") (:file "obj") (:file "cpu") (:file "rand") (:file "tok") (:file "op") (:file "decode") (:file "main")))
462
Common Lisp
.asd
16
17.0625
33
0.394619
njm64/lzm
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
5a3249288b19c1d90a5e176c97dcae32e60fe887e6ae976b679757192d27fea6
20,364
[ -1 ]
20,391
data.lisp
ryuslash_scrumli/data.lisp
;; scrumli --- A simple scrum web application ;; Copyright (C) 2013 Tom Willemse ;; scrumli is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; scrumli is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; You should have received a copy of the GNU Affero General Public License ;; along with scrumli. If not, see <http://www.gnu.org/licenses/>. (in-package :scrumli) (defclass story () ((id :col-type serial :reader story-id) (state :col-type string :reader state :initform "TODO") (role :col-type string :reader role :initarg :role) (necessity :col-type string :reader necessity :initarg :necessity) (title :col-type string :reader title :initarg :title) (priority :col-type integer :reader priority :initarg :priority) (content :col-type string :reader content :initarg :content) (reporter :col-type string :reader reporter :initarg :reporter) (assignee :col-type string :reader assignee :initarg :assignee)) (:metaclass dao-class) (:keys id)) (defclass task () ((id :col-type serial :reader story-id) (state :col-type string :reader state :initform "TODO") (description :col-type string :reader description :initarg :description) (priority :col-type integer :reader priority :initarg :priority) (reporter :col-type string :reader reporter :initarg :reporter) (assignee :col-type string :reader assignee :initarg :assignee) (story-id :col-type integer :reader story-id :initarg :story-id)) (:metaclass dao-class) (:keys id)) (deftable task (!dao-def) (!foreign 'story 'story-id 'id)) (defun datainit () (unless (table-exists-p 'story) (execute (dao-table-definition 'story))) (unless (table-exists-p 'task) (create-table 'task))) (defun get-all-stories () (query (:order-by (:select :* (:as (:md5 'assignee) 'md5) :from 'story) 'priority) :alists)) (defun get-stories-for (username) (query (:order-by (:select :* (:as (:md5 'assignee) 'md5) :from 'story :where (:= 'assignee username)) 'priority) :alists)) (defun get-story (id) (append (query (:select :* (:as (:md5 'assignee) 'md5) :from 'story :where (:= 'id id)) :alist) `((tasks . ,(get-tasks-for-story id))))) (defun get-tasks-for-story (id) (query (:order-by (:select :* (:as (:md5 'assignee) 'md5) :from 'task :where (:= 'story-id id)) 'priority) :alists)) (defun post-story (role necessity title content reporter) (let ((obj (make-instance 'story :role role :necessity necessity :title title :priority (+ 1 (or (query (:select (:coalesce (:max 'priority) 0) :from 'story) :single) 0)) :content content :assignee "" :reporter reporter))) (save-dao obj))) (defun post-task (story-id description reporter) (let ((obj (make-instance 'task :description description :priority (+ 1 (query (:select (:coalesce (:max 'priority) 0) :from 'task :where (:= 'story-id story-id)) :single)) :reporter reporter :story-id (parse-integer story-id) :assignee ""))) (save-dao obj))) (defun story-get-state (type id) (query (:select 'state :from type :where (:= 'id id)) :single)) (defun story-set-state (type id state) (execute (:update type :set 'state state :where (:= 'id id)))) (defun story-change-priority (id dir) (let* ((current-priority (query (:select 'priority :from 'story :where (:= 'id id)) :single)) (next-priority (funcall (ecase dir (:up #'-) (:down #'+)) current-priority 1)) (max-priority (query (:select (:max 'priority) :from 'story) :single))) (execute (:update 'story :set 'priority current-priority :where (:= 'priority next-priority))) (execute (:update 'story :set 'priority (max 1 (min next-priority max-priority)) :where (:= 'id id))))) (defun task-change-priority (id dir) (destructuring-bind (priority story-id) (query (:select 'priority 'story-id :from 'task :where (:= 'id id)) :list) (let* ((next-priority (funcall (ecase dir (:up #'-) (:down #'+)) priority 1)) (max-priority (query (:select (:max 'priority) :from 'task :where (:= 'story-id story-id)) :single))) (execute (:update 'task :set 'priority priority :where (:and (:= 'priority next-priority) (:= 'story-id story-id)))) (execute (:update 'task :set 'priority (max 1 (min next-priority max-priority)) :where (:= 'id id)))))) (defun set-assignee (type id assignee) (execute (:update type :set 'assignee assignee :where (:= 'id id))))
5,679
Common Lisp
.lisp
115
38.556522
78
0.575654
ryuslash/scrumli
2
0
2
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
40860a3767e711834367cd18762c123133122564d8b8af07bd59396a71ee9c15
20,391
[ -1 ]
20,392
packages.lisp
ryuslash_scrumli/packages.lisp
;; scrumli --- A simple scrum web application ;; Copyright (C) 2013 Tom Willemse ;; scrumli is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; scrumli is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; You should have received a copy of the GNU Affero General Public License ;; along with scrumli. If not, see <http://www.gnu.org/licenses/>. (defpackage #:scrumli (:use :cl :ningle :drakma :clack.builder :clack.middleware.session :clack.response :clack.request :clack.middleware.static :postmodern :clack.middleware.postmodern :parenscript) (:import-from :clack :clackup) (:import-from :json :encode-json-to-string :decode-json) (:export #:start-scrumli)) (in-package #:scrumli)
1,095
Common Lisp
.lisp
20
52.3
78
0.75514
ryuslash/scrumli
2
0
2
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
60deda2924b0fcc9f376b8348882cb08491478233c784e96a018643e70b39589
20,392
[ -1 ]
20,393
scrumli.asd
ryuslash_scrumli/scrumli.asd
;; scrumli --- A simple scrum web application ;; Copyright (C) 2013 Tom Willemse ;; scrumli is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; scrumli is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; You should have received a copy of the GNU Affero General Public License ;; along with scrumli. If not, see <http://www.gnu.org/licenses/>. (defpackage #:scrumli-config (:export #:*base-directory*)) (defparameter scrumli-config:*base-directory* (make-pathname :name nil :type nil :defaults *load-truename*)) (asdf:defsystem #:scrumli :serial t :description "Scrum with Lisp" :author "Tom Willemse" :license "AGPLv3" :depends-on (:ningle :postmodern :cl-json :drakma :closure-template :md5 :clack-middleware-postmodern :parenscript) :defsystem-depends-on (:closure-template) :components ((:closure-template "templates/scrumli") (:file "packages") (:file "data") (:file "scrumli")))
1,440
Common Lisp
.asd
33
37.454545
78
0.679743
ryuslash/scrumli
2
0
2
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7b377138613560c4fea2f66890974b3c61c65593df2d6092514b35d462725bf8
20,393
[ -1 ]
20,398
scrumli.tmpl
ryuslash_scrumli/templates/scrumli.tmpl
/* scrumli --- A simple scrum web application Copyright (C) 2013 Tom Willemse scrumli is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. scrumli is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with scrumli. If not, see <http://www.gnu.org/licenses/>. */ {namespace scrumli-templates} {template main} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>{$title}</title> {foreach $css in $csss} <link href="{$css}" rel="stylesheet" type="text/css"> {/foreach} {foreach $js in $jss} <script src="{$js}" type="text/javascript" language="javascript"> </script> {/foreach} </head> <body> <div class="navbar navbar-static-top navbar-inverse"> <div class="navbar-inner"> <div class="container"> <a class="brand">scrumli</a> <div class="pull-right"> <ul class="nav pull-right"> <li> <span class="navbar-text"> <img src="https://secure.gravatar.com/avatar/{$usermd5}?s=16" /> {$username} </span> </li> <li class="divider-vertical"></li> <li id="filter"></li> <li><a href="{$ulogout}"> <i class="icon-signout icon-light"></i> Logout </a></li> <li class="divider-vertical"></li> </ul> </div> </div> </div> </div> <div class="container"> <h1> <button data-target=".newTaskModal" role="button" data-toggle="modal" class="nothing"> <i class="icon-plus-sign icon-2x"></i> </button> Backlog </h1> <div id="content"></div> <script src="{$umainjs}" type="text/jsx"></script> </div> <footer class="footer"> <div class="container"> <small> Scrumli available under the <a href="https://www.gnu.org/licenses/agpl-3.0.html">GNU Affero General Public License</a>. You can download its source code <a href="http://code.ryuslash.org/cgit.cgi/scrumli/">here</a>. </small> </div> </footer> </body> </html> {/template} {template login} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>{$title}</title> {foreach $css in $csss} <link href="{$css}" rel="stylesheet" type="text/css"> {/foreach} {foreach $js in $jss} <script src="{$js}" type="text/javascript" language="javascript"> </script> {/foreach} </head> <body> <div class="navbar navbar-static-top navbar-inverse"> <div class="navbar-inner"> <div class="container"> <a class="brand">scrumli</a> <ul class="nav pull-right"> <li class="divider-vertical"></li> <li><a href="javascript:login()"> <i class="icon-signin icon-light"></i> Login </a></li> <li class="divider-vertical"></li> </ul> </div> </div> </div> <div class="container"> <br /> <div class="hero-unit"> <h1>Scrumli</h1> <p> As a <em>developer</em> I <em>love</em> to <em>scrum</em>... </p> <a class="btn btn-primary btn-large" href="javascript:login()"> <i class="icon-signin"></i> Login </a> </div> </div> <form id="login-form" method="POST" action=""> <input id="assertion-field" type="hidden" name="assertion" /> </form> <footer class="footer"> <div class="container"> <small> Scrumli available under the <a href="https://www.gnu.org/licenses/agpl-3.0.html">GNU Affero General Public License</a>. You can download its source code <a href="http://code.ryuslash.org/cgit.cgi/scrumli/">here</a>. </small> </div> </footer> </body> </html> {/template}
4,724
Common Lisp
.l
138
24.521739
84
0.531148
ryuslash/scrumli
2
0
2
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b7cc7b632ccea7f0a9ded61499a3ff73aae0a5f408d61e617aaaef9465ba68fc
20,398
[ -1 ]
20,399
scrumli.css
ryuslash_scrumli/static/css/scrumli.css
/* scrumli --- A simple scrum web application Copyright (C) 2013 Tom Willemse scrumli is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. scrumli is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with scrumli. If not, see <http://www.gnu.org/licenses/>. */ .clickable { cursor: pointer; } button.nothing { background-color: inherit; border: none; } div.normalText { white-space: pre-wrap; }
887
Common Lisp
.l
22
36.818182
78
0.753201
ryuslash/scrumli
2
0
2
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
14a2abab91966117bcde1a9258a8fc09b0e2e3c78c505c2c6c6876bac99eeb8b
20,399
[ -1 ]
20,414
plan.lisp
whounslo_reasoner/test/plan.lisp
;;; Copyright (C) 2007-2009, 2011 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Graphsearch planning ;;; ;;; Graphsearch adapted from: ANSI Common Lisp by Paul Graham, Prentice Hall, 1996. (in-package reasoner) (declaim (special *expansion-count*)) (defclass state () ((environment :accessor environment :initarg :environment) (depth :reader depth :initarg :depth :initform 0) (cost :accessor cost) (all-environments :accessor all-environments :initarg :all-environments :initform nil) (environments-fn :reader environments-fn :initarg :environments-fn :initform (constantly nil)))) (defmethod describe-state ((s state)) (describe-data (environment s))) (defmethod cost-to-goal ((s state) (goal environment) &optional path) (let ((goal-assumptions (assumptions goal)) (environment (next-environment s)) (fleshed-out (not nil)) in-position-count) (unless environment (setq environment (environment s) fleshed-out nil)) (setq in-position-count (count-if #'(lambda (assumption) (find assumption goal-assumptions :test #'eq)) (assumptions environment))) (if (or fleshed-out (null path)) (- (size goal) in-position-count) (- (cost-to-goal (first path) goal) in-position-count)))) (defparameter heuristic-weighting 2) (defmethod estimated-cost ((s state) (goal environment) &optional path) ;; Evaluation function given by ;; ;; f = g + wh, ;; ;; where g is the depth of the search tree, h an estimate of the cost of a minimal ;; path to the goal, and w a positive number. Smaller values of w tend toward ;; breadth-first search; greater values emphasize the heuristic component. ;; (Source: Principles of Artificial Intelligence, Nils J. Nilsson, Tioga, 1980.) (+ (depth s) (* heuristic-weighting (cost-to-goal s goal path)))) (defmethod next-environment ((s state)) (with-accessors ((environment environment) (environments all-environments)) s (if environments (let ((rest-environments (member environment environments :test #'eq))) (if rest-environments (second rest-environments) ;; Look-ahead generated the fleshed-out environment(s) but ;; the original, partial, version has not yet been replaced. (first environments)))))) (defmethod fetch-environment ((s state) &optional tentative) (with-accessors ((environment environment) (environments all-environments) (fn environments-fn)) s (unless environments (setf environments (funcall fn)) (unless environments (return-from fetch-environment environment))) (let ((next-environment (next-environment s))) (when next-environment (setq next-environment (ensure-environment *atms* next-environment 'ordered)) (unless tentative (setf environment next-environment))) next-environment))) (defun decompose1 (object assumptions) (remove object assumptions :key #'(lambda (assumption) (datum-object (assumed-datum assumption))) :test-not #'eq)) ;;; decompose partitions assumptions describing a state according to ;;; the object to which their assumed datum refers. (defun decompose (assumptions) (let (objects) (dolist (assumption assumptions) (pushnew (datum-object (assumed-datum assumption)) objects :test #'eq)) (mapcar #'(lambda (object) (decompose1 object assumptions)) objects))) (defun all-solutions-internal (old-component new-component catchall-assumption) (solutions (uniquify-environment *atms* (if catchall-assumption (cons catchall-assumption new-component) new-component)) old-component *atms* 'dont-create)) ;;; all-solutions uses the sets of assumptions produced by decompose ;;; to vivify a similarly-partitioned list of new assumptions that are ;;; the consequents of actions and auxiliary rules, based on the intuition ;;; that the consequences of actions are local to the objects they affect. (defun all-solutions (assumption-sets new-assumptions catchall-assumption &aux extra-new extra-old) (setq extra-new (set-difference new-assumptions assumption-sets :test #'(lambda (assumption set) (eq (datum-object (assumed-datum assumption)) (datum-object (assumed-datum (car set))))))) (when (and extra-new catchall-assumption) (push catchall-assumption extra-new)) (nconc (if extra-new (list (list extra-new))) ; New assumptions that have no ; corresponding old component ; just pass straight through. (mapcan #'(lambda (old-component &aux new-component) (setq new-component (decompose1 (datum-object (assumed-datum (car old-component))) new-assumptions)) (cond (new-component (list (all-solutions-internal old-component new-component catchall-assumption))) ;; No corresponding new component; merge with ;; all new assumptions. (t (setq extra-old (nconc extra-old old-component)) nil))) assumption-sets) (let (solutions) (setq solutions (mapcar #'(lambda (solution) (nconc (if catchall-assumption (list catchall-assumption)) (intersection extra-old (assumptions solution) :test #'eq))) (all-solutions-internal extra-old new-assumptions catchall-assumption))) (if solutions (list solutions))))) ;;; join-solutions reassembles the solution fragments produced by all-solutions ;;; into one or more full descriptions of successor states. (defun join-solutions (solution-sets) (mapcar #'(lambda (environments) (union-environments *atms* environments)) (cross-product solution-sets))) (defun find-successor-nodes (environment antecedents &optional (all-antecedents nil progressed) past-environments) (flet ((successorp (consequent antecedents) (not (or (contradictoryp consequent) (typep consequent 'temporary-node) (typep (datum-object consequent) 'well-formed-formula) (member consequent all-antecedents :test #'eq) (notevery #'(lambda (node) (or (typep (datum-object node) 'well-formed-formula) (in-p node environment) (some #'(lambda (e) (in-p node e)) past-environments))) antecedents)))) (operatorp (node &aux (object (datum-object node))) (and (typep object 'well-formed-formula) (instance-assumption object)))) (delete-duplicates (mapcan #'(lambda (antecedent) (mapcan #'(lambda (justification) (with-slots (consequent antecedents) justification (cond ((not (successorp consequent antecedents)) nil) ((and progressed (find-if #'operatorp antecedents)) ; Parallel operator applications ; only: is consequent the result of ; successive applications of a ; single operator? nil) (t (list consequent))))) (consequents antecedent))) antecedents) :test #'eq))) (defmethod omit-from-state-p ((object t) (slot-name t)) nil) (defun make-new-assumptions (environment successor-nodes &optional added-assumptions) (mapcan #'(lambda (consequent &aux assumption) (cond ((in-p consequent environment) nil) ((omit-from-state-p (datum-object consequent) (datum-slot consequent)) nil) (t (setq assumption (datum-assumption consequent 'oldest)) (unless assumption (setq assumption (make-assumption *atms*)) (add-justification *atms* consequent (list assumption) 'premise)) (cond ((member assumption added-assumptions :test #'eq) nil) ((add-assumption *atms* assumption added-assumptions 'dont-create) (list assumption)))))) successor-nodes)) (defmethod pooledp ((object-1 t) (object-2 t)) nil) (defmethod pooledp ((n1 standard-slot-value) (n2 standard-slot-value)) (if (eq (datum-slot n1) (datum-slot n2)) (let ((object-1 (datum-object n1)) (object-2 (datum-object n2)) (value-1 (datum-value n1)) (value-2 (datum-value n2))) (or (and (eq value-1 value-2) (pooledp object-1 object-2)) (and (eq object-1 object-2) (pooledp value-1 value-2)))))) (defmethod pooledp ((a1 assumption) (a2 assumption)) (pooledp (assumed-datum a1) (assumed-datum a2))) (defun seed-environments (assumptions new-assumptions &optional (progressed nil)) (nschedule *atms* (uniquify-environment *atms* (append assumptions new-assumptions))) (if progressed ;; Operator ramifications. (solutions *empty-environment* new-assumptions *atms* 'dont-create) ;; Operator. If parallel operator applications are possible, generate ;; subsets as well, removing variants indicated by a POOLEDP method. (delete-duplicates (schedule *atms* (uniquify-environment *atms* new-assumptions)) :test #'(lambda (e1 e2) (if (eql (size e1) (size e2)) (subsetp (assumptions e1) (assumptions e2) :test #'pooledp)))))) (defun vivify (environment past-environment &optional added-assumptions) (let* ((assumptions (assumptions past-environment)) ;; A single assumption may be used to justify all data which ;; participates in inferences but is known a priori to be ;; unchanging from state to state. (catchall-assumption (find-if-not #'singletonp assumptions :key #'consequents))) (when catchall-assumption (setq assumptions (remove catchall-assumption assumptions :test #'eq))) (join-solutions (all-solutions (decompose (set-difference assumptions added-assumptions :test #'eq)) (append (assumptions environment) added-assumptions) catchall-assumption)))) (defun progress-all (environments past-environments successor-nodes new-assumptions &optional all-antecedents added-assumptions) (or (mapcan #'(lambda (environment) (let ((nodes (remove-if-not #'(lambda (consequent) (in-p consequent environment)) successor-nodes))) (progress environment past-environments nodes (append all-antecedents nodes) (append added-assumptions (intersection new-assumptions (assumptions environment) :test #'eq))))) environments) environments)) (defmethod progress ((e environment) past-environments antecedents &optional all-antecedents added-assumptions) (let* ((successor-nodes (find-successor-nodes e antecedents all-antecedents past-environments)) (new-assumptions (make-new-assumptions e successor-nodes added-assumptions))) (if new-assumptions (progress-all (mapcan #'(lambda (environment) (vivify environment e added-assumptions)) (seed-environments (assumptions e) new-assumptions 'progressed)) (cons e past-environments) successor-nodes new-assumptions all-antecedents added-assumptions)))) (defmethod progress-delayed ((initial-state state) antecedents) (with-accessors ((environment environment) (depth depth)) initial-state (let* ((successor-nodes (find-successor-nodes environment antecedents)) (new-assumptions (make-new-assumptions environment successor-nodes))) (mapcar #'(lambda (seed-environment) (make-instance (class-of initial-state) :depth (1+ depth) :environment seed-environment :environments-fn #'(lambda () (progress-all (vivify seed-environment environment) (list environment) successor-nodes new-assumptions)))) (seed-environments (assumptions environment) new-assumptions))))) (defmethod progress-through ((initial-state state) (action forward-rule)) (nschedule *atms* (add-assumption *atms* (instance-assumption action) (environment initial-state) nil 'no-check)) (progress-delayed initial-state (slot-values action 'source-form t))) (defmethod repeated-state-p ((s state) path repetition-test) (let ((environment (environment s)) full-environment) (map-plan #'(lambda (previous-state) (with-accessors ((e environment)) previous-state (unless full-environment (when (subsumesp environment e) (setq full-environment (fetch-environment s 'tentative)))) (when full-environment (when (funcall repetition-test full-environment e) (return-from repeated-state-p (not nil)))))) path))) (defun new-paths (path initial-state operators goal repetition-test) (incf *expansion-count*) (mapcan #'(lambda (operator) (mapcar #'(lambda (state) (setf (cost state) (estimated-cost state goal path)) (list* state operator path)) (delete-if #'(lambda (state) (repeated-state-p state path repetition-test)) (progress-through initial-state operator)))) operators)) (defvar *trace-graphsearch* nil) (defmacro trace-graphsearch (state) `(when *trace-graphsearch* (format t "~&[~D:~D]" *expansion-count* (depth state)) (describe-state ,state) (when (multiple-value-bind (quotient remainder) (truncate *expansion-count* 5) (and (plusp quotient) (zerop remainder))) (unless (y-or-n-p "Continue?") (return-from graphsearch nil))))) (defmethod intermediate-state-p ((s state) path intermediate-test) (unless path (return-from intermediate-state-p (not nil))) (do ((environment (environment s) (fetch-environment s)) (previous-environment (environment (car path)))) ((null environment) nil) (when (and (subsetp (assumptions previous-environment) (assumptions environment) :key #'(lambda (a) (datum-object (assumed-datum a)))) ; No entities clobbered (by ; multiple application of an ; operator)? (funcall intermediate-test environment path)) (return (not nil))))) (defun graphsearch (goal queue operators goal-test intermediate-test repetition-test) (if (null queue) nil (let* ((path (car queue)) (state (car path)) (environment (fetch-environment state))) (if (funcall goal-test goal environment path) (reverse path) (let ((expandable (intermediate-state-p state (rest-path path) intermediate-test))) (when expandable (trace-graphsearch state)) (graphsearch goal (if expandable (sort (append (if (next-environment state) queue (cdr queue)) (new-paths path state operators goal repetition-test)) #'< :key #'(lambda (path) (cost (car path)))) (cdr queue)) operators goal-test intermediate-test repetition-test)))))) (defun plan (initial-state goal operators &key (goal-test #'(lambda (goal environment path) (declare (ignore path)) (subsumesp goal environment))) (intermediate-test (constantly t)) (repetition-test #'eq)) (setq *expansion-count* 0) (graphsearch goal (list (list initial-state)) operators goal-test intermediate-test repetition-test)) (defun rest-path (path) (cddr path)) (defun map-plan (fn path) (do ((rest-path path (cddr rest-path))) ((endp rest-path) nil) (funcall fn (car rest-path)))) (defun describe-plan (path) (describe-state (car path)) ; Initial state. (do ((rest-path (cdr path) (cddr rest-path))) ((endp rest-path)) (format t "--- Applied operator ~S ---~%" (car rest-path)) (describe-state (cadr rest-path))))
22,532
Common Lisp
.lisp
445
29.822472
90
0.471642
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ffa427e850e5e1669608e0e8fa71289b283d4dacbf54436b5b9f8df7fab1138f
20,414
[ -1 ]
20,415
queens.lisp
whounslo_reasoner/test/queens.lisp
;;; Copyright (C) 2007, 2009-11, 2017 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; n-queens problem ;;; ;;; Requires combin.lisp (in-package :rs-user) (eval-when (:execute :compile-toplevel :load-toplevel) (import '(atms:assumed-datum atms:oneof-disjunction rs::place-randomly rs::find-assumed-value rs::min-conflicts))) (defclass board () ((queens :type queen))) (defclass queen () ((rank-number :type queen-coord) (file-number :type queen-coord))) (defrange queen-coord 1 big) (defun attackp (col1 row1 col2 row2) (or (= row2 (- row1 (- col2 col1))) (= row2 (+ row1 (- col2 col1))))) (defmethod added-assumption ((q queen) (a assumption) (assumptions list) (tms core-atms)) (let ((col (find-assumed-value a 'rank-number t)) (row (find-assumed-value a 'file-number))) (dolist (assumption assumptions) (unless (conflictp a assumption) ; Note: local search only. (when (attackp (range-min col) (range-min row) (range-min (find-assumed-value assumption 'rank-number t)) (range-min (find-assumed-value assumption 'file-number))) (add-contradiction tms (list (assumed-datum a) (assumed-datum assumption)))))))) (let (board a) (defun make-board () (setq a (make-assumption *atms*) board (make-instance 'board))) (defmethod initialize-instance :after ((q queen) &rest initargs) (assume-slot-value board 'queens q a) (assume-slot-values q initargs a)) (defun print-board (solution) (let* ((queens (slot-value-reduce board 'queens t)) (n (length queens)) queen rank-number) (unless queens (return-from print-board nil)) (dotimes (row n) (setq queen (find (1+ row) queens :key #'(lambda (queen) (range-min (slot-value-reduce queen 'file-number solution)))) rank-number (range-min (slot-value-reduce queen 'rank-number t))) (dotimes (column n) (princ (if (= (1+ column) rank-number) " X |" " |"))) (terpri) (dotimes (column n) (princ "----")) (terpri)) solution)) ) ;end let board ;;; n-queens (backtracking search) (defun queens (&optional (n 8) &key (verbose t)) (let ((*atms* (make-instance 'basic-atms))) (queens1 n :verbose verbose))) (defun queens1 (&optional (n 8) &key (verbose t)) (let (queen a control-disjunctions (rows (make-list n)) stream) (make-board) (dotimes (column n) (let ((d (make-list n))) (setq queen (make-instance 'queen 'rank-number (1+ column))) (dotimes (row n) (setq a (assume-slot-value queen 'file-number (1+ row))) (place-randomly a d n) (push a (nth row rows))) (push d control-disjunctions))) (dolist (d rows) (oneof-disjunction d 'no-check 'ordered)) ; Stipulate only one queen per ; row. (setq stream (backtrack (uniquify-environment *atms* nil) (nreverse control-disjunctions) ; Stipulate only one queen per ; column. *atms*)) (if verbose (print-board (head stream)) stream))) ;;; n-queens (local search) ;;; ;;; Initially assign queens randomly one per column, and in different rows. ;;; Repeatedly swap pairs of queens' rows. (defun queens2 (&optional (n 8) &key (verbose t)) (flet ((queen-row (assumption) (find-assumed-value assumption 'file-number)) (reassign-queen (queen row) (or (fetch-assumption queen 'file-number row) (assume-slot-value queen 'file-number row)))) (let ((assumptions (make-list n)) (row 0) solution) (make-board) (dotimes (column n) (place-randomly (make-instance 'queen 'rank-number (1+ column)) assumptions n)) (map-into assumptions #'(lambda (queen) (assume-slot-value queen 'file-number (incf row))) assumptions) (setq solution (min-conflicts assumptions #'queen-row #'reassign-queen)) (if (and solution verbose) (print-board solution) solution))))
4,898
Common Lisp
.lisp
120
29
89
0.53346
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9e560c4809f2d9ec3e09f13aaf853cdd58f0702a988bb4b0a309adacd9506a5a
20,415
[ -1 ]
20,416
mult.lisp
whounslo_reasoner/test/mult.lisp
;;; Copyright (C) 2007, 2009, 2011, 2013 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Multiple-Fault Diagnosis (in-package :rs-user) (defrange device-statuses faulty working) (defrange device-inputs 0 big) (defclass device (component) ((status :type device-statuses) (in1 :type device-inputs) (in2 :type device-inputs) (out :type device-inputs))) (defclass adder (device) ()) (defclass multiplier (device) ()) (defclass complex-device (assembly) ((mult1 :type multiplier :initarg :mult1) (mult2 :type multiplier :initarg :mult2) (mult3 :type multiplier :initarg :mult3) (add1 :type adder :initarg :add1) (add2 :type adder :initarg :add2))) (defmethod shared-initialize :after ((d complex-device) slot-names &rest initargs) (declare (ignore slot-names)) (do ((name (instance-name d)) (rest-initargs initargs (cddr rest-initargs))) ((endp rest-initargs)) (when (typep (second rest-initargs) 'component) (setf (instance-name (second rest-initargs)) (intern (concatenate 'string (string name) (string #\-) (string (first rest-initargs)))))))) (defconstraint multiplier-output ((m multiplier)) m status is working -> m out = m in1 * m in2) (defconstraint adder-output ((a adder)) a status is working -> a out = a in1 + a in2) (defconstraint mult1-add1 ((d complex-device) (m1 multiplier) (a1 adder)) d mult1 is m1 and d add1 is a1 -> m1 out = a1 in1) (defconstraint mult2-add1 ((d complex-device) (m2 multiplier) (a1 adder)) d mult2 is m2 and d add1 is a1 -> m2 out = a1 in2) (defconstraint mult2-add2 ((d complex-device) (m2 multiplier) (a2 adder)) d mult2 is m2 and d add2 is a2 -> m2 out = a2 in1) (defconstraint mult3-add2 ((d complex-device) (m3 multiplier) (a2 adder)) d mult3 is m3 and d add2 is a2 -> m3 out = a2 in2) ;;; 3---->|----| ;;; | M1 |--------->|----| ;;; 2---->|----| | A1 |---->10 ;;; +---->|----| ;;; 3---->|----| | ;;; | M2 |----| ;;; 2---->|----| | ;;; +---->|----| ;;; 3---->|----| | A2 |---->12 ;;; | M3 |--------->|----| ;;; 2---->|----| ;;; ;;; {m1}, {a1}, {m2,m3}, {m2,a2} ;;; {m1,m2,m3}, {m1,m2,a2}, {m2,m3,a1}, {m2,a1,a2} (with measurement) (defvar *observations* '((mult1 in1 3) (mult1 in2 2) (mult2 in1 3) (mult2 in2 2) (mult3 in1 3) (mult3 in2 2) (add1 out 10) (add2 out 12))) (defvar *measurement* '(mult2 out 5)) (defvar *normal-statuses* '((mult1 status working) (mult2 status working) (mult3 status working) (add1 status working) (add2 status working))) (defun assume-system-data (system data) (mapcar #'(lambda (datum) (apply #'assume-system-datum system datum)) data)) (defun assume-system-datum (system role slot-name value) (assume-slot-value (car (slot-value-reduce system role t)) slot-name value)) (let* ((a1 (make-assumption *atms*)) (dev (make-instance 'complex-device :name 'dev1 :antecedents (list a1))) (observations (assume-system-data dev (cons *measurement* *observations*))) (normal-statuses (assume-system-data dev *normal-statuses*))) (defun faulty-parts (environment) (remove 'working (slot-value-reduce dev 'parts environment) :key #'(lambda (part) (car (slot-value-reduce part 'status environment))))) (defun diagnoses (observations verbose &aux environments) (setq environments (solutions (uniquify-environment *atms* (cons a1 observations)) normal-statuses *atms*)) (if verbose (mapcar #'faulty-parts environments) environments)) (defun diagnoses1 (&key (verbose t)) (diagnoses (cdr observations) verbose)) (defun diagnoses2 (&key (verbose t)) (diagnoses observations verbose)) (defun describe-system-status (environment) (dolist (part (slot-value-reduce dev 'parts environment)) (format t "~S - ~S~%" part (slot-value-reduce part 'status environment)))) ) ;end let* a1
4,579
Common Lisp
.lisp
108
34.018519
82
0.565374
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b748f3b2555d2f1fd894e44695c85dd08e2f80ba7f5c594248ee3ad01c900ba4
20,416
[ -1 ]
20,417
combin.lisp
whounslo_reasoner/test/combin.lisp
;;; Copyright (C) 2007, 2009 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (in-package reasoner) (defun place-randomly (value list limit &aux (n (random limit))) (do ((tail (nthcdr n list) (or (cdr tail) list))) ((null (car tail)) (setf (car tail) value)))) (defmethod find-assumed-value ((a assumption) slot-name &optional (environment (first (label a)))) (slot-value-reduce (datum-object (assumed-datum a)) slot-name environment)) (defmethod find-assumed-value ((object extended-object) slot-name &optional (environment t)) (slot-value-reduce object slot-name environment)) (defun map-elements (range function) "Applies function to each element of a fully enumerated numeric range or range set." (flet ((map-elements-internal (range) (do ((i (range-min range) (1+ i))) (nil) (funcall function i) (when (eql i (range-max range)) (return))))) (etypecase range (numeric-range* (map-elements-internal range)) (range-set (dolist (subrange (range-set-elements range)) (map-elements-internal subrange)))))) ;;; min-conflicts (defparameter max-steps 100) (defun min-conflicts (assumptions value-fn reassign-fn &key (index-key (constantly t)) (top-limit 3) (index-limit nil)) (let (environment index assignment1 value1 siblings candidates) (flet ((initial-environment (assumptions) (do ((rest-assumptions assumptions (rest rest-assumptions)) (environment nil (add-assumption *atms* (first rest-assumptions) environment nil 'no-check))) ((endp rest-assumptions) environment))) (conflictp (assumption) (conflictp assumption environment)) (conflict-count (assumption) (conflict-count assumption environment))) (setq environment (initial-environment assumptions)) (dotimes (i max-steps) (nschedule *atms* environment) (setq assumptions (sort assumptions #'> :key #'conflict-count)) (unless (conflictp (first assumptions)) ; Solution? (return-from min-conflicts (values environment i))) ;; Select conflict-ridden assignment at random. (if index-limit (setq index (random index-limit) assignment1 (find index assumptions :key index-key :test #'eql)) (setq assignment1 (nth (random top-limit) assumptions) index (funcall index-key assignment1))) (setq assumptions (delete assignment1 assumptions :test #'eq) siblings (remove index assumptions :key index-key :test (complement #'eql)) value1 (funcall value-fn assignment1) candidates (mapcar #'(lambda (assumption) (funcall reassign-fn (datum-object (assumed-datum assumption)) value1)) siblings)) (dolist (candidate candidates) (nschedule *atms* (add-assumption *atms* candidate assumptions nil 'no-check))) ;; Find assignment to swap value with that minimizes conflicts. (let ((assignment2 (first siblings)) (reassignment2 (first candidates)) reassignment1) (mapc #'(lambda (a r) (when (< (conflict-count r) (conflict-count reassignment2)) (setq assignment2 a reassignment2 r))) (rest siblings) (rest candidates)) (nsubstitute reassignment2 assignment2 assumptions :test #'eq) (setq reassignment1 (funcall reassign-fn (datum-object (assumed-datum assignment1)) (funcall value-fn assignment2)) environment (add-assumption *atms* reassignment1 assumptions nil 'no-check) assumptions (cons reassignment1 assumptions)))) nil)))
4,787
Common Lisp
.lisp
91
34.582418
86
0.524727
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7aea673279903832671fc29148f3e4f8ac37117ce2277351a3df624e8eb38f25
20,417
[ -1 ]
20,418
pref.lisp
whounslo_reasoner/test/pref.lisp
;;; Copyright (C) 2011, 2013 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (in-package reasoner) (defun preferred-extension (e1 e2) (unless (and e1 e2) (return-from preferred-extension nil)) (if (< (size e1) (size e2)) e2 e1)) (defun fetch-premises (node environment) (flet ((fetch-premises-internal (justification) (union-environments *atms* (mapcan #'(lambda (n) (let ((e (fetch-premises n environment))) (if e (list e)))) (antecedents justification))))) (with-accessors ((justifications justifications) (label label)) node (cond ((rest justifications) ;; Partially regenerate label, to include any subsumed ;; environments removed by the ATMS. (reduce #'preferred-extension (mapcar #'fetch-premises-internal justifications))) ((subsumesp (first label) environment) (first label)))))) (defun find-preferred-extension (object slot-name premises more-premises) (reduce #'preferred-extension (solutions (uniquify-environment *atms* premises) more-premises *atms*) :key #'(lambda (e) (let ((node (first (slot-values object slot-name e)))) (if node (fetch-premises node e))))))
1,554
Common Lisp
.lisp
34
32.794118
84
0.555409
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
52e49298c3d4f076fb8fc284a101b5bd03953e80e25bb4c4472f947e1a587ab1
20,418
[ -1 ]
20,419
miss.lisp
whounslo_reasoner/test/miss.lisp
;;; Copyright (C) 2009, 2011, 2012 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Missionaries-and-cannibals problem ;;; ;;; Requires plan.lisp (in-package :rs-user) (eval-when (:execute :compile-toplevel :load-toplevel) (import '(rs::pooledp rs::make-instances rs::state rs::intermediate-state-p rs::plan rs::describe-plan))) (defrange numbers-of-crew 0 2) (defclass place () ()) (defclass physical-object () ((location :type place :count location-count) (location-count :type exactly-one) ; An object cannot be in two ; places at once. )) (defclass river () ((near-bank :type river-bank) (far-bank :type river-bank))) (defclass river-bank (place) ((missionary-occupants :type missionary) (cannibal-occupants :type cannibal))) (defclass rowing-boat (place physical-object) ((crew :type traveller :count number-of-crew) (number-of-crew :type numbers-of-crew))) (defclass traveller (physical-object) ()) (defclass missionary (traveller) ()) (defclass cannibal (traveller) ()) (defmethod pooledp ((m1 missionary) (m2 missionary)) (not nil)) (defmethod pooledp ((c1 cannibal) (c2 cannibal)) (not nil)) (defrule embark :assume ((r river) (b river-bank) (rb rowing-boat) (t traveller)) r near-bank is b and rb location is b and t location is b -> t location is rb) (defrule embarked ((rb rowing-boat) (t traveller)) t location is rb -> rb crew includes t) (defrule row-outward :assume ((r river) (nb river-bank) (fb river-bank) (rb rowing-boat)) r near-bank is nb and r far-bank is fb and rb location is nb and rb number-of-crew > 0 -> rb location is fb) (defrule row-back :assume ((r river) (nb river-bank) (fb river-bank) (rb rowing-boat)) r near-bank is nb and r far-bank is fb and rb location is fb and rb number-of-crew > 0 -> rb location is nb) (defrule disembark :assume ((r river) (b river-bank) (rb rowing-boat) (t traveller)) r far-bank is b and rb location is b and t location is rb -> t location is b) (defrule disembarked-1 ((b river-bank) (m missionary)) m location is b -> b missionary-occupants includes m) (defrule disembarked-2 ((b river-bank) (c cannibal)) c location is b -> b cannibal-occupants includes c) (defun cannibalism-free-p (number-of-missionaries number-of-cannibals) (or (zerop number-of-missionaries) (<= number-of-cannibals number-of-missionaries))) ; Cannibals must never outnumber ; missionaries. (defun miss-operators () (mapcar #'find-instance '(embark row-outward row-back disembark))) (defun miss (&key (verbose t)) (let ((river (make-instance 'river)) (near-bank (make-instance 'river-bank :name 'near-bank)) (far-bank (make-instance 'river-bank :name 'far-bank)) (boat (make-instance 'rowing-boat :name 'rowing-boat-1)) (missionaries (make-instances 'missionary 3 ())) (cannibals (make-instances 'cannibal 3 ())) plan) (flet ((miss-initial-state () (make-instance 'state :environment (uniquify-environment *atms* (nconc (assume-slot-values river `(near-bank ,near-bank far-bank ,far-bank) (make-assumption *atms*)) (mapcar #'(lambda (object) (assume-slot-value object 'location near-bank)) (cons boat (append missionaries cannibals))))))) (miss-goal () (uniquify-environment *atms* (mapcar #'(lambda (object) (assume-slot-value object 'location far-bank)) (append missionaries cannibals)))) (miss-intermediate-state-p (environment path) (declare (ignore path)) (let ((bank (first (slot-value-reduce boat 'location environment)))) (cannibalism-free-p (length (slot-value-reduce bank 'missionary-occupants environment)) (length (slot-value-reduce bank 'cannibal-occupants environment)))))) (setq plan (plan (miss-initial-state) (miss-goal) (miss-operators) :intermediate-test #'miss-intermediate-state-p)) (if (and plan verbose) (describe-plan plan) plan))))
5,873
Common Lisp
.lisp
135
27.059259
89
0.479881
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4f4b4a5fdb2aefbf2f3cca6a065dcd1346c78dc6b18d3b219feccf2135c20fd4
20,419
[ -1 ]
20,420
blocks.lisp
whounslo_reasoner/test/blocks.lisp
;;; Copyright (C) 2007, 2009, 2011-13 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Blocks-world planning ;;; ;;; Requires plan.lisp (in-package :rs-user) (eval-when (:execute :compile-toplevel :load-toplevel) (import '(rs::make-instances rs::state rs::plan rs::describe-plan rs::omit-from-state-p rs::pooledp))) (defclass supporting-object () ((supporting :type supported-object))) (defclass supported-object () ((on :type supporting-object :count number-of-supporting-objects :inverse supporting) (number-of-supporting-objects :type zero-or-one) (firmly-supported :type true-or-false) (held-by :type robot-hand :count number-of-hands-holding) (number-of-hands-holding :type zero-or-one))) (defclass toy-block (supporting-object supported-object) ((supporting :type supported-object :count number-of-supported-objects) (number-of-supported-objects :type zero-or-one) (clear :type true-or-false))) (defclass table (supporting-object) ()) (defclass robot-hand () ((above :type table) (holding :type toy-block :count number-of-blocks-held :inverse held-by) (number-of-blocks-held :type zero-or-one))) (defrule block-pickup :assume ((b toy-block) (so supporting-object) (h robot-hand) (t table)) h above t and b on so and b clear is true -> h holding b) ;;; Governs both picking up and releasing behaviour. (defrule block-picked ((b1 toy-block) (b2 toy-block) (h robot-hand)) b1 on b2 and h holding b1 -> b2 clear is true) ;;; Governs both picking up and releasing behaviour. (defrule block-released ((b toy-block) (h robot-hand) (t table)) b on t and h holding b -> not t supporting b) (defmethod omit-from-state-p ((so supporting-object) (slot-name (eql 'supporting))) (not nil)) (defrule block-putdown :assume ((b toy-block) (h robot-hand) (t table)) h above t and h holding b -> b on t) (defrule block-firm ((b1 toy-block) (b2 toy-block) (t table)) (b1 on b2 and b2 firmly-supported is true) or b1 on t -> b1 firmly-supported is true) (defrule block-stack :assume ((b1 toy-block) (b2 toy-block) (h robot-hand)) h holding b1 and b2 firmly-supported is true and b2 clear is true -> b1 on b2) (defrule block-stacked ((b toy-block)) b number-of-supported-objects > 0 -> b clear is false) (defmethod pooledp ((h1 robot-hand) (h2 robot-hand)) (not nil)) (defun blocks-operators () (mapcar #'find-instance '(block-pickup block-putdown block-stack))) (defun blocks (&key (verbose t) (twin-hands nil)) (let ((table (make-instance 'table :name 'table-1)) (blocks (make-instances 'toy-block 3 ())) (robot-hands (make-instances 'robot-hand (if twin-hands 2 1) ())) plan) (flet ((blocks-initial-state () (make-instance 'state :environment (uniquify-environment *atms* (mapcan #'assume-slot-values (append blocks robot-hands) `((on ,table) (on ,table clear true) (on ,(first blocks) clear true) (above ,table) (above ,table)))))) (blocks-goal () (uniquify-environment *atms* (mapcan #'assume-slot-values blocks `((on ,(second blocks)) (on ,(third blocks)) (on ,table)))))) (setq plan (plan (blocks-initial-state) (blocks-goal) (blocks-operators))) (if (and plan verbose) (describe-plan plan) plan))))
4,327
Common Lisp
.lisp
103
29.776699
87
0.539339
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
06875b94dc777b856656b231415accf6e9d76b9e92cbef113be8c94bf50082f9
20,420
[ -1 ]
20,421
range.lisp
whounslo_reasoner/src/range.lisp
;;; Copyright (C) 2007, 2009, 2011, 2012, 2014 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (in-package reasoner) (defrange (numeric-range (:include range)) -big big) (defrange (symbolic-range (:include range))) (defrange zero-or-more 0 big) (defrange (zero-or-one (:include zero-or-more)) 0 1) (defrange (one-or-more (:include zero-or-more)) 1 big) (defrange (exactly-one (:include one-or-more)) 1 1) (defrange true-or-false true false) (defrange false false) (defrange true true) (defmethod initialize-instance :before ((instance symbolic-range) &key value) (unless value (error "Attempt to create an empty range."))) (defmethod initialize-instance ((instance symbolic-range) &key object slot-name value) "Ensures that range is initialized as a list of items." (call-next-method instance :object object :slot-name slot-name :value (if (listp value) value (list value)))) (defmethod initialize-instance ((instance numeric-range) &key object slot-name value) "Ensures that range is initialized as a list of items." (call-next-method instance :object object :slot-name slot-name :value (typecase value ((or numeric-range* range-set) value) (t (make-numeric-range :min value :max value))))) (defmethod range-intersection ((range1 numeric-range) (range2 numeric-range)) (numeric-range-intersection (elements range1) (elements range2))) (defmethod range-intersection ((range1 t) (range2 numeric-range)) (numeric-range-intersection range1 (elements range2))) (defmethod range-intersection ((range1 symbolic-range) (range2 symbolic-range)) (intersection (elements range1) (elements range2))) (defmethod range-intersection ((range1 list) (range2 symbolic-range)) (intersection range1 (elements range2))) (defmethod slot-value-equal-1 ((element symbol) (range symbolic-range)) (and (eql (length (elements range)) 1) (eq (car (elements range)) element))) (defmethod slot-value-equal-1 ((range1 list) (range2 symbolic-range)) (and (subsetp range1 (elements range2) :test #'eq) (subsetp (elements range2) range1 :test #'eq))) (defmethod slot-value-equal-1 ((range1 t) (range2 numeric-range) &aux ranges) (flet ((numeric-range-equal (range1 range2) (and (eql (range-min range1) (range-min range2)) (eql (range-max range1) (range-max range2))))) (cond ((and (typep range1 'range-set) (typep (elements range2) 'range-set)) (equal (range-set-elements range1) (range-set-elements (elements range2)))) ((typep range1 'range-set) (setq ranges (range-set-elements range1)) (and (singletonp ranges) (numeric-range-equal (car ranges) (elements range2)))) ((typep (elements range2) 'range-set) (setq ranges (range-set-elements (elements range2))) (and (singletonp ranges) (numeric-range-equal (car ranges) range1))) (t (numeric-range-equal range1 (elements range2))))))
3,597
Common Lisp
.lisp
72
38.208333
78
0.598288
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e078a4ba1c7b106daa14455bdb39ef0231644e40bb4f807ad15d83c7894079f4
20,421
[ -1 ]
20,422
xmlnames.lisp
whounslo_reasoner/src/xmlnames.lisp
;;; Copyright (C) 2011, 2012, 2013 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; XML names and namespaces (in-package :reasoner-ext) (defparameter *case-preference* (readtable-case *readtable*)) (defun preserve-case-p (&optional (readtable *readtable*)) (eq (readtable-case readtable) :preserve)) ;;; pprint-subst - intended to be called from within a format string. ;;; Substitutes characters with characters or strings in accordance with ;;; *subst-chars*. The case of characters at word boundaries, delimited ;;; by the substitutions, is controlled by the use of the modifiers: ;;; colon all words are capitalized, as if by string-capitalize, except the first ;;; at-sign the first character is forced to uppercase; no others are affected ;;; (if object is a symbol, other characters are forced to lowercase) ;;; both all words are capitalized ;;; neither the first character is forced to lowercase; no others are affected ;;; (if object is a symbol, all characters are forced to lowercase) (defparameter *subst-chars* '((#\- . "") (#\_ . #\space))) (defun pprint-subst (stream object &optional colon-p at-sign-p &aux (is-symbol (symbolp object))) (let ((str (if is-symbol (symbol-name object) object)) ch entry (break at-sign-p)) (dotimes (i (length str)) (setq ch (char str i) entry (assoc ch *subst-chars* :test #'char=)) (cond ((null entry) (write-char (cond (at-sign-p (char-upcase ch)) (colon-p (prog1 (cond (break (char-upcase ch)) ((eq *case-preference* :upcase) (char-downcase ch)) (t ch)) (setq break nil))) ((or (zerop i) is-symbol) (char-downcase ch)) (t ch)) stream) (setq at-sign-p nil break (char= ch #\space))) ((characterp (cdr entry)) (write-char (cdr entry) stream) (setq break (char= (cdr entry) #\space))) ((setq break (zerop (length (cdr entry))))) (t (write-string (cdr entry) stream)))))) (defun set-xml-name (name format-control &optional (package (symbol-package name))) (let ((xml-name (intern (format nil format-control name) package))) (setf (get xml-name :lisp-name) name (get name :xml-name) xml-name) xml-name)) (defmethod get-xml-name ((name t) &optional mandatory format-control) (declare (ignore mandatory format-control)) name) (defmethod get-xml-name ((name symbol) &optional mandatory (format-control "~:/rse::pprint-subst/")) (cond ((get name :xml-name)) ((and (preserve-case-p) (not mandatory)) name) (t (set-xml-name name format-control)))) (defparameter *emphasize-type-name* (not nil)) (defgeneric ensure-xml-type-name (name) (:method ((name symbol)) (when *emphasize-type-name* (get-xml-name name nil "~:@/rse::pprint-subst/")) name) (:method ((names cons)) (mapc #'ensure-xml-type-name names)) (:method ((class standard-class)) (ensure-xml-type-name (class-name class)))) (defun ensure-symbol (name package) ;; Avoid re-importing name - might be uninterned, i.e., fresh. (or (find-symbol (string name) package) #+abcl(if (symbol-package name) nil (intern (string name) package)) (progn (import name package) name))) (defmacro define-xml-name (name lisp-name namespace) `(let ((package (namespace-package ,namespace))) (set-xml-name (ensure-symbol ,lisp-name package) (string ,name) package))) (defun pprint-lisp-name (stream object &optional colon-p at-sign-p) (declare (type string object) (ignore colon-p at-sign-p)) (let (ch) (dotimes (i (length object)) (setq ch (char object i)) (cond ((not (upper-case-p ch))) ((zerop i)) ((lower-case-p (char object (1- i))) (write-char #\- stream))) (write-char (if (eq *case-preference* :upcase) (char-upcase ch) (char-downcase ch)) stream)))) (defun set-lisp-name (xml-name) (let ((symbol (intern (format nil "~/rse::pprint-lisp-name/" (string xml-name)) (symbol-package xml-name)))) (setf (get symbol :xml-name) xml-name (get xml-name :lisp-name) symbol) symbol)) (defun get-lisp-name (xml-name) (or (get xml-name :lisp-name) (set-lisp-name xml-name))) (defun get-content-lisp-name (xml-name) (if (preserve-case-p) xml-name (get-lisp-name xml-name))) (defun get-tag-lisp-name (name &optional mandatory) ;; Name has already been converted by GET-LISP-NAME. (if (preserve-case-p) (get-xml-name name mandatory) name)) (defun ensure-lisp-name (name) (or (and (preserve-case-p) (get name :lisp-name)) name)) (defmacro add-lisp-name-suffix (name &rest names) `(get-tag-lisp-name (intern (concatenate 'string (string (ensure-lisp-name ,name)) ,@(mapcan #'(lambda (name) `((string #\-) (string (ensure-lisp-name ,name)))) names)) (symbol-package ,name)) 'mandatory)) (defun namespace-prefix (name) (declare (type symbol name)) (get name 'xml-prefix)) (defun (setf namespace-prefix) (new-value name) (declare (type symbol name)) (setf (get name 'xml-prefix) new-value)) (defun namespace-uri (name) (declare (type symbol name)) (get name 'xml-uri)) (defun (setf namespace-uri) (new-value name) (declare (type symbol name)) (setf (get name 'xml-uri) new-value)) (defun namespace-package (name) (declare (type symbol name)) (get name 'xml-namespace)) (defun (setf namespace-package) (new-value name) (declare (type symbol name)) (setf (get name 'xml-namespace) new-value)) (defparameter *namespace-package-prefix* :xml) (defun ensure-namespace-package (name) (declare (type (and symbol (not null)) name)) (or (namespace-package name) (setf (namespace-package name) (make-package (concatenate 'string (string *namespace-package-prefix*) (string name)) :use ())))) (defvar *namespace-names* nil) (defun make-namespace (namespace-name uri &optional package) (when (and package (namespace-package namespace-name)) (error "A namespace named ~A already exists." namespace-name)) (setf (namespace-prefix namespace-name) (string-downcase (string namespace-name)) (namespace-uri namespace-name) uri) (when package (setf (namespace-package namespace-name) package)) (pushnew namespace-name *namespace-names* :test #'eq) namespace-name) (defmacro defnamespace (namespace-name uri &body body) `(eval-when (:execute :compile-toplevel :load-toplevel) (make-namespace ',namespace-name ,uri) (ensure-namespace-package ',namespace-name) ,@(if (and body (not (consp (car body)))) `((let ((package (namespace-package ',namespace-name))) (dolist (name ',body) (when (consp name) (return)) ; Reached documentation. (etypecase name (string (get-xml-name (intern name package) 'mandatory)) (symbol (import (get-xml-name (ensure-symbol name package) 'mandatory) package))))))) ',namespace-name))
8,402
Common Lisp
.lisp
186
33.774194
97
0.562469
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
153887d4c493d90c92b96109ad7a4803581c6797b95c9f18270f5022862e4fe7
20,422
[ -1 ]
20,423
genrule.lisp
whounslo_reasoner/src/genrule.lisp
;;; Copyright (C) 2012 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Automatically-generated rules (in-package reasoner) (defclass class-slot-dependency () ((name :initarg :name :reader name) (option :initarg :option :reader option) (value :initarg :value :accessor value) (dependee :initarg :dependee :reader dependee) (dependent :initform nil :accessor dependent) (finalized :initform nil :accessor finalized))) (defun find-slot-type (class slot-name) (let ((slot-definition (find-slot-definition class slot-name))) (if slot-definition (slot-definition-type slot-definition) (error "Slot ~A is missing from class ~A." slot-name class)))) (defmethod generate-inverse-wff ((class extended-class) slot-name-1 slot-name-2) (let* ((slot-type (find-slot-type class slot-name-1)) (variable-1 (make-variable :class-name (class-name class) :name (gensym))) (variable-2 (make-variable :class-name slot-type :name (gensym))) (attribute-reference-1 (make-attribute-reference :attribute-reference-variable variable-1 :attribute-name slot-name-1)) (attribute-reference-2 (make-attribute-reference :attribute-reference-variable variable-2 :attribute-name slot-name-2))) (find-slot-type (find-class slot-type) slot-name-2) ; Check that slot exists. `(and (or ,(make-instance 'relational-proposition 'specializer variable-2 'attribute-references (list attribute-reference-1)) (not ,(make-instance 'relational-proposition 'specializer variable-1 'attribute-references (list attribute-reference-2)))) (or ,(make-instance 'relational-proposition 'specializer variable-1 'attribute-references (list attribute-reference-2)) (not ,(make-instance 'relational-proposition 'specializer variable-2 'attribute-references (list attribute-reference-1))))))) (defmethod generate-wff ((class extended-class) slot-name (composition cons) &aux variable) (flet ((make-body (expression-1 expression-2) (if expression-2 (list 'and expression-2 expression-1) expression-1))) (setq variable (make-variable :class-name (class-name class) :name (gensym))) (do ((slot-names composition (rest slot-names)) (next-class class (find-class slot-type)) (next-variable variable specializer) slot-type specializer (attribute-reference-1 (make-attribute-reference :attribute-reference-variable variable :attribute-name slot-name)) (tail nil (make-body (make-instance 'relational-proposition 'specializer specializer 'attribute-references (list (make-attribute-reference :attribute-reference-variable next-variable :attribute-name (first slot-names)))) tail))) ((endp slot-names) (values tail (make-instance 'relational-proposition 'specializer specializer 'attribute-references (list attribute-reference-1)))) (setq slot-type (find-slot-type next-class (first slot-names))) ; Check that slot exists, whether ; or not we need its type. (when (singletonp slot-names) (setq slot-type (find-slot-type class slot-name)) ; Use type of destination slot ; in specializer. ) (when (subtypep slot-type 'range) (return (values tail (let ((attribute-reference-2 (make-attribute-reference :attribute-reference-variable next-variable :attribute-name (first slot-names)))) (if (subtypep slot-type 'numeric-range) (make-instance 'arithmetic-proposition 'attribute-references (list attribute-reference-1) 'relation '= 'prefix-rhs attribute-reference-2) (make-instance 'literal-proposition 'attribute-references (list attribute-reference-2 attribute-reference-1))))))) (setq specializer (make-variable :class-name slot-type :name (gensym)))))) (defmethod generate-wff ((class extended-class) slot-name (composition (eql :transitive))) (generate-wff class slot-name (list slot-name slot-name))) (defmethod generate-wff ((class extended-class) slot-name (composition (eql :symmetric))) (flet ((swap-variables (proposition) (declare (type relational-proposition proposition)) (with-slots (attribute-references specializer) proposition (psetf specializer (attribute-reference-variable (first attribute-references)) (first attribute-references) (make-attribute-reference :attribute-reference-variable specializer :attribute-name (attribute-name (first attribute-references))))) proposition)) (multiple-value-bind (body head) (generate-wff class slot-name (list slot-name)) (values body (swap-variables head))))) (defmacro generated-wff-neck (composition) `(case ,composition (:symmetric biconditional-token) (t implication-token))) (defmethod add-generated-wff (composition body head) (make-instance 'forward-rule :body body :neck (generated-wff-neck composition) :head head)) (defmethod add-generated-wff (composition body (head null)) (declare (ignore composition)) (make-instance 'constraint :body body)) (defmethod slot-value-dependentp (class name option) (declare (ignore class name option)) ) (defmethod slot-value-dependentp ((class extended-class) name option) (map-dependents class #'(lambda (dependent) (when (and (eq name (name dependent)) (eq option (option dependent))) (return-from slot-value-dependentp (not nil))))) nil) (defmethod add-dependent-wff ((class extended-class) &key name composition inverse &allow-other-keys) (flet ((record-dependent (&rest initargs) (let ((dependent (apply #'make-instance 'class-slot-dependency :name name :dependee class initargs))) (add-dependent class dependent) dependent))) (when composition (unless (slot-value-dependentp class name :composition) (record-dependent :option :composition :value composition))) (when inverse (unless (slot-value-dependentp class name :inverse) (record-dependent :option :inverse :value inverse))) class)) (defmethod add-dependent-wffs ((class extended-class) direct-slots) (dolist (direct-slot direct-slots) (apply #'add-dependent-wff class direct-slot))) (defmethod initialize-instance :after ((class extended-class) &key direct-slots &allow-other-keys) (add-dependent-wffs class direct-slots)) (defmacro generate-slot-option-wff (class slot-name option value) `(ecase ,option (:composition (generate-wff ,class ,slot-name ,value)) (:inverse (generate-inverse-wff ,class ,slot-name ,value)))) (defun find-dependee (class slot-name) (find-class (find-slot-type class slot-name))) (defmethod add-dependees (class dependency (composition symbol)) (declare (ignore class dependency)) ) (defmethod add-dependees (class dependency (composition cons)) (do ((slot-names composition (rest slot-names)) (next-class class)) ((endp slot-names)) (setq next-class (find-dependee next-class (first slot-names))) (unless (slot-value-dependentp next-class (name dependency) :composition) (add-dependent next-class dependency)))) (defmethod finalize-dependent :before ((dependent class-slot-dependency)) (ecase (option dependent) (:composition (add-dependees (dependee dependent) dependent (value dependent))) (:inverse (let* ((name (name dependent)) (dependee (find-dependee (dependee dependent) name))) (unless (slot-value-dependentp dependee name :inverse) (add-dependent dependee dependent)))))) (defmethod finalize-dependent ((dependent class-slot-dependency)) (with-accessors ((class dependee) (slot-name name) (option-key option) (option-value value) (wff dependent) (finalized finalized)) dependent (when option-value (unless finalized (setf finalized (not nil)) ; Lock so won't be generated ; recursively via ; FINALIZE-INHERITANCE. ; If error, cleanup handled by ; UPDATE-DEPENDENT. (multiple-value-bind (body head) (generate-slot-option-wff class slot-name option-key option-value) (setf wff (add-generated-wff option-value body head))))))) (defmethod reinitialize-instance :before ((class extended-class) &key direct-slots &allow-other-keys) (add-dependent-wffs class direct-slots)) (defmethod update-dependent ((class extended-class) (dependency class-slot-dependency) &key direct-slots &allow-other-keys) (with-accessors ((slot-name name) (option-key option) (option-value value) (dependee dependee) (wff dependent) (finalized finalized)) dependency (flet ((update-wff () (cond ((not finalized)) (wff (multiple-value-bind (body head) (generate-slot-option-wff dependee slot-name option-key option-value) (reinitialize-instance wff :body body :neck (generated-wff-neck option-value) :head head))) (t ; Error occurred. (setf finalized nil) (finalize-dependent dependency))))) (if (eq class dependee) (let ((direct-slot (find slot-name direct-slots :key #'(lambda (slot) (getf slot :name)))) value) (cond ((and direct-slot (setq value (getf direct-slot option-key))) (unless (eq value option-value) (setf option-value value) (update-wff))) (direct-slots (setf option-value nil) (when wff (uncompile wff))))) (update-wff)))))
13,131
Common Lisp
.lisp
260
32.276923
86
0.514359
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c962c658c3ed1d275285f8acc60de07ac3a72d4373a70de335cb598226fc013c
20,423
[ -1 ]
20,424
backtrack.lisp
whounslo_reasoner/src/backtrack.lisp
;;; Copyright (C) 2007, 2009-10, 2014, 2017, 2022 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (eval-when (:compile-toplevel) (declaim (optimize (speed 3) (safety 1) (space 0) (debug 0)))) (in-package atms) (eval-when (:execute :compile-toplevel :load-toplevel) (import '(streams:flatmap streams:singleton streams:the-empty-stream rparallel:do-deferred-results)) (export '(datum-object map-intersection oneof-disjunction conflictp conflict-count added-assumption order-control-disjunction backtrack add-assumption ensure-environment schedule solutions nschedule ))) ;;; map-intersection applies function to every element that occurs in both ;;; list-1 and list-2. Successive pairs of elements in both lists are assumed ;;; to satisfy predicate. (defun map-intersection (function list-1 list-2 predicate &key (key #'identity) (test #'eql)) (do ((rest-list-1 list-1 (rest rest-list-1)) (rest-list-2 list-2) (comparison-fn (complement predicate))) ((endp rest-list-1) nil) (setq rest-list-2 (member (funcall key (first rest-list-1)) rest-list-2 :test #'(lambda (item1 item2) (funcall comparison-fn item2 item1)) :key key)) (when (funcall test (first rest-list-1) (first rest-list-2)) (funcall function (first rest-list-1))))) (defmethod oneof-disjunction ((assumptions list) &optional (no-check (not nil)) ordered) (when assumptions (oneof-disjunction (rest assumptions) no-check ordered) (dolist (a (rest assumptions)) (when (or no-check (not (conflictp (first assumptions) a))) (add-contra (first assumptions) a) (unless ordered (add-contra a (first assumptions))))))) (defmethod datum-object ((object t)) object) (defmethod added-assumption ((object t) (a assumption) (assumptions list) (tms core-atms)) a) (defmethod order-control-disjunction ((object t) (e environment) (assumptions list)) assumptions) (defmethod order-first-control-disjunction ((e environment) (control-disjunctions list) (tms core-atms)) (setf (car control-disjunctions) (order-control-disjunction (datum-object (assumed-datum (caar control-disjunctions))) e (car control-disjunctions)))) ;(defmethod backtrack ((e environment) (control-disjunctions list) (tms core-atms)) ; (cond (control-disjunctions ; (order-first-control-disjunction e control-disjunctions tms) ; (do ((d (car control-disjunctions) (cdr d)) ; eprime ; (solutions nil)) ; ((endp d) solutions) ; (setq eprime (add-assumption tms (car d) e)) ; (when eprime ; (setq solutions (nconc solutions ; (backtrack eprime ; (cdr control-disjunctions) ; tms))) ; (when (contradictoryp e) ; (return nil))))) ; (t (nschedule tms e) ; (if (contradictoryp e) ; nil ; (list e))))) (defmethod backtrack ((e environment) (control-disjunctions list) (tms core-atms)) (cond (control-disjunctions (order-first-control-disjunction e control-disjunctions tms) (flatmap #'(lambda (a &aux eprime) (cond ((contradictoryp e) the-empty-stream) ((setq eprime (add-assumption tms a e)) (backtrack eprime (cdr control-disjunctions) tms)) (t the-empty-stream))) (car control-disjunctions))) (t (nschedule tms e) (if (contradictoryp e) the-empty-stream (singleton e))))) ;;; conflictp examines the intersection of assumption's contras and environment. (defmethod conflictp ((a assumption) (e environment) &optional (ordered (not nil))) (conflictp a (assumptions e) ordered)) (defmethod conflictp ((a assumption) (assumptions list) &optional (ordered nil)) (if ordered (map-intersection #'(lambda (a) (declare (ignore a)) (return-from conflictp (not nil))) (contras a) assumptions assumption-ordering-predicate :key #'serial-number) (some #'(lambda (assumption) (conflictp a assumption)) assumptions))) ;;; conflict-count is like conflictp, but returns the number of conflicts. (defmethod conflict-count ((a assumption) (e environment) &optional (ordered (not nil))) (conflict-count a (assumptions e) ordered)) (defmethod conflict-count ((a assumption) (assumptions list) &optional (ordered nil)) (if ordered (let ((count 0)) (map-intersection #'(lambda (a) (declare (ignore a)) (incf count)) (contras a) assumptions assumption-ordering-predicate :key #'serial-number) count) (count-if #'(lambda (assumption) (conflictp a assumption)) assumptions))) (defmethod conflictp ((a1 assumption) (a2 assumption) &optional ordered) (declare (ignore ordered)) (find a1 (contras a2) :test #'eq)) ;;; add-assumption adds a single assumption to an environment. ;;; Does nothing (returns NIL) if the result would contain a binary ;;; contradiction. Also returns NIL if resulting environment is found to be ;;; inconsistent when checked against nogood database. (These checks are ;;; inhibited if no-check is non-NIL.) (defmethod add-assumption ((tms core-atms) (a assumption) (e environment) &optional (dont-create nil) (no-check nil) (at-front (not nil)) (ordered (not nil))) "Specialized environment union used where one environment is of length one." (add-assumption tms a (assumptions e) dont-create no-check at-front ordered)) (defmethod add-assumption ((tms atms) (a assumption) (e environment) &optional (dont-create nil) (no-check nil) (at-front nil at-front-supp) (ordered (not nil)) &aux (assumptions (assumptions e))) "Specialized environment union used where one environment is of length one." (flet ((at-front-p () (cond (at-front-supp at-front) (assumptions (funcall assumption-ordering-predicate (serial-number a) (serial-number (first assumptions))))))) (add-assumption tms a assumptions dont-create no-check (at-front-p) ordered))) (defmethod add-assumption :around ((tms core-atms) (a assumption) (assumptions list) &optional (dont-create nil) (no-check nil) (at-front nil) (ordered nil)) (declare (ignore dont-create no-check at-front ordered)) (multiple-value-bind (result e) (call-next-method) (when result (added-assumption (datum-object (assumed-datum a)) a assumptions tms)) (values result e))) (defmethod add-assumption ((tms core-atms) (a assumption) (assumptions list) &optional (dont-create nil) (no-check nil) (at-front nil) (ordered nil)) "Specialized environment union used where one environment is of length one." (flet ((subsumed-by-nogood-p (environment) (or (contradictoryp environment) (let ((size (size environment)) assumptions) (dolist (e (nogoods a)) (unless (< (size e) size) (return nil)) (setq assumptions (assumptions e)) (when (or (not at-front) (eq (first assumptions) a)) (when (subsumesp assumptions environment 'ordered) (set-contradictory environment) (return (not nil))))))))) (let (superset e) (values (if (or (if no-check nil (or (contradictoryp a) (conflictp a assumptions (or at-front ordered)))) (progn (setq superset (cons a assumptions)) (when (or (not at-front) no-check) (setq e (uniquify-environment tms superset dont-create))) (cond (no-check nil) ((subsumed-by-nogood-p (or e superset))) (at-front (setq e (uniquify-environment tms superset dont-create 'ordered)) nil)))) nil (or e superset)) e)))) (defmethod contradictoryp ((assumptions list)) nil) (defmethod set-contradictory ((assumptions list)) nil) (defun execute-pending-consumers (&optional environment) (declare (ignorable environment)) (do-deferred-results matched-node (when matched-node (if environment (execute-consumers environment) (mapc #'execute-consumers (label matched-node)))))) (defmethod schedule ((tms core-atms) (e environment)) "Run all consumers in all subsets of an environment." ;; For the environment {A, B, C}, consumers are executed in the order: ;; {A}, {B}, {A, B}, {C}, {A, C}, {B, C}, {A, B, C}. (let (no-check (subsets nil)) (dolist (assumption (reverse (assumptions e))) ; Reverse so that ordering ; of assumptions is ; preserved when adding. (setq no-check (not nil) subsets (nconc subsets (mapcan #'(lambda (subset &aux result e) (multiple-value-setq (result e) (add-assumption tms assumption subset 'dont-create no-check 'at-front)) (when result (when e (execute-consumers e) (execute-pending-consumers e) (when (contradictoryp e) (setq no-check nil ; Check that further environments ; generated during this iteration ; (i.e., containing assumption) ; are not subsumed by this ; environment. result nil)))) (if result (list result)) ; Eliminate contradictory ; environment to prevent ; generation of supersets. ) (cons nil subsets))))) subsets)) (defmethod ensure-environment ((tms core-atms) (e environment) &optional (ordered nil)) (declare (ignore ordered)) e) (defmethod ensure-environment ((tms core-atms) (assumptions list) &optional (ordered nil)) (uniquify-environment tms assumptions nil ordered)) (defmethod assumptions ((assumptions list)) assumptions) (defmethod solutions ((e environment) (choices list) (tms core-atms) &optional (dont-create nil)) "Find maximal consistent supersets of environment, with respect to choices." (flet ((subsumesp (e1 e2) (subsumesp e1 e2 'ordered))) (let (subsets) (declare (type list subsets)) (setq subsets (schedule tms (uniquify-environment tms (append (assumptions e) choices)))) (unless (zerop (size e)) (deletef subsets e :test-not #'subsumesp)) (setq subsets (delete-duplicates subsets :test #'subsumesp)) (unless dont-create (map-into subsets #'(lambda (subset) (ensure-environment tms subset 'ordered)) subsets)) subsets))) ;;; nschedule is the non-consing version of schedule. Environments are ;;; executed in size order and those of the same size in an arbitrary order. (defmethod nschedule ((tms core-atms) (e environment) &aux (size (size e))) (with-accessors ((index environment-index)) tms (do ((rest-index index (rest rest-index)) (entry-point (first index) (second rest-index)) ; Be sure to find newly- ; created entry points. (exit-point (first index) entry-point)) ((eql (indexed-size entry-point) size)) (do ((environments entry-point (rest environments))) ((eq environments exit-point)) (when (and (node-added (first environments)) (subsumesp (first environments) e)) (execute-consumers (first environments)))) (execute-pending-consumers))) (unless (zerop size) (execute-consumers e) (execute-pending-consumers e)))
14,720
Common Lisp
.lisp
297
33.636364
88
0.515432
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ecd6dbe2934baeb141ca2388f205f4e6db951b714595dc8f56360872310b9286
20,424
[ -1 ]
20,425
pstreams.lisp
whounslo_reasoner/src/pstreams.lisp
;;; Copyright (C) 2014, 2016-17 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Requires Lisp in Parallel (lparallel.org). (defpackage :pstreams (:use :cl :lparallel) (:import-from :streams #:the-empty-stream #:empty-stream-p #:head #:singleton #:flatmap*) (:export #:the-empty-stream #:empty-stream-p #:head #:singleton #:pcons-stream #:gtail #:gflatmap #:pmap-stream #:pflatmap #:pmap-stream* #:pflatmap*)) (in-package :pstreams) (defun tail (stream) "Obtain the tail of stream by fulfilling promise." (force (cdr stream))) (defgeneric gforce (object) (:method ((delayed-object function)) "Evaluate delayed-object produced by (non-lparallel) DELAY." (funcall delayed-object)) (:method ((object t)) "Promise, or anything else." (force object))) (defun gtail (stream) "Obtain the tail of stream." (gforce (cdr stream))) (defmacro gflatmap (proc stream) `(flatmap* ,proc ,stream #'gtail)) (defmacro cons-stream (a b) "Returns a pair comprising A and a delayed object." `(cons ,a (delay ,b))) (defmacro pcons-stream (a b) "Returns a pair comprising A and B, evaluated concurrently." `(let ((f (future ,b))) (cons ,a f))) (defun pmap-stream-deferred (proc stream) "Delay after eagerly obtaining the next element in input stream." (chain (delay (pmap-stream proc stream)))) (defun pmap-stream (proc stream) "Generates the stream formed by applying procedure to each element in input stream." (if (empty-stream-p stream) the-empty-stream (pcons-stream (funcall proc (head stream)) (pmap-stream-deferred proc (tail stream))))) (defun pflatmap (proc stream) "Generate the single stream formed by applying the procedure (which returns a stream) to each item in the input stream and appending the results." (flatten (pmap-stream proc stream))) (defun pmap-stream-deferred* (proc stream tail-fn) "Delay after eagerly obtaining the next element in input stream." (chain (delay (pmap-stream* proc stream tail-fn)))) (defun pmap-stream* (proc stream tail-fn) "Generates the stream formed by applying procedure to each element in input stream." (if (empty-stream-p stream) the-empty-stream (pcons-stream (funcall proc (head stream)) (pmap-stream-deferred* proc (funcall tail-fn stream) tail-fn)))) (defun pflatmap* (proc stream tail-fn) "Generate the single stream formed by applying the procedure (which returns a stream) to each item in the input stream and appending the results." (flatten (pmap-stream* proc stream tail-fn))) (defun flatten (stream) "Appends the elements of a stream of streams to form a single stream." (accumulate-delayed #'interleave-delayed the-empty-stream stream)) (defun accumulate-delayed (combiner initial-value stream) "Accumulates items in stream using combiner, beginning with initial-value. Combiner must expect to explicitly force its second argument." (if (empty-stream-p stream) initial-value (funcall combiner (head stream) ;; To handle infinite streams, delay the recursive call. (delay (accumulate-delayed combiner initial-value (tail stream)))))) (defun interleave-delayed (stream delayed-stream) "Append two streams, taking elements alternately from each." (if (empty-stream-p stream) (force delayed-stream) (cons-stream (head stream) (interleave-delayed (force delayed-stream) (delay (gtail stream))))))
3,683
Common Lisp
.lisp
76
42.605263
148
0.691451
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
677eda3edb7536a2e2850281d87d32f36367aa45b7ba2a43166247ec1234fa17
20,425
[ -1 ]
20,426
rsuser.lisp
whounslo_reasoner/src/rsuser.lisp
;;; Copyright (C) 2007-2009, 2011, 2016 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (defpackage :reasoner-ext (:nicknames :rs-ext :rse) (:use :reasoner :cl) #-mop (:import-from :reasoner #:defclass*) (:shadow #:defclass) #+clisp (:shadowing-import-from :reasoner #:subtypep) (:export #:*default-metaclass* #:yes-or-no #:yes #:no)) (in-package :rs-ext) (defparameter *default-metaclass* 'extended-class) #+mop (defmacro defclass (name direct-superclasses direct-slots &rest options) `(cl:defclass ,name ,direct-superclasses ,direct-slots ,@(if (assoc :metaclass options :test #'eq) options (cons `(:metaclass ,*default-metaclass*) options)))) #-mop (defmacro defclass (name direct-superclasses direct-slots &rest options) `(defclass* ,name ,direct-superclasses ,direct-slots ,@(if (assoc :metaclass options :test #'eq) options (cons `(:metaclass ,*default-metaclass*) options)))) (defrange yes-or-no yes no) (defrange yes yes) (defrange no no) (defpackage :reasoner-user (:nicknames :rs-user) (:use :reasoner-ext :reasoner :cl) (:shadowing-import-from :reasoner-ext #:defclass #+clisp #:subtypep))
1,374
Common Lisp
.lisp
37
30.702703
72
0.637801
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
161675794f24fd99106e4057732d0825201619369c97f97612ada5ec68c47e54
20,426
[ -1 ]
20,427
composite.lisp
whounslo_reasoner/src/composite.lisp
;;; Copyright (C) 2011 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Composite objects: compound objects and assemblies (in-package reasoner) (defclass composite-object () ((parts :type part)) (:metaclass extended-class)) (defclass compound-object (composite-object) ((parts :type part :initarg :part :initarg :parts)) (:metaclass extended-class)) (defclass assembly (composite-object) ((parts :type component)) (:metaclass extended-class)) (defclass part () () (:metaclass extended-class)) (defclass component (part) () (:metaclass extended-class)) (defmethod find-part ((object compound-object) slot-name) (find slot-name (slot-values object 'parts t) :key #'datum-value :test #'(lambda (slot-name object) (slot-exists-p object slot-name)))) (defmethod slot-missing ((class extended-class) (object compound-object) slot-name (operation (eql 'slot-boundp)) &optional new-value) (declare (ignore new-value)) (if (find-part object slot-name) (not nil) (call-next-method))) (defmethod slot-missing ((class extended-class) (object compound-object) slot-name (operation (eql 'slot-value)) &optional new-value) (declare (ignore new-value)) (let ((slot-value (find-part object slot-name))) (if slot-value (slot-value (datum-value slot-value) slot-name) (call-next-method)))) (defmethod slot-definition-missing ((class extended-class) (object compound-object) slot-name (operation (eql 'add-slot-value)) new-value antecedents informant &rest args) (let ((slot-value (find-part object slot-name))) (if slot-value (apply #'add-slot-value (datum-value slot-value) slot-name new-value antecedents informant args) (call-next-method)))) (defmethod add-slot-value-using-class :after ((class extended-class) (object assembly) slot (new-value component) antecedents (informant (eql :initial-value)) &rest args &key slot-name &allow-other-keys) (declare (ignore slot)) (unless (eq slot-name 'parts) (apply #'add-slot-value object 'parts new-value antecedents informant args))) (defmethod initialize-instance ((instance assembly) &rest initargs &aux (class (class-of instance))) (do ((slots (class-slots class) (cdr slots)) antecedents count pair (more-initargs () (nconc more-initargs pair))) ((endp slots) (apply #'call-next-method instance (append initargs more-initargs))) (with-accessors ((slot-initargs slot-definition-initargs) (slot-type slot-definition-type) (slot-count slot-definition-count)) (car slots) (setq antecedents (if (subtypep slot-type 'assembly) (getf initargs :antecedents)) count (if slot-count (range-min (range-elements (find-slot-definition class slot-count))) 1) pair (if (and slot-initargs (not (get-properties initargs slot-initargs)) (subtypep slot-type 'component) (plusp count)) (list (car slot-initargs) (if (eql count 1) (make-instance slot-type :antecedents antecedents) (do ((i 0 (1+ i)) (instances () (cons (make-instance slot-type :antecedents antecedents) instances))) ((eql i count) instances)))))))))
4,852
Common Lisp
.lisp
104
27.923077
84
0.471818
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ce26787db08a7873d6b6ea8b1b3317c8dfe1e11c9dbc29c9138891afe8d0dc76
20,427
[ -1 ]
20,428
triple.lisp
whounslo_reasoner/src/triple.lisp
;;; Copyright (C) 2012, 2013, 2014, 2016 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; RDF/XML (de)serialization (in-package :reasoner-ext) (eval-when (:execute :compile-toplevel :load-toplevel) (import '(rs::numeric-range-intersection rs::validate-superclass rs::direct-slot-definition-class rs::effective-slot-definition-class rs::extended-direct-slot-definition rs::extended-effective-slot-definition rs::compute-effective-slot-definition rs::default-direct-superclass rs::slot-definition-composition rs::slot-definition-inverse rs::class-dependents-finalized-p)) (export '(with-rdf with-ontology serialize-objects *allow-multiple-domains* with-deserialization-unit class-label slot-definition-label resource-label-lang resource-label-text)) (ensure-xml-type-name (intern (string '#:class) (ensure-namespace-package :rdfs))) (ensure-xml-type-name (intern (string '#:datatype) (ensure-namespace-package :rdfs))) (ensure-xml-type-name (intern (string '#:resource) (ensure-namespace-package :rdfs))) (ensure-xml-type-name '(r-d-f i-d description property)) (ensure-xml-type-name (intern (string '#:class) (ensure-namespace-package :owl))) (ensure-xml-type-name (intern (string '#:restriction) (ensure-namespace-package :owl))) (ensure-xml-type-name '(ontology object-property datatype-property thing transitive-property symmetric-property functional-property inverse-functional-property ))) (defnamespace :rdf "http://www.w3.org/1999/02/22-rdf-syntax-ns" r-d-f description #:resource about i-d #:type #:datatype property) (defnamespace :rdfs "http://www.w3.org/2000/01/rdf-schema" comment label #:class #:resource sub-class-of sub-property-of domain range #:datatype) (defnamespace :owl "http://www.w3.org/2002/07/owl" ontology #:class object-property datatype-property thing same-as transitive-property symmetric-property functional-property inverse-of inverse-functional-property #:restriction on-property cardinality min-cardinality max-cardinality all-values-from some-values-from) (define-xml-name "TransitiveProperty" :transitive :owl) (define-xml-name "SymmetricProperty" :symmetric :owl) (define-xml-name "FunctionalProperty" :functional :owl) (define-xml-name "InverseFunctionalProperty" :inverse-functional :owl) (define-ignored-elements :rdfs "seeAlso" "isDefinedBy") (define-ignored-elements :owl "equivalentClass" "equivalentProperty" "differentFrom" "AllDifferent" "distinctMembers" "versionInfo" "imports" "priorVersion" "backwardCompatibleWith" "incompatibleWith" "AnnotationProperty" "OntologyProperty" "DeprecatedClass" "DeprecatedProperty") #+(or allegro ecl lispworks sbcl) (defstruct (resource-label (:type list)) "Human-readable version of a resource's name." lang text) #-(or allegro ecl lispworks sbcl) (progn (defun make-resource-label (&key lang text) (list lang text)) (defun resource-label-lang (label) (car label)) (defun resource-label-text (label) (cadr label)) ) (defclass resource-metaobject (standard-class) ((label :reader class-label :initarg :label :documentation "Human-readable version of a resource's name.")) (:metaclass standard-class) (:default-initargs :label nil )) (defclass resource-slot-definition-mixin () ((label :reader slot-definition-label :initarg :label :documentation "Human-readable version of a property's name.")) (:metaclass standard-class) (:default-initargs :label nil )) (defclass resource-direct-slot-definition (resource-slot-definition-mixin extended-direct-slot-definition) () (:metaclass standard-class)) (defclass resource-effective-slot-definition (resource-slot-definition-mixin extended-effective-slot-definition) () (:metaclass standard-class)) (defmethod direct-slot-definition-class ((class resource-metaobject) &rest initargs) (declare (ignore initargs)) (find-class 'resource-direct-slot-definition)) (defmethod effective-slot-definition-class ((class resource-metaobject) &rest initargs) (declare (ignore initargs)) (find-class 'resource-effective-slot-definition)) (defclass resource-class (resource-metaobject) () (:metaclass standard-class)) (eval-when (:execute #+lispworks :compile-toplevel :load-toplevel) (defmethod validate-superclass ((class resource-class) (superclass standard-class)) "Declare compatibility of RESOURCE-CLASS and standard-class." (not nil)) ) (defclass xmlrdfs::class (resource-metaobject extended-class) () (:metaclass resource-class)) (defclass xmlowl::class (xmlrdfs::class) () (:metaclass resource-class)) (defclass xmlrdfs::resource (extended-object) () (:metaclass xmlrdfs::class)) (defmethod compute-effective-slot-definition :before ((class xmlrdfs::class) name direct-slot-definitions) (when (find-slot-definition class name :direct (not nil) :key #'slot-definition-count) (do ((type-1 (slot-definition-type (car direct-slot-definitions)) type-2) type-2 (direct-slots direct-slot-definitions (cdr direct-slots))) ((endp (cdr direct-slots))) (setq type-2 (slot-definition-type (cadr direct-slots))) (adjust-count-type type-1 type-2)))) (let ((the-class-resource (find-class 'xmlrdfs::resource))) (setf (find-class 'thing) the-class-resource) (defmethod default-direct-superclass ((class xmlrdfs::class)) the-class-resource) ) ;end let the-class-resource (defmethod initialize-instance :after ((class xmlrdfs::class) &key same-as &allow-other-keys) (when same-as (setf (find-class same-as) class))) (defmethod reinitialize-instance :after ((class xmlrdfs::class) &key same-as &allow-other-keys) (when same-as (setf (find-class same-as) class))) (defun get-id (name) ;; Inhibit expansion to URI. (symbol-name (get-xml-name name))) (defun name-attribute (name) (if (eq (symbol-package name) (or (namespace-package *target-namespace*) *package*)) (list :i-d (get-id name)) (list :about name))) (defparameter *allow-multiple-domains* nil) (defmethod slot-definition-label ((slot slot-definition)) nil) (defmethod serialize-language-label ((label string)) (as :label label)) (defmethod serialize-language-label ((label cons)) (as (:label :lang (resource-label-lang label)) (resource-label-text label))) (defmethod serialize-label ((label string)) (serialize-language-label label)) (defmethod serialize-label ((label list)) (if (singletonp label) (serialize-language-label (resource-label-text (first label))) (mapc #'serialize-language-label label))) (defun serialize-property-documentation (slot-definition) (let ((comment (documentation slot-definition t)) (label (slot-definition-label slot-definition))) (serialize-label label) (when comment (as :comment comment)))) (defmethod serialize-property-definition ((class extended-class) (slot slot-definition) count-slot (format (eql :rdfs))) (declare (ignore count-slot)) (let ((slot-name (slot-definition-name slot))) (labels ((add-properties (class slot supertype &aux type) (setq type (if slot (slot-definition-type slot))) (when (and type (not (eq type t))) (unless (eq type supertype) (as (:domain 'xmlrdf::resource (ensure-xml-type-name class))) (as (:range 'xmlrdf::resource (if (subtypep type 'extended-object) (ensure-xml-type-name type) type))))) (when *allow-multiple-domains* (dolist (subclass (class-direct-subclasses class)) (add-properties subclass (find-slot-definition subclass slot-name :direct (not nil)) (or type supertype)))))) (xml-newline) (with* :property (name-attribute slot-name) (serialize-property-documentation slot) (add-properties class slot nil))))) (defmethod serialize-class ((class extended-class) (format (eql :rdfs)) &optional (derived (not nil))) (serialize-resource-class class format derived)) (defmethod serialize-class ((class resource-class) (format (eql :rdfs)) &optional derived) (declare (ignore derived)) (serialize-resource-class class format 'derived (find-class 'xmlrdfs::class))) (defmethod serialize-class ((class range-class) (format (eql :rdfs)) &optional derived &aux (tag 'xmlrdfs::datatype)) (declare (ignore derived)) (as (tag :about (class-name class)))) (defun primary-slot-definition (class slot &aux (name (slot-definition-name slot))) (ensure-cpl class) (map-slots class #'(lambda (slot-definition) (when (eq (slot-definition-name slot-definition) name) (return-from primary-slot-definition slot-definition))) :from-end (not nil))) (defun functional-property-p (min max) (and (zerop min) (eql max 1))) (defmethod serialize-property-definition ((class extended-class) (slot slot-definition) count-slot (format (eql :owl)) &aux tag) (with-accessors ((slot-name slot-definition-name) (slot-type slot-definition-type) (slot-composition slot-definition-composition) (slot-inverse slot-definition-inverse)) slot (setq tag (if (subtypep slot-type 'extended-object) :object-property :datatype-property)) (xml-newline) (with* tag (name-attribute slot-name) (serialize-property-documentation slot) (cond ((null slot-composition) (multiple-value-bind (min max) (element-occurrence-bounds count-slot) (when (functional-property-p min max) (as (:type 'xmlrdf::resource :functional))))) ((symbolp slot-composition) (as (:type 'xmlrdf::resource slot-composition))) ((singletonp slot-composition) (let ((slot (find-slot-definition class (first slot-composition)))) (when slot (as (:sub-property-of 'xmlrdf::resource (slot-definition-name slot))))))) (when slot-inverse (as (:inverse-of 'xmlrdf::resource slot-inverse))) (as (:domain 'xmlrdf::resource (ensure-xml-type-name class))) (as (:range 'xmlrdf::resource (if (eq tag :object-property) (ensure-xml-type-name slot-type) slot-type)))))) (defun direct-slot-definition-p (class slot count-slot) (or (not count-slot) (find-slot-definition class slot :direct (not nil) :key #'identity))) (defmethod serialize-resource-class :before ((class extended-class) format derived &optional metaclass) (declare (ignore metaclass)) (map-core-slots class #'(lambda (slot count-slot) (when (direct-slot-definition-p class slot count-slot) (when (or (not derived) (eq slot (primary-slot-definition class slot))) (serialize-property-definition class slot count-slot format) (separate-definitions)))) :direct (not nil))) (defmethod subclass-restriction-p ((class extended-class) format) (declare (ignore format)) nil) (defmethod subclass-restriction-p ((class resource-class) format) (declare (ignore format)) nil) (defmethod subclass-restriction-p ((class extended-class) (format (eql :owl))) (map-core-slots class #'(lambda (slot count-slot) (when count-slot (multiple-value-bind (min max) (element-occurrence-bounds count-slot) (unless (and (functional-property-p min max) (eq slot (primary-slot-definition class slot))) (return-from subclass-restriction-p (not nil)))))) :direct (not nil))) (defmethod serialize-restrictions ((class extended-class) format) (declare (ignore format)) ) (defmethod serialize-restrictions ((class resource-class) format) (declare (ignore format)) ) (defmethod serialize-restrictions ((class extended-class) (format (eql :owl))) (flet ((serialize-anonymous-superclass (slot &optional property value) (with :sub-class-of (with :restriction (as (:on-property 'xmlrdf::resource (slot-definition-name slot))) (if property (as (property 'xmlrdf::datatype :non-negative-integer) value) (as (:all-values-from 'xmlrdf::resource (slot-definition-type slot)))))))) (map-core-slots class #'(lambda (slot count-slot &aux primary-slot) (when (direct-slot-definition-p class slot count-slot) (setq primary-slot (primary-slot-definition class slot)) (unless (eq slot primary-slot) (when (subtypep (slot-definition-type slot) (slot-definition-type primary-slot)) (serialize-anonymous-superclass slot)))) (when count-slot (multiple-value-bind (min max) (element-occurrence-bounds count-slot) (cond ((eql min max) (serialize-anonymous-superclass slot :cardinality min)) ((and (functional-property-p min max) (eq slot primary-slot))) (t (unless (eql min 0) (serialize-anonymous-superclass slot :min-cardinality min)) (unless (eql max 'unbounded) (serialize-anonymous-superclass slot :max-cardinality max))))))) :direct (not nil)))) (defmethod serialize-resource-class (class format derived &optional (metaclass (class-of class))) (let ((type-name (ensure-xml-type-name class)) (tag (ensure-xml-type-name metaclass)) (superclasses (class-direct-superclasses class)) show-superclasses (comment (documentation class t)) (label (class-label class))) (setq show-superclasses (and derived (notevery #'(lambda (superclass) (eq (class-name superclass) 'xmlrdfs::resource)) superclasses))) (cond ((or comment label show-superclasses (subclass-restriction-p class format)) (xml-newline) (with* tag (name-attribute type-name) (when show-superclasses (dolist (superclass superclasses) (as (:sub-class-of 'xmlrdf::resource (ensure-xml-type-name superclass))))) (serialize-restrictions class format) (serialize-label label) (when comment (as :comment comment)))) (t (as* tag (name-attribute type-name) nil 'freshline))))) (defmethod class-label ((class extended-class)) nil) (defmethod serialize-class ((class extended-class) (format (eql :owl)) &optional (derived (not nil))) (serialize-resource-class class format derived)) (defmethod serialize-class ((class resource-class) (format (eql :owl)) &optional derived) (declare (ignore derived)) (serialize-resource-class class format 'derived (find-class 'xmlowl::class))) (defmethod serialize-value ((instance extended-object) (format (eql :rdf)) (e environment) tag slot-type &aux (instance-name (instance-name instance))) (if instance-name (as (tag 'xmlrdf::resource (instance-name instance))) (with tag (serialize-object instance format e tag slot-type nil)))) (defmethod serialize-slot ((instance extended-object) (slot slot-definition) (format (eql :rdf)) (e environment) &aux value) (with-accessors ((slot-name slot-definition-name) (slot-type slot-definition-type) (slot-count slot-definition-count)) slot (setq value (slot-value-reduce instance slot-name e)) (if (or slot-count (subtypep slot-type 'extended-object)) (revdolist (object value) (serialize-value object format e slot-name slot-type)) (serialize-value value format e slot-name slot-type)))) (defmethod instance-content-p ((instance extended-object) (e environment)) (map-core-slots (class-of instance) #'(lambda (slot count-slot) (declare (ignore count-slot)) (with-accessors ((slot-name slot-definition-name) (slot-type slot-definition-type)) slot (when (if (subtypep slot-type 'extended-object) (slot-values instance slot-name e) (slot-value-to-content (slot-value-reduce instance slot-name e) slot-type)) (return-from instance-content-p (not nil))))))) (defmethod serialize-object ((instance extended-object) (format (eql :rdf)) (e environment) &optional tag type (global (not nil)) &aux (class (class-of instance)) (instance-name (instance-name instance)) name-attribute) (declare (ignore type)) (unless (or instance-name (not global)) (error "Attempt to serialize an unnamed instance.")) (flet ((serialize-slot (slot count-slot) (when count-slot (setq e (satisfy-occurrence-constraint class instance slot count-slot e))) (serialize-slot instance slot format e))) (setq tag (ensure-xml-type-name (class-name class)) name-attribute (if instance-name (name-attribute instance-name))) (cond ((instance-content-p instance e) (xml-newline) (with* tag name-attribute (map-core-slots class #'serialize-slot))) (t (as* tag name-attribute nil 'freshline))))) (defmethod serialize-object ((instance extended-object) (format (eql :owl)) (e environment) &optional tag type global) (serialize-object instance :rdf e tag type global)) (defmethod serialize-object ((object t) (format (eql :rdf)) (e environment) &optional tag type global &aux (datatype (range-external-type type))) (declare (ignore global)) (serialize-simple-object object tag (list 'xmlrdf::datatype datatype) datatype)) (defmethod serialize-object ((object null) (format (eql :rdf)) (e environment) &optional tag type global) (declare (ignore tag type global)) ) (defmethod serialize-objects ((instance extended-object) (format (eql :rdf)) (e environment) &optional (global (not nil))) (when (instance-name instance) (unless global (separate-definitions)) (serialize-object instance format e)) (map-core-slots (class-of instance) #'(lambda (slot count-slot) (with-accessors ((slot-name slot-definition-name) (slot-type slot-definition-type)) slot (when (or count-slot (subtypep slot-type 'extended-object)) (dolist (instance (slot-value-reduce instance slot-name e)) (serialize-objects instance format e nil))))))) (defparameter *rdf-unique-name-fn* (constantly nil)) (defmacro with-rdf ((&key (xml-version nil version-supp) (xml-base nil target-supp) (namespaces nil) (default-namespace nil)) &body body) `(with-xml (,@(if version-supp `(:version ,xml-version)) ,@(if target-supp `(:target-namespace ,xml-base)) :namespaces ,namespaces :default-namespace ,default-namespace) (let ((*expand-attribute-value* (not nil)) (*unique-name-fn* *rdf-unique-name-fn*)) (with* :r-d-f (nconc (if *target-namespace* (list "xml:base" (namespace-uri-variant *target-namespace*))) (namespace-declarations)) ,@body)))) (defmacro with-ontology ((&key (xml-version nil version-supp) (about nil) (namespaces nil) (default-namespace nil) (comment nil) (label nil) (label-lang nil)) &body body) `(with-rdf (,@(if version-supp `(:version ,xml-version)) :xml-base ,about :namespaces ,namespaces :default-namespace ,default-namespace) (with (:ontology :about "") (when ,label (as* :label (if ,label-lang (list :lang ,label-lang)) (princ ,label) 'freshline)) (when ,comment (as :comment ,comment))) ,@body)) ;;; Deserialization (defun get-resource-name (element &optional about) (or (and (not about) (let ((*default-namespace* *target-namespace*)) ; ID always relative to base URI. (element-attribute element 'i-d :rdf))) (element-attribute element 'about :rdf))) (defun get-resource-reference (element) (element-attribute element 'resource :rdf)) (defun ensure-lisp-type-name (name) (let ((lisp-name (ensure-lisp-name name))) (if (find-class lisp-name nil) lisp-name name))) (defmacro modify-slot-specification (specification tag value-form) (ecase tag ;; Property definition. (:type `(setf (getf ,specification :composition) ,(if value-form `(ensure-lisp-name ,value-form)))) (:sub-property-of `(setf (getf ,specification :composition) (list ,value-form))) (:inverse-of `(setf (getf ,specification :inverse) ,value-form)) ((:domain :range) (let ((indicator (case tag (:domain :name) ; Temporary storage. (:range :type)))) `(let ((value (getf ,specification ,indicator)) (new-value (ensure-lisp-type-name ,value-form))) (unless (and value (or (eq value 'xmlrdfs::resource) (find-class value nil)) (find-class new-value nil) (not (subtypep new-value value))) (setf (getf ,specification ,indicator) new-value))))) ;; Class definition. (:on-property `(setf (getf ,specification :name) ,value-form)) (:all-values-from `(setf (getf ,specification :type) (ensure-lisp-type-name ,value-form))) (:some-values-from `(progn (setf (getf ,specification :type) (ensure-lisp-type-name ,value-form)) (setf (getf ,specification :composition) tag))) (:cardinality `(setf (getf ,specification :count) (make-numeric-range :min ,value-form :max ,value-form))) (:min-cardinality `(setf (getf ,specification :count) (make-numeric-range :min ,value-form :max 'big))) (:max-cardinality `(setf (getf ,specification :count) (make-numeric-range :min 0 :max ,value-form))))) (defmacro modify-class-options (options option new-value) `(case ,option ((:direct-superclasses :direct-slots :label) (push-on-end (getf ,options ,option) ,new-value)) (t (setf (getf ,options ,option) ,new-value)))) (defmacro class-options-p (content) `(find :metaclass ,content :test #'eq)) (defmacro member-specification (key-form specifications &key (indicator :name)) `(member ,key-form ,specifications :test #'eq :key #'(lambda (slot) (getf slot ,indicator)))) (defvar *class-slot-specifications* nil) (defmacro with-deserialization-unit (&body body) `(let ((*class-slot-specifications* nil)) ,@body)) (defun map-slot-specifications (fn) (revdolist (item *class-slot-specifications*) (destructuring-bind (class-name . slot-specifications) item (funcall fn class-name slot-specifications)))) (defun find-slot-specification (name) (when name (map-slot-specifications #'(lambda (class-name slot-specifications &aux specification) (setq specification (first (member-specification name slot-specifications))) (when specification (modify-slot-specification specification :domain class-name) (return-from find-slot-specification specification)))))) (defmacro make-slot-specification (&key name (domain ''xmlrdfs::resource) (range ''xmlrdfs::resource) type) `(let ((specification (find-slot-specification ,name))) (unless specification (modify-slot-specification specification :domain ,domain)) ,@(if range `((modify-slot-specification specification :range ,range))) ,@(if type `((modify-slot-specification specification :type ,type))) specification)) (defmethod find-element-type (tag (object xmlrdfs::resource)) (declare (ignore tag)) nil) (defmethod find-element-object ((tag (eql 'r-d-f)) element superelements) (declare (ignore element superelements)) tag) (defmethod find-element-object ((tag (eql 'description)) element superelements) (declare (ignore element superelements)) nil) (defmethod find-element-object ((tag (eql 'xmlrdfs::datatype)) element superelements) (declare (ignore element superelements)) nil) (defmethod find-element-object ((tag (eql 'property)) element superelements) (declare (ignore element superelements)) (make-slot-specification :range nil)) (defmethod element-object-missing (class element superelement) (declare (ignore class element superelement)) nil) (defun ensure-finished (class) (unless (class-dependents-finalized-p class) (finish-classes))) (defmethod element-object-missing ((class xmlrdfs::class) element superelement) (declare (ignore superelement)) (let ((name (get-resource-name element))) (or (and name (let ((instance (find-instance name nil))) (when instance (unless (or (eq (class-name class) 'xmlrdfs::resource) ; Being referred to as 'Thing'. (eq (class-of instance) class)) ;; Forward reference. (change-class instance class))) instance)) (progn (ensure-finished class) (make-instance class :name name))))) (defmethod element-object-missing ((class resource-class) element superelement) (declare (ignore element superelement)) (let (options) (modify-class-options options :metaclass class) options)) (defmethod find-element-object :around (tag element superelements) (or (call-next-method) (element-object-missing (or (find-class tag nil) (find-class (get-tag-lisp-name tag) nil)) element (first superelements)))) (defmethod assimilate-content (element (element-content (eql 'r-d-f)) subelement tag content) (declare (ignore element subelement tag)) (when (consp content) (call-next-method))) (defgeneric get-class-reference (object) (:method ((class-name symbol)) (or (find-class class-name nil) (find-class (ensure-lisp-name class-name) nil))) (:method ((object element)) (get-class-reference (get-resource-reference object)))) (defmethod assimilate-content (element element-content subelement (tag (eql 'xmlrdf::type)) content) (declare (ignore element-content content)) (setf (element-content element) (element-object-missing (get-class-reference subelement) element nil))) (defmethod assimilate-content (element (element-content xmlrdfs::resource) subelement (tag (eql 'xmlrdf::type)) content) (declare (ignore element content)) (let ((class (find-class (get-resource-reference subelement)))) (ensure-finished class) (change-class element-content class))) (defmacro get-instance-reference (element &optional type &aux (default-type ''xmlrdfs::resource)) `(let ((name (get-resource-reference ,element))) (and name (or (find-instance name nil) ;; Forward reference. (make-instance ,(if type `(or ,type ,default-type) default-type) :name name))))) (defmethod assimilate-content (element (element-content xmlrdfs::resource) subelement tag (content null)) (let ((value (get-instance-reference subelement (default-element-type tag element-content)))) (when value (assimilate-content element element-content subelement tag value)))) (defmethod assimilate-content (element (element-content xmlrdfs::resource) subelement (tag (eql 'same-as)) content) (declare (ignore content)) (let ((object (get-instance-reference subelement))) (when object (setf (find-instance (get-resource-name element)) object)))) (defmethod find-element-object ((tag (eql 'object-property)) element superelements) (declare (ignore element superelements)) (make-slot-specification)) (defmethod find-element-object ((tag (eql :transitive)) element superelements) (declare (ignore superelements)) (make-slot-specification :name (get-resource-name element 'about) :type :transitive)) (defmethod find-element-object ((tag (eql :symmetric)) element superelements) (declare (ignore superelements)) (make-slot-specification :name (get-resource-name element 'about) :type :symmetric)) (defmethod find-element-object ((tag (eql :functional)) element superelements) (declare (ignore superelements)) (make-slot-specification :name (get-resource-name element 'about))) (defmethod find-element-object ((tag (eql :inverse-functional)) element superelements) (declare (ignore superelements)) (make-slot-specification :name (get-resource-name element 'about) :type :inverse-functional)) (defmethod find-element-object ((tag (eql 'datatype-property)) element superelements) (declare (ignore element superelements)) (make-slot-specification :range nil)) (defmethod find-element-object ((tag (eql 'sub-class-of)) element superelements) (declare (ignore element superelements)) nil) (defmethod find-element-object ((tag (eql 'xmlowl::restriction)) element superelements) (declare (ignore element superelements)) (make-slot-specification :range nil)) (defmacro class-slot-specifications (class-name) `(cdr (assoc ,class-name *class-slot-specifications* :test #'eq))) (defmacro merge-specifications (place specification) `(do ((properties ,specification (cddr properties))) ((endp properties)) (setf (getf ,place (car properties)) (cadr properties)))) (defun propagate-slot-specification (class-name specification) (let ((class-specifications (class-slot-specifications class-name)) (specifications (expand-slot-specification (list specification)))) (if class-specifications (let* ((name (getf specification :name)) (rest-specifications (member-specification name class-specifications))) (cond ((null rest-specifications) (nconc class-specifications specifications)) ((singletonp specifications) (error "Attempt to redefine property \"~A,\" domain \"~A\"." (get-xml-name name) (get-xml-name class-name))) (t ; Cardinality. (merge-specifications (car rest-specifications) (car specifications)) (let ((specification (car (member-specification (getf (cadr specifications) :name) class-specifications)))) (if specification (setf (getf specification :type) (numeric-range-intersection (getf specification :type) (getf (cadr specifications) :type))) ; Combine min and max cardinality ; constraints. (push-on-end class-specifications (cadr specifications))))))) (push (cons class-name specifications) *class-slot-specifications*)))) (defun assimilate-to-slot (name specification) (let ((class-name (getf specification :name))) (modify-slot-specification specification :on-property name) (propagate-slot-specification class-name specification))) (defmethod assimilate-content (element element-content subelement (tag (eql 'property)) (content cons)) (declare (ignore element element-content)) (assimilate-to-slot (get-resource-name subelement) content)) (defmacro property-characteristic (slot-specification) `(getf ,slot-specification :composition)) (defmacro modify-functional-slot-specification (specification) `(progn (modify-slot-specification ,specification :min-cardinality 0) (modify-slot-specification ,specification :max-cardinality 1))) (defun finalize-functional-property (element) (modify-functional-slot-specification (element-content element)) (modify-slot-specification (element-content element) :type nil)) (defmethod finalize-content (element (tag (eql :functional)) (content cons)) (finalize-functional-property element)) (defmethod finalize-content (element (tag (eql 'object-property)) (content cons)) (when (eq (property-characteristic content) :functional) (finalize-functional-property element))) (defmethod assimilate-content (element element-content subelement (tag (eql 'object-property)) (content cons)) (declare (ignore element element-content)) (assimilate-to-slot (get-resource-name subelement) content)) (defmethod assimilate-content (element element-content subelement (tag (eql :transitive)) (content cons)) (declare (ignore element element-content)) (assimilate-to-slot (get-resource-name subelement) content)) (defmethod assimilate-content (element element-content subelement (tag (eql :symmetric)) (content cons)) (declare (ignore element element-content)) (assimilate-to-slot (get-resource-name subelement) content)) (defmethod assimilate-content (element element-content subelement (tag (eql :functional)) (content cons)) (declare (ignore element element-content)) (assimilate-to-slot (get-resource-name subelement) content)) (defmethod assimilate-content (element element-content subelement (tag (eql :inverse-functional)) (content cons)) (declare (ignore element element-content)) (assimilate-to-slot (get-resource-name subelement) content)) (defmethod assimilate-content (element element-content subelement (tag (eql 'datatype-property)) (content cons)) (declare (ignore element element-content)) (assimilate-to-slot (get-resource-name subelement) content)) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'xmlrdf::type)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :type (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'sub-property-of)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :sub-property-of (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'inverse-of)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :inverse-of (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'domain)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :domain (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'range)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :range (get-resource-reference subelement))) (defmethod assimilate-content (element element-content subelement (tag (eql 'xmlrdfs::class)) (content cons)) (declare (ignore element element-content)) (let ((class-name-1 (getf content :same-as)) (class-name-2 (get-resource-name subelement)) class-name) (unless class-name-2 (error "Attempt to deserialize an unnamed class.")) (when class-name-1 (modify-class-options content :same-as class-name-2)) (setq class-name (or class-name-1 class-name-2)) (dolist (specification (getf content :direct-slots)) (propagate-slot-specification class-name specification)) (remf content :direct-slots) (apply #'ensure-class class-name content))) (defmethod assimilate-content (element element-content subelement (tag (eql 'xmlowl::class)) (content cons)) (assimilate-content element element-content subelement 'xmlrdfs::class content)) (defmethod assimilate-content (element element-content subelement (tag (eql 'description)) (content cons)) (assimilate-content element element-content subelement 'xmlrdfs::class content)) (defmethod assimilate-content (element element-content subelement tag (content cons)) (declare (ignore tag)) (if (class-options-p content) ;; Arbitrary metaclass. (assimilate-content element element-content subelement 'xmlrdfs::class content) (call-next-method))) (defmethod finalize-content (element (tag (eql 'label)) (content string)) (declare (ignore element)) ;; Preserve as string. ) (defmethod finalize-content (element (tag (eql 'comment)) (content string)) ;; Preserve as string. (setf (element-content element) (string-trim whitespace content))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'label)) content) ;; Modify class or slot specification. (modify-class-options (element-content element) :label (make-resource-label :lang (element-attribute subelement 'xmlxml::lang :xml "en") :text content))) (defmethod assimilate-content (element element-content subelement (tag (eql 'comment)) content) (declare (ignore element element-content subelement content)) ;; Ontology header. ) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'comment)) content) (declare (ignore subelement)) ;; Modify class or slot specification. (modify-class-options (element-content element) :documentation content)) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'same-as)) content) (declare (ignore content)) (modify-class-options (element-content element) :same-as (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'sub-class-of)) content) (declare (ignore content)) (let* ((superclass-name (get-resource-reference subelement)) (superclass (get-class-reference superclass-name))) (when (and superclass (subtypep superclass 'extended-class)) ; Metaclass (subclass of a metaclass)? (modify-class-options (element-content element) :metaclass 'resource-class)) (modify-class-options (element-content element) :direct-superclasses (if superclass (class-name superclass) superclass-name)))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'sub-class-of)) (content cons)) (declare (ignore subelement)) (modify-class-options (element-content element) :direct-slots content)) (defmethod finalize-content (element (tag (eql 'xmlowl::restriction)) (content cons)) (when (eq (getf content :composition) 'some-values-from) (let ((name (getf content :name))) (modify-slot-specification (element-content element) :on-property (add-lisp-name-suffix name (getf content :type))) (modify-slot-specification (element-content element) :sub-property-of name) (modify-slot-specification (element-content element) :min-cardinality 1)))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'on-property)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :on-property (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'all-values-from)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :all-values-from (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'some-values-from)) content) (declare (ignore content)) (modify-slot-specification (element-content element) :some-values-from (get-resource-reference subelement))) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'cardinality)) content) (declare (ignore subelement)) (modify-slot-specification (element-content element) :cardinality content)) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'min-cardinality)) content) (declare (ignore subelement)) (modify-slot-specification (element-content element) :min-cardinality content)) (defmethod assimilate-content (element (element-content cons) subelement (tag (eql 'max-cardinality)) content) (declare (ignore subelement)) (modify-slot-specification (element-content element) :max-cardinality content)) (defun finish-classes () (map-slot-specifications #'(lambda (class-name slot-specifications) (dolist (specification slot-specifications) (when (getf specification :inverse) (let ((specifications (member-specification (getf specification :inverse) (class-slot-specifications (getf specification :type))))) (when specifications (cond ((eq (property-characteristic specification) :inverse-functional) (modify-slot-specification specification :type nil) (modify-functional-slot-specification (first specifications)) (propagate-slot-specification (getf specification :type) (first specifications))) ((eq (property-characteristic (first specifications)) :inverse-functional) (modify-slot-specification (first specifications) :type nil) (modify-functional-slot-specification specification) (propagate-slot-specification class-name specification))))))))) (map-slot-specifications #'(lambda (class-name slot-specifications &aux (class (find-class class-name))) ;; Apply accumulated slot specifications to class. (ensure-class-using-class class class-name :metaclass (class-of class) ; If absent, most Lisps compare default ; with actual, and signal an error. :direct-slots (finalize-slots class-name slot-specifications))))) (defmethod finalize-content (element (tag (eql 'r-d-f)) content) (declare (ignore element content)) (finish-classes))
50,687
Common Lisp
.lisp
972
37.333333
91
0.574751
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
582d972c6c1fe985c9e3f61b706224e75c9bf7d55412e5ae5ccb7b670f9913a3
20,428
[ -1 ]
20,429
deserial.lisp
whounslo_reasoner/src/deserial.lisp
;;; Copyright (C) 2011-2014, 2016, 2017 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; XML deserialization (in-package :reasoner-ext) (eval-when (:execute :compile-toplevel :load-toplevel) (shadowing-import 'rs::variable) (import '(atms:singletonp rs::revdolist rs::class-direct-superclasses rs::ensure-class rs::ensure-class-using-class rs::slot-definition rs::slot-definition-name rs::slot-definition-type rs::slot-definition-count rs::ensure-range-class rs::ensure-range-class-using-class rs::make-numeric-range rs::numeric-subrangep rs::range-external-type rs::find-slot-definition rs::forward-rule rs::constraint rs::proposition rs::arithmetic-proposition rs::functional-proposition rs::lisp-proposition rs::literal-proposition rs::numeric-proposition rs::relational-proposition rs::attribute-reference rs::attribute-references rs::make-attribute-reference rs::make-variable rs::variable-name rs::variable-class-name rs::collect-rhs-attribute-references rs::attribute-reference-class rs::relation rs::function-name rs::prefix-rhs rs::arguments rs::value rs::specializer rs::implication-token rs::biconditional-token)) (export '(defnamespace make-namespace ensure-namespace-package namespace-package namespace-uri find-uri-namespace *namespace-package-prefix* *namespaces* *namespace-names* *count-slot-suffix* *count-type-suffix* *xml-id-attribute* find-prefix-namespace parse-qualified-name find-xml-name intern-xml-name parse-as-type into-xml-element store-xml-content outof-xml-element pop-elements define-ignored-elements *ignored-elements* *count-subelements* count-subelements-p *assumptions* *assumption* deserialize-as-objects deserialize-as-object ))) ;(define-modify-macro push-on-end (object) ; (lambda (place object) ; (nconc place (list object)))) (defmacro push-on-end (place object) `(setf ,place (nconc ,place (list ,object)))) (defun map-objects (object paths-fn before-fn &optional after-fn) (funcall before-fn object) (dolist (object (funcall paths-fn object)) (map-objects object paths-fn before-fn after-fn)) (when after-fn (funcall after-fn object))) (defparameter *count-subelements* (not nil)) (defmethod count-subelements-p (object slot-name) (declare (ignore object slot-name)) *count-subelements*) (defun write-slot-value (object slot-name value &rest args) (let* ((class (class-of object)) (slot-definition (find-slot-definition class slot-name))) (apply #'write-slot-value-using-class class object slot-definition value :premise :slot-name slot-name args))) (defmethod write-slot-value-using-class (class object (slot null) value informant &key slot-name (no-error nil)) (cond (no-error nil) ((slot-definition-missing class object slot-name 'write-slot-value value () informant)) (t (call-next-method)))) (defmethod write-slot-value-using-class (class object slot value informant &key (slot-name (slot-definition-name slot)) (no-check nil no-check-supp) (no-error nil) assumption) (cond ((or no-check (slot-value-typep value (slot-definition-type slot))) (or (fetch-assumption object slot-name value) (let ((assumption (or assumption (make-assumption *atms*)))) (add-slot-value-using-class class object slot value (list assumption) informant :no-check (if no-check-supp no-check (not nil)) :no-count (not (count-subelements-p object slot-name))) assumption))) (no-error nil) (t (error "Slot value ~A is not of type ~A." value (slot-definition-type slot))))) ;;; XML namespaces (defnamespace :xml "http://www.w3.org/XML/1998/namespace" lang) (defnamespace :xmlns "http://www.w3.org/2000/xmlns/") (defnamespace :xsd "http://www.w3.org/2001/XMLSchema" schema annotation #:documentation element name ref #:type complex-type #:sequence choice all min-occurs max-occurs unbounded complex-content extension restriction base simple-type min-inclusive max-inclusive value enumeration #:boolean #:integer #:string #:list non-negative-integer positive-integer date-time #:time date g-year-month g-year g-month-day g-day g-month duration) (defnamespace :xsi "http://www.w3.org/2001/XMLSchema-instance" #:type #:nil) (eval-when (:execute :compile-toplevel :load-toplevel) (ensure-xml-type-name '(arithmetic-proposition functional-proposition lisp-proposition literal-proposition numeric-proposition relational-proposition compound-object assembly part component))) (defnamespace :rs "http://reasoner.sourceforge.net/reasoner" ;; Rule language. rule-set #:if iff formula rule-label name assume #:comment head body if-and-only-if implies #:or #:and #:not proposition arithmetic-proposition functional-proposition lisp-proposition literal-proposition numeric-proposition relational-proposition variable attribute-reference name ref #:type value value-attribute-reference #:specializer relation arithmetic-expr operator constant minus function-name arguments aggregate-function-name relational-attribute-reference numeric-attribute-reference ;; Predefined ranges. numeric-range symbolic-range true-or-false true false ;; Composite objects. compound-object assembly part component parts) (defparameter *namespaces* nil) (defparameter *target-namespace* nil) (defparameter *default-namespace* nil) (defconstant xml-prefix-separator #\:) (defconstant xml-fragment-separator #\#) (defparameter *xml-id-attribute* :name) #-sbcl (defconstant whitespace '(#\Space #\Tab #\Newline)) #+sbcl (defparameter whitespace '(#\Space #\Tab #\Newline)) ;;; XML parser interface (defun parse-tag (tag-and-options) (let* ((options (if (consp tag-and-options) (cdr tag-and-options))) (tag (if options (car tag-and-options) tag-and-options))) (values tag options))) (defun namespace-uri-variant (name) (declare (type symbol name)) (or (get name 'rdf-uri) (let ((uri (namespace-uri name))) (if uri (setf (get name 'rdf-uri) (format nil "~A~C" uri xml-fragment-separator)))))) (defmacro find-namespace (namespace namespaces errorp &rest args) `(cond ((find ,namespace ,namespaces ,@args)) (,errorp (error "Namespace not found: ~S." ,namespace)))) (defun find-uri-namespace (uri &optional (namespaces *namespaces*) (errorp t)) (declare (type string uri)) (when (zerop (length uri)) (return-from find-uri-namespace nil)) (find-namespace uri namespaces errorp :test #'string= :key (if (eq (char uri (1- (length uri))) xml-fragment-separator) #'namespace-uri-variant #'namespace-uri))) (defun find-prefix-namespace (prefix &optional (errorp t)) (declare (type string prefix)) (find-namespace prefix *namespace-names* errorp :test #'string= :key #'namespace-prefix)) (defun parse-qualified-name (name) (declare (type string name)) (let* ((split (position-if #'(lambda (ch) (or (eq ch xml-prefix-separator) (eq ch xml-fragment-separator))) name :from-end (not nil))) (prefix (if (and split (plusp split)) (subseq name 0 split))) (separator (if split (char name split)))) (values (if split (subseq name (1+ split)) name) (cond ((null separator) *default-namespace*) ((eq separator xml-prefix-separator) (find-prefix-namespace prefix)) (prefix (find-uri-namespace prefix *namespace-names*)) ; PREFIX is a uri. (t *target-namespace*))))) (defmethod find-xml-name ((name string) (namespace symbol) &optional (errorp t)) (declare (ignore errorp)) (find-symbol name (ensure-namespace-package namespace))) (defun find-xml-name-using-known-namespaces (name) (dolist (ns *namespaces*) (let ((symbol (find-xml-name name ns nil))) (when symbol (return symbol))))) (defun find-xml-name-using-used-packages (name) (dolist (package (package-use-list *package*)) (unless (eq package #.(find-package "COMMON-LISP")) (let ((symbol (find-symbol name package)) lisp-name) (when symbol (setq lisp-name (get-lisp-name symbol)) (when (eq (find-symbol (string lisp-name)) lisp-name) (return symbol))))))) (defmethod find-xml-name ((name string) (namespace null) &optional (errorp t)) (declare (ignore errorp)) (or (find-xml-name-using-known-namespaces name) (find-symbol name) (find-xml-name-using-used-packages name))) (defmethod find-xml-name :around ((name string) (namespace symbol) &optional (errorp t)) (cond ((call-next-method)) (errorp (error "Name not found~@[ in namespace ~S~]: ~S." (namespace-prefix namespace) name)))) (defmethod find-xml-name ((name string) (uri string) &optional (errorp t)) (find-xml-name name (find-uri-namespace uri) errorp)) (defmethod intern-xml-name ((name string) (namespace symbol)) (intern name (ensure-namespace-package namespace))) (defmethod intern-xml-name ((name string) (uri string)) (intern-xml-name name (find-uri-namespace uri))) (defmethod intern-xml-name ((name string) (namespace null)) (or (find-xml-name-using-known-namespaces name) (intern name))) (defvar *ignored-elements* nil) (defmacro define-ignored-elements (namespace-name &body body) `(dolist (name ',body) (pushnew (intern-xml-name (string name) ,namespace-name) *ignored-elements* :test #'eq))) (defun ignore-element-p (tag) (find tag *ignored-elements* :test #'eq :key #'get-lisp-name)) (defun whitespacep (ch) (or (not (graphic-char-p ch)) (eq ch #\space))) (defun find-token (string start end &optional (predicate #'whitespacep)) (let* ((start (max (or (position-if (complement predicate) string :start start) start) start)) (end (min (or (position-if predicate string :start start) end) end))) (values start end))) (defmethod parse-as-type ((object string) datatype start end) (declare (ignore datatype)) (or (parse-integer object :start start :end end :junk-allowed (not nil)) (get-content-lisp-name (intern-xml-name (subseq object start end) nil)))) (defmethod parse-as-type ((object string) (datatype (eql t)) start end) (declare (ignorable start end)) (call-next-method)) (defmethod parse-content ((content string) datatype) (do ((bound (length content)) (object nil) (last-object nil object) (objects ()) (start 0 end) end) ((eql start bound) (if objects (push-on-end objects object) object)) (multiple-value-setq (start end) (find-token content start bound)) (setq object (parse-as-type content datatype start end)) (when last-object (push-on-end objects last-object)))) (defmethod parse-content ((object string) (datatype (eql 'number))) (or (parse-integer object :junk-allowed (not nil)) object)) (defmethod parse-content ((content string) (datatype (eql 'xmlxsd::string))) (string-trim whitespace content)) (defmethod parse-content ((content string) (datatype null)) ;; Defer parsing. content) (defvar *element-default-attribute-fn* (constantly nil)) (defstruct element tag attribute-fn content) (defun element-attribute (element name &optional namespace default) (let ((value (or (funcall (element-attribute-fn element) (string (get-xml-name name 'mandatory)) namespace) default))) (cond ((null value) value) ((parse-integer value :junk-allowed (not nil))) (t (multiple-value-bind (name namespace) (parse-qualified-name value) (get-content-lisp-name (intern-xml-name name namespace))))))) (defparameter *assumptions* nil) (defparameter *assumption* nil) (defmethod get-tag-slot-name (name) (get-tag-lisp-name name)) (defmethod get-tag-slot-name ((name (eql 'parts))) name) (defun default-element-type (tag object) (let ((slot (find-slot-definition (class-of object) (get-tag-slot-name tag)))) (values (if slot (slot-definition-type slot)) (if slot (slot-definition-count slot))))) (defmethod find-element-type (tag object) (declare (ignore tag object)) nil) (defmethod find-element-type (tag (object extended-object)) (default-element-type tag object)) (defmethod find-superelement-type (element (superelement null)) (declare (ignore element)) nil) (defmethod find-superelement-type (element superelement) (find-element-type (element-tag element) (element-content superelement))) (defmethod find-element-object (tag element superelements) (let ((type (or (element-attribute element 'xmlxsi::type :xsi) (multiple-value-bind (type count) (find-element-type tag (element-content (first superelements))) (if (null count) type)) (find-superelement-type (first superelements) (second superelements))))) (if (and type (subtypep type 'extended-object)) (ensure-named-instance (element-attribute element *xml-id-attribute*) :class type)))) (defmethod find-element-object (tag element (superelements null)) (ensure-named-instance (element-attribute element *xml-id-attribute*) :class (or (element-attribute element 'xmlxsi::type :xsi) (let ((name (get-tag-lisp-name tag))) (or (get name :xml-type) name))))) (defmethod finalize-content (element tag content) (declare (ignore element tag content)) ) (defmethod finalize-content (element tag (content string)) (declare (ignore tag)) (setf (element-content element) (parse-content content (ensure-lisp-name (element-attribute element 'datatype :rdf))))) (defmethod assimilate-content (element element-content subelement tag content) (declare (ignore element-content subelement tag)) ;;; Default behaviour: propagate content up a level. (when content (setf (element-content element) content))) (defmethod assimilate-content (element (element-content cons) subelement tag content) (declare (ignore subelement tag)) (push-on-end (element-content element) content)) (defmethod capture-assumption (assumption) (pushnew assumption *assumptions*)) (defmethod assimilate-content (element (element-content extended-object) subelement tag content) (declare (ignore element subelement)) (when content (capture-assumption (write-slot-value element-content (get-tag-slot-name tag) content :assumption *assumption*)))) (defmethod find-datatype (type) (range-external-type type)) (defmethod find-datatype ((type (eql 'xmlxsd::string))) type) (defmethod assimilate-content (element (element-content extended-object) subelement tag (content string)) (call-next-method element element-content subelement tag (parse-content content (find-datatype (or (find-element-type tag element-content) (error "Cannot determine content type of subelement \"~A\"." (get-xml-name tag))))))) (defmethod assimilate-content (element (element-content extended-object) subelement tag (content cons)) (if (every #'(lambda (object) (typep object 'extended-object)) content) (dolist (value content) (assimilate-content element element-content subelement tag value)) (call-next-method))) (defmethod assimilate-content (element (element-content extended-object) subelement tag (content extended-object)) (declare (ignore subelement)) (if (slot-exists-p element-content (get-tag-slot-name tag)) (call-next-method) ;; A single object was created from a slot's type because ;; it had no :count option - overwrite it. (setf (element-content element) (list content)))) (defmethod assimilate-content (element (element-content list) subelement tag (content extended-object)) (declare (ignore subelement tag)) (push-on-end (element-content element) content)) ;;; Rule ML (define-xml-name "implies" implication-token :rs) (define-xml-name "ifAndOnlyIf" biconditional-token :rs) (defvar *declarations* nil "List of variable declarations; reset when a rule is encountered.") (defmethod find-element-object ((tag (eql 'rule-set)) element superelements) (declare (ignore element superelements)) (not nil)) (defmethod assimilate-content (element (element-content null) subelement (tag (eql 'xmlrs::comment)) (content string)) (declare (ignore subelement)) (setf (element-content element) (list content))) (defmethod find-element-object :after ((tag (eql 'rule-label)) element superelements) (declare (ignore element superelements)) (setq *declarations* nil)) (defmethod assimilate-content (element element-content subelement (tag (eql 'rule-label)) content) (declare (ignore element-content content)) (setf (element-attribute-fn element) (element-attribute-fn subelement))) (defun finalize-rule (element tag content &aux name qualifier comment instance) (flet ((finalize-rule-content (name tag qualifier comment head &optional body) (ensure-named-instance name :qualifier qualifier :documentation comment :body body :neck (ecase tag (formula) (xmlrs::if implication-token) (iff biconditional-token)) :head head :class (if (eq tag 'formula) 'constraint 'forward-rule)))) (setq name (element-attribute element 'name :rs) qualifier (if (eq (element-attribute element 'assume :rs) 'true) :assume) comment (if (stringp (first content)) (first content)) instance (if (eq tag 'formula) (finalize-rule-content name tag qualifier comment nil (if comment (second content) content)) (apply #'finalize-rule-content name tag qualifier comment (if comment (rest content) content)))) (when qualifier (capture-assumption (instance-assumption instance))))) (defmethod assimilate-content (element element-content subelement (tag (eql 'xmlrs::if)) content) (declare (ignore element element-content)) (finalize-rule subelement tag content)) (defmethod assimilate-content (element element-content subelement (tag (eql 'iff)) content) (declare (ignore element element-content)) (finalize-rule subelement tag content)) (defmethod assimilate-content (element element-content subelement (tag (eql 'formula)) content) (declare (ignore element element-content)) (finalize-rule subelement tag content)) (defmethod finalize-content (element (tag (eql 'xmlrs::comment)) (content string)) ;; Preserve as string. (setf (element-content element) (string-trim whitespace content))) (defmethod assimilate-content (element (element-content null) subelement (tag (eql 'head)) content) (declare (ignore subelement)) (setf (element-content element) (list content))) (defmethod find-element-object ((tag (eql biconditional-token)) element superelements) (declare (ignore element superelements)) (list 'and)) (defmethod finalize-content (element (tag (eql biconditional-token)) (content cons)) (declare (ignore element)) ;; A <-> B is re-written as (A or not B) and (not A or B). (psetf (second content) `(or ,(second content) (not ,(third content))) (third content) `(or ,(third content) (not ,(second content))))) (defmethod find-element-object ((tag (eql implication-token)) element superelements) (declare (ignore element superelements)) (list 'or)) (defmethod finalize-content (element (tag (eql implication-token)) (content cons)) (declare (ignore element)) ;; A -> B is re-written as not A or B. (setf (second content) `(not ,(second content)))) (defmethod find-element-type (tag (object proposition)) (declare (ignore tag)) nil) (defmethod find-element-object ((tag (eql 'proposition)) element superelements) (declare (ignore superelements)) (make-instance (ensure-lisp-name (element-attribute element 'xmlrs::type :rs)))) (defmethod find-element-object ((tag (eql 'xmlrs::or)) element superelements) (declare (ignore element superelements)) (list 'or)) (defmethod find-element-object ((tag (eql 'xmlrs::and)) element superelements) (declare (ignore element superelements)) (list 'and)) (defmethod find-element-object ((tag (eql 'xmlrs::not)) element superelements) (declare (ignore element superelements)) (list 'not)) (defmethod find-element-object ((tag (eql 'attribute-reference)) element superelements) (declare (ignore element superelements)) (not ())) (defmethod find-element-object ((tag (eql 'relational-attribute-reference)) element superelements) (declare (ignore element superelements)) (not ())) (defmethod find-element-object ((tag (eql 'numeric-attribute-reference)) element superelements) (declare (ignore element superelements)) (not ())) (defmethod find-element-object ((tag (eql 'value-attribute-reference)) element superelements) (declare (ignore element superelements)) (not ())) (defmethod find-element-object ((tag (eql 'arithmetic-expr)) element superelements) (declare (ignore element superelements)) ;; An arithmetic expression may be a single attribute reference or number. (not ())) (defmethod find-element-object ((tag (eql 'variable)) element superelements) (declare (ignore element superelements)) nil) (defmethod find-element-object ((tag (eql 'xmlrs::specializer)) element superelements) (declare (ignore element superelements)) nil) (defmethod assimilate-content (element (element-content proposition) subelement tag content) (declare (ignore element subelement)) (setf (slot-value element-content tag) content)) (defmethod assimilate-content (element (element-content literal-proposition) subelement (tag (eql 'value)) content) (call-next-method element element-content subelement tag (let ((value (parse-content content t))) (if (symbolp value) (list value) value)))) (defmethod assimilate-content (element (element-content relational-proposition) subelement (tag (eql 'xmlrs::specializer)) content) (call-next-method element element-content subelement 'specializer content)) (defmethod finalize-content (element (tag (eql 'relation)) (content string)) (setf (element-content element) (parse-content content t))) (defmethod finalize-content (element (tag (eql 'function-name)) (content string)) (setf (element-content element) (parse-content content t))) (defmethod finalize-content (element (tag (eql 'aggregate-function-name)) (content string)) (setf (element-content element) (parse-content content t))) (defmethod finalize-content (element (tag (eql 'constant)) (content string)) (setf (element-content element) (parse-content content 'number))) (defmethod assimilate-content (element (element-content functional-proposition) subelement (tag (eql 'aggregate-function-name)) content) (call-next-method element element-content subelement 'function-name content)) (defmethod assimilate-content (element (element-content arithmetic-proposition) subelement (tag (eql 'arithmetic-expr)) content) (call-next-method element element-content subelement 'prefix-rhs content)) (defmethod assimilate-content (element (element-content arithmetic-proposition) subelement (tag (eql 'value)) content) (call-next-method element element-content subelement 'prefix-rhs content)) (defmacro proposition-attribute-datatype (proposition) `(let* ((attribute-reference (first (attribute-references ,proposition))) (slot-definition (find-slot-definition (attribute-reference-class attribute-reference) (attribute-name attribute-reference)))) (if slot-definition (range-external-type (slot-definition-type slot-definition))))) (defun finalize-proposition-content (proposition slot-name) (let ((value (slot-value proposition slot-name))) (when (stringp value) (setf (slot-value proposition slot-name) (parse-content value (or (proposition-attribute-datatype proposition) t)))))) (defmethod finalize-content (element tag (content arithmetic-proposition)) (declare (ignore element tag)) (finalize-proposition-content content 'prefix-rhs)) (defmethod finalize-content (element tag (content numeric-proposition)) (declare (ignore element tag)) (finalize-proposition-content content 'value)) (defmethod assimilate-content (element element-content subelement (tag (eql 'operator)) content) (call-next-method element element-content subelement tag (list (parse-content content t)))) (defmethod assimilate-content (element (element-content null) subelement (tag (eql 'attribute-reference)) content) (call-next-method element element-content subelement tag (list content))) (defmethod assimilate-content (element (element-content null) subelement (tag (eql 'variable)) content) (call-next-method element element-content subelement tag (list content))) (defmethod assimilate-content (element (element-content null) subelement (tag (eql 'constant)) content) (call-next-method element element-content subelement tag (list content))) (defun finalize-attribute-reference (element content) (setf (element-content element) (make-attribute-reference :attribute-name (element-attribute element 'name :rs) :attribute-reference-variable content))) (defmethod finalize-content (element (tag (eql 'attribute-reference)) content) (finalize-attribute-reference element content)) (defmethod finalize-content (element (tag (eql 'value-attribute-reference)) content) (finalize-attribute-reference element content)) (defmethod finalize-content (element (tag (eql 'relational-attribute-reference)) content) (finalize-attribute-reference element content)) (defmethod finalize-content (element (tag (eql 'numeric-attribute-reference)) content) (finalize-attribute-reference element content)) (defmethod assimilate-content (element (element-content proposition) subelement (tag (eql 'attribute-reference)) content) (declare (ignore element subelement)) (push-on-end (slot-value element-content 'attribute-references) content)) (defmethod assimilate-content (element (element-content literal-proposition) subelement (tag (eql 'value-attribute-reference)) content) (declare (ignore element subelement)) (push content (slot-value element-content 'attribute-references))) (defmethod assimilate-content (element (element-content functional-proposition) subelement (tag (eql 'relational-attribute-reference)) content) (declare (ignore element subelement)) (push content (slot-value element-content 'arguments))) (defmethod assimilate-content (element (element-content functional-proposition) subelement (tag (eql 'numeric-attribute-reference)) content) (declare (ignore element subelement)) (push-on-end (slot-value element-content 'arguments) content)) (defmethod assimilate-content :after (element (element-content proposition) subelement (tag (eql 'arguments)) content) (declare (ignore element subelement)) (collect-rhs-attribute-references element-content content)) (defun collect-attribute-reference-arguments (functional-proposition) (let ((arguments (slot-value functional-proposition 'arguments))) (when (cdr arguments) (collect-rhs-attribute-references functional-proposition arguments)))) (defmethod assimilate-content :after (element (element-content functional-proposition) subelement (tag (eql 'relational-attribute-reference)) content) (declare (ignore element subelement content)) (collect-attribute-reference-arguments element-content)) (defmethod assimilate-content :after (element (element-content functional-proposition) subelement (tag (eql 'numeric-attribute-reference)) content) (declare (ignore element subelement content)) (collect-attribute-reference-arguments element-content)) (defmethod finalize-content (element (tag (eql 'arithmetic-expr)) content) (when (typep content 'variable) (finalize-attribute-reference element content))) (defmethod assimilate-content :around (element element-content subelement (tag (eql 'arithmetic-expr)) content) (call-next-method element element-content subelement tag (if (eq (element-attribute subelement 'minus :rs) 'true) (list '- content) content))) (defmethod assimilate-content :after (element (element-content arithmetic-proposition) subelement (tag (eql 'arithmetic-expr)) content) (declare (ignore element subelement)) (collect-rhs-attribute-references element-content content)) (defun finalize-variable (element) (let* ((variable-name (or (element-attribute element 'name :rs) (element-attribute element 'ref :rs))) (variable (assoc variable-name *declarations* :test #'eq)) (variable-class-name (variable-class-name variable))) (unless variable-class-name (setq variable-class-name (element-attribute element 'xmlrs::type :rs)) (when variable ;; Forward reference. (setf (variable-class-name variable) variable-class-name))) (setf (element-content element) (or variable (car (push (make-variable :name variable-name :class-name variable-class-name) *declarations*)))))) (defmethod finalize-content (element (tag (eql 'variable)) content) (declare (ignore content)) (finalize-variable element)) (defmethod finalize-content (element (tag (eql 'xmlrs::specializer)) content) (declare (ignore content)) (finalize-variable element)) ;;; XML Schema (setf (find-class 'xmlxsd::integer) (find-class 'numeric-range)) (setf (find-class 'non-negative-integer) (find-class 'zero-or-more)) (setf (find-class 'positive-integer) (find-class 'one-or-more)) (setf (find-class 'xmlxsd::boolean) (find-class 'true-or-false)) (deftype xmlxsd::string nil 'string) (let (class-specifications) (defmethod find-element-object ((tag (eql 'schema)) element superelements) (declare (ignore element superelements)) (setq class-specifications nil) nil) (defun add-class-specification (class-specification) (push class-specification class-specifications)) (defun get-class-specifications () class-specifications) ) ;end let class-specifications (defmacro deferred-ensure-class-using-class (&rest args) `(add-class-specification (list ,@args))) (defmethod find-element-object ((tag (eql 'simple-type)) element superelements) (declare (ignore element superelements)) nil) (defmethod find-element-object ((tag (eql 'complex-type)) element superelements) (declare (ignore element superelements)) nil) (defmethod find-element-object ((tag (eql 'complex-content)) element superelements) (declare (ignore element)) (element-attribute (first superelements) 'name :xsd)) (defun retrieve-type (content) (typecase content (string nil) ; simpleType or complexType. (t content) ; null: simpleType or complexType. )) (defun ensure-derived-type (element superelement) (let ((type (retrieve-type (element-content superelement)))) (when type ; complexContent, not simpleType? (ensure-class type :direct-superclasses (list (ensure-lisp-name (element-attribute element 'base :xsd))) :metaclass *default-metaclass*)))) (defmethod find-element-object ((tag (eql 'restriction)) element superelements) (ensure-derived-type element (first superelements))) (defmethod find-element-object ((tag (eql 'extension)) element superelements) (ensure-derived-type element (first superelements))) (defmethod find-element-object ((tag (eql 'xmlxsd::sequence)) element superelements) (declare (ignore element superelements)) nil) (defmethod find-element-object ((tag (eql 'element)) element superelements) (declare (ignore element superelements)) nil) (define-ignored-elements :xsd "appinfo") (defmethod finalize-content (element (tag (eql 'xmlxsd::documentation)) (content string)) ;; Preserve as string. (setf (element-content element) (string-trim whitespace content))) (defmethod assimilate-content (element element-content subelement (tag (eql 'complex-content)) content) (declare (ignore element element-content subelement content)) ;; Don't overwrite documentation. ) (defmethod assimilate-content :around (element element-content subelement (tag (eql 'complex-type)) content) (declare (ignore element element-content)) (let ((name (element-attribute subelement 'name :xsd))) (if name (ensure-class name :documentation content :metaclass *default-metaclass*) (call-next-method)))) #+allegro (defmethod finalize-content (element (tag (eql 'xmlxsd::sequence)) (content string)) ;; Empty sequence. (setf (element-content element) nil)) (defparameter *count-slot-suffix* :count) (defparameter *count-type-suffix* :numbers) (defun ensure-count-type (class-name slot-name numeric-range) (let ((count-type-name (if (symbolp numeric-range) numeric-range)) count-type) (unless count-type-name (setq count-type-name (add-lisp-name-suffix class-name slot-name *count-type-suffix*) count-type (find-class count-type-name nil)) ;; Define type. (if count-type (ensure-range-class-using-class count-type count-type-name :elements numeric-range) (let ((supertype-name (case (range-min numeric-range) (0 (case (range-max numeric-range) (1 'zero-or-one) (big 'zero-or-more))) (1 (case (range-max numeric-range) (1 'exactly-one) (big 'one-or-more)))))) (ensure-range-class count-type-name :include supertype-name :elements numeric-range)))) count-type-name)) (defun adjust-count-type (type supertype) (let ((class (find-class type)) (superclass (find-class supertype))) (when (numeric-subrangep (elements class) (elements superclass)) (ensure-range-class-using-class class type :direct-superclasses (list supertype))))) (defun finalize-slots (class-name specifications) (dolist (specification specifications) (let ((count-slot-name (getf specification :count)) count-slot-specification count-type-name) (cond ((null count-slot-name)) ((symbolp count-slot-name) (setq count-slot-specification (find count-slot-name specifications :test #'eq :key #'(lambda (specification) (getf specification :name))) count-type-name (ensure-count-type class-name (getf specification :name) (getf count-slot-specification :type))) (setf (getf count-slot-specification :type) count-type-name)) (t ;; Surplus occurrence constraint. (setf (getf specification :count) nil))))) specifications) (defun assimilate-top-level-group (element element-content specifications) (let* ((class (retrieve-type element-content)) (name (or (if class (class-name class)) (element-attribute element 'name :xsd)))) (when name (deferred-ensure-class-using-class class name :direct-slots (finalize-slots name specifications) :metaclass *default-metaclass*) (not nil)))) (defmethod assimilate-content (element element-content subelement (tag (eql 'xmlxsd::sequence)) content) (declare (ignore subelement)) (or (assimilate-top-level-group element element-content content) (call-next-method))) (defmethod assimilate-content (element element-content subelement (tag (eql 'all)) content) (declare (ignore subelement)) (assimilate-top-level-group element element-content content)) (defun convert-lower-bound (bound) (case bound ((nil) 1) ((unbounded |unbounded|) '-big) (t bound))) (defun convert-upper-bound (bound) (case bound ((nil) 1) ((unbounded |unbounded|) 'big) (t bound))) (defun expand-slot-specification (specifications &optional name) (let* ((specification (first specifications)) (occurrence (getf specification :count)) count-slot-name) (when name (unless (getf specification :type) ;; Preserve reference for later retrieval. (setf (getf (first specifications) :ref) (getf specification :name))) (setf (getf specification :name) name)) (unless (singletonp specifications) (error "Element declaration \"~A\" has unexpected content." (get-xml-name (getf specification :name)))) (when occurrence (setf count-slot-name (add-lisp-name-suffix (getf specification :name) *count-slot-suffix*) (getf specification :count) count-slot-name) (push `(:name ,count-slot-name :type ,occurrence) (rest specifications))) specifications)) (defun element-slot-specifications (element content) (let ((name (element-attribute element 'name :xsd)) (type (element-attribute element 'xmlxsd::type :xsd)) (ref (element-attribute element 'ref :xsd))) (if (or type ref) ;; Innermost element. (let ((min-occurs (element-attribute element 'min-occurs :xsd)) (max-occurs (element-attribute element 'max-occurs :xsd)) occurrence) (when (or min-occurs max-occurs) (setq occurrence (make-numeric-range :min (convert-lower-bound min-occurs) :max (convert-upper-bound max-occurs)))) (list (list* :name (or name ref) ; May be temporary. :type (if type (ensure-lisp-name type)) (if occurrence (list :count occurrence))))) ;; Outer element. Pick up inner specification; flesh out. (expand-slot-specification content name)))) (defmethod assimilate-content :around (element (element-content list) subelement (tag (eql 'element)) content) (setf (element-content element) (nconc (element-slot-specifications subelement content) element-content))) (defmethod assimilate-content :around (element (element-content list) subelement (tag (eql 'choice)) content) (declare (ignore subelement)) (setf (element-content element) (nconc content element-content))) (defmethod assimilate-content (element (element-content string) subelement (tag (eql 'element)) content) ;; Global element: overwrite schema documentation. (setf (element-content element) (element-slot-specifications subelement content))) (defmethod assimilate-content (element element-content subelement (tag (eql 'restriction)) (content cons)) (let ((name (element-attribute element 'name :xsd)) (superclass (element-attribute subelement 'base :xsd))) (ensure-range-class name :include (case superclass ((nil xmlxsd::string xmlxsd::integer) nil) (t superclass)) :documentation (if (stringp element-content) element-content) :elements content))) (defmethod assimilate-content :around (element element-content subelement (tag (eql 'min-inclusive)) content) (declare (ignore element-content content)) (push (convert-lower-bound (element-attribute subelement 'value :xsd)) (element-content element))) (defmethod assimilate-content :around (element element-content subelement (tag (eql 'max-inclusive)) content) (declare (ignore element-content content)) (push-on-end (element-content element) (convert-upper-bound (element-attribute subelement 'value :xsd)))) (defmethod assimilate-content :around (element element-content subelement (tag (eql 'enumeration)) content) (declare (ignore element-content content)) (push-on-end (element-content element) (element-attribute subelement 'value :xsd))) (defmethod finalize-content (element (tag (eql 'schema)) (content string)) ;; Ignore schema documentation. (finalize-content element tag nil)) (defmethod finalize-content (element (tag (eql 'schema)) (content list)) (declare (ignore element)) (flet ((finish-class (class name &key direct-slots metaclass) (flet ((find-global-specification (specification indicator) (find (getf specification indicator) content :test #'eq :key #'(lambda (specification) (getf specification :name))))) (do ((rest-slots direct-slots (rest rest-slots))) ((endp rest-slots)) (unless (getf (first rest-slots) :type) ;; Global element reference. (setf (getf (first rest-slots) :type) (getf (or (find-global-specification (first rest-slots) :name) ;; Reference from inner element. (prog1 (find-global-specification (first rest-slots) :ref) (remf (first rest-slots) :ref))) :type)))) (ensure-class-using-class (or class (find-class name)) name :direct-slots direct-slots :metaclass metaclass))) (adjust-count-types (class name &key direct-slots metaclass) (declare (ignore name metaclass)) (when class ;; Derived class. (let ((superclass (first (class-direct-superclasses class)))) (dolist (specification direct-slots) (let ((name (getf specification :name)) (type (getf specification :type))) (when (find name direct-slots :test #'eq :key #'(lambda (specification) (getf specification :count))) (let ((slot-definition (find-slot-definition superclass name :direct (not nil)))) (when slot-definition ;; Cardinality restriction. (adjust-count-type type (slot-definition-type slot-definition))))))))))) ;; Local elements. (revdolist (specification (get-class-specifications)) (apply #'finish-class specification)) (dolist (specification (get-class-specifications)) (apply #'adjust-count-types specification)) ;; Global elements. (dolist (specification content) (let ((type (getf specification :type))) (setf (get (getf specification :name) :xml-type) type))))) (let ((element-stack ())) (defun into-xml-element (tag attribute-fn) (push (make-element :tag (get-lisp-name tag) :attribute-fn (or attribute-fn *element-default-attribute-fn*)) element-stack) (unless (or (ignore-element-p (element-tag (first element-stack))) (element-content (first element-stack))) (let ((object (find-element-object (element-tag (first element-stack)) (first element-stack) (rest element-stack)))) (when object (setf (element-content (first element-stack)) object))))) (defun store-xml-content (content) (when content (setf (element-content (first element-stack)) content))) (defun outof-xml-element () (unless (ignore-element-p (element-tag (first element-stack))) (finalize-content (first element-stack) (element-tag (first element-stack)) (element-content (first element-stack))) (when (second element-stack) (assimilate-content (second element-stack) (element-content (second element-stack)) (first element-stack) (element-tag (first element-stack)) (element-content (first element-stack))))) (pop element-stack)) (defun pop-elements () (setq element-stack nil)) ) ;end let element-stack (defmethod deserialize-as-object (element &key (tag-fn nil) ; Tag. (attribute-fn nil) ; Named attribute's value. (content-fn #'cdr) ; List of objects. ) (flet ((element-content (xml-node) (let* ((content (funcall content-fn xml-node)) (textual (stringp (car content)))) (values (if textual (car content) content) textual)))) (map-objects element #'(lambda (xml-node) (multiple-value-bind (content textual) (element-content xml-node) (if textual nil content))) #'(lambda (xml-node) (let (tag attributes) (if tag-fn (setq tag (funcall tag-fn xml-node)) (multiple-value-setq (tag attributes) (parse-tag (car xml-node)))) (into-xml-element tag (cond (attribute-fn #'(lambda (name uri) (funcall attribute-fn xml-node name uri))) (attributes #'(lambda (name uri) (declare (ignore uri)) (cdr (assoc name attributes :test #'eq)))))))) #'(lambda (xml-node) (multiple-value-bind (content textual) (element-content xml-node) (when textual (store-xml-content content))) (outof-xml-element))))) (defmethod deserialize-as-object :around (element &key &allow-other-keys) (declare (ignore element)) (unwind-protect (call-next-method) (pop-elements))) (defmethod deserialize-as-objects ((parse-tree cons) &key (namespace nil) (base namespace) (namespaces *namespace-names*)) (let (*assumptions* (*default-namespace* namespace) (*target-namespace* base) (*namespaces* (if namespace (adjoin namespace namespaces :test #'eq) namespaces))) (dolist (element parse-tree) (deserialize-as-object element)) *assumptions*))
55,076
Common Lisp
.lisp
1,078
37.221707
100
0.585301
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
02f11739acb016ff3c0ccd98d32b5b7e130587cb587d3a2e5e2913507422d871
20,429
[ -1 ]
20,430
slotval.lisp
whounslo_reasoner/src/slotval.lisp
;;; Copyright (C) 2007-2014, 2017 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (in-package reasoner) ;;; Slot values (defclass standard-slot-value (node) ((object :reader datum-object :initarg :object) (slot-name :reader datum-slot :initarg :slot-name) (value :reader datum-value :initarg :value))) (defclass excluded-slot-value (standard-slot-value) ()) (defmethod print-object ((instance standard-slot-value) stream) (print-unreadable-object (instance stream) (format stream "~:(~S~) ~S" (class-name (class-of instance)) (datum-value instance))) instance) (defmethod combine ((n1 standard-slot-value) (n2 standard-slot-value)) "Combine two slot values to yield a single value." (combine1 (datum-value n1) (datum-value n2))) (defmethod combine ((values t) (n standard-slot-value)) "Combine an arbitrary combination of values and a STANDARD-SLOT-VALUE object." (combine1 values (datum-value n))) (defmethod combine ((values null) (n standard-slot-value)) nil) (defmethod combine ((n1 standard-slot-value) (n2 excluded-slot-value)) (combine1 (datum-value n1) n2)) (defmethod combine ((n1 excluded-slot-value) (n2 standard-slot-value)) (combine1 n1 (datum-value n2))) (defmethod combine ((n1 excluded-slot-value) (n2 excluded-slot-value)) (combine1 n1 n2)) (defmethod combine ((values t) (n excluded-slot-value)) "Combine a combination of values and an EXCLUDED-SLOT-VALUE object." (combine1 values n)) (defmethod combine1 ((value1 t) (value2 t)) (if (combinep value1 value2) (list value2 value1))) (defmethod combine1 ((values cons) (value excluded-slot-value)) (combine2 values value)) (defmethod combine2 ((values cons) (value t)) (if (every #'(lambda (element) (combinep element value)) values) (cons value values))) (defmethod combinep ((value t) (n excluded-slot-value)) (not (slot-value-equal value n t))) (defmethod combinep ((n excluded-slot-value) (value t)) (not (slot-value-equal value n t))) (defmethod combinep ((n1 excluded-slot-value) (n2 excluded-slot-value)) (not nil)) (defmethod combinep ((value1 t) (value2 t)) (not nil)) (defmethod slot-value-equal ((value t) (n standard-slot-value) &optional (negatedp nil)) (if negatedp nil (slot-value-equal-1 value n))) (defmethod slot-value-equal ((value t) (n excluded-slot-value) &optional (negatedp nil)) (if negatedp (slot-value-equal-1 value n))) (defmethod slot-value-equal-1 ((value1 t) (value2 standard-slot-value)) (equal value1 (datum-value value2))) (defmethod elements ((node standard-slot-value)) "Returns a list of the value(s) denoted by a standard-slot-value." (list (datum-value node))) (defmethod elements ((node excluded-slot-value)) (list node)) (defconstant contradictory-value '? "The value returned when slot values cannot be combined.") (defun contradictory-value-p (value) (eq value contradictory-value)) ;;; Ranges (defclass range-class (standard-class) ((elements :reader elements :initarg :elements) (external-type :reader direct-external-type :initarg :external-type) (effective-external-type :accessor external-type)) (:default-initargs :external-type nil )) (defmethod direct-external-type ((class t)) nil) (defmethod finalize-inheritance :after ((class range-class)) (let ((superclass (find nil (class-precedence-list class) :key #'direct-external-type :test-not #'eq))) (setf (external-type class) (if superclass (direct-external-type superclass))))) (defmacro range-elements (name) `(elements (find-class ,name))) (defmacro range-external-type (name) `(or (let ((class (find-class ,name))) (unless (class-finalized-p class) (finalize-inheritance class)) (external-type class)) ,name)) (eval-when (:execute #+lispworks :compile-toplevel :load-toplevel) (defmethod validate-superclass ((class range-class) (superclass standard-class)) "Declare compatibility of RANGE-CLASS and standard-class." (not nil)) ) (defclass range (standard-slot-value) ((value :reader elements)) (:metaclass range-class)) ;;; (defclass numeric-range (range) ;;; () ;;; (:metaclass range-class) ;;; (:elements (-big big))) ;;; ;;; (defclass symbolic-range (range) ;;; () ;;; (:metaclass range-class)) #+(or allegro ecl sbcl) (defstruct (numeric-range (:type list)) "A set of consecutive integers." min max) #-(or allegro ecl sbcl) (progn (defmacro make-numeric-range (&key min max) `(list ,min ,max)) (defmacro numeric-range-min (numeric-range) `(car ,numeric-range)) (defmacro numeric-range-max (numeric-range) `(cadr ,numeric-range)) ) (progn (defmacro make-range-set (&key elements) `(cons 'range-set ,elements)) (defmacro range-set-elements (range-set) `(cdr ,range-set)) ) (deftype range-set nil "A set of numeric ranges, representing an arbitrary set of integers." '(satisfies range-set-p)) (defun range-set-p (x) (if (listp x) (eq (car x) 'range-set))) (deftype symbolic-range* nil '(satisfies symbolic-rangep)) (deftype numeric-range* nil '(satisfies numeric-rangep)) (deftype unbounded-number nil '(satisfies unbounded-number-p)) (defmethod symbolic-rangep ((x t)) nil) (defmethod symbolic-rangep ((x list)) (every #'symbolp x)) (defmethod symbolic-rangep ((x null)) nil) (defmethod numeric-rangep ((x t)) nil) (defmethod numeric-rangep ((x list)) (flet ((unbounded-number-p (x) (or (numberp x) (unbounded-number-p x)))) (and (eql (length x) 2) (unbounded-number-p (car x)) (unbounded-number-p (cadr x)) (unbounded>= (cadr x) (car x))))) (defun unbounded-number-p (x) (member x '(big -big) :test #'eq)) (defun slot-value-typep (object type &optional (check-bounds (not (eq type 'symbolic-range)))) "Determines if object is of type, where type may be a range and object a number, symbol, or list thereof." (typecase object ((or number numeric-range*) (and (subtypep type 'numeric-range) (or (not check-bounds) (numeric-subrangep object (range-elements type))))) (symbol (and (subtypep type 'symbolic-range) (or (not check-bounds) (member object (range-elements type) :test #'eq)))) (symbolic-range* (and (subtypep type 'symbolic-range) (or (not check-bounds) (subsetp object (range-elements type) :test #'eq)))) (t ;; True instance or arbitrary Lisp object. (typep object type)))) (defmacro defrange (&rest args) (multiple-value-bind (name include external-type documentation body) (parse-defrange args) `(ensure-range-class ',name :include ',include :external-type ',external-type :documentation ,documentation :elements ',body))) (defun parse-defrange (args) (let* ((options (if (consp (car args)) (cdar args))) (name (if options (caar args) (car args))) (documentation nil) (body (cdr args))) (when (stringp (car body)) (setq documentation (pop body))) (when (and (numberp (car body)) (endp (cdr body))) (setq body (make-numeric-range :min (car body) :max (car body)))) (values name (cadr (assoc :include options :test #'eq)) (cadr (assoc :external-type options :test #'eq)) documentation body))) (defun ensure-range-class-using-class (class class-name &rest initargs &key elements &allow-other-keys) (declare (ignorable elements)) (apply #'ensure-class-using-class class class-name :metaclass 'range-class (nconc #+(and mop (not allegro)) (if elements (list :direct-default-initargs `((:value ',elements ,(constantly elements))))) initargs))) (defun ensure-range-class (name &key include external-type documentation elements &aux (class (find-class name nil))) (labels ((find-include (superclass elements) (or (dolist (subrange (class-direct-subclasses superclass)) (unless (or (eq class subrange) (equal elements (elements subrange))) (when (subsetp elements (elements subrange)) (return (find-include subrange elements))))) superclass))) (let (superclasses) (setq superclasses (list (or (and include (find-class include nil)) (etypecase elements (numeric-range* (find-class 'numeric-range)) (symbolic-range* (find-include (find-class 'symbolic-range) elements)))))) (ensure-range-class-using-class class name :direct-superclasses superclasses :external-type external-type :documentation documentation :elements elements)))) (defun numeric-subrangep (range1 range2) (and (unbounded>= (range-min range1) (range-min range2)) (unbounded<= (range-max range1) (range-max range2)))) (defun numeric-range-intersection (range1 range2) (labels ((numeric-range-intersection-internal (range1 range2) (let ((min (unbounded-max (range-min range1) (range-min range2))) (max (unbounded-min (range-max range1) (range-max range2)))) (cond ((unbounded> min max) nil) ((and (eql min (range-min range1)) (eql max (range-max range1))) range1) ((and (eql min (range-min range2)) (eql max (range-max range2))) range2) (t (make-numeric-range :min min :max max))))) (combine-ranges (element-or-set set &aux (result ())) "Combines two range sets, or a single range with a range set." (do ((element-or-rest-set element-or-set) (is-set (not (numeric-rangep element-or-set))) (rest-set set) element new-element) ((or (and is-set (endp element-or-rest-set)) (endp rest-set))) (setq element (if is-set (car element-or-rest-set) element-or-rest-set) new-element (numeric-range-intersection-internal element (car rest-set))) (when new-element (push new-element result)) (cond ((unbounded> (range-max element) (range-max (car rest-set))) (pop rest-set)) (is-set (pop element-or-rest-set)) (t (return)))) (nreverse result))) (if (or (typep range1 'range-set) (typep range2 'range-set)) (let ((elements (cond ((not (typep range1 'range-set)) (combine-ranges range1 (range-set-elements range2))) ((not (typep range2 'range-set)) (combine-ranges range2 (range-set-elements range1))) (t (combine-ranges (range-set-elements range1) (range-set-elements range2)))))) (cond ((singletonp elements) (car elements)) (elements (make-range-set :elements elements)))) (numeric-range-intersection-internal range1 range2)))) (defun numeric-range-negation (numeric-range) (make-numeric-range :min (unbounded- (range-max numeric-range)) :max (unbounded- (range-min numeric-range)))) (defun numeric-range-union (range1 range2) (let ((min (unbounded-min (range-min range1) (range-min range2))) (max (unbounded-max (range-max range1) (range-max range2)))) (if (unbounded<= min max) (make-numeric-range :min min :max max)))) (defun unary-minus-p (arithmetic-expression) (and (eq (car arithmetic-expression) '-) (endp (cddr arithmetic-expression)))) (defun range-eval (arithmetic-expression) "Evaluator for prefix arithmetic expressions containing ranges." (flet ((numeric-rangep (arithmetic-expression) (or (numberp arithmetic-expression) (unbounded-number-p arithmetic-expression) (range-set-p arithmetic-expression) (numeric-rangep arithmetic-expression)))) (cond ((numeric-rangep arithmetic-expression) arithmetic-expression) ((unary-minus-p arithmetic-expression) (numeric-range-negation (range-eval (cadr arithmetic-expression)))) (t (range-apply (car arithmetic-expression) (range-eval (cadr arithmetic-expression)) (range-eval (caddr arithmetic-expression))))))) (defun range-apply (arithmetic-operator range1 range2 &aux fn) (flet ((unbounded+ (&rest numbers) (macrolet ((memq (item list) `(member ,item ,list :test #'eq))) (cond ((memq 'big numbers) (if (memq '-big numbers) (error "Attempt to add ~S and ~S" 'big '-big) 'big)) ((memq '-big numbers) (if (memq 'big numbers) (error "Attempt to add ~S and ~S" 'big '-big) '-big)) (t (apply #'+ numbers))))) (unbounded* (&rest numbers) ; Currently takes exactly two ; arguments. (let ((min (apply #'unbounded-min numbers)) (max (apply #'unbounded-max numbers))) (cond ((eq min 'big) 'big) ((eq min '-big) (case max (big '-big) (-big 'big) (t (if (plusp max) '-big 'big)))) ((eq max 'big) 'big) (t (apply #'* numbers))))) (unbounded/ (&rest numbers) ; Currently takes exactly two ; arguments. (cond ((eq (first numbers) 'big) (case (second numbers) (big 'big) (-big '-big) (t (if (plusp (second numbers)) 'big '-big)))) ((eq (first numbers) '-big) (case (second numbers) (big '-big) (-big 'big) (t (if (plusp (second numbers)) '-big 'big)))) ((unbounded-number-p (second numbers)) 0) (t (/ (first numbers) (second numbers)))))) (setq fn (ecase arithmetic-operator (+ #'unbounded+) (- #'unbounded-) (* #'unbounded*) (/ #'unbounded/))) (funcall #'(lambda (combinations) (make-numeric-range :min (apply #'unbounded-min combinations) :max (apply #'unbounded-max combinations))) (list (funcall fn (range-min range1) (range-min range2)) (funcall fn (range-max range1) (range-max range2)) (funcall fn (range-min range1) (range-max range2)) (funcall fn (range-max range1) (range-min range2)))))) (defun invert-relation (numeric-relation) (ecase numeric-relation (= '/=) (/= '=) (< '>=) (> '<=) (>= '<) (<= '>))) (defun flip-relation (numeric-relation) (case numeric-relation (< '>) (> '<) (>= '<=) (<= '>=) (t numeric-relation))) (defun numeric-range-disjointp (range-or-set range) (flet ((range-disjointp (range1 range2) (or (unbounded> (range-min range1) (range-max range2)) (unbounded< (range-max range1) (range-min range2))))) (if (numeric-rangep range-or-set) (range-disjointp range-or-set range) (every #'(lambda (element) (range-disjointp element range)) (range-set-elements range-or-set))))) (defun relation-satisfied-p (range1 relation range2) "Determine if relation holds between the two ranges." (ecase relation (= (and (unbounded= (range-min range1) (range-max range1)) (unbounded= (range-min range2) (range-max range2)) (unbounded= (range-min range1) (range-min range2)))) (/= (numeric-range-disjointp range1 range2)) (> (unbounded> (range-min range1) (range-max range2))) (< (unbounded< (range-max range1) (range-min range2))) (>= (unbounded>= (range-min range1) (range-max range2))) (<= (unbounded<= (range-max range1) (range-min range2))))) (defun unbounded1+ (number) (if (unbounded-number-p number) number (1+ (floor number)))) (defun unbounded1- (number) (if (unbounded-number-p number) number (1- (ceiling number)))) (defun satisfy-relation (range relation sub-range) "Returns that sub-range that satisfies a relation between a range and a sub-range." (ecase relation (= (make-numeric-range :min (unbounded-max (range-min range) (range-min sub-range)) :max (unbounded-min (range-max range) (range-max sub-range)))) (/= (satisfy-not-equal range (if (eql (range-min sub-range) (range-max sub-range)) (round (range-min sub-range)) sub-range))) (> (make-numeric-range :min (unbounded1+ (range-min sub-range)) :max (range-max range))) (< (make-numeric-range :min (range-min range) :max (unbounded1- (range-max sub-range)))) (>= (make-numeric-range :min (range-min sub-range) :max (range-max range))) (<= (make-numeric-range :min (range-min range) :max (range-max sub-range))))) (defun satisfy-not-equal (range1 range2) "Returns the sub-range of the first range not contained in the second." (cond ((numeric-range-disjointp range1 range2) ; Disjoint ranges? range1) ((and (unbounded< (range-min range1) (range-min range2)) (unbounded> (range-max range1) (range-max range2))) ; Exclusion of middle? (make-range-set :elements (list (make-numeric-range :min (range-min range1) :max (unbounded1- (range-min range2))) (make-numeric-range :min (unbounded1+ (range-max range2)) :max (range-max range1)))) ; Return two sub-ranges. ) ((unbounded< (range-min range1) (range-min range2)) ; Top of first range overlaps ; bottom of second? (make-numeric-range :min (range-min range1) :max (unbounded1- (range-min range2)))) ((unbounded> (range-max range1) (range-max range2)) ; Top of second range overlaps ; bottom of first? (make-numeric-range :min (unbounded1+ (range-max range2)) :max (range-max range1))) (t (error "Could not determine sub-range of ~S not contained in ~S." range1 range2)))) (defun range-max (x) (etypecase x ((or number unbounded-number) x) (range-set (range-set-max x)) (numeric-range* (numeric-range-max x)))) (defun range-min (x) (etypecase x ((or number unbounded-number) x) (range-set (range-set-min x)) (numeric-range* (numeric-range-min x)))) (defun range-set-max (range-set) "Returns largest of an arbitrary set of integers." (range-max (first (last (range-set-elements range-set))))) (defun range-set-min (range-set) "Returns smallest of an arbitrary set of integers." (range-min (first (range-set-elements range-set)))) (defun unbounded- (number &rest more-numbers) ; Currently takes one or two ; arguments only. (cond ((unbounded-number-p number) (if (eq number (car more-numbers)) (error "Attempt to subtract ~S and ~S" number number) number)) ((eq (car more-numbers) 'big) '-big) ((eq (car more-numbers) '-big) 'big) ((car more-numbers) (- number (car more-numbers))) (t (- number)))) (defun unbounded-max (number &rest more-numbers) (cond ((or (eq number 'big) (member 'big more-numbers :test #'eq)) 'big) ((not (eq number '-big)) (apply #'max number (remove '-big more-numbers :test #'eq))) ((singletonp more-numbers) (car more-numbers)) (t (apply #'max (remove '-big more-numbers :test #'eq))))) (defun unbounded-min (number &rest more-numbers) (cond ((or (eq number '-big) (member '-big more-numbers :test #'eq)) '-big) ((not (eq number 'big)) (apply #'min number (remove 'big more-numbers :test #'eq))) ((singletonp more-numbers) (car more-numbers)) (t (apply #'min (remove 'big more-numbers :test #'eq))))) (defun unbounded< (number &rest more-numbers) ; Currently takes exactly two ; arguments. (unbounded> (car more-numbers) number)) (defun unbounded<= (number &rest more-numbers) ; Currently takes exactly two ; arguments. (not (unbounded> number (car more-numbers)))) (defun unbounded= (number &rest more-numbers) ; Currently takes exactly two ; arguments. (eql number (car more-numbers))) (defun unbounded> (number &rest more-numbers) ; Currently takes exactly two ; arguments. (cond ((eql number (car more-numbers)) nil) ((eq number 'big)) ((eq number '-big) nil) ((eq (car more-numbers) 'big) nil) ((eq (car more-numbers) '-big)) (t (> number (car more-numbers))))) (defun unbounded>= (number &rest more-numbers) ; Currently takes exactly two ; arguments. (not (unbounded< number (car more-numbers)))) ;;; Slot-value combination (defmethod combine ((value t) (r range)) (range-intersection value r)) (defmethod combine ((range1 range) (range2 range)) "Combine two ranges to yield a single range." (range-intersection range1 range2))
25,564
Common Lisp
.lisp
568
30.93838
108
0.520954
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fee747b69f25413e5955967b8f69daeb81af1419f9e7f0b60840b7982a4f875f
20,430
[ -1 ]
20,431
datatype.lisp
whounslo_reasoner/src/datatype.lisp
;;; Copyright (C) 2012, 2013 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; XML Schema built-in datatypes (in-package :reasoner-ext) (defconstant field-missing-indicator 'field-missing) (defun parse-integers (string start end predicate &rest flags) (do ((rest-flags flags (rest rest-flags)) (i 1 (1+ i)) (bound end) (end start) object (integers nil (cons (if (first rest-flags) object 0) integers)) (start start end)) ((endp rest-flags) integers) (when (first rest-flags) (multiple-value-setq (start end) (find-token string start bound #'(lambda (ch) (funcall predicate ch i)))) (setq object (or (parse-integer string :start start :end end :junk-allowed (not nil)) field-missing-indicator))))) ;;; Date, time (defconstant xml-date-separator #\-) (defconstant xml-time-separator #\:) (defconstant xml-date-time-separator #\T) (defconstant xml-time-zone-separator #\+) (defconstant xml-time-zone-indicator #\Z) (defparameter *date-time-encoding-fn* #'encode-universal-time) (defparameter *date-time-decoding-fn* #'decode-universal-time) (defun leap-year-p (year) (and (zerop (mod year 4)) (or (not (zerop (mod year 100))) (zerop (mod year 400))))) (defun last-day (month &optional year) (case month (2 (if (and year (leap-year-p year)) 29 28)) ((9 4 6 11) 30) (t 31))) (defun negativep (object) (declare (type string object)) (eq (char object 0) #\-)) (defun parse-date-time (string start end &rest flags &aux integers) (setq integers (apply #'parse-integers string start end #'(lambda (ch i) (cond ((eq ch xml-date-separator) (or (< i 5) (> i 5))) ; Also a time zone separator. ((eq ch xml-date-time-separator) (or (= i 3) (= i 4))) ((eq ch xml-time-separator) (> i 3)) ((eq ch xml-time-zone-separator) (or (> i 1) (< i 5) (> i 5))) ((eq ch xml-time-zone-indicator) (= i 6)))) flags)) (when (find field-missing-indicator integers :start 1) (error "Malformed date or time encountered: ~A." string)) (cond ((eq (first integers) field-missing-indicator) (setf (first integers) 0)) ((find xml-time-zone-separator string) (setf (first integers) (- (first integers))))) (when (negativep string) (let ((last (last integers))) (setf (first last) (- (first last))))) (values-list integers)) (defmacro convert-to-universal-time (&rest args) `(funcall *date-time-encoding-fn* ,@args)) (defmacro convert-from-universal-time (&rest args) `(funcall *date-time-decoding-fn* ,@args)) (defmacro make-time-range (&key min max) `(make-numeric-range :min (min ,min ,max) :max (max ,min ,max))) (defrange date-time -big big) (defrange xmlxsd::time -big big) (defrange date -big big) (defrange g-year-month -big big) (defrange g-year -big big) (defrange g-month-day -big big) (defrange g-day -big big) (defrange g-month -big big) (defmethod parse-as-type ((object string) (datatype (eql 'date-time)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end t t t t t t t) (convert-to-universal-time sec min hour day month year zone))) (defmethod parse-as-type ((object string) (datatype (eql 'xmlxsd::time)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end nil nil nil t t t t) (declare (ignore day month year)) (convert-to-universal-time sec min hour 1 1 1900 zone))) (defmethod parse-as-type ((object string) (datatype (eql 'date)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end t t t nil nil nil t) (declare (ignore sec min hour)) (make-time-range :min (convert-to-universal-time 0 0 0 day month year zone) :max (convert-to-universal-time 59 59 23 day month year zone)))) (defmethod parse-as-type ((object string) (datatype (eql 'g-year-month)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end t t nil nil nil nil t) (declare (ignore sec min hour day)) (make-time-range :min (convert-to-universal-time 0 0 0 1 month year zone) :max (convert-to-universal-time 59 59 23 (last-day month year) month year zone)))) (defmethod parse-as-type ((object string) (datatype (eql 'g-year)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end t nil nil nil nil nil t) (declare (ignore sec min hour day month)) (make-time-range :min (convert-to-universal-time 0 0 0 1 1 year zone) :max (convert-to-universal-time 59 59 23 31 12 year zone)))) (defmethod parse-as-type ((object string) (datatype (eql 'g-month-day)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end nil t t nil nil nil t) (declare (ignore sec min hour year)) (make-time-range :min (convert-to-universal-time 0 0 0 day month 1900 zone) :max (convert-to-universal-time 59 59 23 day month 1900 zone)))) (defmethod parse-as-type ((object string) (datatype (eql 'g-day)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end nil nil t nil nil nil t) (declare (ignore sec min hour month year)) (make-time-range :min (convert-to-universal-time 0 0 0 day 1 1900 zone) :max (convert-to-universal-time 59 59 23 day 1 1900 zone)))) (defmethod parse-as-type ((object string) (datatype (eql 'g-month)) start end) (multiple-value-bind (zone sec min hour day month year) (parse-date-time object start end nil t nil nil nil nil t) (declare (ignore sec min hour day year)) (make-time-range :min (convert-to-universal-time 0 0 0 1 month 1900 zone) :max (convert-to-universal-time 59 59 23 (last-day month) month 1900 zone)))) (defmethod range-to-content (value slot-type (datatype (eql 'date))) (declare (ignore slot-type)) value) (defmethod range-to-content (value slot-type (datatype (eql 'g-year-month))) (declare (ignore slot-type)) value) (defmethod range-to-content (value slot-type (datatype (eql 'g-year))) (declare (ignore slot-type)) value) (defmethod range-to-content (value slot-type (datatype (eql 'g-month-day))) (declare (ignore slot-type)) value) (defmethod range-to-content (value slot-type (datatype (eql 'g-day))) (declare (ignore slot-type)) value) (defmethod range-to-content (value slot-type (datatype (eql 'g-month))) (declare (ignore slot-type)) value) (defun print-date-time (object has-time has-day has-month has-year) (let (zone sec min hour day month year) (multiple-value-setq (sec min hour day month year) (convert-from-universal-time object)) (unless has-time (unless (zerop hour) ;; Recoverable timezone. (setq zone (multiple-value-bind (quot rem) (round hour 24) (declare (ignore quot)) rem)) (when (minusp zone) (multiple-value-setq (sec min hour day month year) (convert-from-universal-time object zone))))) (format t "~:[~;-~]~@[~4,'0D~]~:[~;-~]~@[~2,'0D~]~:[~;-~]~@[~2,'0D~]~ ~:[~2*~;~:[-~;+~]~2,'0D:00~]~:[~;T~]~:[~;~2,'0D:~2,'0D:~2,'0DZ~]" (or (minusp year) (and (not has-year) (or has-month has-day))) (and has-year year) (or has-month has-day) (and has-month month) has-day (and has-day day) zone (and zone (minusp zone)) (and zone (abs zone)) (and has-day has-time) has-time hour min sec))) (defmethod print-as-type ((object number) (datatype (eql 'date-time))) (print-date-time object t t t t)) (defmethod print-as-type ((object number) (datatype (eql 'xmlxsd::time))) (print-date-time object t nil nil nil)) (defmethod print-as-type ((object number) (datatype (eql 'date))) (print-date-time object nil t t t)) (defmethod print-as-type ((object number) (datatype (eql 'g-year-month))) (print-date-time object nil nil t t)) (defmethod print-as-type ((object number) (datatype (eql 'g-year))) (print-date-time object nil nil nil t)) (defmethod print-as-type ((object number) (datatype (eql 'g-month-day))) (print-date-time object nil t t nil)) (defmethod print-as-type ((object number) (datatype (eql 'g-day))) (print-date-time object nil t nil nil)) (defmethod print-as-type ((object number) (datatype (eql 'g-month))) (print-date-time object nil nil t nil)) (defmethod print-as-type ((object cons) (datatype (eql 'date))) (print-as-type (range-min object) datatype)) (defmethod print-as-type ((object cons) (datatype (eql 'g-year-month))) (print-as-type (range-min object) datatype)) (defmethod print-as-type ((object cons) (datatype (eql 'g-year))) (print-as-type (range-min object) datatype)) (defmethod print-as-type ((object cons) (datatype (eql 'g-month-day))) (print-as-type (range-min object) datatype)) (defmethod print-as-type ((object cons) (datatype (eql 'g-day))) (print-as-type (range-min object) datatype)) (defmethod print-as-type ((object cons) (datatype (eql 'g-month))) (print-as-type (range-min object) datatype)) ;;; Duration (defconstant xml-duration-year-indicator #\Y) (defconstant xml-duration-month-indicator #\M) (defconstant xml-duration-day-indicator #\D) (defconstant xml-duration-hour-indicator #\H) (defconstant xml-duration-min-indicator #\M) (defconstant xml-duration-sec-indicator #\S) (let ((min-month-days #(0 28 59 89 120 150 181 212 242 273 303 334)) (max-month-days #(0 31 62 92 123 153 184 215 245 276 306 337))) (defun month-days-table (maximizing) (if maximizing max-month-days min-month-days)) ) ;end let min-month-days (defmacro months-to-days (months maximizing) `(aref (month-days-table ,maximizing) ,months)) (defmacro days-to-months (days maximizing) `(position ,days (month-days-table ,maximizing) :test #'>= :from-end (not nil))) (defun convert-to-seconds (maximizing neg secs mins hours days months years) (flet ((leap-years-in (years maximizing) (let (leap-years years-over leap-centuries centuries-over) (multiple-value-setq (leap-years years-over) (truncate years 4)) (multiple-value-setq (leap-centuries centuries-over) (truncate years 400)) (decf leap-years (- (truncate years 100) leap-centuries)) (when maximizing (when (plusp years-over) (incf leap-years)) (when (plusp centuries-over) (incf leap-years))) leap-years))) (multiple-value-bind (year-months months-over) (truncate months 12) (* (if neg -1 1) (+ secs (* mins 60) (* hours 60 60) (* (+ days (months-to-days months-over maximizing) (leap-years-in (+ years year-months) maximizing)) 24 60 60) (* years 365 24 60 60)))))) (defrange duration -big big) (defmethod parse-as-type ((object string) (datatype (eql 'duration)) start end) (let (integers (neg (negativep object))) (setq integers (parse-integers object (if neg (1+ start) start) end #'(lambda (ch i) (declare (ignore i)) (alpha-char-p ch)) (find xml-duration-year-indicator object) (find xml-duration-month-indicator object :end (or (position xml-date-time-separator object) end)) (find xml-duration-day-indicator object) (find xml-duration-hour-indicator object) (find xml-duration-min-indicator object :start (or (position xml-date-time-separator object) end)) (find xml-duration-sec-indicator object))) (when (find field-missing-indicator integers) (error "Malformed duration encountered: ~A." object)) (make-time-range :min (apply #'convert-to-seconds nil neg integers) :max (apply #'convert-to-seconds 'maximizing neg integers)))) (defmethod range-to-content (value slot-type (datatype (eql 'duration))) (declare (ignore slot-type)) value) (defun decompose-duration (duration maximizing) (flet ((years-in (days maximizing) (do ((periods '(400 100 4 1) (rest periods)) (extra-days '(97 24 1 0) (rest extra-days)) (days-over days) (years 0 (+ years (* n (first periods)))) n) ((endp periods) (values years days-over)) (multiple-value-setq (n days-over) (truncate days-over (+ (* (first periods) 365) (first extra-days)))) (when maximizing (when (case (first periods) (100 (plusp n)) (4 (> days-over 365))) (decf days-over)))))) (let (secs mins hours days months years) (multiple-value-setq (mins secs) (truncate duration 60)) (multiple-value-setq (hours mins) (truncate mins 60)) (multiple-value-setq (days hours) (truncate hours 24)) (multiple-value-setq (years days) (years-in days maximizing)) (setq months (days-to-months days maximizing) days (- days (months-to-days months maximizing))) (values secs mins hours days months years)))) (defmethod print-as-type ((object cons) (datatype (eql 'duration))) (let (secs has-secs mins hours days months has-months years) (multiple-value-setq (secs mins hours days months years) (decompose-duration (min (abs (range-min object)) (abs (range-max object))) nil)) (setq has-months (and (or (plusp years) (/= (range-min object) (range-max object))) (plusp months)) has-secs (or (zerop (range-min object)) (plusp secs))) (unless has-months (setq days (+ days (months-to-days months nil)))) (format t "~:[~;-~]P~@[~DY~]~@[~DM~]~@[~DD~]~:[~;T~]~@[~DH~]~@[~DM~]~@[~DS~]" (minusp (range-min object)) (and (plusp years) years) (and has-months months) (and (plusp days) days) (or (plusp hours) (plusp mins) has-secs) (and (plusp hours) hours) (and (plusp mins) mins) (and has-secs secs))))
15,770
Common Lisp
.lisp
325
38.344615
87
0.592246
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a81b26bc8076a04f54d09cbc6abfe7bf59aac136d70049aef0eb01575e57136b
20,431
[ -1 ]
20,432
prop.lisp
whounslo_reasoner/src/prop.lisp
;;; Copyright (C) 2007-2011, 2013, 2014 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (in-package reasoner) (defclass proposition () ((attribute-references :initform nil :accessor attribute-references :initarg attribute-references) (class-consumer :accessor class-consumer) (negatedp :initform nil :initarg negatedp) (node-cache :initform nil :accessor node-cache :documentation "Cache for nodes that have matched proposition."))) (defclass arithmetic-proposition (proposition) ((relation :reader relation :initarg relation) (prefix-rhs :reader prefix-rhs :initarg prefix-rhs) (source-proposition :reader source-proposition :initarg source-proposition :documentation "Proposition corresponding to source expression, if different.")) (:default-initargs source-proposition nil )) (defclass functional-proposition (proposition) ((relation :reader relation :initarg relation) (function-name :reader function-name :initarg function-name) (arguments :reader arguments :initarg arguments)) (:default-initargs arguments nil )) (defclass lisp-proposition (proposition) ((function-name :reader function-name :initarg function-name) (arguments :reader arguments :initarg arguments))) (defclass literal-proposition (proposition) ((value :reader value :initarg value))) (defclass numeric-proposition (proposition) ((value :reader value :initarg value))) (defclass relational-proposition (proposition) ((specializer :reader proposition-specializer :initarg specializer))) (defmethod head-attribute-reference ((p arithmetic-proposition)) (car (last (attribute-references p)))) (defmethod head-attribute-reference ((p functional-proposition)) (car (last (attribute-references p)))) (defun lastp (item list &key (test #'eq)) "Determines if item is last in list." (endp (cdr (member item list :test test)))) (defun head-attribute-reference-p (attribute-reference proposition) "Determines if attribute reference stands to be asserted into if proposition forms the head of a class-consumer." (lastp attribute-reference (attribute-references proposition))) ;;; (defstruct (attribute-reference (:conc-name nil) (:type list)) ;;; attribute-reference-variable attribute-name) (progn (defmacro make-attribute-reference (&key attribute-reference-variable attribute-name) `(list ,attribute-reference-variable ,attribute-name)) (defmacro attribute-reference-variable (attribute-reference) `(car ,attribute-reference)) (defmacro attribute-name (attribute-reference) `(cadr ,attribute-reference)) ) ;;; (defstruct (variable (:type list)) ;;; name class-name) (progn (defmacro make-variable (&key name class-name) `(list ,name ,class-name)) (defmacro variable-name (variable) `(car ,variable)) (defmacro variable-class-name (variable) `(cadr ,variable)) ) (deftype attribute-reference nil '(satisfies attribute-reference-p)) (deftype variable nil '(satisfies variablep)) (defmethod attribute-reference-p ((x t)) nil) (defmethod attribute-reference-p ((x list)) (and (variablep (attribute-reference-variable x)) (attribute-name x) (symbolp (attribute-name x)))) (defmethod attribute-reference-p ((x null)) nil) (defmacro attribute-reference-variable-name (attribute-reference) `(variable-name (attribute-reference-variable ,attribute-reference))) (defun attribute-reference-class (attribute-reference) (find-class (variable-class-name (attribute-reference-variable attribute-reference)))) (defmethod variablep ((x t)) nil) (defmethod variablep ((x list)) (and (symbolp (variable-class-name x)) (find-class (variable-class-name x) nil))) (defmethod variablep ((x null)) nil) ;;; Proposition initialization (defmethod initialize-instance :after ((p arithmetic-proposition) &rest initargs) (collect-rhs-attribute-references p (getf initargs 'prefix-rhs))) (defmethod initialize-instance :after ((p functional-proposition) &rest initargs) (collect-rhs-attribute-references p (getf initargs 'arguments))) (defmethod initialize-instance :after ((p lisp-proposition) &rest initargs) (collect-rhs-attribute-references p (getf initargs 'arguments))) (defun collect-rhs-attribute-references (proposition arithmetic-expression) "Attribute references found in the prefix arithmetic expression are consed onto the list of attribute references for the proposition." (typecase arithmetic-expression (attribute-reference (pushnew arithmetic-expression (attribute-references proposition) :test #'equal)) (list (dolist (sub-expression arithmetic-expression) (collect-rhs-attribute-references proposition sub-expression))))) ;;; Manipulation of propositions prior to indexing (defmethod negate ((p proposition)) (copy-instance p 'negatedp (not nil))) (defmethod negate ((p numeric-proposition)) (if (slot-value p 'negatedp) (let ((p (copy-instance p))) (setf (slot-value p 'negatedp) nil) p) (call-next-method))) (defmethod disjoin ((p1 proposition) (p2 proposition)) nil) (defmethod disjoin ((p1 numeric-proposition) (p2 numeric-proposition)) (flet ((value (numeric-proposition) (if (slot-value numeric-proposition 'negatedp) (satisfy-not-equal (attribute-values (car (attribute-references numeric-proposition))) (value numeric-proposition)) (value numeric-proposition)))) (let (new-value) (if (and (eq (attribute-name (car (attribute-references p1))) (attribute-name (car (attribute-references p2)))) (setq new-value (numeric-range-union (value p1) (value p2)))) (copy-instance p1 'value new-value 'negatedp nil))))) (defmethod disjoin ((p1 literal-proposition) (p2 literal-proposition)) (flet ((attribute-reference (literal-proposition) (car (last (attribute-references literal-proposition)))) (value (literal-proposition) (let* ((attribute-values (attribute-values (car (attribute-references literal-proposition)))) (value (if (slot-boundp literal-proposition 'value) (value literal-proposition) attribute-values ; Note: disjoined proposition ; will be tautologous. ))) (if (slot-value literal-proposition 'negatedp) (set-difference attribute-values value :test #'eq) value)))) (let (new-value) (if (and (eq (attribute-name (attribute-reference p1)) (attribute-name (attribute-reference p2))) (setq new-value (union (value p1) (value p2)))) (copy-instance p1 'value new-value 'negatedp nil))))) (defmethod tautologousp ((p proposition)) nil) (defmethod tautologousp ((p literal-proposition)) (subsetp (attribute-values (car (last (attribute-references p)))) (value p))) (defmethod tautologousp ((p numeric-proposition)) (numeric-subrangep (attribute-values (car (attribute-references p))) (value p))) (defmethod rewrite ((p proposition)) (list p)) (defmethod rewrite ((p arithmetic-proposition) &aux flip-count) "Return list of propositions representing all possible ways of writing arithmetic expression." (labels ((rewrite-expression (rhs target-lhs lhs) "Rewrites expression LHS = RHS with target expression (currently part of the RHS) as the LHS; returns RHS." (flet ((rewrite (operator argument1 argument2 rhs) "Returns an expression for evaluating an unknown argument (notated by ?) of a binary operator whose result is RHS." (flet ((invert (operator) (ecase operator (+ '-) (- '+) (* '/) (/ '*)))) (cond ((eq argument1 '?) (list (invert operator) rhs argument2)) ((member operator '(* +) :test #'eq) (list (invert operator) rhs argument1)) (t (list operator argument1 rhs)))))) (setq flip-count 0) (cond ((unary-minus-p rhs) (rewrite-expression (cadr rhs) target-lhs (list '- lhs))) ((operatorp (car rhs)) (let ((operator (car rhs)) (left (cadr rhs)) (right (caddr rhs))) (or (rewrite-expression left target-lhs (rewrite operator '? right lhs)) (let* ((expr (rewrite operator left '? lhs)) (expression (rewrite-expression right target-lhs expr))) (when (and (eq (car expr) operator) expression) (incf flip-count)) expression)))) ((equal rhs target-lhs) lhs))))) (let ((relation (relation p)) (prefix-rhs (prefix-rhs p)) (head-attribute-reference (head-attribute-reference p))) (cons p (mapcar #'(lambda (attribute-reference) (copy-instance p 'prefix-rhs (rewrite-expression prefix-rhs attribute-reference head-attribute-reference) 'relation (if (oddp flip-count) relation (flip-relation relation)) 'source-proposition p 'attribute-references (list attribute-reference))) (butlast (attribute-references p))))))) ;;; Proposition indexing (defmethod index ((p proposition) attribute-reference) "Index proposition so that its class-consumer will be triggered by incoming assertions corresponding to attribute-reference." ;; Index each attribute reference once only per consumer. (pushnew (list p attribute-reference) (gethash (attribute-name attribute-reference) (class-rule-index (attribute-reference-class attribute-reference))) :test #'(lambda (node-class-1 node-class-2) (and (equal (second node-class-1) (second node-class-2)) (eq (class-consumer (first node-class-1)) (class-consumer (first node-class-2))))))) (defmethod index ((p relational-proposition) attribute-reference) "Index proposition so that its class-consumer will be triggered by incoming assertions corresponding to attribute-reference." ;; Multiple relational propositions within a consumer may have the same ;; attribute reference, but their specializers will (should) be ;; different. So index them all. (push (list p attribute-reference) (gethash (attribute-name attribute-reference) (class-rule-index (attribute-reference-class attribute-reference))))) (defmethod index-head ((p proposition) attribute-reference) "Index proposition as potentially affecting slots corresponding to attribute-reference." (push (list p attribute-reference) (gethash (attribute-name attribute-reference) (class-rule-head-index (attribute-reference-class attribute-reference))))) (defmethod remove-head-index ((p proposition) attribute-reference) (unless (setf (gethash (attribute-name attribute-reference) (class-rule-head-index (attribute-reference-class attribute-reference))) (delete (list p attribute-reference) (gethash (attribute-name attribute-reference) (class-rule-head-index (attribute-reference-class attribute-reference))) :test #'equal)) (remhash (attribute-name attribute-reference) (class-rule-head-index (attribute-reference-class attribute-reference))))) (defmethod remove-index ((p proposition) attribute-reference) (unless (setf (gethash (attribute-name attribute-reference) (class-rule-index (attribute-reference-class attribute-reference))) (delete (list p attribute-reference) (gethash (attribute-name attribute-reference) (class-rule-index (attribute-reference-class attribute-reference))) :test #'equal)) (remhash (attribute-name attribute-reference) (class-rule-index (attribute-reference-class attribute-reference))))) ;;; Matching propositions (defmacro first-conjunct (conjuncts) `(car ,conjuncts)) (defmacro rest-conjuncts (conjuncts) `(cdr ,conjuncts)) (defmethod conjoinedp ((p proposition) rest-conjuncts) (declare (special head-proposition-p)) (or (and head-proposition-p (not (rest-conjuncts rest-conjuncts))) ; Just the head attribute ; reference remaining? (not (first-conjunct rest-conjuncts)))) (defmethod conjoinedp ((p lisp-proposition) rest-conjuncts) ;; Lisp propositions do not have a distinguished head attribute ;; reference. (not (first-conjunct rest-conjuncts))) (defmethod conjoin ((p proposition) attribute-references initial-frame-stream) "Takes the attribute references (from proposition) and frame-stream and returns the stream of extended frames." (declare (special head-proposition-p)) (do ((rest-conjuncts attribute-references (rest-conjuncts rest-conjuncts)) (frame-stream initial-frame-stream ;; Filter the stream of frames by finding the stream of all ;; possible extensions to the first conjunct, to use as new ;; frame-stream for rest of conjuncts. (assertedp p (first-conjunct rest-conjuncts) frame-stream)) (remaining-attribute-references attribute-references rest-conjuncts) (old-frame-stream initial-frame-stream frame-stream)) ((empty-stream-p frame-stream) ;; Failure. (values p ; Failed proposition. (first-conjunct remaining-attribute-references) ; Attribute reference within ; proposition not matched. old-frame-stream ; Bindings accumulated up to ; point of failure. )) (when (conjoinedp p rest-conjuncts) ;; Finished matching a proposition in the tail or head of a ;; class-consumer. (return (values p nil frame-stream))))) (defmethod assertedp ((p proposition) attribute-reference frame-stream) "Returns the stream formed by extending each frame by all the matches of attribute reference." (mapcan #'(lambda (frame) (find-assertions p attribute-reference frame)) frame-stream)) (defmethod find-assertions ((p proposition) attribute-reference frame) "Returns stream of frames that extend frame by a match of attribute reference." (mapcan #'(lambda (datum) (pattern-match p attribute-reference datum frame)) (fetch-assertions p attribute-reference frame))) (defmethod pattern-match ((p proposition) attribute-reference datum frame) "Takes an attribute reference, a data object and a frame and returns either a one-element stream, or THE-EMPTY-STREAM if the match fails." (let ((result (internal-match p attribute-reference datum frame))) (if (eq result 'failed) the-empty-stream (singleton result)))) (defmethod internal-match ((p proposition) attribute-reference datum frame) "Returns either the symbol FAILED or an extension of the given frame." (if (or (not (head-attribute-reference-p attribute-reference p)) ; Just accumulate binding? (satisfiesp datum p frame) ; Test proposition against ; datum, using accumulated ; bindings for any other ; attribute references in ; proposition. ) (extend-if-consistent p attribute-reference datum frame) 'failed)) (defmethod internal-match ((p lisp-proposition) attribute-reference datum frame) "Returns either the symbol FAILED or an extension of the given frame." ;; Accumulate all the bindings before testing. (declare (special head-proposition-p)) (let ((extended-frame (extend-if-consistent p attribute-reference datum frame))) (if (or head-proposition-p ; If in the head, all attribute ; references are being matched, ; so be sure not to test. (not (head-attribute-reference-p attribute-reference p)) ; Just accumulate binding? (satisfiesp datum p extended-frame) ; Test proposition against ; datum, using accumulated ; bindings for attribute ; references in proposition. ) extended-frame 'failed))) (defmethod extend-if-consistent ((p proposition) attribute-reference datum frame) "Extend frame by adding bindings for attribute reference and single variable within attribute reference, if not bound." (if (eq (lookup-in-frame attribute-reference frame) datum) ; Is there a binding for the ; attribute reference? We ; examine the binding because, ; in the case of multiple ; relational propositions with ; the same attribute reference, ; we must accumulate a binding ; for each one. frame (extend attribute-reference datum (if (binding-in-frame (attribute-reference-variable-name attribute-reference) frame) ; Is there a binding for the ; variable? frame (extend (attribute-reference-variable-name attribute-reference) (datum-object datum) frame) ; Extend frame by adding ; variable binding. )) ; Extend frame by adding ; attribute reference binding. )) (defmethod extend-if-consistent ((p relational-proposition) attribute-reference datum frame) "Extend frame by adding binding for variable that specializes proposition, if not bound." (declare (ignore attribute-reference)) (if (binding-in-frame (variable-name (proposition-specializer p)) frame) (call-next-method) (extend (variable-name (proposition-specializer p)) (datum-value datum) (call-next-method)))) (defmethod satisfiesp ((node standard-slot-value) (p literal-proposition) frame) (flet ((disjointp (list1 list2) (notany #'(lambda (element) (member element list1 :test #'eq)) list2))) (let ((other-node (if (slot-boundp p 'value) nil (lookup-in-frame (car (attribute-references p)) frame)))) (if (and other-node (eq node other-node)) nil ; The proposition is ; tautologous if the two ; attribute references are ; bound to the same node. (let ((value (if other-node (elements other-node) (value p))) (datum-value (elements node))) (cond ((negatedp p (class-consumer p)) (disjointp datum-value value)) ((not other-node) (subsetp datum-value value)) ((and (singletonp datum-value) (singletonp value)) (equal datum-value value)))))))) (defmethod satisfiesp ((node standard-slot-value) (p numeric-proposition) frame) (declare (ignore frame)) (if (negatedp p (class-consumer p)) (numeric-range-disjointp (elements node) (value p)) (numeric-subrangep (elements node) (value p)))) (defmethod satisfiesp ((node standard-slot-value) (p arithmetic-proposition) frame) (relation-satisfied-p (elements node) (if (negatedp p (class-consumer p)) (invert-relation (relation p)) (relation p)) (range-eval (instantiate (prefix-rhs p) frame)))) (defmethod satisfiesp ((node standard-slot-value) (p functional-proposition) frame) (relation-satisfied-p (elements node) (if (negatedp p (class-consumer p)) (invert-relation (relation p)) (relation p)) (let ((function (ecase (function-name p) (min #'unbounded-min) (max #'unbounded-max))) (arguments (instantiate (arguments p) frame))) (make-numeric-range :min (apply function (mapcar #'range-min arguments)) :max (apply function (mapcar #'range-max arguments)))))) (defmethod satisfiesp ((node standard-slot-value) (p relational-proposition) frame) (if (negatedp p (class-consumer p)) nil (let ((specializer-binding (binding-in-frame (variable-name (proposition-specializer p)) frame))) (if specializer-binding (eq (datum-value node) (binding-value specializer-binding)) (typep (datum-value node) (variable-class-name (proposition-specializer p))))))) (defmethod satisfiesp ((node excluded-slot-value) (p relational-proposition) frame) (if (negatedp p (class-consumer p)) (let ((specializer-binding (binding-in-frame (variable-name (proposition-specializer p)) frame))) (if specializer-binding (eq (datum-value node) (binding-value specializer-binding)) (typep (datum-value node) (variable-class-name (proposition-specializer p))))))) (defmethod satisfiesp ((node standard-slot-value) (p lisp-proposition) frame) (funcall (if (negatedp p (class-consumer p)) #'not #'identity) (apply (function-name p) (mapcar #'(lambda (expression) (instantiate expression frame)) (arguments p))))) (defun fetch-assertions (proposition attribute-reference frame) "Return assertions that are potential matches for attribute reference, taking advantage of the information in frame." (if (use-index-p attribute-reference frame) (get-indexed-assertions proposition attribute-reference) (get-all-assertions proposition attribute-reference frame))) (defun use-index-p (attribute-reference frame) "Returns non-nil if variable in attribute reference is not bound in frame." (null (binding-in-frame (attribute-reference-variable-name attribute-reference) frame))) (defmethod get-all-indexed-assertions ((p proposition) attribute-reference) "Use cache to locate assertions that may match attribute reference." (cdr (assoc attribute-reference (node-cache p) :test #'eq))) (defmethod get-indexed-assertions ((p proposition) attribute-reference) "Use cache to locate assertions that may match attribute reference." (let ((class (attribute-reference-class attribute-reference)) (nodes (get-all-indexed-assertions p attribute-reference))) (flet ((invalid-datum-p (node) (not (typep (datum-object node) class)))) (if (some #'invalid-datum-p nodes) ;; If class-changing has been used, nodes that were once potential ;; matches may no longer be so; these are removed here. (remove-if #'invalid-datum-p nodes) nodes)))) (defmethod add-to-cache ((node standard-slot-value) (p proposition) attribute-reference &optional tentative) "Add to cache of nodes that have matched proposition." (let ((attribute-reference-bucket (assoc attribute-reference (node-cache p) :test #'eq))) (when (and tentative (find node (cdr attribute-reference-bucket) :test #'eq)) (return-from add-to-cache nil)) (if attribute-reference-bucket (push node (cdr attribute-reference-bucket)) (push (list attribute-reference node) (node-cache p))) node)) (defmethod remove-from-cache ((node standard-slot-value) (p proposition) attribute-reference) "Remove from cache of nodes that have matched proposition." (let* ((proposition-bucket (node-cache p)) (attribute-reference-bucket (assoc attribute-reference proposition-bucket :test #'eq))) (delete node attribute-reference-bucket :test #'eq) (or (cdr attribute-reference-bucket) (setf (node-cache p) (delete attribute-reference-bucket proposition-bucket :test #'eq))) node)) (defmethod get-all-assertions ((p proposition) attribute-reference frame) "Use bindings in frame to locate assertions that may match attribute reference." (let ((value (lookup-in-frame attribute-reference frame))) (if value (singleton value) ; Attribute reference itself is ; bound; just return binding. (get-all-assertions-1 p attribute-reference frame)))) (defmethod get-all-assertions ((p relational-proposition) attribute-reference frame) "Use bindings in frame to locate assertions that may match attribute reference." ;; We cannot simply return the binding of attribute reference, if it is ;; bound: the binding for one relational proposition won't satisfy ;; another (they will have different specializers). (get-all-assertions-1 p attribute-reference frame)) (defun get-all-assertions-1 (proposition attribute-reference frame) "Access object that is binding of variable in attribute reference." ;; Nodes that have yet to be matched against their class consumers, and so ;; are not in the node cache (see GET-INDEXED-ASSERTIONS), must be removed to ;; prevent duplicate firing of class-consumers. (let ((object (lookup-in-frame (attribute-reference-variable-name attribute-reference) frame)) (slot-name (attribute-name attribute-reference))) (if (slot-exists-p object slot-name) ; Culprits are relational proposition ; specializer bindings: see ; INITIALLY-SATISFIES-P. (intersection (all-slot-values object slot-name) (get-indexed-assertions proposition attribute-reference) :test #'eq)))) ;;; Asserting propositions (defmethod satisfy ((p literal-proposition) frame antecedents informant) (let ((attribute-reference (car (last (attribute-references p)))) value object) (when (and (if (slot-boundp p 'value) (setq value (value p)) (singletonp (setq value (elements (lookup-in-frame (car (attribute-references p)) frame))))) (setq object (lookup-in-frame (attribute-reference-variable-name attribute-reference) frame))) (add-slot-value object (attribute-name attribute-reference) (if (negatedp p (class-consumer p)) (set-difference (attribute-values attribute-reference) value :test #'eq) value) antecedents informant)))) (defmethod satisfy ((p numeric-proposition) frame antecedents informant &aux object) (with-slots (attribute-references value) p (when (setq object (lookup-in-frame (attribute-reference-variable-name (car attribute-references)) frame)) (add-slot-value object (attribute-name (car attribute-references)) (if (negatedp p (class-consumer p)) (satisfy-not-equal (attribute-values (car attribute-references)) value) value) antecedents informant)))) (eval-when (:execute :compile-toplevel) (defmethod make-load-form ((object numeric-range) &optional environment) (declare (ignore environment)) `(make-instance ',(class-of object))) ) (defmethod satisfy ((p arithmetic-proposition) frame antecedents informant &aux head-attribute-reference head-attribute-values object) (flet ((rhs-minusp (attribute-reference) (if (eq attribute-reference head-attribute-reference) nil (unbounded< (range-max (elements (lookup-in-frame attribute-reference frame))) 0))) (extend (attribute-reference value frame) (let ((range #.(make-instance 'numeric-range))) (reinitialize-instance range :value (if (eql (range-min value) (range-min head-attribute-values)) (range-max value) (range-min value))) (extend attribute-reference range frame)))) (setq head-attribute-reference (head-attribute-reference p) head-attribute-values (attribute-values head-attribute-reference) object (lookup-in-frame (attribute-reference-variable-name head-attribute-reference) frame)) (when object (let ((relation (if (negatedp p (class-consumer p)) (invert-relation (relation p)) (relation p))) (source-proposition (source-proposition p)) (rhs-value (range-eval (instantiate (prefix-rhs p) frame))) value) ;; Ensure that we have the right end of the range. Unsubtle but guaranteed. (when (and (not (member relation '(= /=))) source-proposition (some #'rhs-minusp (attribute-references p))) (unless (member relation '(<= >=)) (setq value (satisfy-relation head-attribute-values relation rhs-value))) (let ((attribute-reference-value (lookup-in-frame (head-attribute-reference source-proposition) frame)) (frame (extend head-attribute-reference (or value (satisfy-relation head-attribute-values (if (eq relation '<=) '< '>) rhs-value)) frame))) (unless (satisfiesp attribute-reference-value source-proposition frame) (setq value (satisfy-relation head-attribute-values (flip-relation relation) rhs-value))))) (add-slot-value object (attribute-name head-attribute-reference) (or value (satisfy-relation head-attribute-values relation rhs-value)) antecedents informant))))) (defmethod satisfy ((p functional-proposition) frame antecedents informant &aux head-attribute-reference object) (setq head-attribute-reference (head-attribute-reference p) object (lookup-in-frame (attribute-reference-variable-name head-attribute-reference) frame)) (when object (add-slot-value object (attribute-name head-attribute-reference) (satisfy-relation (attribute-values head-attribute-reference) (if (negatedp p (class-consumer p)) (invert-relation (relation p)) (relation p)) (let ((function (ecase (function-name p) (min #'unbounded-min) (max #'unbounded-max))) (arguments (instantiate (arguments p) frame))) (make-numeric-range :min (apply function (mapcar #'range-min arguments)) :max (apply function (mapcar #'range-max arguments))))) antecedents informant))) (defmethod satisfy ((p relational-proposition) frame antecedents informant &aux object new-value) (let ((attribute-reference (car (attribute-references p)))) (when (and (setq object (lookup-in-frame (attribute-reference-variable-name attribute-reference) frame)) (setq new-value (lookup-in-frame (variable-name (proposition-specializer p)) frame))) (add-slot-value object (attribute-name attribute-reference) new-value antecedents informant :negated (negatedp p (class-consumer p)))))) (defmethod satisfy ((p lisp-proposition) frame antecedents informant) (apply (function-name p) (nconc (mapcar #'(lambda (expression) (instantiate expression frame)) (arguments p)) (list antecedents informant)))) (defun instantiate (expression frame) "Instantiates prefix expression using the bindings in frame." (typecase expression (attribute-reference (elements (lookup-in-frame expression frame))) (variable (lookup-in-frame (variable-name expression) frame)) (list (mapcar #'(lambda (expression) (instantiate expression frame)) expression)) (t expression))) ;;; Low-level manipulation of bindings (defun make-frame nil (list)) (defun lookup-in-frame (variable frame) (binding-value (binding-in-frame variable frame))) (defun binding-value (binding) (cdr binding)) (defun binding-in-frame (variable frame) (assoc variable frame :test #'equal)) (defun extend (variable value frame) (acons variable value frame))
39,742
Common Lisp
.lisp
739
36.113667
140
0.54202
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
2d2f65e7d066b33102cdac8c2f1d48bc1c1db9618d185ea7b6ee4530360e3b13
20,432
[ -1 ]
20,433
xmlis.lisp
whounslo_reasoner/src/xmlis.lisp
;;; Copyright (C) 2011, 2012, 2013 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Interface to SAX parsers (Allegro, cxml). (eval-when (:execute :compile-toplevel :load-toplevel) (when #+allegro (find-package :cxml) #-allegro t (pushnew :cxml *features*))) #-cxml (require :sax) (defpackage #-cxml :net.xml.rs #+cxml :rs-sax #-cxml (:use :reasoner-ext :net.xml.sax :cl) #+cxml (:use :reasoner-ext :sax :cl) #+cxml (:import-from :cxml #:parse) #+cxml (:import-from :sax #:dtd) (:import-from :reasoner-ext #:rdf #:xml-fragment-separator #:push-on-end #:get-lisp-name) #-cxml (:export #:sax-parse-file #:sax-parse-stream #:sax-parse-string) #+cxml (:export #:parse) (:export #:deserializer #:namespace-missing #:default-namespace-missing)) #-cxml (in-package :net.xml.rs) #+cxml (in-package :rs-sax) (defclass deserializer (#-cxml sax-parser #+cxml abstract-handler) ((namespaces :initform (list :xml :xmlns) :accessor namespaces) (default-stack :initform nil :accessor defaults) #-cxml (base :initform nil :accessor xml-base) (all-content :initform nil :accessor all-content) (content-valid :accessor content-valid))) (defmacro with-prefix-mappings (&body body) `(let ((*namespaces* (namespaces parser)) (*default-namespace* (car (defaults parser))) (*target-namespace* (xml-base parser))) ,@body)) #-cxml (defun attribute-triple (attr) (multiple-value-bind (name namespace) (parse-qualified-name (car attr)) (cons (cons name namespace) (cdr attr)))) #+cxml (defun attribute-triple (attr) (cons (cons (attribute-local-name attr) (let ((uri (attribute-namespace-uri attr))) (if uri (find-uri-namespace uri) *default-namespace*))) (attribute-value attr))) (defmethod start-document ((parser deserializer)) (pop-elements)) #+cxml (defmethod start-dtd ((parser deserializer) name public-id system-id) (declare (ignore name public-id system-id))) #+cxml (defmethod end-dtd ((parser deserializer)) ) #+cxml (defmethod start-internal-subset ((parser deserializer)) ) #+cxml (defmethod end-internal-subset ((parser deserializer)) ) #+cxml (defmethod internal-entity-declaration ((parser deserializer) kind name value) (declare (ignore kind name value))) #+cxml (defmethod entity-resolver ((parser deserializer) resolver) (declare (ignore resolver))) #+cxml (defmethod dtd ((parser deserializer) dtd) (declare (ignore dtd))) #-cxml (defmethod start-element :before ((parser deserializer) iri localname qname attrs) (declare (ignore iri qname)) (when (string= localname "RDF") (setf (xml-base parser) (cdr (assoc "xml:base" attrs :test #'string=))))) (defmethod start-element ((parser deserializer) iri localname qname attrs) (declare (ignore qname)) (with-prefix-mappings (let ((attributes (mapcar #'attribute-triple attrs))) (setf (all-content parser) nil (content-valid parser) (not nil)) (into-xml-element (find-xml-name localname iri) (if attributes #'(lambda (name namespace) (cdr (find-if #'(lambda (pair) (and (string= (caar pair) name) (or (null (cdar pair)) (eq (cdar pair) namespace)))) attributes)))))))) (defmethod end-element ((parser deserializer) iri localname qname) (declare (ignore iri localname qname)) (with-accessors ((content all-content) (valid content-valid)) parser (when content (when valid (store-xml-content (apply #'concatenate 'string content))) (setf content nil)) (setf valid nil) (with-prefix-mappings (outof-xml-element)))) (defmethod namespace-missing ((parser deserializer) prefix iri) (let* ((namespace-name (find-prefix-namespace prefix nil)) (uri (if namespace-name (namespace-uri namespace-name)))) (unless (or (null uri) (string= iri uri)) (error "A namespace named ~A already exists, but not with uri ~S." prefix iri)) (make-namespace (or namespace-name (get-lisp-name (intern prefix (find-package :keyword)))) iri))) (defmethod default-namespace-missing ((parser deserializer) iri) (make-namespace (gensym (string :ns)) iri)) (defmethod new-namespace ((parser deserializer) prefix iri) (let* ((is-default (zerop (length prefix))) (truncated-iri (subseq iri 0 (position xml-fragment-separator iri :from-end (not nil)))) (namespace-name (if is-default (default-namespace-missing parser truncated-iri) (namespace-missing parser prefix truncated-iri)))) (when is-default (push namespace-name (defaults parser))) namespace-name)) (defmethod start-prefix-mapping ((parser deserializer) prefix iri) (let ((namespace-name (find-uri-namespace iri *namespace-names* nil))) (pushnew (cond ((null namespace-name) (new-namespace parser prefix iri)) ((eq namespace-name (car (defaults parser))) (let ((package (namespace-package namespace-name)) (namespace-name (new-namespace parser prefix iri))) (when package (setf (namespace-package namespace-name) package)) namespace-name)) (t namespace-name)) (namespaces parser) :test #'eq))) (defmethod end-prefix-mapping ((parser deserializer) prefix) (declare (ignore prefix)) (with-accessors ((namespaces namespaces) (defaults defaults)) parser (when (eq (pop namespaces) (car defaults)) (pop defaults)))) #-cxml (defmethod content ((parser deserializer) content start end ignorable) (declare (ignore ignorable)) (push-on-end (all-content parser) (subseq content start end))) #-cxml (defmethod content-character ((parser deserializer) character ignorable) (declare (ignore ignorable)) (push-on-end (all-content parser) (string character))) #+cxml (defmethod characters ((parser deserializer) content) (push-on-end (all-content parser) content)) #+cxml (defmethod comment ((parser deserializer) data) (declare (ignore data))) (defmethod end-document ((parser deserializer)) )
6,656
Common Lisp
.lisp
163
33.472393
88
0.640161
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
298f1bee038e80f5b91b1e4d1be169bd9391d1d1b30a17bdf72da1d0a0238636
20,433
[ -1 ]
20,434
compat.lisp
whounslo_reasoner/src/compat.lisp
;;; Copyright (C) 2007-2009, 2014 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Implements: ;;; :count slot option ;;; :type slot property inheritance (overriding of standard behaviour) ;;; extra instance storage ;;; assuming only the existence of: ;;; class-slots ;;; slot-definition-name ;;; (or equivalents). (in-package reasoner) #-mop (progn (defvar *count-slot-options* nil) (defvar *type-slot-options* nil) (defvar *finalized-classes* nil) (defmacro defclass* (name direct-superclasses direct-slots &rest options) (let (count-slot-options type-slot-options form) (dolist (spec direct-slots) (when (find :count spec :test #'eq) (setf (getf count-slot-options (car spec)) (getf (cdr spec) :count))) (when (find :type spec :test #'eq) (setf (getf type-slot-options (car spec)) (getf (cdr spec) :type)))) (setq form `(defclass ,name ,direct-superclasses ,(mapcar #'(lambda (spec &aux count-slot-name) (setq count-slot-name (getf count-slot-options (car spec))) (if count-slot-name (remove-if #'(lambda (element) (or (eq element :count) (eq element count-slot-name))) spec) spec)) direct-slots) ,@options)) `(progn (push ',(cons name count-slot-options) *count-slot-options*) (push ',(cons name type-slot-options) *type-slot-options*) ,(macroexpand-1 form)))) (defmethod shared-initialize :after ((class extended-class) slot-names &rest initargs) (declare (ignore slot-names initargs)) ;; Redo finalization of a redefined class and its subclasses. (setq *finalized-classes* (delete class *finalized-classes* :test #'(lambda (x y) (subtypep y x))))) (defun find-option (class slot-name options &aux class-options slot-option) (dolist (superclass (class-precedence-list class)) (setq class-options (assoc (class-name superclass) options :test #'eq) slot-option (getf (cdr class-options) slot-name)) (when slot-option (return slot-option)))) (defun slot-definition-name (slot-definition) (clos::slot-definition-name slot-definition)) (defun slot-definition-initargs (slot-definition) (clos::slot-definition-initargs slot-definition)) (defmethod class-slots ((class t)) (clos::class-slots class)) (defmethod class-slots ((class extended-class)) (let ((slots (call-next-method))) (unless (find class *finalized-classes* :test #'eq) (dolist (slot slots) (finalize-slot-definition class slot)) (push class *finalized-classes*)) slots)) (let ((instance-name-table (make-hash-table :test #'eq)) (instance-node-table (make-hash-table :test #'eq)) (slot-definition-count (make-hash-table :test #'eq)) (slot-definition-type (make-hash-table :test #'eq))) (defun instance-name (instance) (gethash instance instance-name-table)) (defmethod (setf extd-instance-name) (new-name (instance extended-object)) (setf (gethash instance instance-name-table) new-name)) (defun instance-node (instance) (gethash instance instance-node-table)) (defun (setf instance-node) (node instance) (setf (gethash instance instance-node-table) node)) (defmethod finalize-slot-definition ((class extended-class) slot-definition) (let ((slot-name (slot-definition-name slot-definition)) count-slot-name slot-type) (setq count-slot-name (find-option class slot-name *count-slot-options*)) (when count-slot-name (setf (gethash slot-definition slot-definition-count) count-slot-name)) (setq slot-type (find-option class slot-name *type-slot-options*)) (when slot-type (setf (gethash slot-definition slot-definition-type) slot-type)) slot-definition)) (defun slot-definition-count (slot-definition) (gethash slot-definition slot-definition-count)) (defun slot-definition-type (slot-definition) (gethash slot-definition slot-definition-type t)) ) ;end let ) ;end progn
4,462
Common Lisp
.lisp
95
38.147368
90
0.635691
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9f08c125faecf574c233aa6e04a32e60c3b67622984b2929683969d3b9b3fdf2
20,434
[ -1 ]
20,435
rsexport.lisp
whounslo_reasoner/src/rsexport.lisp
;;; Copyright (C) 2007, 2009, 2011-14, 2016-17 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (defpackage :reasoner (:nicknames :rs) (:use :rparallel :streams :atms #-closer-mop :cl #+closer-mop :c2cl) #-(or closer-mop abcl clozure cmu mcl sbcl) (:use :clos) #+(and (not closer-mop) abcl) (:use :mop) #+(and (not closer-mop) (or clozure mcl)) (:use :ccl) #+(and (not closer-mop) cmu) (:use :clos-mop) #+(and (not closer-mop) sbcl) (:use :sb-mop) (:shadow #:variable) #+(or abcl clisp sbcl) (:shadow #:ensure-class #:ensure-class-using-class) #+clisp (:shadow #:subtypep) #+ecl (:shadow #:class-slots) #+lispworks (:shadow #:find-slot-definition) #+(and (not closer-mop) lispworks) (:shadow #:make-method-lambda #:slot-value-using-class)) (in-package reasoner) (eval-when (:execute :compile-toplevel :load-toplevel) (export '(make-assumption uniquify-environment in-p truep contradictoryp subsumesp assumption environment core-atms atms basic-atms head tail schedule nschedule backtrack solutions order-control-disjunction added-assumption add-contradiction conflictp describe-data map-slots classify notice-slot-values assume-slot-value assume-slot-values reinitialize-atms *atms* *empty-environment* contradictory-value contradictory-value-p extended-class extended-object instance-name instance-assumption find-instance slot-value-typep add-slot-value slot-value-reduce slot-values add-slot-value-using-class slot-definition-missing validate-combination fetch-node fetch-assumption elements remove-slot-value remove-node numeric-range symbolic-range big -big true-or-false true false zero-or-one zero-or-more exactly-one one-or-more defrange numeric-rangep range-max range-min ensure-named-instance ensure-named-instance-using-class source-form rule-compile uncompile defconstraint defrule -> <-> lisp is in includes aggregate-min aggregate-max aggregate-sum *trace-rule-failure* *rule-trace-output* rules-using rules-affecting slot-affected slots-used attribute-reference-class attribute-name compound-object assembly part component parts )) ) ;;; Hide some CLOS implementation idiosyncrasies. #+(and (not closer-mop) abcl) (defconstant ensure-class-using-class-fn #'mop:ensure-class-using-class) #+(and (not closer-mop) clisp) (defconstant ensure-class-using-class-fn #'clos:ensure-class-using-class) #+(and (not closer-mop) sbcl) (defconstant ensure-class-using-class-fn #'sb-mop:ensure-class-using-class) #+(and closer-mop (or abcl clisp sbcl)) (defconstant ensure-class-using-class-fn #'c2cl:ensure-class-using-class) #+(or abcl clisp) (defun ensure-class-using-class (class name &rest initargs &key direct-superclasses &allow-other-keys) (if (and class (null direct-superclasses)) (apply ensure-class-using-class-fn class name :direct-superclasses (class-direct-superclasses class) ; Leave value unchanged. initargs) (apply ensure-class-using-class-fn class name initargs))) #+sbcl (defun ensure-class-using-class (class name &rest initargs &key direct-superclasses &allow-other-keys) (if class (apply ensure-class-using-class-fn class name initargs) (apply ensure-class-using-class-fn class name :direct-superclasses direct-superclasses ; Supply explicitly to inhibit ; over-eager defaulting. initargs))) #+(or abcl clisp sbcl) (defun ensure-class (name &rest initargs) (apply #'ensure-class-using-class (find-class name nil) name initargs)) #+clisp (defun subtypep (type-1 type-2 &optional environment) (let (subtype-p valid-p normal) (ignore-errors (multiple-value-setq (subtype-p valid-p) (cl:subtypep type-1 type-2 environment)) ; Signals an error if a symbol ; associated with a class using ; setf and find-class is received. (setq normal (not nil))) (if normal (values subtype-p valid-p) (cl:subtypep (or (if (symbolp type-1) (find-class type-1 nil)) type-1) (or (if (symbolp type-2) (find-class type-2 nil)) type-2) environment)))) #+ecl (defmethod class-slots ((class t)) (clos:class-slots class)) #+(and (not closer-mop) lispworks) (defmacro slot-value-using-class (class object slot) `(clos:slot-value-using-class ,class ,object (slot-definition-name ,slot)))
5,282
Common Lisp
.lisp
122
33.032787
81
0.616042
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
39f4b3663ff0188ab299e904a16098e567feea83b334db9e011ca14c3696541f
20,435
[ -1 ]
20,436
atms.lisp
whounslo_reasoner/src/atms.lisp
;;; Copyright (C) 2007-2011, 2014, 2017 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (eval-when (:compile-toplevel) (declaim (optimize (speed 3) (safety 1) (space 0) (debug 0)))) (defpackage :atms (:use :cl)) (in-package atms) (eval-when (:execute :compile-toplevel :load-toplevel) (export '(assumption core-atms atms basic-atms environment justification node standard-node false-node temporary-node antecedents consequent consequents contradictoryp datum informant justifications label name contras assumptions nodes size datum-assumption assumed-datum make-assumption discard-assumption add-justification delete-from-environments subsumesp in-p truep union-environments uniquify-environment add-consumer consumer execute-consumer execute-consumers add-contradiction absorb insert singletonp ))) (defclass core-atms () ((environment-hash-table :initform (make-hash-table :test #'equal) :reader environment-hash-table :initarg :environment-hash-table) (environments :initform nil :accessor environments :initarg :environments :documentation "Set of all environments, ordered by decreasing size.") (environment-index :initform nil :accessor environment-index :initarg :environment-index) (nogoods :initform nil :accessor nogoods :documentation "Database of contradictory environments, ordered by increasing size.") (false-node :initform (make-instance 'false-node) :reader false-node :documentation "The distinguished false node.")) (:documentation "An assumption-based TMS.")) (defclass atms (core-atms) () (:documentation "An assumption-based TMS.")) (defclass basic-atms (core-atms) () (:documentation "ATMS requiring ordered adding, by serial number, of assumptions.")) (defclass environment () ((assumptions :reader assumptions :initarg :assumptions) (nodes :initform nil :accessor nodes :documentation "The set of nodes whose label mentions the environment.") (node-added :initform nil :reader node-added :documentation "Indicates whether any new nodes have appeared recently.") (node-for-deletion :initform nil :accessor node-for-deletion :documentation "Indicates whether there are spent temporary nodes.") (contradictory :initform nil :accessor contradictoryp) (size :reader size :initarg :size :documentation "Number of assumptions.")) (:documentation "A set (or, logically, a conjunction) of assumptions.")) (defclass justification () ((informant :accessor informant :initarg :informant :documentation "A problem-solver-supplied description of the inference.") (consequent :reader consequent :initarg :consequent :documentation "The node justified.") (antecedents :reader antecedents :initarg :antecedents :documentation "The nodes upon which the inference depends.")) (:documentation "Describes how a node is derivable from other nodes.")) (defclass node () ((label :initform nil :accessor label :documentation "A set of environments.") (justifications :initform nil :accessor justifications :documentation "The derivations of the datum.") (consequents :initform nil :accessor consequents :documentation "The justifications for which the node is an antecedent.") (contradictory :initform nil :accessor contradictoryp)) (:documentation "Records a problem-solver datum.")) (defclass assumption (node) ((name :reader name :initarg :name) (serial-number :accessor serial-number :documentation "Unique identifier.") (last-serial-number :initform 0 :accessor last-serial-number :allocation :class) (nogoods :initform nil :accessor nogoods :documentation "Minimal nogoods of length three or greater in which assumption appears.") (contras :initform nil :accessor contras :documentation "Assumptions that assumption is inconsistent with.")) (:documentation "Designates a decision to assume, without any commitment as to what is assumed." )) (defclass false-node (node) ((contradictory :initform t :accessor contradictoryp))) (defclass standard-node (node) ((datum :reader datum :initarg :datum :documentation "The problem-solver's representation of a fact."))) (defclass temporary-node (node) ((order :reader order :initarg :order :documentation "Ordering placed on consumers within an environment.")) (:documentation "Used to record a consumer of a list of nodes.")) (defmethod initialize-instance :after ((instance core-atms) &rest initargs) (declare (ignore initargs)) (uniquify-environment instance nil)) (defmethod print-object ((instance assumption) stream) (print-unreadable-object (instance stream :identity t) (format stream "~:(~S~) ~:[~7,'0D~;~:*~S~]" (class-name (class-of instance)) (name instance) (serial-number instance))) instance) (defmethod datum-assumption ((n node) &optional (oldest nil)) (let ((environment (find-if #'singletonp (label n) :key #'assumptions :from-end oldest))) (if environment (car (assumptions environment))))) (defmethod assumed-datum ((n assumption)) (consequent (car (consequents n)))) (defmethod add-justification ((tms core-atms) (n assumption) antecedents &optional informant) (declare (ignore antecedents informant)) (error "Attempt to justify an assumption.")) (defmethod add-justification ((tms core-atms) (n node) (antecedents list) &optional informant) "Add a justification to a node." (let ((justification (make-instance 'justification :informant informant :consequent n :antecedents antecedents))) (dolist (node antecedents) (push justification (consequents node))) (add-justification tms n justification))) (defmethod add-justification ((tms core-atms) (n node) (j justification) &optional informant) "Add a justification to a node, and propagate." (declare (ignore informant)) (push j (justifications n)) (propagate-label-update j tms)) ;(define-modify-macro deletef (item &rest args) ; (lambda (place item &rest args) ; (apply #'delete item place args))) (defmacro deletef (place item &rest args) `(setf ,place (delete ,item ,place ,@args))) (defmethod propagate-label-update ((j justification) (tms core-atms)) "Propagate the belief states of the antecedents to the consequent." (update-label (consequent j) tms (mapcar #'(lambda (environments) (union-environments tms environments)) (cross-product (mapcar #'label (antecedents j)))))) (defmethod update-label ((n node) (tms core-atms) (label-increment list)) "Updates label following the addition of a new justification to a node." ;; The increment contributed by the new justification is appended to the ;; label, after removing the following: ;; 1. Nogoods, and environments subsumed by existing label, in contribution. ;; 2. Subsumptions within contribution. ;; 3. Environments in existing label subsumed by contribution. (flet ((subsumed-within-p (new-environment environments) (declare (type list environments)) (some #'(lambda (environment) (subsumesp environment new-environment)) environments))) (let (filtered-label-increment) (setq filtered-label-increment (remove-subsumptions (delete-if #'(lambda (new-environment) (or (contradictoryp new-environment) (subsumed-within-p new-environment (label n)))) label-increment))) (when filtered-label-increment (dolist (environment filtered-label-increment) (add-to-agenda n environment)) (setf (label n) (nconc filtered-label-increment (delete-if #'(lambda (environment) (when (subsumed-within-p environment filtered-label-increment) (deletef (nodes environment) n :test #'eq) (not nil))) (the list (label n))))) (propagate-label-update n tms))) n)) (defmethod propagate-label-update ((n node) (tms core-atms)) "Propagate label change forward or contradiction backward." (if (contradictoryp n) (propagate-contradiction n tms) (dolist (justification (consequents n)) (propagate-label-update justification tms)))) (defmethod propagate-contradiction ((n node) (tms core-atms)) "Propagate a contradiction backwards." (dolist (environment (label n)) (no-good environment tms)) (dolist (justification (justifications n)) (let ((untrue-antecedents (remove-if #'truep (antecedents justification)))) (when (singletonp untrue-antecedents) ;; All but one antecedent is true, so the other must also be false. (setf (contradictoryp (car untrue-antecedents)) (not nil)) (propagate-contradiction (car untrue-antecedents) tms))))) (defmethod indexed-size ((environments cons)) (size (car environments))) (defun find-environments (size atms &key (test #'=)) (find size (environment-index atms) :key #'indexed-size :test test)) (defmethod no-good ((e environment) (tms core-atms)) "Makes environment nogood." (with-slots (assumptions size) e (unless assumptions (error "Contradiction of the empty environment.")) (if (eql size 2) (record-binary-contradiction tms (first assumptions) (second assumptions)) (record-nogood tms e)) ;; Set contradictory bit of this and all subsumed environments. ;; Remove all of these environments from every node label. (do ((exit-point (find-environments size tms)) (environments (environments tms) (cdr environments))) ((eq environments exit-point)) (unless (contradictoryp (car environments)) (when (subsumesp e (car environments)) (set-contradictory (car environments))))) (set-contradictory e) e)) (defconstant assumption-ordering-predicate #'>) (defmethod add-contra ((a1 assumption) (a2 assumption)) (or (insert a2 (contras a1) assumption-ordering-predicate :key #'serial-number) (setf (contras a1) (list a2)))) (defmethod record-binary-contradiction ((tms core-atms) (a1 assumption) (a2 assumption)) "Record binary contradiction, employing specialized representation." (add-contra a1 a2) (not nil)) (defmethod record-binary-contradiction ((tms atms) (a1 assumption) (a2 assumption)) "Record binary contradiction, employing specialized representation." (add-contra a1 a2) (add-contra a2 a1) (not nil)) (defun add-nogood (object environment cleanup) (with-slots (nogoods) object ;; Database is a list ordered by increasing size of environment. (cond ((not (insert environment nogoods #'< :key #'size)) (setf nogoods (list environment))) (cleanup (delete-if #'(lambda (e) (unless (eq e environment) (when (subsumesp environment e) (dolist (a (assumptions e)) (deletef (nogoods a) e :test #'eq)) (not nil)))) (member environment nogoods :test #'eq)))))) (defmethod record-nogood ((tms core-atms) (e environment)) "Adds environment to nogood database." (add-nogood tms e nil) (add-nogood (first (assumptions e)) e nil)) (defmethod record-nogood ((tms atms) (e environment)) "Adds environment to nogood database." (add-nogood tms e 'cleanup) (dolist (a (assumptions e)) (add-nogood a e nil))) (defmethod set-contradictory ((e environment)) "Set contradictory bit of environment and remove from every node label." (dolist (node (nodes e)) (deletef (label node) e :test #'eq)) (setf (nodes e) nil (contradictoryp e) (not nil))) (defmethod make-environment ((tms core-atms) (assumptions list)) (let* ((size (length assumptions)) (environment (make-instance 'environment :assumptions assumptions :size size)) entry-point entry-point-size insertion-point) (unless (singletonp assumptions) (setf (gethash assumptions (environment-hash-table tms)) environment)) ;; Set of all environments is a list ordered by decreasing size. (with-slots (environments environment-index) tms (cond (environments (setq entry-point (or (find-environments size tms :test #'<=) environments) entry-point-size (indexed-size entry-point)) (unless (> size entry-point-size) (insert environment entry-point #'>= :key #'size)) (when (/= size entry-point-size) (setq insertion-point (if (> size entry-point-size) (push environment environments) (member environment entry-point :test #'eq))) ;; Index is organized by increasing size of environment. (insert insertion-point environment-index #'< :key #'indexed-size))) (t (setf entry-point (list environment) environments entry-point environment-index (list entry-point))))) environment)) (defmethod make-assumption ((tms core-atms) &optional (name nil)) (let ((assumption (make-instance 'assumption :name name))) (setf (serial-number assumption) (incf (last-serial-number assumption)) (label assumption) (list (make-environment tms (list assumption)))) assumption)) (defmethod discard-assumption ((tms core-atms) (n assumption)) "Garbage assumption." ;; Should really be done when environment hash-table is grown. (let ((environment (car (label n)))) (when (or (contradictoryp environment) (every #'(lambda (justification) (with-slots (consequent) justification (or (contradictoryp consequent) (truep consequent)))) (consequents n))) (with-slots (environments nogoods (index environment-index)) tms (setf index (mapcan #'(lambda (entry-point &aux rest-environments) (setq rest-environments (member environment entry-point :test (complement #'subsumesp))) (if (eql (indexed-size rest-environments) (indexed-size entry-point)) (list rest-environments))) index)) (deletef environments environment :test #'subsumesp) (deletef nogoods environment :test #'subsumesp)) (dolist (contra (contras n)) (deletef (contras contra) n :test #'eq)) n))) (defmethod truep ((n node)) (with-slots (label) n (if label (null (assumptions (car label)))))) (defmethod in-p ((n node) environment) (some #'(lambda (e) (subsumesp e environment)) (the list (label n)))) (defmethod subsumesp ((e1 environment) (e2 environment) &optional (ordered (not nil))) (or (eq e1 e2) (subsumesp (assumptions e1) (assumptions e2) ordered))) (defmethod subsumesp ((e environment) (assumptions list) &optional (ordered nil)) (subsumesp (assumptions e) assumptions ordered)) (defmethod subsumesp ((assumptions list) (e environment) &optional (ordered nil)) (subsumesp assumptions (assumptions e) ordered)) (defmethod subsumesp ((assumption-set-1 list) (assumption-set-2 list) &optional (ordered nil)) (unless assumption-set-1 (return-from subsumesp (not nil))) (if ordered ;; Optimised for ordered-list representation of assumption sets. (do ((list1 assumption-set-1 (rest list1)) (list2 assumption-set-2 (member (first list1) list2 :test #'eq))) ((endp list1) (not (null list2))) (when (null list2) (return nil))) (subsetp assumption-set-1 assumption-set-2 :test #'eq))) (defmethod size ((assumptions list)) (length assumptions)) (defmethod add-consumer ((tms core-atms) (antecedents list) consumer &optional (order :after)) "Add a consumer, attached to a temporary node." (add-justification tms (make-instance 'temporary-node :order order) antecedents consumer)) (defmethod consumer ((n temporary-node)) "Fetch consumer from informant of justification." (let ((justification (car (justifications n)))) (if justification (informant justification)))) (defmethod order ((n node)) :after) (defmethod add-to-agenda ((n node) (e environment)) "Add to partially-ordered list of nodes associated with environment." (with-slots (nodes node-added) e (if nodes (insert n nodes #'(lambda (node1 node2) (not (and (eq (order node1) :after) (eq (order node2) :before))))) (setf nodes (list n))) (setf node-added (not nil)))) (defmethod execute-consumers ((e environment)) "Exhaustively execute consumers of nodes in environment." ;; Executing a consumer may cause a new node, with a consumer, to ;; appear in environment. (with-slots (nodes node-added contradictory) e (loop (unless node-added (return)) (setf node-added nil) (dolist (node nodes) (execute-consumer node) (when contradictory (return-from execute-consumers)) (when node-added (return)))))) (defmethod execute-consumers :after ((e environment)) "Clean up temporary nodes in environment." (with-slots (nodes node-for-deletion) e (when node-for-deletion (deletef nodes nil :key #'justifications :test #'eq) (setf node-for-deletion nil)))) (defmethod execute-consumer ((n node)) nil) (defmethod execute-consumer ((n temporary-node)) (let ((consumer (consumer n))) (when consumer (funcall consumer (car (justifications n)))))) (defmethod mark-for-deletion ((n temporary-node)) (setf (justifications n) nil) (dolist (environment (label n)) (setf (node-for-deletion environment) (not nil)))) (defmethod reinitialize-instance :before ((j justification) &rest initargs) (declare (ignore initargs)) (mark-for-deletion (consequent j))) (defun add-contradiction (atms antecedents &aux (falsity (false-node atms))) (add-consumer atms antecedents #'(lambda (justification) (reinitialize-instance justification :informant 'contradiction :consequent falsity) (add-justification atms falsity justification)) :before)) (defun remove-subsumptions (environments) "Removes environments that are supersets of others." (if environments (absorb (car environments) (remove-subsumptions (cdr environments)) #'(lambda (e1 e2) (if (> (size e1) (size e2)) (if (subsumesp e2 e1) e2) (if (subsumesp e1 e2) e1)))))) (defun delete-from-environments (node) (dolist (environment (label node)) (deletef (nodes environment) node :test #'eq))) (defmethod union-environments ((tms core-atms) (environments list)) (uniquify-environment tms (if environments (reduce #'union environments :key #'assumptions)))) (defmethod uniquify-environment ((tms core-atms) (assumptions list) &optional (dont-create nil) (ordered nil)) "Returns a unique environment object." (when (singletonp assumptions) (return-from uniquify-environment (car (label (car assumptions))))) (unless ordered (setq assumptions (sort (copy-list assumptions) assumption-ordering-predicate :key #'serial-number))) (cond ((gethash assumptions (environment-hash-table tms))) ((not dont-create) (make-environment tms assumptions)))) (defun cross-product (sets) (if sets (mapcan #'(lambda (element) (mapl #'(lambda (sets) (push element (car sets))) (cross-product (cdr sets)))) (car sets)) (make-list 1))) (defun absorb (item list combiner &key (count 1)) "Combines item with one or more elements of, or conses onto, list." (do ((tail list (cdr tail)) (occurrences-matched 0) new-element) ((endp tail) (if (zerop occurrences-matched) (cons item list) list)) (cond ((= occurrences-matched count) (return list)) ((setf new-element (funcall combiner item (car tail))) (setf (car tail) new-element) (incf occurrences-matched))))) (defun insert (item list test &key (key #'identity)) "Inserts item in list at place satisfied by test, a binary predicate." (if (do ((item-key (funcall key item)) (old-tail nil tail) (tail list (cdr tail))) ((endp tail) (cond (old-tail (setf (cdr old-tail) (list item)) ; Insert at end. (not nil)) (t ;; List is empty - cannot insert. nil))) (cond ((not (funcall test item-key (funcall key (car tail)))) ;; Not at insertion point yet. ) (old-tail (setf (cdr old-tail) (cons item tail)) ; Insert. (return (not nil))) (t (setf (cdr tail) (cons (car tail) (cdr tail)) (car tail) item) ; Insert at front. (return (not nil))))) list)) (defmethod singletonp ((l cons)) "True for a list of one element." (endp (cdr l))) (defmethod singletonp ((l null)) "True for a list of one element." nil)
23,669
Common Lisp
.lisp
511
35.616438
98
0.611974
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f2bc8aa9ae5dae567a9c6c12d1027559131c43c2e095251627ec00886ac8f09c
20,436
[ -1 ]
20,437
streams.lisp
whounslo_reasoner/src/streams.lisp
;;; Copyright (C) 2007, 2011, 2014, 2017 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Adapted from: Structure and Interpretation of Computer Programs ;;; by Harold Abelson and Gerald Jay Sussman with Julie Sussman, ;;; MIT Press, 1985. (defpackage :streams (:use :cl) (:import-from :rparallel #:delay #:force)) (in-package streams) (eval-when (:execute :compile-toplevel :load-toplevel) (export '(accumulate-delayed cons-stream delay empty-stream-p flatmap flatmap* flatten force head interleave interleave-delayed map-stream map-stream* memo-proc singleton tail the-empty-stream ))) (defconstant the-empty-stream nil) (defun empty-stream-p (stream) (null stream)) (defun head (stream) "Obtain first element in stream." (car stream)) (defun tail (stream) "Obtain the tail of stream by evaluating delayed expression." (force (cdr stream))) (defmacro cons-stream (a b) "Returns a pair comprising A and a delayed object." `(cons ,a (delay ,b))) (defun singleton (s) "Generates a single-element stream." ;;; (cons-stream s the-empty-stream) (cons s the-empty-stream) ; Handled by generic FORCE. ) (defun map-stream (proc stream) "Generates the stream formed by applying procedure to each element in input stream." (if (empty-stream-p stream) the-empty-stream (cons-stream (funcall proc (head stream)) (map-stream proc (tail stream))))) (defun flatmap (proc stream) "Generate the single stream formed by applying the procedure (which returns a stream) to each item in the input stream and appending the results." (flatten (map-stream proc stream))) (defun map-stream* (proc stream tail-fn) "Generates the stream formed by applying procedure to each element in input stream." (if (empty-stream-p stream) the-empty-stream (cons-stream (funcall proc (head stream)) (map-stream* proc (funcall tail-fn stream) tail-fn)))) (defun flatmap* (proc stream tail-fn) "Generate the single stream formed by applying the procedure (which returns a stream) to each item in the input stream and appending the results." (flatten (map-stream* proc stream tail-fn))) (defun flatten (stream) "Appends the elements of a stream of streams to form a single stream." (accumulate-delayed #'interleave-delayed the-empty-stream stream)) (defun accumulate-delayed (combiner initial-value stream) "Accumulates items in stream using combiner, beginning with initial-value. Combiner must expect to explicitly force its second argument." (if (empty-stream-p stream) initial-value (funcall combiner (head stream) ;; To handle infinite streams, delay the recursive call. (delay (accumulate-delayed combiner initial-value (tail stream)))))) (defun interleave (s1 s2) "Append two streams, taking elements alternately from each -- appropriate for infinite streams." (if (empty-stream-p s1) s2 (cons-stream (head s1) (interleave s2 (tail s1))))) (defun interleave-delayed (stream delayed-stream) "Append two streams, taking elements alternately from each." (if (empty-stream-p stream) (force delayed-stream) (cons-stream (head stream) (interleave-delayed (force delayed-stream) (delay (tail stream))))))
3,511
Common Lisp
.lisp
75
41.2
148
0.696872
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
cd5a2a57703be7277f8c2e2fa10ecfbc88c61a488d80d81b25f73ed3b30a6ce1
20,437
[ -1 ]
20,438
rparallel.lisp
whounslo_reasoner/src/rparallel.lisp
;;; Copyright (C) 2013, 2014, 2017 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Interface to Lisp in Parallel (lparallel.org). (defpackage :rparallel (:use :cl #+lparallel :bordeaux-threads #+lparallel :lparallel)) (in-package :rparallel) (eval-when (:execute :compile-toplevel :load-toplevel) (export '(lockable-object hold-lock delay force initiate defer perform task do-deferred-results if-in-parallel))) (defconstant worker-count 2) #+lparallel (defvar *pending-tasks* nil) #+lparallel (setf *kernel* (make-kernel worker-count)) (defclass lockable-object () #-lparallel () #+lparallel ((lock :initform (make-lock) :reader lock)) ) (defmacro hold-lock (object &body body) (declare (ignorable object)) #-lparallel `(progn ,@body) #+lparallel `(with-lock-held ((lock ,object)) ,@body)) #-lparallel (defmacro delay (exp) "Packages expression as a memoized procedure for evaluation later on demand." `(let (already-run result) #'(lambda () (unless already-run (setq result ,exp already-run (not nil))) result))) #-lparallel (defgeneric force (object) (:method ((delayed-object function)) "Evaluate delayed-object produced by DELAY." (funcall delayed-object)) (:method ((tail list)) "List: simply return tail." tail)) #-lparallel (progn (defmacro initiate (form) form) (defmacro defer (form) form) ) #+lparallel (defmacro initiate (form) `(future ,form)) #+lparallel (defmacro defer (form) `(chain (delay ,form))) (defmacro perform (&body body) #-lparallel `(macrolet ((task (form) form)) ,@body) #+lparallel (let ((results-var (gensym))) `(macrolet ((task (form) (list 'push form ',results-var))) (push (future (let (,results-var) ,@body (nreverse ,results-var))) *pending-tasks*) ; Start dispatcher. ))) (defmacro do-deferred-results (result-var &body body) (declare (ignorable result-var body)) #+lparallel (let ((tasks-var (gensym)) (task-var-1 (gensym)) ; Dispatchers. (task-var-2 (gensym))) ; Class consumers. `(do ((,tasks-var *pending-tasks* *pending-tasks*)) ((endp ,tasks-var)) (setq *pending-tasks* ()) (dolist (,task-var-1 (nreverse ,tasks-var)) (do ((,task-var-2 (force ,task-var-1) (rest ,task-var-2)) ,result-var) ((endp ,task-var-2)) (setq ,result-var (force (first ,task-var-2))) ,@body))))) (defmacro if-in-parallel (form) (declare (ignorable form)) #+lparallel form)
2,793
Common Lisp
.lisp
90
25.666667
87
0.620305
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c6f786093f6397a905203f14d7917a52f54b922c2b31a6b7b0293b801042b7bd
20,438
[ -1 ]
20,439
defrule.lisp
whounslo_reasoner/src/defrule.lisp
;;; Copyright (C) 2007, 2009, 2011, 2013 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html (in-package reasoner) (defmacro defconstraint (&rest args) (let (name qualifier documentation source-form (class-name 'constraint)) (multiple-value-setq (name qualifier documentation source-form) (parse-defrule args)) `(ensure-named-instance ',name :qualifier ,qualifier :documentation ,documentation :source-form ',source-form :class (find-class ',class-name)))) (defmacro defrule (&rest args) (let (name qualifier documentation source-form (class-name 'forward-rule)) (multiple-value-setq (name qualifier documentation source-form) (parse-defrule args)) `(ensure-named-instance ',name :qualifier ,qualifier :documentation ,documentation :source-form ',source-form :class (find-class ',class-name)))) (defmethod parse-defrule (args) (let ((name (car args)) qualifier declarations (documentation nil) body) (setq qualifier (if (and (atom (cadr args)) (not (null (cadr args)))) (cadr args)) declarations (if qualifier (caddr args) (cadr args)) body (if qualifier (cdddr args) (cddr args))) (when (stringp (car body)) (setq documentation (pop body))) (values name qualifier documentation (cons declarations body)))) (defun ensure-named-instance (name &rest initargs) (apply #'ensure-named-instance-using-class (find-instance name nil) name :name name initargs)) (defmethod ensure-named-instance-using-class ((instance extended-object) name &rest initargs &key class &allow-other-keys) "Updates a named instance." (if (eq (class-of instance) (if (symbolp class) (find-class class) class)) (apply #'reinitialize-instance instance initargs) (error "~S already exists as an instance,~@ but is not of class ~S." name (if (symbolp class) class (class-name class))))) (defmethod ensure-named-instance-using-class ((instance null) name &rest initargs &key class qualifier &allow-other-keys) "Creates a named instance." (declare (ignore name)) (apply #'make-instance class :antecedents (if (eq qualifier :assume) (list (make-assumption *atms*))) initargs)) (defmethod uncompile ((wff well-formed-formula)) (dolist (node (all-slot-values wff 'class-consumers)) (dolist (class-consumer (datum-value node)) (dolist (proposition (propositions class-consumer)) (remove-indexes proposition class-consumer))) (when (truep node) (remove-node node nil))) wff) (defmethod shared-initialize ((instance well-formed-formula) slot-names &key source-form &allow-other-keys) (declare (ignore slot-names)) (let ((re-compile nil)) (when source-form (unless (and (fetch-node instance 'source-form source-form) (all-slot-values instance 'class-consumers)) (uncompile instance) (setq re-compile (not nil)))) (call-next-method) (when re-compile (rule-compile instance)) instance)) (defmethod shared-initialize :after ((instance constraint) slot-names &key body &allow-other-keys) (declare (ignore slot-names)) (when body (uncompile instance) (add-class-consumers instance (make-constraint-consumers body nil) ()))) (defmethod shared-initialize :after ((instance forward-rule) slot-names &key head neck body &allow-other-keys) (declare (ignore slot-names)) (when head (uncompile instance) (add-class-consumers instance (make-all-class-consumers body neck (collect-head-propositions head) nil) ())))
5,130
Common Lisp
.lisp
111
28.963964
77
0.501198
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
cc512ab041da21e8dc2e197b61063df2b051a82ae6c6c4d8de28b1fa73d632be
20,439
[ -1 ]
20,440
xmlic.lisp
whounslo_reasoner/src/xmlic.lisp
;;; Copyright (C) 2011, 2012, 2013 by William Hounslow ;;; This is free software, covered by the GNU GPL (v2) ;;; See http://www.gnu.org/copyleft/gpl.html ;;; ;;; Interface to CLLIB XML parser. (require :cllib-xml "clocc:src;cllib;xml") (in-package :reasoner-ext) (eval-when (:compile-toplevel :load-toplevel :execute) (import '(cllib::xml-decl cllib:xml-obj cllib:xmlo-name cllib:xmlo-tag cllib:xmlo-data cllib:xmln-ln cllib:xmln-ns cllib:xmlns-uri cllib:xml-find-name cllib::xmlns-get))) (defun find-xmln (xmln) (find-xml-name (xmln-ln xmln) (xmlns-uri (xmln-ns xmln)))) (defun get-xmln (name uri) (xml-find-name name (xmlns-get uri))) (defmethod deserialize-as-object ((element xml-obj) &key tag-fn attribute-fn content-fn &aux (rdf nil)) (declare (ignore tag-fn attribute-fn content-fn)) (call-next-method element :tag-fn #'(lambda (xml-obj) (let ((name (find-xmln (xmlo-name xml-obj)))) (when (eq name 'rdf) (setq rdf (not nil))) name)) ; Tag. :attribute-fn #'(lambda (xml-obj name namespace) (let ((xmln (if namespace (get-xmln name (if rdf (namespace-uri-variant namespace) (namespace-uri namespace)))))) (or (and xmln (xmlo-tag xml-obj xmln)) (xmlo-tag xml-obj name)))) ; Named attribute's value. :content-fn #'(lambda (xml-obj) (remove-if #'(lambda (object) (and (stringp object) (eq (char object 0) #\space))) (xmlo-data xml-obj))) ; List of objects. )) (defmethod deserialize-as-object ((element xml-decl) &key tag-fn attribute-fn content-fn) (declare (ignore tag-fn attribute-fn content-fn)) )
2,719
Common Lisp
.lisp
50
29.12
86
0.4003
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e272df5336e82399acb32fd05f1ec05473b47ab3a58ba94529c632317a5a4d64
20,440
[ -1 ]
20,441
reasoner-sax.asd
whounslo_reasoner/reasoner-sax.asd
(defsystem "reasoner-sax" :description "Reasoner plus XML, RDF/XML (de)serialization (Allegro SAX parser)." :licence "GPL" :author "William Hounslow" :depends-on ("reasoner-xml") :pathname "src" :components ((:file "xmlis")))
237
Common Lisp
.asd
7
31.285714
83
0.709957
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
bf63230bb4cf52980f2121abd4ec105e23dc11978a8a920b0686adcac751e388
20,441
[ -1 ]
20,442
reasoner-xml.asd
whounslo_reasoner/reasoner-xml.asd
(defsystem "reasoner-xml" :description "Reasoner plus XML, RDF/XML (de)serialization." :licence "GPL" :author "William Hounslow" :depends-on ("reasoner") :pathname "src" :serial t :components ((:file "xmlnames") (:file "deserial") (:file "serial") (:file "datatype") (:file "triple")))
359
Common Lisp
.asd
12
22.833333
62
0.571839
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
91b9a079b9b16ed2a19dddcbccc83f427e25c6dadaa9886eb6cc50ba33d1b508
20,442
[ -1 ]
20,443
reasoner-cxml.asd
whounslo_reasoner/reasoner-cxml.asd
(defsystem "reasoner-cxml" :description "Reasoner plus XML, RDF/XML (de)serialization plus parser." :licence "GPL" :author "William Hounslow" :depends-on ("reasoner-xml" "cxml") :pathname "src" :components ((:file "xmlis")))
236
Common Lisp
.asd
7
31.142857
74
0.708696
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
95fb790d5e8683a9b68e1168cdf7ad0deefe40127bf633d6b6e3f30d2fc0009b
20,443
[ -1 ]
20,444
reasoner.asd
whounslo_reasoner/reasoner.asd
#+(or abcl allegro clisp clozure cmu ecl lispworks mcl sbcl scl) (pushnew :mop *features*) (defsystem "reasoner" :description "Problem-solving and reasoning in Lisp." :licence "GPL" :author "William Hounslow" :depends-on (#+rparallel "lparallel") :pathname "src" :serial t :components ((:file "rparallel") (:module "streams" :pathname "" :serial t :components ((:file "streams") #+rparallel (:file "pstreams"))) (:module "atms" :pathname "" :serial t :components ((:file "atms") (:file "backtrack"))) (:file "rsexport") (:module "reasoner-object" :pathname "" :serial t :components ((:file "slotval") (:file "extclass") #-mop (:file "compat") (:file "composite") (:file "range"))) (:module "reasoner-rule" :pathname "" :serial t :components ((:file "prop") (:file "consumer") (:file "wff") (:file "defrule") (:file "genrule"))) (:file "rsuser")))
1,093
Common Lisp
.asd
40
20.45
64
0.541311
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
46d14a9d2973b98911348d8775612377f9c4c9885b921fce6fdeb1c756794c69
20,444
[ -1 ]
20,445
reasoner-demos.asd
whounslo_reasoner/reasoner-demos.asd
(defsystem "reasoner-demos" :description "Problem-solving and reasoning demonstrations." :licence "GPL" :author "William Hounslow" :depends-on ("reasoner") :pathname "test" :components ((:file "plan") (:file "combin") (:file "pref") (:file "miss" :depends-on ("plan")) (:file "blocks" :depends-on ("plan")) (:file "queens" :depends-on ("combin")) (:file "su" :depends-on ("combin")) (:file "mult") (:file "career" :depends-on ("pref")) (:file "boris" :depends-on ("pref"))))
515
Common Lisp
.asd
17
26.941176
62
0.625251
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8bed7817eee233f3982cd6ff41af6872cda3f145bd4e1fb31e93e219c27e14ba
20,445
[ -1 ]
20,476
serialize.html
whounslo_reasoner/doc/serialize.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>XML Reference - Common Lisp Reasoner</title> <style type="text/css" media="all"> @import "reasonerdef.css"; </style> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> </head> <body> <h1 class="title">XML Serialization and Deserialization</h1> <dl> <dt> <span class="section"><a href="reasoner.html">Main Document</a></span> </dt> <dd> </dl> <dl> <dt> <span class="section"><a href="#sectionA1">Overview</a></span> </dt> <dd> <dt> <span class="section"><a href="#sectionA2">Namespaces and Prefixes</a></span> </dt> <dd> <dt> <span class="section"><a href="#sectionA3">XML Serialization</a></span> </dt> <dd> <dl> <dt> <span class="section"><a href="#sectionA3.1">Classes</a></span> </dt> <dt> <span class="section"><a href="#sectionA3.2">Instances</a></span> </dt> <dt> <span class="section"><a href="#sectionA3.3">Rules</a></span> </dt> <dt> <span class="section"><a href="#sectionA3.4">XML Schema Built-in Datatypes</a></span> </dt> <dd> </dl> </dd> <dt> <span class="section"><a href="#sectionA4">XML Deserialization</a></span> </dt> <dd> <dl> <dt> <span class="section"><a href="#sectionA4.0">Processing of XML Schema Subelements</a></span> </dt> <dt> <span class="section"><a href="#sectionA4.1">General Parsing Interface</a></span> </dt> <dt> <span class="section"><a href="#sectionA4.1a">Parsing of XML Schema Built-in Datatypes</a></span> </dt> <dt> <span class="section"><a href="#sectionA4.2">Integration with Specific Parsers</a></span> </dt> <dd> <dl> <dt> <span class="section"><a href="#sectionA4.2.1">Parse Tree Traversal</a></span> </dt> <dt> <span class="section"><a href="#sectionA4.2.2">SAX</a></span> </dt> <dd> </dl> </dd> </dl> </dd> </dl> <h2><a id="sectionA1">Overview</a></h2> <p class="bodytext">Classes (as an XML schema) and instances, including rules, may be serialized. (Those unfamiliar with XML should read the following in conjunction with <a href="http://www.w3.org/TR/xmlschema-0/">XML Schema Part 0: Primer Second Edition</a>.)</p> <p class="bodytext">An interface is provided that can be used in conjunction with a parser to perform the reverse operation.</p> <p class="bodytext">All symbols referred to below are accessible in the package <code class="package">REASONER-EXT</code> (nickname <code class="package">RS-EXT</code>) and external, unless otherwise indicated.</p> <h2><a id="sectionA2">Namespaces and Prefixes</a></h2> <p class="bodytext">XML names that belong to a particular namespace are stored in a Lisp package associated with a namespace name (a symbol); this name (converted to a lower case string) is used to qualify the names of the namespace in serialized output.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="defns"><span class="defn">defnamespace</span></a> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">namespace-name uri {name}* [<span class="arglist">(:documentation</span> string<span class="arglist">)</span>] </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Associates <span class="argname">namespace-name</span> with <span class="argname">uri</span> and a set of Lisp-style, symbol or string, names.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="makens"><span class="defn">make-namespace</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">namespace-name uri <span class="arglist">&amp;optional</span> package </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Makes a new namespace, associating it with <span class="argname">uri</span>. The <span class="argname">package</span> argument is used to associate the namespace with an existing Lisp package. Signals an error if a package is already associated with the namespace.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="ensp"><span class="defn">ensure-namespace-package</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">name </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the package associated with a namespace name, setting it if none exists.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*namespace-package-prefix*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Used by <span class="defn"><a href="#ensp">ensure-namespace-package</a></span> when creating a Lisp package associated with a namespace name. Initially <code class="sexpr">:xml</code>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">namespace-package</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">name </td> <td>&nbsp; </td> </tr> </table> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">(setf namespace-package)</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">new-value name </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Retrieves or sets the package associated with a namespace name.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">namespace-uri</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">name </td> <td>&nbsp; </td> </tr> </table> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">(setf namespace-uri)</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">new-value name </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Retrieves or sets the uri (a string) associated with a namespace name.</p> <h2><a id="sectionA3">XML Serialization</a></h2> <p class="bodytext">Names are formatted in the standard XML mixed-case style.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*emphasize-type-name*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">If non-<span class="defn">nil</span> (the default), <span class="xmldefn">complexType</span> names have their initial character capitalized.</p> <p class="bodytext">Serialized output is sent to <span class="defn">*standard-output*</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">redirect-to-stream</span> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">stream {form}* </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Redirects <span class="defn">*standard-output*</span> to <span class="argname">stream</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*xml-print-pretty*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Determines whether elements are printed on separate lines and indented; initially non-<span class="defn">nil</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*xml-pprint-indent*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Determines how far inner elements are indented; initially 2.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*separate-definitions*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Determines whether, within a schema or ruleset, a blank line is inserted between definitions; initially non-<span class="defn">nil</span>.</p> <h3><a id="sectionA3.1">Classes</a></h3> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">with-schema</span> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2"><span class="arglist">(&amp;key</span> target-namespace namespaces default-namespace documentation documentation-lang<span class="arglist">)</span> {form}* </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Incorporates the output of the <span class="argname">form</span>s in a schema element. <span class="argname">documentation</span> is a documentation string, used to annotate the schema; <span class="argname">documentation-lang</span> defaults to <code class="sexpr">:en</code>.</p> <p class="bodytext"><span class="argname">target-namespace</span> is a prefix used to determine the value of the <span class="xmldefn">targetNamespace</span> attribute of the schema element, and to create a temporary binding of <span class="defn"><a href="#tarnsp">*target-namespace*</a></span>. Defaults to <code class="sexpr">:xsd</code>, denoting the <a href="http://www.w3.org/2001/XMLSchema">XML Schema namespace</a>.</p> <p class="bodytext"><span class="argname">namespaces</span> is used to create a temporary binding of <span class="defn"><a href="#nsp">*namespaces*</a></span>. Defaults to <code class="sexpr">(list :xsd)</code>.</p> <p class="bodytext"><span class="argname">default-namespace</span> is used to create a temporary binding of <span class="defn"><a href="#defnsp">*default-namespace*</a></span>.</p> <p class="bodytext">The values of the schema attributes <span class="xmldefn">elementFormDefault</span> and <span class="xmldefn">attributeFormDefault</span> are governed by <span class="defn"><a href="#qual">*qualified-local-elements*</a></span> and <span class="defn"><a href="#qual">*qualified-local-attributes*</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">as-top-level-element</span> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">name <span class="arglist">&amp;optional</span> type </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Outputs a top-level element declaration. If <span class="argname">type</span> is omitted, it will be the same as <span class="argname">name</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="serclassh"><span class="defn">serialize-class-hierarchy</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">root <span class="arglist">&amp;optional</span> format tangled derived </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Serializes the portion of the class hierarchy of which <span class="argname">root</span> is the root, as a sequence of <span class="xmldefn">complexType</span> (<span class="xmldefn">simpleType</span> if it is a <span class="defn">range-class</span>) elements. <span class="argname">format</span> defaults to <code class="sexpr">:xml</code>.</p> <p class="bodytext">If <span class="argname">format</span> is <code class="sexpr">:xml</code>, signals an error if any of the classes have multiple superclasses, unless <span class="argname">tangled</span> is non-<span class="defn">nil</span>. In this case, the rightmost superclass is used as the base type and the derived type will contain all the elements (i.e., slot definitions) inherited from the other superclasses.</p> <p class="bodytext">If <span class="argname">derived</span> is non-<span class="defn">nil</span>, a derived type will be output for the root class.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="serclass"><span class="defn">serialize-class</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>class <span class="arglist">extended-class)</span> <span class="arglist">(</span>format <span class="arglist">(eql :xml))</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> derived </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Outputs a derived (unless <span class="argname">derived</span> is <span class="defn">nil</span>) <span class="xmldefn">complexType</span> definition.</p> <p class="bodytext">If a class both restricts and extends the slot definitions of a superclass, two derived type definitions will be output, with the extended type being the subordinate of the restricted type.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*restricted-type-suffix*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Used to construct the restricted type name from the class name; initially <code class="sexpr">:restricted</code>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">serialize-class</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>class <span class="arglist">range-class)</span> <span class="arglist">(</span>format <span class="arglist">(eql :xml))</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Outputs <span class="xmldefn">simpleType</span> definitions derived from <span class="xmldefn">integer</span> if a subclass of <span class="defn">numeric-range</span>, or <span class="xmldefn">string</span> otherwise.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="ulst"><span class="defn">*use-list-simple-types*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">If non-<span class="defn">nil</span>, <span class="xmldefn">simpleType</span> definitions will be list types; if <span class="defn">nil</span> (the default), atomic types.</p> <p class="bodytext">Also affects the serialization of instances: in the latter case if a range has not been narrowed to a single value there will be no element content and the <span class="xmldefn">nil</span> attribute of the element will be set, whereas in the former case element content will comprise a list of values.</p> <h3><a id="sectionA3.2">Instances</a></h3> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="wixml"><span class="defn">with-xml</span></a> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2"><span class="arglist">(&amp;key</span> version target-namespace namespaces default-namespace<span class="arglist">)</span> {form}* </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Precedes output of forms with XML header. <span class="argname">version</span> defaults to 1.0.</p> <p class="bodytext"><span class="argname">target-namespace</span> is a prefix indicating the target namespace declared in the schema, if any; used to create a temporary binding of <span class="defn"><a href="#tarnsp">*target-namespace*</a></span>.</p> <p class="bodytext"><span class="argname">namespaces</span> and <span class="argname">default-namespace</span> are used to create temporary bindings for <span class="defn"><a href="#nsp">*namespaces*</a></span> and <span class="defn"><a href="#defnsp">*default-namespace*</a></span>, respectively.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="tarnsp"><span class="defn">*target-namespace*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Prefix that should be used to qualify elements and attributes (and type references in the schema), unless it is also the default namespace. (<span class="defn"><a href="#qual">*qualified-local-elements*</a></span> and <span class="defn"><a href="#qual">*qualified-local-attributes*</a></span> are used to exert further control over qualification.) Is added at the front of <span class="defn"><a href="#nsp">*namespaces*</a></span>, if not already present.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="nsp"><span class="defn">*namespaces*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">A list of prefixes corresponding to the namespaces that should be declared at the beginning of an element. Names belonging to a namespace in this list will be qualified, unless it is also the default namespace. Initially set to <code class="sexpr">(list :xsi)</code> (<code class="sexpr">:xsi</code> denotes the <a href="http://www.w3.org/2001/XMLSchema-instance">XMLSchema instance namespace</a>).</p> <p class="bodytext">When determining whether to qualify a name, this list is first searched for a namespace which has an associated Lisp package that is the same as the name&rsquo;s home package. Upon failure, it is searched again, for the first package in which there is a symbol with the same <span class="defn">symbol-name</span> as the name.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="defnsp"><span class="defn">*default-namespace*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Prefix indicating the namespace, if any, that should be declared as the default at the beginning of an element.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="qual"><span class="defn">*qualified-local-elements*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*qualified-local-attributes*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Determine whether locally defined element and attribute names belonging to the target namespace are qualified. Correspond to the schema attributes <span class="xmldefn">elementFormDefault</span> and <span class="xmldefn">attributeFormDefault</span>. Both are initially <span class="defn">nil</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*xml-id-attribute*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">The name of the uniquely-identifying (unqualified) attribute that will be associated with elements corresponding to named instances; initially <code class="sexpr">:name</code>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="serobj"><span class="defn">serialize-object</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>object <span class="arglist">extended-object)</span> <span class="arglist">(</span>format <span class="arglist">(eql :xml))</span> <span class="arglist">(</span>e <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> tag type global </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Recursively serializes <span class="argname">object</span> and all objects to which it refers. Does not detect circularities (but see <span class="defn"><a href="#sersl">serialize-slot</a></span>).</p> <p class="bodytext"><span class="argname">tag</span> and <span class="argname">type</span> are the name and type, respectively, of the corresponding element (root element if <span class="argname">global</span> is non-<span class="defn">nil</span>).</p> <p class="bodytext"><span class="argname">global</span> indicates whether the element corresponding to <span class="argname">object</span> is defined globally in the schema. Defaults to non-<span class="defn">nil</span>.</p> <p class="bodytext">If <span class="argname">global</span> is non-<span class="defn">nil</span>, namespace declarations are added according to the values of <span class="defn"><a href="#nsp">*namespaces*</a></span> and <span class="defn"><a href="#defnsp">*default-namespace*</a></span>, and the element itself will be qualified with <span class="defn"><a href="#tarnsp">*target-namespace*</a></span>, if non-<span class="defn">nil</span> and not the default namespace.</p> <p class="bodytext"><span class="argname">global</span> is bound to <span class="defn">nil</span> for recursively serialized objects. The qualification of local elements and attributes is governed by <span class="defn"><a href="#qual">*qualified-local-elements*</a></span> and <span class="defn"><a href="#qual">*qualified-local-attributes*</a></span>.</p> <p class="bodytext">If a slot refers to fewer instances than indicated by the lower bound of the <span class="defn">:count</span> slot option in the instance&rsquo;s class definition, then the missing instances will be created beforehand. If there is no such slot option, a value of 1 is used.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">rse::*unique-name-fn*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Designates a function of one argument, a class name, that is used to generate unique names for instances.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="sersl"><span class="defn">serialize-slot</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">object slot format e </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Serializes the contents of a slot. <span class="argname">slot</span> is a slot definition metaobject; other arguments are the same as for <span class="defn"><a href="#serobj">serialize-object</a></span>.</p> <p class="bodytext">A method can be supplied in order to inhibit the serialization of a particular slot.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="fat"><span class="defn">format-as-type</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">object datatype </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called to format an element of a range. <span class="argname">datatype</span> is either a datatype associated with the range, or the name of the range itself. See <span class="defn"><a href="reasoner.html#defr">defrange</a></span>. The default method returns an XML-style name, if appropriate; if not, the object itself.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="pat"><span class="defn">print-as-type</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">object datatype </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called to print an element of a range. The default method calls <span class="defn">princ</span> on the value returned by <span class="defn"><a href="#fat">format-as-type</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">range-to-content</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">value slot-type datatype </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Examines <span class="defn"><a href="#ulst">*use-list-simple-types*</a></span> and returns the value to be passed to <span class="defn"><a href="#pat">print-as-type</a></span>. Should be overridden if a <span class="defn"><a href="#pat">print-as-type</a></span> method always requires access to all elements of a range.</p> <h3><a id="sectionA3.3">Rules</a></h3> <p class="bodytext">An XML schema for the rule language is in <a href="reasoner.xsd"> reasoner.xsd</a>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">serialize-rules</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">rules <span class="arglist">&amp;optional</span> format comment </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Serializes <span class="argname">rules</span> (a list of instances or their names), enclosing them in a <span class="xmldefn">ruleSet</span> element, incorporating namespace declarations according to <span class="defn"><a href="#nsp">*namespaces*</a></span> and <span class="defn"><a href="#defnsp">*default-namespace*</a></span>. <span class="argname">format</span> defaults to <code class="sexpr">:xml</code>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">serialize-rule</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">instance format </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Serializes a rule (<span class="defn">well-formed-formula</span>) instance.</p> <h3><a id="sectionA3.4">XML Schema Built-in Datatypes</a></h3> <p class="bodytext"><span class="defn"><a href="#pat">print-as-type</a></span> methods are defined for the datatypes mentioned in the section <span class="section"><a href="#sectionA4.1a">Parsing of XML Schema Built-in Datatypes</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">rse::*date-time-decoding-fn*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Used to decode a range bound representing a time. Initially <span class="defn">decode-universal-time</span>.</p> <h2><a id="sectionA4">XML Deserialization</a></h2> <p class="bodytext">The deserialization operation utilizes an external XML parser.</p> <p class="bodytext">Parsers can be categorized according to whether they produce a complete parse tree, or expose an interface (e.g., SAX) that enables parsing to be interleaved with subsequent processing.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="dserobjs"><span class="defn">deserialize-as-objects</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">parse-tree </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;key</span> namespace base namespaces </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Takes a complete parse tree and creates or reinitializes the equivalent classes or instances. Calls <span class="defn"><a href="#dserobj">deserialize-as-object</a></span>. Returns a set of assumptions.</p> <p class="bodytext"><span class="argname">namespaces</span> is used to create a temporary binding for <span class="defn"><a href="#nsp">*namespaces*</a></span>, which is used to find the Lisp package associated with a namespace; it defaults to all defined namespaces (see <span class="defn"><a href="#makens">make-namespace</a></span>). <span class="argname">namespace</span>, used to create a temporary binding for <span class="defn"><a href="#nsp">*default-namespace*</a></span>, is added to the front of this list if non-<span class="defn">nil</span>. <span class="argname">base</span> is used to create a temporary binding for <span class="defn"><a href="#tarnsp">*target-namespace*</a></span> and defaults to the value of <span class="argname">namespace</span> (see <span class="section"><a href="triple.html">RDF and OWL Compatibility</a></span>).</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="dserobj"><span class="defn">deserialize-as-object</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">element </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;key</span> tag-fn attribute-fn content-fn </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Takes a top-level element and creates or reinitializes the equivalent class or instance.</p> <p class="bodytext"><span class="argname">tag-fn</span>, when applied to a node of the tree, should return a tag name, unqualified; <span class="argname">attribute-fn</span> should return an attribute value, given a node, a name and, if the name is qualified, the uri of the namespace; <span class="argname">content-fn</span> should return a list comprising either a single string, or subordinate nodes.</p> <p class="bodytext"><span class="argname">tag-fn</span> defaults to <span class="defn">caar</span> (or <span class="defn">car</span>, if atomic); <span class="argname">attribute-fn</span> defaults to <span class="defn">assoc</span> applied to the <span class="defn">cdar</span> of the node; <span class="argname">content-fn</span> defaults to <span class="defn">cdr</span>.</p> <p class="bodytext"> Uses a <span class="section"><a href="#sectionA4.1">low-level interface</a></span> that is also compatible with the second category of parsers.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*assumptions*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Captures assumptions created during deserialization. Rebound by <span class="defn"><a href="#dserobjs">deserialize-as-objects</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*assumption*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">If assigned a single assumption, will be used in place of any number of assumptions that would otherwise be created.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="defie"><span class="defn">define-ignored-elements</span></a> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">namespace-name {name}* </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Defines a set of XML-style, symbol or string, element names, belonging to <span class="argname">namespace-name</span>, whose presence should not affect the processing of surrounding elements in an XML document.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*ignored-elements*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">The full list of elements that are to be treated as no-ops.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*count-subelements*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">If bound to <span class="defn">nil</span> (default non-<span class="defn">nil</span>), will eliminate the considerable overhead of maintaining a count of subelements, if there are many. See <span class="section"><a href="reasoner.html#section7">Cardinality</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">count-subelements-p</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">object slot-name </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">The system-supplied method examines the above variable. May be specialized to exert finer-grained control.</p> <h3><a id="sectionA4.0">Processing of XML Schema Subelements</a></h3> <p class="bodytext">A <span class="xmldefn">complexType</span> definition is always treated as corresponding to a CLOS class definition.</p> <p class="bodytext">Global <span class="xmldefn">element</span> declarations and references to them are recognized.</p> <p class="bodytext">The built-in datatypes <span class="xmldefn">boolean</span>, <span class="xmldefn">integer</span>, <span class="xmldefn">nonNegativeInteger</span>, <span class="xmldefn">positiveInteger</span> and <span class="xmldefn">string</span>, as well as those mentioned in the section <span class="section"><a href="#sectionA4.1a">Parsing of XML Schema Built-in Datatypes</a></span>, may be used in element declarations.</p> <p class="bodytext">The <span class="xmldefn">all</span> and <span class="xmldefn">choice</span> group elements are recognized, but no processing is performed beyond that for <span class="xmldefn">sequence</span>.</p> <p class="bodytext">Named <span class="xmldefn">group</span> elements are not recognized.</p> <h3><a id="sectionA4.1">General Parsing Interface</a></h3> <p class="bodytext">Usually, an XML name is converted into a Lisp equivalent, with hyphens inserted at the points marked by a transition between lower and upper case. However, if <span class="defn">readtable-case</span>, when called with the current readtable, returns <code class="sexpr">:preserve</code>, the XML variant will be used exclusively.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="findxn"><span class="defn">find-xml-name</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">name namespace <span class="arglist">&amp;optional</span> errorp </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Locates the symbol named <span class="argname">name</span> (a string) in the package associated with the namespace given by <span class="argname">namespace</span>, which can be either a uri (string) or a keyword symbol. If none is found, signals an error, unless <span class="argname">errorp</span> is <span class="defn">nil</span>. For use with element names. See <span class="defn"><a href="#defns">defnamespace</a></span>, <span class="defn"><a href="#defie">define-ignored-elements</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="intxn"><span class="defn">intern-xml-name</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">name namespace </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Enters a symbol named <span class="argname">name</span> (a string) into the package associated with the namespace given by <span class="argname">namespace</span>, which can be either a uri (string) a keyword symbol, or <span class="defn">nil</span>. In the latter case, if the name is not already present in one of the members of <span class="defn"><a href="#nsp">*namespaces*</a></span>, it is interned in the current package.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="part"><span class="defn">parse-as-type</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">object datatype min max </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called to parse non-whitespace content within an instance document, bounded by <span class="argname">min</span> and <span class="argname">max</span>. The default method calls <span class="defn">parse-integer</span>, and then, if <span class="defn">nil</span> is returned, <span class="defn"><a href="#intxn">intern-xml-name</a></span>. See <span class="defn"><a href="#fat">format-as-type</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">into-xml-element</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">tag attributes </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Should be called when an element is first encountered.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">store-xml-content</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">content </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Records the content of a leaf element.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">outof-xml-element</span> </td> <td class="methsig1">Function </td> </tr> </table> <p class="bodytext">Should be called when unwinding out of an element.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*count-slot-suffix*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*count-type-suffix*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Used to derive from a schema element&rsquo;s name, if it contains occurrence constraints, the name and type of an additional slot definition that is created to hold this information (see <span class="section"><a href="reasoner.html#section7">Cardinality</a></span>). Initially <code class="sexpr">:count</code> and <code class="sexpr">:numbers</code>.</p> <h3><a id="sectionA4.1a">Parsing of XML Schema Built-in Datatypes</a></h3> <p class="bodytext"><span class="defn"><a href="#part">parse-as-type</a></span> methods are defined for the datatypes enumerated below. All return a numeric range; in cases other than <span class="xmldefn">dateTime</span> and <span class="xmldefn">time</span> the lower and upper bounds will differ (<em>may</em> differ in the case of <span class="xmldefn">duration</span>).</p> <p class="bodytext"><span class="xmldefn">dateTime</span> and its truncated variants (<span class="xmldefn">time</span>, <span class="xmldefn">date</span>, <span class="xmldefn">gYearMonth</span>, <span class="xmldefn">gYear</span>, <span class="xmldefn">gMonthDay</span>, <span class="xmldefn">gDay</span>, <span class="xmldefn">gMonth</span>) are represented, viewed as sets of times, by their earliest and latest elements, and are converted by <span class="defn"><a href="#dte">*date-time-encoding-fn*</a></span>. Fractional seconds are ignored.</p> <p class="bodytext">A <span class="xmldefn">duration</span> is converted to a number of seconds. A fraction in the seconds component is ignored. Ambiguity arises from the varying lengths of months and years.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="dte"><span class="defn">rse::*date-time-encoding-fn*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Initially <span class="defn">encode-universal-time</span>; will reject a negative-signed year. A substitute should accept the same arguments that it does.</p> <h3><a id="sectionA4.2">Integration with Specific Parsers</a></h3> <h4><a id="sectionA4.2.1">Parse Tree Traversal</a></h4> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">deserialize-as-object</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>element <span class="arglist">xml-object)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Takes as its input an element in the parse tree generated by the <a href="http://clocc.sourceforge.net/dist/cllib.html">CLLIB XML Parser</a>. See <span class="defn"><a href="#dserobjs">deserialize-as-objects</a></span>.</p> <h4><a id="sectionA4.2.2">SAX</a></h4> <p class="bodytext">Both the <a href="http://common-lisp.net/project/cxml"> CXML</a> and <a href="http://www.franz.com/support/documentation/current/doc/sax.htm"> Allegro</a> parsers are supported. If both are present, CXML takes precedence.</p> <p class="bodytext">A class <span class="defn">deserializer</span> is defined (in package <code class="package">rs-sax</code>), which can be used in conjunction with the CXML function <span class="defn">parse</span>.</p> <p class="bodytext">For Allegro users, <span class="defn">deserializer</span> is defined in package <code class="package">net.xml.rs</code>, and can be used with the functions <span class="defn">sax-parse-file</span>, <span class="defn">sax-parse-stream</span> and <span class="defn">sax-parse-string</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">namespace-missing</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">parser prefix iri </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called if there is no namespace definition corresponding to (having the same uri as) a declaration in the document. The default behaviour is to call <span class="defn"><a href="#makens">make-namespace</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">default-namespace-missing</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">parser iri </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called if there is no namespace definition having the same uri as the default namespace declaration in the document. The default behaviour is to call <span class="defn"><a href="#makens">make-namespace</a></span>, passing it a fresh symbol.</p> </body> </html>
39,786
Common Lisp
.l
1,105
34.852489
103
0.72791
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4ada7ac101900c048c8889f8353799c47b887d8177a57af07f0a84124e88930b
20,476
[ -1 ]
20,477
intro.html
whounslo_reasoner/doc/intro.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>Common Lisp Reasoner</title> <style type="text/css" media="all"> @import "reasoner.css"; </style> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> </head> <body> <div id="header"> <div class="titlebar"> <div class="title"> <h1>Common Lisp Reasoner</h1> <h3>Version 3.6</h3> </div> <div class="menubar"> <ul> <li class="nav"><a href="mailto:[email protected]">Contact</a></li> <li class="nav"><a href="demos.html">Demonstrations</a></li> <li class="nav"><a href="reasoner.html">Reference</a></li> </ul> </div> </div> </div> <h2>Introduction</h2> <p class="bodytext">The Common Lisp Reasoner project aims to create a practical technology that exploits the synergy between its three major components to make AI-related applications, such as scheduling and diagnosis, easier to develop. These components are:</p> <ul> <li>A portable extension of the Common Lisp Object System (CLOS)</li> <li>The Assumption-Based Truth-Maintenance System (ATMS) of de Kleer</li> <li>A rule language comprising non-directional constraints as well as unidirectional rules</li> </ul> <p class="bodytext">Because CLOS permits, by means of the <a href="http://www.alu.org/mop">Metaobject Protocol</a>, open-ended extension, it is both the implementation language and the kernel of the implemented system, within which a set of sound principles appropriate to the practice of knowledge representation rather than programming have been realized.</p> <p class="bodytext">In reasoning applications, the values stored into the slots of an instance (the data to be reasoned with) are accumulated rather than replaced. Permitted values are specified in the class of the instance. They are either other instances, or enumerated ranges of (mutually exclusive) values that may subsequently be narrowed by reasoning activity.</p> <p class="bodytext">Each stored value is encapsulated in an ATMS <em>node</em>&mdash;a record not only of the value, but also its <em>justification</em> (derivation) and the resultant belief states (or <em>environments</em>), determined by the ATMS, in which it holds. An environment is given by a set of primitive <em>assumptions</em>; an assumption constitutes an explicit, problem-specific decision to assume some datum or data. The ATMS enables environments to be explored systematically and efficiently. Contradictions are isolated and recorded as <em>nogoods</em>.</p> <p class="bodytext">The rule language permits the expression of arbitrarily complex logical sentences. The slot definitions of classes collectively constitute a vocabulary of attributes that can be referred to in rule definitions. When reasoning, classes and instances provide an efficient means of retrieving rules and the data upon which they operate.</p> <figure id="fig1"> <img src="strata.png" alt="Stratification Diagram"/> </figure> <h2>Latest Features</h2> <p class="bodytext"><em>RDF and OWL.</em> Earlier <span class="section"><a href="serialize.html">XML serialization and deserialization</a></span> capabilities have been extended to support <span class="section"><a href="triple.html">RDF/XML</a></span>. Features have been added (primarily <span class="section"><a href="reasoner.html#section9a">automatically-generated rules</a></span>) to offer limited support for OWL ontologies.</p> <p class="bodytext"><em>Parallelism.</em> The rule matching cycle has been redesigned to work in parallel. Parallelism is enabled when used in conjunction with <a href="http://lparallel.org">Lisp in Parallel</a>.</p> <h2>Historical Note</h2> <p class="bodytext">The design outlined above was conceived in relation to the development of legal reasoning applications, in order to meet some exacting requirements: to capture the explicit and implicit exceptions inherent in legal language, to accommodate conflicting rules which give rise to competing arguments, and to derive all inferences sanctioned by a logical sentence by restricting the values of attributes.</p> <h2>Compatibility</h2> <p class="bodytext">The source code has been tested in <a href="http://www.franz.com">Allegro</a>, <a href="http://www.clisp.org">CLISP</a>, <a href="http://ecls.sourceforge.net/">ECL</a>, <a href="http://www.lispworks.com">LispWorks</a> and <a href="http://www.sbcl.org">SBCL</a>. Further compatibility information may be found in the release notes.</p> </body> </html>
4,572
Common Lisp
.l
90
48.433333
91
0.760368
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c81bb4c37290854dcdc24aed959eb82b159125270c8a74889ba472396013a24a
20,477
[ -1 ]
20,478
triple.html
whounslo_reasoner/doc/triple.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>RDF/XML Reference - Common Lisp Reasoner</title> <style type="text/css" media="all"> @import "reasonerdef.css"; table.names { font-family: sans-serif; } </style> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> </head> <body> <h1 class="title">RDF and OWL Compatibility</h1> <dl> <dt> <span class="section"><a href="reasoner.html">Main Document</a></span> </dt> <dd> </dl> <dl> <dt> <span class="section"><a href="#sectionB1">Overview</a></span> </dt> <dd> <dt> <span class="section"><a href="#sectionB2">Usage Examples</a></span> </dt> <dd> <dt> <span class="section"><a href="#sectionB3">Serialization and Deserialization</a></span> </dt> <dd> <dl> <dt> <span class="section"><a href="#sectionB3.0">Resource Classes</a></span> </dt> <dt> <span class="section"><a href="#sectionB3.1">RDF and OWL Serialization</a></span> </dt> <dt> <span class="section"><a href="#sectionB3.2">RDF and OWL Deserialization</a></span> </dt> <dd> </dl> </dd> </dl> <h2><a id="sectionB1">Overview</a></h2> <p class="bodytext">For an introduction to RDF and OWL, consult the <a href="http://www.w3.org/TR/rdf-primer/">RDF Primer</a> and the <a href="http://www.w3.org/TR/owl-guide/">OWL Web Ontology Language Guide</a>.</p> <p class="bodytext">There is an obvious correspondence between the representation of a <a href="reasoner.html#section6">slot value</a> as a specialization of an ATMS node and the RDF subject-predicate-object triple.</p> <p class="bodytext">Similarly, there is a clear correspondence between CLOS and RDF Schema, although there is no specialization of properties in CLOS. Conversely, RDF Schema does not allow the restriction of a property (or in CLOS parlance, slot) within a class. Nor does it make any provision for cardinality information. These features are to be found in OWL.</p> <p class="bodytext">The relationship with OWL, however, is less straightforward.</p> <p class="bodytext">The CLOS class hierarchy is solely a mechanism for elision, for recording information (properties and rules) in one place (a superclass), and having it automatically propagate to many places (its subclasses). The name of a class is merely an <em>abbreviation</em> for what it encapsulates (a description of its instances).</p> <p class="bodytext">Specialized class-based reasoning has been added to this framework, in the form of <span class="defn"><a href="reasoner.html#clas">classify</a></span>. It infers that an instance of a class is also a member of a subordinate class that restricts the values of its properties. (<span class="defn">change-class</span> can then be used to change the instance&rsquo;s class to the subordinate class.)</p> <p class="bodytext">Its use presumes that subordinate classes are disjoint (see <span class="section"><a href="reasoner.html#section7a.1">Compound Objects</a></span>), and that <em>either</em> they have been fully enumerated and are differentiated by varying restrictions of the same property or properties, <em>or</em> that each subordinate class constitutes a definition, that is, contains sufficient as well as necessary conditions for membership.</p> <p class="bodytext">Its use further presumes that the subordinate classes define additional properties, whose values can then be sought.</p> <p class="bodytext">In contrast, a primary purpose of OWL DL is to enable one to state that, e.g., &lsquo;<code class="sexpr">WhiteWine</code> is exactly the intersection of the class <code class="sexpr">Wine</code> and the set of things that are white in colour&rsquo;. This amounts to stating that the instances to which this description applies are <em>called</em> <code class="sexpr">WhiteWine</code>.</p> <p class="bodytext">The overlap with OWL, therefore, is roughly the OWL Lite subset. The knowledge representation facilities outlined above do not constitute, as a whole or in part, a description logic.</p> <p class="bodytext">The implemented subset of OWL Lite comprises those features that have counterparts in RDF, plus property restrictions and property characteristics. Cardinality expressions with arbitrary bounds (deriving from OWL DL) and classes as instances (OWL Full) are, however, permitted. Identity of classes, and of instances, is implemented by associating multiple names (as accepted by <span class="defn">find-class</span> and <span class="defn"><a href="reasoner.html#find">find-instance</a></span>) with a single object.</p> <div id="names"> <style scoped> table { border: 1px solid; width: 95%} td, th { border: 1px solid; padding: 5} </style> <table class="names"> <caption> Table 1: Implemented Language Subsets </caption> <thead> <tr> <th> &nbsp; </th> <th> RDF </th> <th> RDFS </th> <th> OWL </th> </tr> </thead> <tbody> <tr> <th> Attributes </th> <td> resource, about, ID, datatype </td> <td> &nbsp; </td> <td> &nbsp; </td> </tr> <tr> <th> Elements </th> <td> RDF, Description, Property, type </td> <td> comment, label, Class, Resource, subClassOf, subPropertyOf, domain, range, Datatype </td> <td> Ontology, Class, ObjectProperty, DatatypeProperty, Thing, sameAs, TransitiveProperty, SymmetricProperty, FunctionalProperty, inverseOf, InverseFunctionalProperty, Restriction, onProperty, cardinality, minCardinality, maxCardinality, allValuesFrom, someValuesFrom </td> </tr> <tr> <th> Elements that have no effect </th> <td> &nbsp; </td> <td> seeAlso, isDefinedBy </td> <td> equivalentClass, equivalentProperty, differentFrom, AllDifferent, distinctMembers, versionInfo, imports, priorVersion, backwardCompatibleWith, incompatibleWith, AnnotationProperty, OntologyProperty, DeprecatedClass, DeprecatedProperty </td> </tr> </tbody> </table> </div> <p class="bodytext">User-defined datatypes are used to denote enumerated sets of values and numeric subranges.</p> <h2><a id="sectionB2">Usage Examples</a></h2> <p class="bodytext">There are example formalizations (ontology fragments) of so-called <a href="stuff.rdf">stuff</a> (with associated <a href="stuff.xsd">datatypes</a>) and <a href="disease.rdf">medical terms</a> (plus <a href="disease.xsd">datatypes</a>).</p> <h2><a id="sectionB3">Serialization and Deserialization</a></h2> <p class="bodytext">The following should be read in conjunction with <a href="serialize.html">XML Serialization and Deserialization.</a></p> <p class="bodytext">In whatever combination is appropriate, <code class="sexpr">:owl</code>, <code class="sexpr">:rdfs</code> and <code class="sexpr">:rdf</code> should appear in <span class="defn"><a href="serialize.html#nsp">*namespaces*</a></span>; <code class="sexpr">:owl</code>, if present, must precede <code class="sexpr">:rdfs</code>.</p> <p class="bodytext">The value of <span class="defn"><a href="serialize.html#tarnsp">*target-namespace*</a></span> is interpreted as the base URI of the document.</p> <h3><a id="sectionB3.0">Resource Classes</a></h3> <p class="bodytext">The distinction between <span class="xmldefn">rdfs:Class</span> and <span class="xmldefn">owl:Class</span> (the latter being a subclass of the former) relevant to OWL Lite is reflected in the CLOS class hierarchy, though not their subclass relationship with <span class="xmldefn">rdfs:Resource</span>. They are instances of <span class="defn">resource-class</span>.</p> <p class="bodytext">In the absence of any property classes, <span class="xmldefn">owl:Thing</span> is treated as identical to <span class="xmldefn">rdfs:Resource</span>.</p> <p class="bodytext">Subclasses of these classes, and their slot definitions, can store multilingual labels, corresponding to <span class="xmldefn">rdfs:label</span> elements of a class or property.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">class-label</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">class </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns multilingual label information for class, the value of the <span class="defn">:label</span> initialization argument.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">slot-definition-label</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">slot </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns multilingual label information for slot, the value of the <span class="defn">:label</span> initialization argument.</p> <p class="bodytext">This information may take the form of a string, a list comprising a single string (if supplied as a <span class="defn">defclass</span> class option), or a list of language-label pairs:</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">resource-label-lang</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">label </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the language tag associated with the label.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">resource-label-text</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">label </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the content of the label.</p> <p class="bodytext">During deserialization information is always stored in this form.</p> <h3><a id="sectionB3.1">RDF and OWL Serialization</a></h3> <p class="bodytext">The generic functions <span class="defn"><a href="serialize.html#serobj">serialize-object</a></span>, <span class="defn"><a href="serialize.html#serclass">serialize-class</a></span> and <span class="defn"><a href="serialize.html#serclassh">serialize-class-hierarchy</a></span> accept <code class="sexpr">:rdf</code>, <code class="sexpr">:rdfs</code> or <code class="sexpr">:owl</code> as their <span class="argname">format</span> argument. <span class="defn"><a href="serialize.html#serobj">serialize-object</a></span> will only recursively serialize unnamed objects.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="serobj"><span class="defn">serialize-objects</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>object <span class="arglist">extended-object)</span> <span class="arglist">(</span>format <span class="arglist">(eql :rdf))</span> <span class="arglist">(</span>e <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> global </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Recursively serializes <span class="argname">object</span> and all (i.e., named and unnamed) objects to which it refers. Does not detect circularity or repetition (but see <span class="defn"><a href="serialize.html#sersl">serialize-slot</a></span>). <span class="argname">global</span> indicates whether the element corresponding to <span class="argname">object</span> is defined globally in the schema; it defaults to non-<span class="defn">nil</span>.</p> <p class="bodytext"><span class="defn"><a href="serialize.html#serclass">serialize-class</a></span> generates both property and class definitions. If generating RDF Schema definitions, this output may not capture all the information in the CLOS hierarchy. When applied to an instance of <span class="defn">range-class</span>, it generates a single <span class="xmldefn">rdfs:Datatype</span> element.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*allow-multiple-domains*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">When generating RDF Schema definitions, determines whether multiple domain and range elements, gleaned from different slot descriptions of the same name in the CLOS hierarchy, may appear within a <span class="xmldefn">rdfs:Property</span> definition. If <span class="defn">nil</span> (the default) it will reflect only the most general slot description in the hierarchy.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="wirdf"><span class="defn">with-rdf</span></a> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2"><span class="arglist">(&amp;key</span> xml-version xml-base namespaces default-namespace<span class="arglist">)</span> {form}* </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Variation on <span class="defn"><a href="serialize.html#wixml">with-xml</a></span>, enclosing <span class="argname">form</span>s in an <span class="xmldefn">rdf:RDF</span> element.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">with-ontology</span> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2"><span class="arglist">(&amp;key</span> xml-version about namespaces default-namespace comment label label-lang<span class="arglist">)</span> {form}* </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Like <span class="defn"><a href="#wirdf">with-rdf</a></span>, but incorporating an <span class="xmldefn">owl:Ontology</span> element. <span class="argname">about</span> is used to set the base URI of the document; the value of <span class="xmldefn">rdf:about</span> attribute is left empty.</p> <h3><a id="sectionB3.2">RDF and OWL Deserialization</a></h3> <p class="bodytext">Both property specialization and property characteristics (other than <span class="xmldefn">owl:FunctionalProperty</span>) are implemented by means of <span class="section"><a href="reasoner.html#section9a">automatically-generated rules</a></span>.</p> <p class="bodytext"><span class="xmldefn">owl:someValuesFrom</span> is treated as a kind of property specialization: a rule is generated to propagate values that satisfy the restriction to a specially-created slot with restricted cardinality. In addition, the effect of <span class="xmldefn">hasValue</span> (OWL DL) can be achieved by specialization to individuals (i.e., by defining a class, say, <code class="sexpr">no-other-than-foo</code> that has a single instance, <code class="sexpr">foo</code>).</p> <p class="bodytext">RDF containers and collections are unimplemented.</p> <p class="bodytext">An attempt to deserialize an unimplemented feature is an error. But see <span class="defn"><a href="serialize.html#defie">define-ignored-elements</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">rse::*class-slot-specifications*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Used to accumulate slot specifications derived from property and class definitions, to be processed upon reaching a closing <span class="xmldefn">rdf:RDF</span> tag.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">with-deserialization-unit</span> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">{form}* </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Binds the above variable. Within a deserialization unit (or if absent) an attempt to redefine a property is treated as an error.</p> </body> </html>
15,255
Common Lisp
.l
412
35.864078
99
0.749966
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
517381ccb835af98c5daa726beaa4c86f1afc03c5331fb51c9742e0b9322f672
20,478
[ -1 ]
20,479
reasoner.html
whounslo_reasoner/doc/reasoner.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>Reference - Common Lisp Reasoner</title> <style type="text/css" media="all"> @import "reasonerdef.css"; </style> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> </head> <body> <h1 class="title">Common Lisp Reasoner</h1> <h3 class="version">Version 3.6</h3> <h3 class="author">William Hounslow</h3> <dl> <dt> <span class="section"><a href="#section1">Overview</a></span> </dt> <dd> <dt> <span class="section"><a href="#section2">Assumption-Based Truth-Maintenance System (ATMS)</a></span> </dt> <dd> <dt> <span class="section"><a href="#section3">Reasoning Extensions to the Object System</a></span> </dt> <dd> <dt> <span class="section"><a href="#section4">Object Creation</a></span> </dt> <dd> <dt> <span class="section"><a href="#section5">Ranges</a></span> </dt> <dd> <dt> <span class="section"><a href="#section6">Reading and Writing Slots</a></span> </dt> <dd> <dt> <span class="section"><a href="#section7">Cardinality</a></span> </dt> <dd> <dt> <span class="section"><a href="#section7a">Composite Objects</a></span> </dt> <dd> <dl> <dt> <span class="section"><a href="#section7a.1">Compound Objects</a></span> </dt> <dt> <span class="section"><a href="#section7a.2">Assemblies</a></span> </dt> <dd> </dl> </dd> <dt> <span class="section"><a href="#section8">Class-Changing</a></span> </dt> <dd> <dt> <span class="section"><a href="#section9">Rule Language</a></span> </dt> <dd> <dl> <dt> <span class="section"><a href="#section9.1">Note on Lisp Propositions</a></span> </dt> <dt> <span class="section"><a href="#section9.2">Note on Use of Relational Propositions in Rules</a></span> </dt> <dt> <span class="section"><a href="#section9.3">Example Well-Formed Formulae</a></span> </dt> <dd> </dl> </dd> <dt> <span class="section"><a href="#section9a">Automatically-Generated Rules</a></span> </dt> <dd> <dt> <span class="section"><a href="#section10">Rule Objects</a></span> </dt> <dd> <dt> <span class="section"><a href="#section11">Reasoning With Assumed Data</a></span> </dt> <dd> <dt> <span class="section"><a href="serialize.html">Appendix: XML Serialization and Deserialization</a></span> </dt> <dd> <dt> <span class="section"><a href="triple.html">Appendix: RDF and OWL Compatibility</a></span> </dt> <dd> </dl> <h2><a id="section1">Overview</a></h2> <p class="bodytext">This document describes a reasoning tool that extends (and is implemented in) the Common Lisp Object System (CLOS) and that is intended to be used in a variety of practical search and reasoning tasks, including scheduling, planning, diagnosis and predictive reasoning. It should be read in conjunction with the CLOS specification. Certain features are implemented by means of the CLOS Metaobject Protocol (see Kiczales, des Rivieres and Bobrow, <cite>The Art of the Metaobject Protocol</cite>, MIT Press, 1991).</p> <p class="bodytext">All symbols referred to below are accessible in the package <code class="package">REASONER</code> (nickname <code class="package">RS</code>) and external, unless otherwise indicated.</p> <h2><a id="section2">Assumption-Based Truth-Maintenance System (ATMS)</a></h2> <p class="bodytext">See: de Kleer, &lsquo;An Assumption-Based TMS&rsquo;, <cite>Artificial Intelligence</cite>, <cite>28</cite> (1986).</p> <p class="bodytext">Note: Those that wish to access data structures internal to the ATMS (for the pur&shy;poses of, say, following a chain of justifications, or obtaining the set of assumptions denoted by an environment) should inherit from the package <code class="package">ATMS</code> in their working package.</p> <p class="bodytext">The class <span class="defn">core-atms</span> is the common superclass of <span class="defn">atms</span> and <span class="defn">basic-atms</span>. For details of the distinction between the latter two classes, see <span class="section"><a href="#section11">Reasoning With Assumed Data</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="makea"><span class="defn">make-assumption</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>tms <span class="arglist">core-atms)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> name </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Manufactures an assumption.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="disc"><span class="defn">discard-assumption</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>tms <span class="arglist">core-atms)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>n <span class="arglist">assumption)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Discards an assumption, and all internal ATMS data structures that mention it.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="uniq"><span class="defn">uniquify-environment</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>tms <span class="arglist">core-atms)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>assumptions <span class="arglist">list)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> dont-create ordered </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the environment object corresponding to a list of assumptions. Unless <span class="argname">ordered</span> is non-<span class="defn">nil</span>, the assumptions are first sorted. If there is no such object and the <span class="argname">dont-create </span>argument is not supplied or is <span class="defn">nil</span>, an object is created; otherwise <span class="defn">nil</span> is returned.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">subsumesp</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>e1 <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>e2 <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Determines if the assumptions of <span class="argname">e1</span> are a subset of those of <span class="argname">e2</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">contradictoryp</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>environment <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Determines if an environment is contradictory.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">in-p</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>n <span class="arglist">node)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2">environment </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Determines if a node holds in an environment (i.e., an environment in the label of <span class="argname">n</span> subsumes <span class="argname">environment</span>).</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">truep</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>n <span class="arglist">node)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Determines if a node holds in the environment of no assumptions.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="empt"><span class="defn">*empty-environment*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">The distinguished environment of no assumptions.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="atms"><span class="defn">*atms*</span></a> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">The ATMS used by the reasoning sub-system.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">reinitialize-atms</span> </td> <td class="methsig1">Function </td> </tr> </table> <p class="bodytext">Reinitializes the above variables: recreates all data structures from scratch.</p> <h2><a id="section3">Reasoning Extensions to the Object System</a></h2> <p class="bodytext">The basic object system is extended to support the treatment of values in slots of instances as data to be reasoned with: reasoning is initiated when a value is stored. This behaviour is provided by a special metaclass, <span class="defn">extended-class</span>. (This alter&shy;native metaclass is specified using the <span class="defn">:metaclass</span> option of <span class="defn">defclass</span>.)</p> <p class="bodytext">The class <span class="defn">extended-object</span> is the instance of <span class="defn">extended-class</span> that is the super&shy;class of all other instances of <span class="defn">extended-class</span> except itself; it is a subclass of <span class="defn">standard-object</span>. A class defined with metaclass <span class="defn">extended-class</span> has <span class="defn">extended-object</span> as its default superclass. In the package <code class="package">REASONER-USER</code>, the metaclass itself defaults to <span class="defn">extended-class</span>.</p> <h2><a id="section4">Object Creation</a></h2> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">make-instance</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">class-name <span class="arglist">&amp;rest</span> initargs </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Creates and returns a new instance of a class; is described fully in the CLOS speci&shy;fication. When applied to a subclass of the class <span class="defn">extended-object</span>, the following initialization arguments are valid:</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">:antecedents</span> </td> <td class="methsig1">Initialization Argument </td> </tr> </table> <p class="bodytext">A list of ATMS nodes such as might be supplied to <span class="defn"><a href="#add">add-slot-value</a></span>. The new instance is justified by the antecedents, so that any values added to its slots will inherit the be&shy;lief status(es) of those antecedents.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">:name</span> </td> <td class="methsig1">Initialization Argument </td> </tr> </table> <p class="bodytext">Gives a name to the instance. The function <span class="defn"><a href="#find">find-instance</a></span> returns the instance named by a symbol. The function <span class="defn"><a href="#inst">instance-name</a></span> returns the name of an instance.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="shar"><span class="defn">shared-initialize</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>instance <span class="arglist">extended-object)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2">slot-names </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;rest</span> initargs </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Implements initialization behaviour whereby values for slots are derived from typing information, where appropriate. See the CLOS specification.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="find"><span class="defn">find-instance</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">name <span class="arglist">&amp;optional</span> errorp </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the instance named by a symbol. Works analogously to <span class="defn">find-class</span>, as de&shy;scribed in the CLOS specification.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="inst"><span class="defn">instance-name</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">instance </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the name of an instance.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">instance-assumption</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">instance </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">If a single assumption has been used to justify <span class="argname">instance</span>, returns that assumption.</p> <h2><a id="section5">Ranges</a></h2> <p class="bodytext">A restriction can be placed on the values that may be stored in a slot, by supplying typing information in the slot specifier (a part of a class definition) as described in the CLOS specification. This must be a valid type specifier; if it is a class name, slot values must be instances of that class. (It may also be a compound type specifier, such as <span class="defn">or</span>, mentioning multiple classes.)</p> <p class="bodytext">We extend this mechanism by allowing the type to denote a range of values: either an enumerated range of values, or a numeric sub-range (for instance, <code class="sexpr">(cerise crimson cyan)</code> for a <code class="sexpr">colour</code> slot, or <code class="sexpr">(0 137)</code> for an <code class="sexpr">age</code> slot). Ranges over symbols (<span class="defn">symbolic-range</span>), numbers (<span class="defn">numeric-range</span>) and truth values (<span class="defn">true-or-false</span>, <span class="defn">true</span>, <span class="defn">false</span>) are provided; the macro <span class="defn"><a href="#defr">defrange</a></span> is used to define specialized ranges, such as <code class="sexpr">age-range</code>.</p> <p class="bodytext">Besides numbers, the distinguished symbols <span class="defn">big</span> and <span class="defn">-big</span> may appear in a numeric range.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="defr"><span class="defn">defrange</span></a> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">name-and-options [documentation-string] <span class="arglist">&amp;rest</span> elements </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Defines a new range abbreviation: <span class="argname">elements</span>, a sequence of symbols, or between one and two values representing the lower and upper bounds of a numeric range, is associated with <span class="argname">name</span>, which may be used as the <span class="defn">:type</span> slot option of a slot specifier in a <span class="defn">defclass</span> form. Options take the form they do in <span class="defn">defstruct</span>; the options that can be given are <span class="defn">:include</span>, which takes an argument which is the name of another range definition, and <span class="defn">:external-type</span>, which is intended to facilitate the translation of numeric values into external formats, such as dates and times. The latter option is inherited.</p> <p class="bodytext">If <span class="argname">elements</span> comprises symbols, and there is a range definition naming a superset of those symbols, it is located in the type hierarchy below the superset range; numeric ranges are always defined as direct sub-types of <span class="defn">numeric-range</span>. The <span class="defn">:include</span> option may be used to defeat this behaviour.</p> <p class="bodytext">Mechanisms for combining and determining the inconsistency of values are factored out into methods defined on these types.</p> <p class="bodytext">Slot values are sub-ranges (not elements) of the declared range; single values are converted to range format when they are stored. Each slot is given an initial value derived from its type (by the default <span class="defn"><a href="#shar">shared-initialize</a></span> method). This represents an initial set of possibilities that subsequent reasoning activity acts to narrow. Type checking is thus achieved by the consistency checking amongst values that happens whenever a new value is stored.</p> <p class="bodytext">Generally, the new value will coexist with one or more existing value(s). In par&shy;ticular, values may hold in differing belief states.</p> <p class="bodytext">For types that are ranges, new values are combined by intersection with each ex&shy;isting value: if two values are disjoint, they are contradictory. When a slot is read, its values (sub-ranges) are combined to yield the value returned.</p> <p class="bodytext">For instance, we may have deduced that a person is of sixteen years of age or above and that they are under 65 from the intelligence that they are married and not of pensionable age. Their age slot would contain the values <code class="sexpr">(0 137)</code> (the initial value), <code class="sexpr">(16 137)</code>, and <code class="sexpr">(0 64)</code>; combination of these values yields <code class="sexpr">(16 64)</code>.</p> <p class="bodytext">The following functions may be used to interpret programmatically the result of value combination:</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">range-max</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">x </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the upper bound of a numeric range.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">range-min</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">x </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the lower bound of a numeric range.</p> <h2><a id="section6">Reading and Writing Slots</a></h2> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="add"><span class="defn">add-slot-value</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">object slot-name new-value antecedents informant </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;key &amp;allow-other-keys</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Adds a value to a slot of an instance, justifying it by <span class="argname">antecedents</span>, a list of ATMS nodes (i.e., slot values or assumptions). If <span class="argname">antecedents</span> is <span class="defn">nil</span> the value is true (i.e., it holds universally). If the value is already present, the existing node is re-justified. The <span class="argname">informant</span> argument is a problem-solver- (or user-) supplied description of the justification.</p> <p class="bodytext">This behaviour is implemented by <span class="defn"><a href="#adduc">add-slot-value-using-class</a></span>, which is also responsible for the processing of keyword arguments.</p> <p class="bodytext">Returns the node corresponding to <span class="argname">new-value</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="adduc"><span class="defn">add-slot-value-using-class</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">class object slot new-value antecedents informant </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;key</span> slot-name no-check no-count negated </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Implements the behaviour of <span class="defn"><a href="#add">add-slot-value</a></span>. <span class="argname">class</span> is the class of <span class="argname">object</span>. <span class="argname">slot</span> is a slot definition object; the <span class="argname">slot-name</span> keyword argument defaults to its name.</p> <p class="bodytext">No checking is done for gross type violations; however, the function <span class="defn"><a href="#sat">slot-value-typep</a></span> is provided for use by client programs. <span class="argname">new-value</span> is combined with each existing value in order to detect con&shy;tradictions; if the values are ranges, and one is not a sub-range of the other, their intersection is added to the slot. (This behaviour can be inhibited by means of the <span class="argname">no-check</span> keyword argument; see also <span class="defn"><a href="#valid">validate-combination</a></span>.) The <span class="argname">no-count</span> keyword argument inhibits the automatic updating of a slot&rsquo;s count; see <span class="section"><a href="#section7">Cardinality</a></span>. The <span class="argname">negated</span> keyword argument is used to make an explicit assertion that some (non-range) instance does not appear in a slot (e.g., that <code class="sexpr">joe</code> is not the spouse of <code class="sexpr">amelia</code>).</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">slot-definition-missing</span> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">class object slot-name operation value antecedents informant </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;key &amp;allow-other-keys</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called by <span class="defn"><a href="#adduc">add-slot-value-using-class</a></span> if the slot definition corresponding to <span class="argname">slot-name</span> is missing from <span class="argname">class</span>. The default method signals an error.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="addc"><span class="defn">add-contradiction</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">atms antecedents </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Records a contradiction; used by <span class="defn"><a href="#adduc">add-slot-value-using-class</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="valid"><span class="defn">validate-combination</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">new-node node nodes </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called by <span class="defn"><a href="#adduc">add-slot-value-using-class</a></span> to determine whether <span class="argname">new-node</span> should be combined with <span class="argname">node</span>, an existing node, for the purposes of detecting contradictions and creating intersections. <span class="argname">nodes</span> is a list of all the existing nodes, most recent arrival first.</p> <p class="bodytext">Depending upon the nature of the application, much of this work may be both time-consuming and unnecessary; an application-specific method may be supplied to indicate such cases by returning <span class="defn">nil</span>. The system-supplied method returns non-<span class="defn">nil</span> constantly.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="sat"><span class="defn">slot-value-typep</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">object type </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Determines if object satisfies type, where <span class="argname">object</span> is an instance, symbol, number or range and <span class="argname">type</span> a class, e.g.,</p> <pre> (slot-value-typep 'true 'true-or-false) &rArr; t (slot-value-typep '(0 100) 'numeric-range) &rArr; t </pre> <p class="bodytext">Automatically-generated reader methods may be specified in a <span class="defn">defclass</span> form.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">slot-value-reduce</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">object slot-name </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> environment </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Combines all the slot values (nodes) that hold in <span class="argname">environment</span>, an object returned by the generic function <span class="defn"><a href="#uniq">uniquify-environment</a></span>. If <span class="argname">environment</span> is <span class="defn">t</span>, all values contained in the slot are combined; if omitted, it defaults to <span class="defn"><a href="#empt">*empty-environment*</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">contradictory-value</span> </td> <td class="methsig1">Constant </td> </tr> </table> <p class="bodytext">The distinguished value returned when slot values cannot be combined.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">contradictory-value-p</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">value </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Predicate that tests for this value.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">slot-values</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">object slot-name environment </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the ATMS nodes in a slot that hold in an environment.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">remove-slot-value</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">object slot-name value </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;key</span> negated recursive </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Removes a value from a slot, and, optionally, all data justified solely by it (the default behaviour). If the corresponding node does not hold in the environment of no assump&shy;tions, signals an error: one cannot remove an assumed datum except by explicitly removing the as&shy;sumption, upon which all internal ATMS data structures that mention it are removed. See <span class="defn"><a href="#remn">remove-node</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">remove-node :before</span> </td> <td class="methsig1">Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>n <span class="arglist">standard-slot-value)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> recursive </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Removes node from its containing slot.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="remn"><span class="defn">remove-node</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>n <span class="arglist">node)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> recursive </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Removes node, and, optionally, all data justified solely by it (the default behaviour).</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">remove-node :after</span> </td> <td class="methsig1">Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>n <span class="arglist">assumption)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> recursive </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Indicates that assumption may be garbage-collected: the application will not use it further. Calls <span class="defn"><a href="#disc">discard-assumption</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="feta"><span class="defn">fetch-assumption</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>object <span class="arglist">extended-object)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2">slot-name value </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> negated </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the assumption corresponding to an assumed datum.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">fetch-node</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>object <span class="arglist">extended-object)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2">slot-name value </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> negated </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the slot-value node corresponding to a datum.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">elements</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>node <span class="arglist">standard-slot-value)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns a list of the value(s) denoted by a slot-value node.</p> <h2><a id="section7">Cardinality</a></h2> <p class="bodytext">Where a slot holds (non-range) instances, it is possible to associate with it an ad&shy;ditional slot that records the number of instances in that slot, being updated auto&shy;matically each time a new instance is added. The additional slot is specified in the normal way (there must be a <span class="defn">:type</span> slot option that names a sub-range of <span class="defn">nu&shy;meric-range</span>); the association is made by giving the name of the additional slot as the value of the <span class="defn">:count</span> option of the slot specifier of the original slot.</p> <p class="bodytext">There are predefined ranges <span class="defn">zero-or-one</span>, <span class="defn">zero-or-more</span>, <span class="defn">exactly-one</span> and <span class="defn">one-or-more</span>.</p> <h2><a id="section7a">Composite Objects</a></h2> <p class="bodytext">Instances of the class <span class="defn">composite-object</span> have a <span class="defn">parts</span> slot referring to one or more closely-related but subordinate objects. The classes of these objects must be subclasses of the class <span class="defn">part</span>. Parts may be added either at instance creation time or subsequently.</p> <p class="bodytext">The class has two subclasses: <span class="defn">compound-object</span> and <span class="defn">assembly</span>.</p> <h3><a id="section7a.1">Compound Objects</a></h3> <p class="bodytext">The <span class="defn">compound-object</span> subclass captures the distinction between necessary and contingent membership of a class. For instance, a <code class="sexpr">person</code> may also be a <code class="sexpr">catholic</code> or a <code class="sexpr">police-officer</code>; these are simpler ideas out of which our idea of a person as a whole is formed. This distinction is a useful organizing principle.</p> <p class="bodytext">Were the subordinate classes to be defined as subclasses of <code class="sexpr">person</code>, some means of stipulating the admissible compound classes (e.g., <code class="sexpr">catholic-police-officer</code> but not <code class="sexpr">catholic-buddhist</code>), either by enumerating them or some other mechanism, would be required. Moreover, new parts could not be added dynamically.</p> <p class="bodytext">A compound object&rsquo;s parts&rsquo; slots may be read or stored into as if they were slots of the object itself. However, within rules the parts must be referred to explicitly.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">:part</span> </td> <td class="methsig1">Initialization Argument </td> </tr> </table> <p class="bodytext">Used to supply a part to a compound object at creation time.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">:parts</span> </td> <td class="methsig1">Initialization Argument </td> </tr> </table> <p class="bodytext">Used to supply a list of parts to a compound object at creation time.</p> <h3><a id="section7a.2">Assemblies</a></h3> <p class="bodytext">An assembly is a group of objects that are created together.</p> <p class="bodytext">When an assembly instance is created, slots whose contents have been defined as of type <span class="defn">component</span>, and for which no value is specified in the initialization argument list, are filled automatically. The number of component instances that are created is determined by the lower bound of of the slot&rsquo;s count (see <span class="section"><a href="#section7">Cardinality</a></span>). If it has no count, one instance is created.</p> <p class="bodytext">Each component, created or supplied, is added to the <span class="defn">parts</span> slot of the assembly.</p> <p class="bodytext">A component can, of course, also be an assembly. Specialized <span class="defn">initialize-instance</span> methods may be written to detect circularities or to create shared parts.</p> <h2><a id="section8">Class-Changing</a></h2> <p class="bodytext">Class-changing, in which the structure of an instance is modified to reflect a new class, may be employed, with the proviso that the target class be below the existing class in the inheritance hierarchy.</p> <p class="bodytext">However, a value stored in a slot of an instance might not trigger an inference as expected after its class is changed. For example, if a value is stored in the <code class="sexpr">children</code> slot of a <code class="sexpr">parent</code> instance, and then that instance is changed to a <code class="sexpr">grandparent</code>, a rule that refers to the <code class="sexpr">children</code> of a <code class="sexpr">grandparent</code> will not succeed. To enable such inferences, use:</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">notice-slot-values</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>instance <span class="arglist">extended-object)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> predicate </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Intended to be called after changing the class of <span class="argname">instance</span>. Ensures that values stored in its slots that satisfy <span class="argname">predicate</span> (by default, all those that hold in a non-empty environment) have been noticed by the reasoning procedure.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="clas"><span class="defn">classify</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>instance <span class="arglist">extended-object)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>class <span class="arglist">extended-class)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2">environment </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Finds class(es) most subordinate to <span class="argname">class</span>, under which <span class="argname">instance</span> falls (may fall). Returns a list of classes.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">map-slots</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">class function </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;key</span> direct from-end </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Applies <span class="argname">function</span> to each element of an ordered list of slot definitions for <span class="argname">class</span>; used by <span class="defn"><a href="#clas">classify</a></span>. <span class="argname">direct</span> indicates that slot definitions local to <span class="argname">class</span> only be used. <span class="argname">from-end </span>determines whether the most or least subordinate of those slot definitions with the same name be used; a type specifier in a subordinate slot definition should always be a subtype of one in a superior definition.</p> <h2><a id="section9">Rule Language</a></h2> <p class="bodytext">The reasoning procedure takes as inputs values stored into slots and a corpus of im&shy;plicitly universally quantified logical expressions (rules and constraints, known collectively as well-formed formulae) written by the user, and produces unit steps called consumers, each of which represents an individual inference. A separate scheduling procedure (see <span class="defn"><a href="#sche">schedule</a></span>) takes each consumer and constructs a new da&shy;tum (slot value), along with a justification, which records the derivation of that da&shy;tum.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="defc"><span class="defn">defconstraint</span></a> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">name [qualifier] declarations <span class="arglist">&amp;rest</span> constraint-body </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">A constraint is an arbitrary logical expression, from which all possible inferences are derived.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="defru"><span class="defn">defrule</span></a> </td> <td class="methsig1">Macro </td> </tr> <tr> <td class="methsig2">name [qualifier] declarations <span class="arglist">&amp;rest</span> rule-body </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">A rule has a distinguished head, the truth of which the rule acts to determine.</p> <div style="border:solid windowtext .75pt"> <table class="layout2" role="presentation"> <tr> <td><var>qualifier</var>::=</td><td><code>:assume</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>declarations</var>::=</td> <td><code>(</code>{<code>(</code><var>variable-name class-name</var><code>)</code>}+<code>)</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>constraint-body</var>::=</td><td>[<var>documentation-string</var>] <var>expression</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>rule-body</var>::=</td> <td><var>if-body</var> | <var>iff-body</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>if-body</var>::=</td> <td>[<var>documentation-string</var>] [<var>disjunction</var> <code>-&gt;</code>] <var>compound-head</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>iff-body</var>::=</td> <td>[<var>documentation-string</var>] <var>disjunction</var> <code>&lt;-&gt;</code> <var>head</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>compound-head</var>::=</td> <td><var>head</var> [<code>and</code> <var>compound-head</var>]</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>head</var>::=</td> <td>[<code>not</code>] <var>proposition</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>expression</var>::=</td> <td><var>condition</var> [<code>-&gt;</code> <var>expression</var>]</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>condition</var>::=</td> <td><var>disjunction</var> [<code>&lt;-&gt;</code> <var>condition</var>]</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>disjunction</var>::=</td> <td><var>conjunction</var> [<code>or</code> <var>disjunction</var>]</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>conjunction</var>::=</td> <td><var>primary</var> [<code>and</code> <var>conjunction</var>]</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>primary</var>::=</td> <td><var>proposition</var> | <code>not</code> <var>primary</var> | <code>(</code><var>expression</var><code>)</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>proposition</var>::=</td><td><var>lisp-proposition</var> |</td> </tr> <tr> <td></td><td><var>literal-proposition</var> |</td> </tr> <tr> <td></td><td><var>relational-proposition</var> |</td> </tr> <tr> <td></td><td><var>numeric-or-arithmetic-proposition</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>lisp-proposition</var>::=</td> <td><code>lisp</code> <code>(</code><var>function-name</var> {<var>arg</var>}+<code>)</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>arg</var>::=</td><td><code>(</code><var>variable-name class-name</var><code>)</code> |</td> </tr> <tr> <td></td><td><var>attribute-reference</var> |</td> </tr> <tr> <td></td><td><var>number</var> | <var>string</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>attribute-reference</var>::=</td><td><var>variable-name slot-name</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>literal-proposition</var>::=</td><td><var>attribute-reference</var> {</td> </tr> <tr> <td></td><td><code>is</code> <var>symbol</var> |</td> </tr> <tr> <td></td><td><code>is in</code> <code>(</code>{<var>symbol</var>}+<code>)</code> |</td> </tr> <tr> <td></td><td><code>is in</code> <var>range-class-name</var> |</td> </tr> <tr> <td></td><td><code>is</code> [<code>in</code>] <var>attribute-reference</var>}</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>relational-proposition</var>::=</td> <td><var>attribute-reference</var> [<code>is</code> | <code>includes</code>] <var>variable-name</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>numeric-or-arithmetic-proposition</var>::=</td><td><var>attribute-reference</var> {</td> </tr> <tr> <td></td><td><code>is in</code> <var>numeric-range</var> |</td> </tr> <tr> <td></td><td><code>is in</code> <var>range-class-name</var> |</td> </tr> <tr> <td></td><td><code>is</code> <var>number</var> |</td> </tr> <tr> <td></td><td><var>relation arithmetic-rhs</var>}</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>numeric-range</var>::=</td><td><code>(</code><var>number number</var><code>)</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>relation</var>::=</td> <td><code>=</code> | <code>&gt;</code> | <code>&lt;</code> | <code>&gt;=</code> | <code>&lt;=</code> | <code>/=</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>arithmetic-rhs</var>::=</td><td><var>arithmetic-expr</var> |</td> </tr> <tr> <td></td><td>{ <code>aggregate-min</code> | <code>aggregate-max</code> | <code>aggregate-sum</code> }</td> </tr> <tr> <td></td><td><code>(</code><var>relational-attribute-reference</var> <var>numeric-attribute-reference</var><code>)</code> |</td> </tr> <tr> <td></td><td>{ <code>min</code> | <code>max</code> } <code>(</code>{<var>attribute-reference</var> | <var>number</var> }+<code>)</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>arithmetic-expr</var>::=</td><td><var>mult-term</var> [<var>plus-op arithmetic-expr</var>]</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>mult-term</var>::=</td><td><var>factor</var> [<var>mult-op mult-term</var>]</td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>factor</var>::=</td> <td><code>(</code><var>arithmetic-expr</var><code>)</code> | <var>number</var> | <var>attribute-reference</var> | <code>-</code> <var>factor</var></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>plus-op</var>::=</td><td><code>+</code> | <code>-</code></td> </tr> </table> <table class="layout2" role="presentation"> <tr> <td><var>mult-op</var>::=</td><td><code>*</code> | <code>/</code></td> </tr> </table> </div> <h3><a id="section9.1">Note on Lisp Propositions</a></h3> <p class="bodytext">The function is applied to the arguments specified; variables and attribute references are de-referenced, but other arguments are not evaluated. If the proposition is in the head of a rule, the function will be passed two additional arguments: the antecedents that triggered the rule, and an informant, to use if it installs a justification (see <span class="defn"><a href="#add">add-slot-value</a></span>). Not intended for use in constraints.</p> <h3><a id="section9.2">Note on the Use of Relational Propositions in Rules</a></h3> <p class="bodytext">If the last <span class="defn"><a href="#defru">defrule</a></span> example below, with a relational proposition in its body and a <code class="sexpr">&lt;-&gt;</code> connective, were written straightforwardly, the negation of the head of the rule would never be inferred. (This is because the logical expressions into which the compiler translates the rule do not exactly reflect the intention of the rule writer.) The formulation used enables all the intended inferences, and is safe provided the negation of the relational proposition in the body of the rule is not asserted.</p> <h3><a id="section9.3">Example Well-Formed Formulae</a></h3> <pre><code> (defconstraint pensionable ((p person)) &quot;Pensionable age rule.&quot; p age &gt; 64 or p sex is female and p age &gt; 59 &lt;-&gt; p of-pensionable-age is true) (defconstraint income ((p person)) p income = p benefit + p earnings) (defrule paternity ((child person) (mum person) (dad person)) child mother is mum and mum spouse is dad and child eye-colour is dad eye-colour -&gt; child father is dad) (defrule combined-age-of-children ((p person) (c person)) p children includes c -&gt; p combined-age-of-children = aggregate-sum (p children c age)) (defrule qualifying-accounts ((cb credit-balance) (sa share-account)) cb accounts-held-in includes sa -&gt; &semi; See note above. cb accounts-held-in includes sa and sa account-name is in qualifying-share-account-names &lt;-&gt; cb qualifying-accounts-held-in includes sa) </code></pre> <h2><a id="section9a">Automatically-Generated Rules</a></h2> <p class="bodytext"><span class="defn">defclass</span> slot specifiers take two additional options, <span class="defn">:composition</span> and <span class="defn">:inverse</span>, which define a slot in terms of one or more others and sanction the derivation of values when those slots are stored into. The latter option takes a single value, a (non-range-valued) slot name. The former may be one of <span class="defn">:symmetric</span> or <span class="defn">:transitive</span>, or alternatively a list of one or more slot names, such as <code class="sexpr">(parent brother)</code> for determining the value of an <code class="sexpr">uncle</code> slot.</p> <h2><a id="section10">Rule Objects</a></h2> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">rule-compile</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>wff <span class="arglist">well-formed-formula)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Compiles a well-formed formula; invoked automatically when a <span class="defn"><a href="#defc">defconstraint</a></span> or <span class="defn"><a href="#defru">defrule</a></span> form is evaluated.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">uncompile</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>wff <span class="arglist">well-formed-formula)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Undoes the effects of a compilation: the wff no longer participates in reasoning.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*trace-rule-failure*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">Controls the printing of information about the point of failure during the evaluation of rules and constraints.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">*rule-trace-output*</span> </td> <td class="methsig1">Variable </td> </tr> </table> <p class="bodytext">The stream to which trace information is printed; initially <span class="defn">*trace-output*</span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">rules-using</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">class slot-name </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the rules and constraints that notice data stored in the given slot.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">rules-affecting</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">class slot-name </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the rules that can affect the contents of the given slot. (A constraint, being non-directional, can affect all the slots it notices.)</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="slotu"><span class="defn">slots-used</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>wff <span class="arglist">well-formed-formula)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns a list of attribute references denoting those slots noticed by a rule or con&shy;straint.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="slota"><span class="defn">slot-affected</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>wff <span class="arglist">forward-rule)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns an attribute reference denoting the slot affected by a rule. (A constraint can affect a slot if it notices it.)</p> <p class="bodytext">The result of <span class="defn"><a href="#slota">slot-affected</a></span> and <span class="defn"><a href="#slotu">slots-used</a></span> can be examined by means of the fol&shy;lowing accessor functions:</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">attribute-reference-class</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">attribute-reference </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the class-name component of an attribute reference.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">attribute-name</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">attribute-reference </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Returns the slot-name component of an attribute reference.</p> <h2><a id="section11">Reasoning With Assumed Data</a></h2> <p class="bodytext">Problem solving with the ATMS requires the making of appropriate assumptions, followed by a search of the space of environments (i.e., combinations of assump&shy;tions), smallest first, for a solution.</p> <p class="bodytext">The former task is accomplished using <span class="defn"><a href="#assv">assume-slot-value</a></span>, or, if the datum to be assumed is an arbitrary logical expression (this will appear in an inferred datum&rsquo;s justification just like the other data that trigger an inference), by using the <span class="defn">:assume</span> qualifier accepted by the <span class="defn"><a href="#defc">defconstraint</a></span> and <span class="defn"><a href="#defru">defrule</a></span> macros.</p> <p class="bodytext">The latter task is performed by <span class="defn"><a href="#back">backtrack</a></span> or <span class="defn"><a href="#solu">solutions</a></span>. Both can be used with <span class="defn">atms</span> or <span class="defn">basic-atms</span>, which can be supplied by dynamically re&shy;binding <span class="defn"><a href="#atms">*atms*</a></span>. <span class="defn">basic-atms</span> exploits incremental, ordered adding of assumptions to record significantly less information about contradictory environments.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="assv"><span class="defn">assume-slot-value</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">object slot-name value </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> assumption no-check </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Uses <span class="defn"><a href="#add">add-slot-value</a></span>; <span class="argname">no-check</span> defaults to non-<span class="defn">nil</span>. If <span class="argname">assumption</span> is omitted or is <span class="defn">nil</span>, manufactures one with <span class="defn"><a href="#makea">make-assumption</a></span>. Returns assumption.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="assu"><span class="defn">assume-slot-values</span></a> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">object initargs </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> catchall-assumption no-check </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Utility function for assuming multiple slot values. Uses <span class="defn"><a href="#assv">assume-slot-value</a></span>. If <span class="argname">catchall-assumption</span> is supplied, it is used exclusively; if a value has previously been assumed (see <span class="defn"><a href="#feta">fetch-assumption</a></span>), that assumption is used; otherwise assumptions are created. Returns a list of assumptions.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">describe-data</span> </td> <td class="methsig1">Function </td> </tr> <tr> <td class="methsig2">environment </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Describes the assumed data of <span class="argname">environment</span>, which may be an object or a list of assumptions.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="back"><span class="defn">backtrack</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>e <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>control-disjunctions <span class="arglist">list)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>tms <span class="arglist">core-atms)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">A recursive backtracking scheme appropriate where a solution must select exactly one choice from each of a number of sets, and where the solution does not depend on the order in which choices are made. See: de Kleer and Williams, &lsquo;Back to Backtracking: Controlling the ATMS&rsquo;, AAAI-86.</p> <p class="bodytext">For optimal performance, the assumption sets should be created in the order in which they will appear in <span class="argname">control-disjunctions</span>. If <span class="defn">basic-atms</span> is used, they <em>must</em> be created in this order.</p> <p class="bodytext">Uses <span class="defn"><a href="#nsche">nschedule</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><span class="defn">atms:oneof-disjunction</span> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>assumptions <span class="arglist">list)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> no-check ordered </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Records every pair from <span class="argname">assumptions</span> as contradictory. May be used to stipulate mutually-exclusive choices in addition to the control disjunctions. If <span class="argname">no-check</span> is non-<span class="defn">nil</span> (the default), no checking for previously-recorded conflicts is performed; if <span class="argname">ordered</span> is non-<span class="defn">nil</span>, any pair of assumptions is guaranteed to be added to an existing environment in the order supplied, so that less information need be recorded.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="ord"><span class="defn">order-control-disjunction</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">object e assumptions </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called by <span class="defn"><a href="#back">backtrack</a></span>. An application-specific method may reorder and return <span class="argname">assumptions</span> (a control disjunction). The first element of the returned value is then added to <span class="argname">e</span> (the partial solution). <span class="argname">object</span> is the instance of which the assumed datum of the first assumption is a slot value.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="added"><span class="defn">added-assumption</span></a> </td> <td class="methsig1">Generic Function </td> </tr> <tr> <td class="methsig2">object a assumptions tms </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Called by <span class="defn"><a href="#back">backtrack</a></span> if <span class="argname">a</span>, the selected assumption, is successfully added to <span class="argname">assumptions </span>(i.e., a consistent environment results). <span class="argname">object</span> is as above. An application-specific method can be supplied to detect contradictions explicitly. See <span class="defn"><a href="#addc">add-contradiction</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="solu"><span class="defn">solutions</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>e <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>choices <span class="arglist">list)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>tms <span class="arglist">core-atms)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">&amp;optional</span> dont-create </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">An ATMS-guided generate-and-test search regime. Supersets of <span class="argname">e</span> are enumerated by incorporating assumptions from <span class="argname">choices</span> and those that are consistent and maximal (i.e., with respect to <span class="argname">choices</span>) returned. No environment objects will be created if <span class="argname">dont-create</span> is non-<span class="defn">nil</span>.</p> <p class="bodytext">Uses <span class="defn"><a href="#sche">schedule</a></span>.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="sche"><span class="defn">schedule</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>tms <span class="arglist">core-atms)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>e <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">Runs all consumers in all subsets of an environment. For the environment {<var>A, B, C</var>}, consumers are executed in the order: {<var>A</var>}, {<var>B</var>}, {<var>A, B</var>}, {<var>C</var>}, {<var>A, C</var>}, {<var>B, C</var>}, {<var>A, B, C</var>}. Returns a list of consistent subsets. See the <a href="reasoner.html#back">paper</a> by de Kleer and Williams.</p> <table class="layout1" role="presentation"> <tr> <td class="methsig"><a id="nsche"><span class="defn">nschedule</span></a> </td> <td class="methsig1">Primary Method </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>tms <span class="arglist">core-atms)</span> </td> <td>&nbsp; </td> </tr> <tr> <td class="methsig2"><span class="arglist">(</span>e <span class="arglist">environment)</span> </td> <td>&nbsp; </td> </tr> </table> <p class="bodytext">The non-consing version of <span class="defn"><a href="#sche">schedule</a></span>. Environments are executed in size order and those of the same size in an arbitrary order.</p> </body> </html>
61,579
Common Lisp
.l
1,883
31.541689
151
0.721611
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fbb05e10439f9ec73c4ebfdff9665a7578c2e1c6178f7cf7b232ce94e502c81d
20,479
[ -1 ]
20,480
demos.html
whounslo_reasoner/doc/demos.html
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>Demonstrations - Common Lisp Reasoner</title> <style type="text/css" media="all"> @import "reasoner.css"; table.demos { background: silver; font-family: sans-serif; } tr.demos { background: white; } span.defn { font-weight: bold; } </style> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> </head> <body> <div id="header"> <div class="titlebar"> <div class="title"> <h1>Common Lisp Reasoner</h1> <h3>Version 3.6</h3> </div> <div class="menubar"> <ul> <li class="nav"><a href="mailto:[email protected]">Contact</a></li> <li class="nav"><a href="demos.html">Demonstrations</a></li> <li class="nav"><a href="reasoner.html">Reference</a></li> </ul> </div> </div> </div> <h2>Demonstrations</h2> <p><em>Names of functions are located in the package </em><code class="package">RS-USER</code>.</p> <div id="demos"> <style scoped> table { border: 1px solid gray; width: 95%} td, th { border: 1px solid gray; padding: 5} </style> <table class="demos"> <tr class="demos"> <th> Demonstration </th> <th> Files </th> <th> Functions </th> <th> Demonstrates </th> </tr> <tr class="demos"> <td rowspan=2> Combinatorial Problems/Scheduling </td> <td> queens.lisp<br/>(n-queens problem) </td> <td> <span class="defn">queens</span> (backtracking search), <span class="defn">queens2</span> (local search) </td> <td> <span class="defn"><a href="reasoner.html#back">backtrack</a></span>, specialization of <span class="defn"><a href="reasoner.html#added">added-assumption</a></span>, <span class="defn"><a href="reasoner.html#assu">assume-slot-values</a></span> </td> </tr> <tr class="demos"> <td> su.lisp<br/>(Sudoku puzzle generator and solver) </td> <td> <span class="defn">sugen</span> (local search), <span class="defn">susolve</span> (backtracking search) </td> <td> <span class="defn"><a href="reasoner.html#back">backtrack</a></span>, specialization of <span class="defn"><a href="reasoner.html#ord">order-control-disjunction</a></span> and <span class="defn"><a href="reasoner.html#added">added-assumption</a></span>, specialization of <span class="defn"><a href="reasoner.html#valid">validate-combination</a></span>, <span class="defn"><a href="reasoner.html#assu">assume-slot-values</a></span> </td> </tr> <tr class="demos"> <td rowspan=2> Planning </td> <td> miss.lisp (missionaries-and-cannibals problem) </td> <td> <span class="defn">miss</span> </td> <td> <span class="defn"><a href="reasoner.html#solu">solutions</a></span>, <a href="#note">non-monotonic reasoning</a>, <span class="defn"><a href="reasoner.html#section11">:assume</a></span> qualifier, <span class="defn"><a href="reasoner.html#section7">:count</a></span> slot option, <span class="defn"><a href="reasoner.html#assu">assume-slot-values</a></span> </td> </tr> <tr class="demos"> <td> blocks.lisp (blocks world) </td> <td> <span class="defn">blocks</span> </td> <td> <span class="defn"><a href="reasoner.html#solu">solutions</a></span>, <a href="#note">non-monotonic reasoning</a>, <span class="defn"><a href="reasoner.html#section11">:assume</a></span> qualifier, <span class="defn"><a href="reasoner.html#section7">:count</a></span> slot option, <span class="defn"><a href="reasoner.html#section9a">:inverse</a></span> slot option, <span class="defn"><a href="reasoner.html#assu">assume-slot-values</a></span> </td> </tr> <tr class="demos"> <td> Multiple-Fault Diagnosis </td> <td> mult.lisp </td> <td> <span class="defn">diagnoses1</span>, <span class="defn">diagnoses2</span> </td> <td> <span class="defn"><a href="reasoner.html#solu">solutions</a></span>, <a href="#note">non-monotonic reasoning</a>, <a href="reasoner.html#defc">constraints</a>, <span class="defn"><a href="reasoner.html#section7a">composite objects</a></span> </td> </tr> <tr class="demos"> <td> Counterfactuals </td> <td> boris.lisp </td> <td> <span class="defn">if-boris</span> </td> <td> <span class="defn"><a href="reasoner.html#solu">solutions</a></span>, <a href="#note">non-monotonic reasoning</a>, <span class="defn"><a href="reasoner.html#section11">:assume</a></span> qualifier </td> </tr> <tr class="demos"> <td> Temporal Reasoning </td> <td> career.lisp </td> <td> <span class="defn">career1</span>, <span class="defn">career2</span> </td> <td> <span class="defn"><a href="reasoner.html#solu">solutions</a></span>, <a href="#note">non-monotonic reasoning</a>, <span class="defn"><a href="reasoner.html#section11">:assume</a></span> qualifier, <span class="defn"><a href="reasoner.html#section7">:count</a></span> slot option, <span class="defn"><a href="reasoner.html#section7a">composite objects</a></span> </td> </tr> </table> </div> <h2><a id="note">Note on Non-Monotonic Reasoning</a></h2> <p>Non-monotonic (or defeasible) reasoning is the the norm in practical, everyday problem-solving: it is reasoning under conditions of uncertainty, from incomplete or unreliable information. Such inferences do not carry a guarantee of soundness and may later need to be revised.</p> <p>The <em>temporal reasoning</em> demonstration clearly illustrates this phenomenon. Assimilating a hiring or promotion event may result in a revision of a inference about a person's employment status made from their employment history.</p> <p>The ATMS is used to realize non-monotonic reasoning by entirely extra-logical means.</p> <p>The <em>counterfactuals</em> demonstration concerns statements of the form &lsquo;if such-and-such were the case, then such-and-such would be the case&rsquo;. It employs a treatment of such statements not simply as implicational rules whose antecedent happens to be false, but as elliptical arguments. One counterfactual can be defeated by another: they sanction conclusions which may be contradicted by subsequently-acquired information.</p> <p><em>Diagnosis</em> is also non-monotonic in the sense that different diagnoses may result from an additional observation of the faulty system's behaviour.</p> <p>The <em>planning</em> demonstrations illustrate the formulation of the actions relevant to (e.g.) a simple &lsquo;blocks world&rsquo; problem as axioms whose consequent contradicts their antecedent. The law of contradiction is used to construct a new situation or possible world, given by a set of statements (i.e., slot values), comprising the consequent and all features of a previous situation that are consistent with it: information is &lsquo;carried over&rsquo; from one situation to another in the absence of knowledge to the contrary.</p> </body> </html>
6,675
Common Lisp
.l
200
31.74
107
0.722601
whounslo/reasoner
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
46548676df8a34a0cf1b45d4e0bd225070b9916d92c6edbf98e93c8c961a0d71
20,480
[ -1 ]
20,496
filesystems.lisp
jnc-nj_jack-tools/src/filesystems.lisp
(in-package #:jack.tools.filesystems) (defun create-directory (name) (ensure-directories-exist (pathname name)) (truename name)) (defun write-file (object target) (with-open-file (file (pathname target) :direction :output :if-exists :supersede :if-does-not-exist :create) (if (stringp object) (format file "~d" object) (format file "~d" (cl-json:encode-json-to-string object))))) (defun add-line (line target) (with-open-file (file (pathname target) :direction :output :if-exists :append :if-does-not-exist :create) (write-line line file))) (defun open-file (target) (with-open-file (file (pathname target)) (let ((contents (make-string (file-length file)))) (read-sequence contents file) contents))) (defun batch-delete (path) (dolist (item (split "\\n" (open-file path))) (when (cl-fad:file-exists-p item) (log:info "[delete][~d]" item) (delete-file item)))) (defun cmd-read-path (path) (format nil "$(<~d)" (pathname path))) (defun *probe-file (path) (when path (probe-file path))) (defun truenamep (path) (handler-case (pathname (truename path)) (error () nil))) (defun get-extension (path) (scan-to-strings "\\.\\w+$" (namestring path)))
1,313
Common Lisp
.lisp
37
29.891892
68
0.635359
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
7117d296265299a514bb1b0752db44cfe81fc271eef6fd96460e7e14f09a9fda
20,496
[ -1 ]
20,497
bootstraps.lisp
jnc-nj_jack-tools/src/bootstraps.lisp
(in-package #:jack.tools.bootstraps) (defun create-bootstrap-id () (cl-ppcre:regex-replace-all "[\\W\\d]" (string-downcase (create-id)) "")) (defmacro bs-btn ((&key (type "default") (size nil)) &body body) `(with-html-output (*standard-output*) (:button :type "button" :class (concatenate 'string "btn" (if ,type (format nil " btn-~a" ,type)) (if ,size (format nil " btn-~a" ,size))) ,@body))) (defmacro bs-btn-lg ((&key (type "default")) &body body) `(with-html-output (*standard-output*) (:button :type "button" :class (format nil "btn btn-lg btn-~a" ,type) ,@body))) (defmacro bs-btn-sm ((&key (type "default")) &body body) `(with-html-output (*standard-output*) (:button :type "button" :class (format nil "btn btn-sm btn-~a" ,type) ,@body))) (defmacro bs-btn-xs ((&key (type "default")) &body body) `(with-html-output (*standard-output*) (:button :type "button" :class (format nil "btn btn-xs btn-~a" ,type) ,@body))) (defmacro bs-btn-default (&body body) `(bs-btn () ,@body)) (defmacro bs-btn-primary (&body body) `(bs-btn (:type "primary") ,@body)) (defmacro bs-btn-success (&body body) `(bs-btn (:type "success") ,@body)) (defmacro bs-btn-info (&body body) `(bs-btn (:type "info") ,@body)) (defmacro bs-btn-warning (&body body) `(bs-btn (:type "warning") ,@body)) (defmacro bs-btn-danger (&body body) `(bs-btn (:type "danger") ,@body)) (defmacro bs-link-btn ((&key (type "default") (size nil) (href "#")) &body body) `(with-html-output (*standard-output*) (:a :role "button" :class (concatenate 'string "btn" (if ,type (format nil " btn-~a" ,type)) (if ,size (format nil " btn-~a" ,size))) :href ,href ,@body))) (defmacro bs-btn-dropdown ((&key (title "")) &body body) "Turn a button into a dropdown toggle with some basic markup changes." `(with-html-output (*standard-output*) (:div :class "btn-group" (:button :type "button" :class "btn btn-default dropdown-toggle" :data-toggle "dropdown" :aria-haspopup "true" :aria-expanded "false" ,title "&nbsp;" (:span :class "caret")) (:ul :class "dropdown-menu" ,@body)))) (defmacro bs-form-text ((&key (label "Text: ") (id nil) (name nil))) `(bs-form-input "text" (:label ,label :id ,id :name ,name))) (defmacro bs-form-embd-static ((&key label id name placeholder value)) (let ((g-id (gensym)) (g-name (gensym)) (g-placeholder (gensym))) `(let ((,g-id ,id) (,g-name ,name) (,g-placeholder ,placeholder)) (list :div :class "form-group" (list :label :for ,g-id ,label) (list :input :type "text" :readonly t :class "form-control-plaintext" :id ,g-id :value ,value ,@(when g-name `(:name ,g-name)) ,@(when g-placeholder `(:placeholder ,g-placeholder))))))) (defmacro bs-form-embd-checkbox (&body body) `(list :div :class "checkbox" (list :label (list :input :type "checkbox" ,@body)))) (defmacro bs-embd-modal ((&key (title "myModal")) &body body) `(list :div :class "modal fade" :id ,title :tabindex "-1" :role "dialog" (list :div :class "modal-dialog modal-lg" :role "document" (list :div :class "modal-content" (list :div :class "modal-header" (list :button :type "button" :class "close" :data-dismiss "modal" :aria-label "Close" (list :span :aria-hidden "true" "&times;")) (list :h4 :class "modal-title" ,title)) (list :div :class "modal-body" ,@body) (list :div :class "modal-footer" (list :button :type "button" :class "btn btn-danger" :data-dismiss "modal" "Close")))))) (defmacro bs-embd-table (&body body) `(list :table :class "table",@body))
3,918
Common Lisp
.lisp
87
38.091954
80
0.587093
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
039097317cf2a80d458889bc00e243c69f4c16ec8430aa118040e96de56347d2
20,497
[ -1 ]
20,498
trees.lisp
jnc-nj_jack-tools/src/trees.lisp
(in-package #:jack.tools.trees) (defun tree-similarity (tree-1 tree-2) (cos-similarity (upsilon tree-1) (upsilon tree-2))) (defun upsilon (tree) "Upsilion of tree." (cond ((null tree) nil) ((atom tree) (list 0)) (t (cons (length tree) (reduce #'append (sort (mapcar #'upsilon tree) #'compare-trees)))))) (defun compare-trees (a b) "Compare tree a to tree b." (cond ((and (atom a) (atom b)) t) ((atom a) t) ((atom b) nil) ((equal (car a) (car b)) (compare-trees (cdr a) (cdr b))) (t (compare-trees (car a) (car b))))) (defun eliminate (item list) "Recusrively eliminate item from list." (delete nil (mapcar #'(lambda (arg) (unless (equal item arg) (if (listp arg) (eliminate item arg) arg))) list))) (defun subber (lst sublist &key read?) (if (listp lst) (loop for item in lst collect (subber item sublist :read? read?)) (let ((found (agethash lst sublist))) (cond ((and read? found) (read-from-string found)) (found found) (t lst))))) (defun unquote (lst &key quote?) "Tail-recursive unquotes all elements in lst." (if (listp lst) (mapcar #'(lambda (arg) (cond ((listp arg) (unquote arg :quote? quote?)) ((stringp arg) (read-from-string arg)) ((symbolp arg) (if quote? (string arg) arg)) (t arg))) lst) (if quote? (string lst) lst))) (defun recursive-alist-hash-table (alist) (cond ((alistp alist) (recursive-alist-hash-table (alist-hash-table (mapcar #'(lambda (arg) (cons (dekeywordfy (car arg)) (cdr arg))) alist)))) ((hash-table-p alist) (maphash #'(lambda (key value) (setf (gethash key alist) (recursive-alist-hash-table value))) alist) alist) ((listp alist) (mapcar #'recursive-alist-hash-table alist)) (t alist)))
1,840
Common Lisp
.lisp
54
29.037037
95
0.615169
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f338d0cb3fe4b756933064866edf7db6adf455ea37f12cf53b4a5a911372312e
20,498
[ -1 ]
20,499
maths.lisp
jnc-nj_jack-tools/src/maths.lisp
(in-package #:jack.tools.maths) (defun random-float (min max &key (seed 2048)) "Calculate a random float within range min max. Algorithm from /Collected Algorithms from the ACM/; 133, 266, 294, 370." (+ (* (/ (random seed) seed) (- max min)) min)) (defun average-vectors (vectors) (let ((length (length vectors))) (map 'vector #'(lambda (n) (/ n length)) (apply #'map 'vector #'+ vectors)))) (defun euclidean-distance (a b) (sqrt (map-reduce #'square #'+ (mapcar #'- a b)))) (defun dot-prod (a b) (reduce #'+ (map 'simple-vector #'* a b))) (defun square (n) (* n n)) (defun sum-of-squares (seq) (reduce #'+ (map 'simple-vector #'square seq))) (defun cos-similarity (vec-1 vec-2) "Calculate the cosine similarity of two non-zero vectors." (/ (dot-prod vec-1 vec-2) (* (sqrt (sum-of-squares vec-1)) (sqrt (sum-of-squares vec-2))))) (defun safe-op (fn &rest args) (let ((arglist (delete nil args))) (when arglist (reduce fn arglist)))) (defun strict-op (fn &rest args) (unless (member nil args) (reduce fn args))) (defun */ (arg-1 arg-2) (if (= 0 arg-2) 0 (/ arg-1 arg-2))) (defun *max (&rest n) (if n (reduce #'max n) 0)) (defun closest-2-base (n) (expt 2 (floor (log n 2)))) (defun fy-shuffle (lst) "Non-destructive Fisher-Yates." (let ((length (length lst)) (list (coerce lst 'vector))) (dotimes (i (- length 2)) (let* ((j (+ i (random length))) (ith (aref list i)) (jth (aref list j))) (setf (aref list i) jth (aref list j) ith))) (coerce list 'list)))
1,594
Common Lisp
.lisp
45
31.311111
75
0.607422
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e085272c224f1cfec6e036be9ebe24c84577170e0bbd2d745d570eec324bfd1a
20,499
[ -1 ]
20,500
objects.lisp
jnc-nj_jack-tools/src/objects.lisp
(in-package #:jack.tools.objects) (defclass address-book () ((interfaces :initarg :interfaces :initform nil) (stack :initarg :stack :initform nil))) (defgeneric copy-instance (object &rest initargs &key &allow-other-keys) (:documentation "Makes and returns a shallow copy of OBJECT with optional reinitialization.") (:method ((object standard-object) &rest initargs &key &allow-other-keys) (let* ((class (class-of object)) (copy (allocate-instance class))) (dolist (slot-name (get-slot-names class)) (when (slot-boundp object slot-name) (setf (slot-value copy slot-name) (slot-value object slot-name)))) (apply #'reinitialize-instance copy initargs)))) (defun to-address-book (object) (let ((output-object (make-instance 'address-book))) (with-slots (interfaces stack) output-object (labels ((interpret (object) (cond ((alistp object) object) ((listp object) (mapcar #'interpret object)) ((objectp object) (let* ((class (class-of object)) (object-id (get-object-id object)) (slot-names (get-slot-names class)) switch) (dolist (slot-name slot-names) (when (slot-boundp object slot-name) (let* ((slot-value (slot-value object slot-name)) (interpreted (interpret (slot-value object slot-name)))) (unless (or switch (equal slot-value interpreted)) (setf switch t)) (setf (slot-value object slot-name) interpreted)))) (if switch (pushnew (cons object-id object) interfaces :test #'slots-equal? :key #'cdr) (pushnew (cons object-id object) stack :test #'slots-equal? :key #'cdr)) object-id)) (t object)))) (interpret object) output-object)))) (defun cast (alist class-map &key strict) (when (alistp alist) (let* ((input-class (find-class-map (mapcar #'car alist) class-map :strict strict)) (instance (when input-class (make-instance input-class))) (class (class-of instance))) (when instance (dolist (slot-name (get-slot-names class)) (let ((value (agethash slot-name alist))) (setf (slot-value instance slot-name) (cond ((alistp value) (cast value class-map :strict strict)) ((or (not (listp value)) (not (listp (car value)))) value) ((listp (caar value)) (mapcar #'(lambda (v) (cast v class-map :strict strict)) value)) (t value))))) (return-from cast instance)) alist)) alist) (defun cast-all (objects class-map) (loop for object in objects collect (cast object class-map))) (defun create-class-map (&rest classes) (let ((collect (make-hash-table :test #'equal))) (dolist (class classes) (let ((temp-object (make-instance class))) (eval (generate-json-method class)) (setf (gethash class collect) (get-slot-names (class-of temp-object))))) collect)) (defun find-class-map (alist-names class-map &key strict) (let ((intersect-length 0) faux-key subset?) ;; if alist-names is equivalent to value, return ;; if alist-names is a subset of value, return largest value ;; if alist-names is an intersection of value, return largest intersection ;; else return nothing (maphash #'(lambda (key value) (let ((equals (set-equals alist-names value :test #'string= :key #'string-upcase)) (subset (unless strict (subsetp alist-names value :test #'string= :key #'string-upcase))) (intersect (unless strict (intersection alist-names value :test #'string= :key #'string-upcase)))) (cond (equals (return-from find-class-map key)) ((and (not strict) (or (and (not subset?) subset) (and subset (> (length value) (length (gethash faux-key class-map)))))) (setf faux-key key subset? t)) ((and (not strict) intersect (not subset?) (> (length intersect) intersect-length)) (setf faux-key key intersect-length (length intersect)))))) class-map) faux-key)) (defun get-class-id (class) (car (cl-ppcre:all-matches-as-strings "(?<=:)(.+?)(?=>)" (write-to-string class)))) (defun get-object-id (object) (car (cl-ppcre:all-matches-as-strings "(?<={)(.+?)(?=})" (write-to-string object)))) (defun get-slot-names (class) (mapcar #'c2mop:slot-definition-name (c2mop:class-slots class))) (defun slots-equal? (object-1 object-2) (let ((class-1 (class-of object-1)) (class-2 (class-of object-2))) (when (eq class-1 class-2) (dolist (slot-name (get-slot-names class-1)) (unless (equal (slot-value object-1 slot-name) (slot-value object-2 slot-name)) (return-from slots-equal? nil))) (return-from slots-equal? t)) (equal object-1 object-2))) (defun objectp (object) (handler-case (make-instance (class-of object)) (error () nil))) (defun object-to-alist (object) (cond ((stringp object) (cl-json:decode-json-from-string object)) ((alistp object) object) (t (object-to-alist (jonathan:to-json object))))) (defun generate-json-method (class-name) (let* ((slot-names (get-slot-names (class-of (make-instance class-name))))) `(defmethod %to-json ((,class-name ,class-name)) (with-slots ,slot-names ,class-name (with-object ,@(loop for item in slot-names collect `(write-key-value ,(dekeywordfy item) (if (alistp ,item) (recursive-alist-hash-table ,item) ,item)))))))) (defun get-object-size (object) (sb-sys:without-gcing (/ (nth-value 2 (sb-vm::reconstitute-object (ash (logandc1 sb-vm:lowtag-mask (sb-kernel:get-lisp-obj-address object)) (- sb-vm:n-fixnum-tag-bits)))) 8))) (defun *slot-value (object slot-name) (handler-case (slot-value object slot-name) (error () nil)))
5,714
Common Lisp
.lisp
137
36.437956
106
0.657616
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
75dc58d8301218cd6fa73aec0efddd66f7c6577660a67fc6c1ac2c9c337b0418
20,500
[ -1 ]
20,501
.withs.lisp.~undo-tree~
jnc-nj_jack-tools/src/.withs.lisp.~undo-tree~
(undo-tree-save-format-version . 1) "0d124615fe1ccf027f9b12e54321fe8cc3ef6b79" [nil nil nil nil (25168 790 489945 0) 0 nil] ([nil nil ((6342 . 6351) (t 25168 790 956879 883000)) nil (25168 895 987377 0) 0 nil] [nil nil ((#("do" 0 2 (fontified t)) . -6351) (undo-tree-id1 . -2) (6351 . 6353) (#("d" 0 1 (fontified t)) . -6351) (undo-tree-id2 . -1) (6342 . 6352) (t 24998 1646 249407 344000)) ((#(" d" 0 1 (fontified t) 1 9 (fontified nil) 9 10 (fontified nil)) . 6342) (undo-tree-id1060 . -1) (undo-tree-id1061 . -1) (undo-tree-id1062 . -9) (undo-tree-id1063 . -9) (undo-tree-id1064 . -9) (undo-tree-id1065 . -9) (undo-tree-id1066 . -1) (undo-tree-id1067 . -9) (undo-tree-id1068 . -9) (undo-tree-id1069 . -9) (undo-tree-id1070 . -9) (undo-tree-id1071 . -9) (undo-tree-id1072 . -9) (undo-tree-id1073 . -9) (undo-tree-id1074 . -9) (undo-tree-id1075 . -9) (undo-tree-id1076 . -9) (undo-tree-id1077 . -9) (undo-tree-id1078 . -9) (undo-tree-id1079 . -9) (undo-tree-id1080 . -9) (undo-tree-id1081 . -9) (undo-tree-id1082 . -9) (undo-tree-id1083 . -9) (undo-tree-id1084 . -9) (undo-tree-id1085 . -9) (undo-tree-id1086 . -9) (undo-tree-id1087 . -9) (undo-tree-id1088 . -9) (undo-tree-id1089 . -9) (undo-tree-id1090 . -9) (undo-tree-id1091 . -9) (undo-tree-id1092 . -9) (undo-tree-id1093 . -9) (undo-tree-id1094 . -9) (undo-tree-id1095 . -9) (undo-tree-id1096 . -9) (undo-tree-id1097 . -9) (undo-tree-id1098 . -9) (undo-tree-id1099 . -9) (undo-tree-id1100 . -9) (undo-tree-id1101 . -9) (undo-tree-id1102 . -9) (undo-tree-id1103 . -9) (undo-tree-id1104 . -9) (undo-tree-id1105 . -9) (undo-tree-id1106 . -9) (undo-tree-id1107 . -9) (undo-tree-id1108 . -9) (undo-tree-id1109 . -9) (undo-tree-id1110 . -9) (undo-tree-id1111 . -9) (undo-tree-id1112 . -9) (undo-tree-id1113 . -9) (undo-tree-id1114 . -9) (undo-tree-id1115 . -9) (undo-tree-id1116 . -9) (undo-tree-id1117 . -9) (undo-tree-id1118 . -9) (undo-tree-id1119 . -9) (undo-tree-id1120 . -9) (undo-tree-id1121 . -9) (undo-tree-id1122 . -9) (undo-tree-id1123 . -9) (undo-tree-id1124 . -9) (undo-tree-id1125 . -9) (undo-tree-id1126 . -9) (undo-tree-id1127 . -9) (undo-tree-id1128 . -9) (undo-tree-id1129 . -9) (undo-tree-id1130 . -9) (undo-tree-id1131 . -9) (undo-tree-id1132 . -9) (undo-tree-id1133 . -9) (undo-tree-id1134 . -9) (undo-tree-id1135 . -9) (undo-tree-id1136 . -9) (undo-tree-id1137 . -9) (undo-tree-id1138 . -9) (undo-tree-id1139 . -9) (undo-tree-id1140 . -9) (undo-tree-id1141 . -9) (undo-tree-id1142 . -9) (undo-tree-id1143 . -9) (undo-tree-id1144 . -9) (undo-tree-id1145 . -9) (undo-tree-id1146 . -9) (undo-tree-id1147 . -9) (undo-tree-id1148 . -9) (undo-tree-id1149 . -9) (undo-tree-id1150 . -9) (undo-tree-id1151 . -9) (undo-tree-id1152 . -9) (undo-tree-id1153 . -9) (undo-tree-id1154 . -9) (undo-tree-id1155 . -9) (undo-tree-id1156 . -9) (undo-tree-id1157 . -9) (undo-tree-id1158 . -9) (undo-tree-id1159 . -9) (undo-tree-id1160 . -9) (undo-tree-id1161 . -9) (undo-tree-id1162 . -9) (undo-tree-id1163 . -9) (undo-tree-id1164 . -9) (undo-tree-id1165 . -9) (undo-tree-id1166 . -9) (undo-tree-id1167 . -9) (undo-tree-id1168 . -9) (undo-tree-id1169 . -1) (undo-tree-id1170 . -1) (undo-tree-id1171 . -9) (undo-tree-id1172 . -9) (undo-tree-id1173 . -9) (undo-tree-id1174 . -9) (undo-tree-id1175 . -9) (undo-tree-id1176 . -9) (undo-tree-id1177 . -9) (undo-tree-id1178 . -9) (undo-tree-id1179 . -9) (undo-tree-id1180 . -9) (undo-tree-id1181 . -9) (undo-tree-id1182 . -9) (undo-tree-id1183 . -9) (undo-tree-id1184 . -9) (undo-tree-id1185 . -9) (undo-tree-id1186 . -9) (undo-tree-id1187 . -9) (undo-tree-id1188 . -9) (undo-tree-id1189 . -9) (undo-tree-id1190 . -9) (undo-tree-id1191 . -9) (undo-tree-id1192 . -9) (undo-tree-id1193 . -9) (undo-tree-id1194 . -9) (undo-tree-id1195 . -9) (undo-tree-id1196 . -9) (undo-tree-id1197 . -9) (undo-tree-id1198 . -9) (undo-tree-id1199 . -9) (undo-tree-id1200 . -9) (undo-tree-id1201 . -9) (undo-tree-id1202 . -9) (undo-tree-id1203 . -9) (undo-tree-id1204 . -9) (undo-tree-id1205 . -9) (undo-tree-id1206 . -9) (undo-tree-id1207 . -9) (undo-tree-id1208 . -9) (undo-tree-id1209 . -9) (undo-tree-id1210 . -9) (undo-tree-id1211 . -9) (undo-tree-id1212 . -9) (undo-tree-id1213 . -9) (undo-tree-id1214 . -9) (undo-tree-id1215 . -9) (undo-tree-id1216 . -9) (undo-tree-id1217 . -9) (undo-tree-id1218 . -9) (undo-tree-id1219 . -9) (undo-tree-id1220 . -9) (undo-tree-id1221 . -9) (undo-tree-id1222 . -9) (undo-tree-id1223 . -9) (undo-tree-id1224 . -9) (undo-tree-id1225 . -9) (undo-tree-id1226 . -9) (undo-tree-id1227 . -9) (undo-tree-id1228 . -9) (undo-tree-id1229 . -9) (undo-tree-id1230 . -9) (undo-tree-id1231 . -9) (undo-tree-id1232 . -9) (undo-tree-id1233 . -9) (undo-tree-id1234 . -9) (undo-tree-id1235 . -9) (undo-tree-id1236 . -9) (undo-tree-id1237 . -9) (undo-tree-id1238 . -9) (undo-tree-id1239 . -9) (undo-tree-id1240 . -9) (undo-tree-id1241 . -9) (undo-tree-id1242 . -9) (undo-tree-id1243 . -9) (undo-tree-id1244 . -9) (undo-tree-id1245 . -9) (undo-tree-id1246 . -9) (undo-tree-id1247 . -9) (undo-tree-id1248 . -9) (undo-tree-id1249 . -9) (undo-tree-id1250 . -9) (undo-tree-id1251 . -9) (undo-tree-id1252 . -9) (undo-tree-id1253 . -9) (undo-tree-id1254 . -9) (undo-tree-id1255 . -9) (undo-tree-id1256 . -9) (undo-tree-id1257 . -9) (undo-tree-id1258 . -9) (undo-tree-id1259 . -9) (undo-tree-id1260 . -9) (undo-tree-id1261 . -9) (undo-tree-id1262 . -9) (undo-tree-id1263 . -9) (undo-tree-id1264 . -9) (undo-tree-id1265 . -9) (undo-tree-id1266 . -9) (undo-tree-id1267 . -9) (undo-tree-id1268 . -9) (undo-tree-id1269 . -9) (undo-tree-id1270 . -9) (undo-tree-id1271 . -9) (undo-tree-id1272 . -9) (undo-tree-id1273 . -9) (undo-tree-id1274 . -9) (undo-tree-id1275 . -9) (undo-tree-id1276 . -9) (undo-tree-id1277 . -9) (undo-tree-id1278 . -9) (undo-tree-id1279 . -9) (undo-tree-id1280 . -9) (undo-tree-id1281 . -9) (undo-tree-id1282 . -9) (undo-tree-id1283 . -9) (undo-tree-id1284 . -9) (undo-tree-id1285 . -9) (undo-tree-id1286 . -9) (undo-tree-id1287 . -9) (undo-tree-id1288 . -9) (undo-tree-id1289 . -9) (undo-tree-id1290 . -9) (undo-tree-id1291 . -9) (undo-tree-id1292 . -9) (undo-tree-id1293 . -9) (undo-tree-id1294 . -9) (undo-tree-id1295 . -9) (undo-tree-id1296 . -9) (undo-tree-id1297 . -9) (undo-tree-id1298 . -9) (undo-tree-id1299 . -9) (undo-tree-id1300 . -9) (undo-tree-id1301 . -9) (undo-tree-id1302 . -9) (undo-tree-id1303 . -9) (undo-tree-id1304 . -9) (undo-tree-id1305 . -9) (undo-tree-id1306 . -9) (undo-tree-id1307 . -9) (undo-tree-id1308 . -9) (undo-tree-id1309 . -9) (undo-tree-id1310 . -9) (undo-tree-id1311 . -9) (undo-tree-id1312 . -9) (undo-tree-id1313 . -9) (undo-tree-id1314 . -9) (undo-tree-id1315 . -9) (undo-tree-id1316 . -9) (undo-tree-id1317 . -9) (undo-tree-id1318 . -9) (undo-tree-id1319 . -9) (undo-tree-id1320 . -9) (undo-tree-id1321 . -9) (undo-tree-id1322 . -9) (undo-tree-id1323 . -9) (undo-tree-id1324 . -9) (6351 . 6352) (#("do" 0 2 (fontified nil)) . 6351) (6351 . 6353)) (25168 790 47368 0) 0 nil]) ([nil nil ((6351 . 6356)) nil (25168 895 987370 0) 0 nil]) ([nil nil ((6351 . 6352)) ((#("都" 0 1 (fontified t)) . 6351) (undo-tree-id957 . -1) (undo-tree-id958 . -1) (undo-tree-id959 . -1) (undo-tree-id960 . -1) (undo-tree-id961 . -1) (undo-tree-id962 . -1) (undo-tree-id963 . -1) (undo-tree-id964 . -1) (undo-tree-id965 . -1) (undo-tree-id966 . -1) (undo-tree-id967 . -1) (undo-tree-id968 . -1) (undo-tree-id969 . -1) (undo-tree-id970 . -1) (undo-tree-id971 . -1) (undo-tree-id972 . -1) (undo-tree-id973 . -1) (undo-tree-id974 . -1) (undo-tree-id975 . -1) (undo-tree-id976 . -1) (undo-tree-id977 . -1) (undo-tree-id978 . -1) (undo-tree-id979 . -1) (undo-tree-id980 . -1) (undo-tree-id981 . -1) (undo-tree-id982 . -1) (undo-tree-id983 . -1) (undo-tree-id984 . -1) (undo-tree-id985 . -1) (undo-tree-id986 . -1) (undo-tree-id987 . -1) (undo-tree-id988 . -1) (undo-tree-id989 . -1) (undo-tree-id990 . -1) (undo-tree-id991 . -1) (undo-tree-id992 . -1) (undo-tree-id993 . -1) (undo-tree-id994 . -1) (undo-tree-id995 . -1) (undo-tree-id996 . -1) (undo-tree-id997 . -1) (undo-tree-id998 . -1) (undo-tree-id999 . -1) (undo-tree-id1000 . -1) (undo-tree-id1001 . -1) (undo-tree-id1002 . -1) (undo-tree-id1003 . -1) (undo-tree-id1004 . -1) (undo-tree-id1005 . -1) (undo-tree-id1006 . -1) (undo-tree-id1007 . -1) (undo-tree-id1008 . -1) (undo-tree-id1009 . -1) (undo-tree-id1010 . -1) (undo-tree-id1011 . -1) (undo-tree-id1012 . -1) (undo-tree-id1013 . -1) (undo-tree-id1014 . -1) (undo-tree-id1015 . -1) (undo-tree-id1016 . -1) (undo-tree-id1017 . -1) (undo-tree-id1018 . -1) (undo-tree-id1019 . -1) (undo-tree-id1020 . -1) (undo-tree-id1021 . -1) (undo-tree-id1022 . -1) (undo-tree-id1023 . -1) (undo-tree-id1024 . -1) (undo-tree-id1025 . -1) (undo-tree-id1026 . -1) (undo-tree-id1027 . -1) (undo-tree-id1028 . -1) (undo-tree-id1029 . -1) (undo-tree-id1030 . -1) (undo-tree-id1031 . -1) (undo-tree-id1032 . -1) (undo-tree-id1033 . -1) (undo-tree-id1034 . -1) (undo-tree-id1035 . -1) (undo-tree-id1036 . -1) (undo-tree-id1037 . -1) (undo-tree-id1038 . -1) (undo-tree-id1039 . -1) (undo-tree-id1040 . -1) (undo-tree-id1041 . -1) (undo-tree-id1042 . -1) (undo-tree-id1043 . -1) (undo-tree-id1044 . -1) (undo-tree-id1045 . -1) (undo-tree-id1046 . -1) (undo-tree-id1047 . -1) (undo-tree-id1048 . -1) (undo-tree-id1049 . -1) (undo-tree-id1050 . -1) (undo-tree-id1051 . -1) (undo-tree-id1052 . -1) (undo-tree-id1053 . -1) (undo-tree-id1054 . -1) (undo-tree-id1055 . -1) (undo-tree-id1056 . -1) (undo-tree-id1057 . -1) (undo-tree-id1058 . -1) (undo-tree-id1059 . -1)) (25168 789 574770 0) 0 nil]) ([nil nil ((#("p" 0 1 (fontified t)) . -6351) (undo-tree-id1325 . -1) (#("r" 0 1 (fontified t)) . -6352) (undo-tree-id1326 . -1) (#("i" 0 1 (fontified t)) . -6353) (undo-tree-id1327 . -1) (#("n" 0 1 (fontified t)) . -6354) (undo-tree-id1328 . -1) (#("t" 0 1 (fontified t)) . -6355) (undo-tree-id1329 . -1) 6356) nil (25168 895 987357 0) 0 nil]) ([nil nil ((#("都" 0 1 (fontified t)) . -6351) (undo-tree-id0 . -1) 6352) ((6351 . 6352)) (25168 789 189611 0) 0 nil]) ([nil nil ((6351 . 6353)) nil (25168 895 987319 0) 0 nil]) ([nil nil ((6351 . 6353)) ((#("do" 0 2 (fontified t)) . 6351) (undo-tree-id616 . -2) (undo-tree-id617 . -2) (undo-tree-id618 . -2) (undo-tree-id619 . -2) (undo-tree-id620 . -2) (undo-tree-id621 . -2) (undo-tree-id622 . -2) (undo-tree-id623 . -2) (undo-tree-id624 . -2) (undo-tree-id625 . -2) (undo-tree-id626 . -2) (undo-tree-id627 . -2) (undo-tree-id628 . -2) (undo-tree-id629 . -2) (undo-tree-id630 . -2) (undo-tree-id631 . -2) (undo-tree-id632 . -2) (undo-tree-id633 . -2) (undo-tree-id634 . -2) (undo-tree-id635 . -2) (undo-tree-id636 . -2) (undo-tree-id637 . -2) (undo-tree-id638 . -2) (undo-tree-id639 . -2) (undo-tree-id640 . -2) (undo-tree-id641 . -2) (undo-tree-id642 . -2) (undo-tree-id643 . -2) (undo-tree-id644 . -2) (undo-tree-id645 . -2) (undo-tree-id646 . -2) (undo-tree-id647 . -2) (undo-tree-id648 . -2) (undo-tree-id649 . -2) (undo-tree-id650 . -2) (undo-tree-id651 . -2) (undo-tree-id652 . -2) (undo-tree-id653 . -2) (undo-tree-id654 . -2) (undo-tree-id655 . -2) (undo-tree-id656 . -2) (undo-tree-id657 . -2) (undo-tree-id658 . -2) (undo-tree-id659 . -2) (undo-tree-id660 . -2) (undo-tree-id661 . -2) (undo-tree-id662 . -2) (undo-tree-id663 . -2) (undo-tree-id664 . -2) (undo-tree-id665 . -2) (undo-tree-id666 . -2) (undo-tree-id667 . -2) (undo-tree-id668 . -2) (undo-tree-id669 . -2) (undo-tree-id670 . -2) (undo-tree-id671 . -2) (undo-tree-id672 . -2) (undo-tree-id673 . -2) (undo-tree-id674 . -2) (undo-tree-id675 . -2) (undo-tree-id676 . -2) (undo-tree-id677 . -2) (undo-tree-id678 . -2) (undo-tree-id679 . -2) (undo-tree-id680 . -2) (undo-tree-id681 . -2) (undo-tree-id682 . -2) (undo-tree-id683 . -2) (undo-tree-id684 . -2) (undo-tree-id685 . -2) (undo-tree-id686 . -2) (undo-tree-id687 . -2) (undo-tree-id688 . -2) (undo-tree-id689 . -2) (undo-tree-id690 . -2) (undo-tree-id691 . -2) (undo-tree-id692 . -2) (undo-tree-id693 . -2) (undo-tree-id694 . -2) (undo-tree-id695 . -2) (undo-tree-id696 . -2) (undo-tree-id697 . -2) (undo-tree-id698 . -2) (undo-tree-id699 . -2) (undo-tree-id700 . -2) (undo-tree-id701 . -2) (undo-tree-id702 . -2) (undo-tree-id703 . -2) (undo-tree-id704 . -2) (undo-tree-id705 . -2) (undo-tree-id706 . -2) (undo-tree-id707 . -2) (undo-tree-id708 . -2) (undo-tree-id709 . -2) (undo-tree-id710 . -2) (undo-tree-id711 . -2) (undo-tree-id712 . -2) (undo-tree-id713 . -2) (undo-tree-id714 . -2) (undo-tree-id715 . -2) (undo-tree-id716 . -2) (undo-tree-id717 . -2) (undo-tree-id718 . -2) (undo-tree-id719 . -2) (undo-tree-id720 . -2) (undo-tree-id721 . -2) (undo-tree-id722 . -2) (undo-tree-id723 . -2) (undo-tree-id724 . -2) (undo-tree-id725 . -2) (undo-tree-id726 . -2) (undo-tree-id727 . -2) (undo-tree-id728 . -2) (undo-tree-id729 . -2) (undo-tree-id730 . -2) (undo-tree-id731 . -2) (undo-tree-id732 . -2) (undo-tree-id733 . -2) (undo-tree-id734 . -2) (undo-tree-id735 . -2) (undo-tree-id736 . -2) (undo-tree-id737 . -2) (undo-tree-id738 . -2) (undo-tree-id739 . -2) (undo-tree-id740 . -2) (undo-tree-id741 . -2) (undo-tree-id742 . -2) (undo-tree-id743 . -2) (undo-tree-id744 . -2) (undo-tree-id745 . -2) (undo-tree-id746 . -2) (undo-tree-id747 . -2) (undo-tree-id748 . -2) (undo-tree-id749 . -2) (undo-tree-id750 . -2) (undo-tree-id751 . -2) (undo-tree-id752 . -2) (undo-tree-id753 . -2) (undo-tree-id754 . -2) (undo-tree-id755 . -2) (undo-tree-id756 . -2) (undo-tree-id757 . -2) (undo-tree-id758 . -2) (undo-tree-id759 . -2) (undo-tree-id760 . -2) (undo-tree-id761 . -2) (undo-tree-id762 . -2) (undo-tree-id763 . -2) (undo-tree-id764 . -2) (undo-tree-id765 . -2) (undo-tree-id766 . -2) (undo-tree-id767 . -2) (undo-tree-id768 . -2) (undo-tree-id769 . -2) (undo-tree-id770 . -2) (undo-tree-id771 . -2) (undo-tree-id772 . -2) (undo-tree-id773 . -2) (undo-tree-id774 . -2) (undo-tree-id775 . -2) (undo-tree-id776 . -2) (undo-tree-id777 . -2) (undo-tree-id778 . -2) (undo-tree-id779 . -2) (undo-tree-id780 . -2) (undo-tree-id781 . -2) (undo-tree-id782 . -2) (undo-tree-id783 . -2) (undo-tree-id784 . -2) (undo-tree-id785 . -2) (undo-tree-id786 . -2) (undo-tree-id787 . -2) (undo-tree-id788 . -2) (undo-tree-id789 . -2) (undo-tree-id790 . -2) (undo-tree-id791 . -2) (undo-tree-id792 . -2) (undo-tree-id793 . -2) (undo-tree-id794 . -2) (undo-tree-id795 . -2) (undo-tree-id796 . -2) (undo-tree-id797 . -2) (undo-tree-id798 . -2) (undo-tree-id799 . -2) (undo-tree-id800 . -2) (undo-tree-id801 . -2) (undo-tree-id802 . -2) (undo-tree-id803 . -2) (undo-tree-id804 . -2) (undo-tree-id805 . -2) (undo-tree-id806 . -2) (undo-tree-id807 . -2) (undo-tree-id808 . -2) (undo-tree-id809 . -2) (undo-tree-id810 . -2) (undo-tree-id811 . -2) (undo-tree-id812 . -2) (undo-tree-id813 . -2) (undo-tree-id814 . -2) (undo-tree-id815 . -2) (undo-tree-id816 . -2) (undo-tree-id817 . -2) (undo-tree-id818 . -2) (undo-tree-id819 . -2) (undo-tree-id820 . -2) (undo-tree-id821 . -2) (undo-tree-id822 . -2) (undo-tree-id823 . -2) (undo-tree-id824 . -2) (undo-tree-id825 . -2) (undo-tree-id826 . -2) (undo-tree-id827 . -2) (undo-tree-id828 . -2) (undo-tree-id829 . -2) (undo-tree-id830 . -2) (undo-tree-id831 . -2) (undo-tree-id832 . -2) (undo-tree-id833 . -2) (undo-tree-id834 . -2) (undo-tree-id835 . -2) (undo-tree-id836 . -2) (undo-tree-id837 . -2) (undo-tree-id838 . -2) (undo-tree-id839 . -2) (undo-tree-id840 . -2) (undo-tree-id841 . -2) (undo-tree-id842 . -2) (undo-tree-id843 . -2) (undo-tree-id844 . -2) (undo-tree-id845 . -2) (undo-tree-id846 . -2) (undo-tree-id847 . -2) (undo-tree-id848 . -2) (undo-tree-id849 . -2) (undo-tree-id850 . -2) (undo-tree-id851 . -2) (undo-tree-id852 . -2) (undo-tree-id853 . -2) (undo-tree-id854 . -2) (undo-tree-id855 . -2) (undo-tree-id856 . -2) (undo-tree-id857 . -2) (undo-tree-id858 . -2) (undo-tree-id859 . -2) (undo-tree-id860 . -2) (undo-tree-id861 . -2) (undo-tree-id862 . -2) (undo-tree-id863 . -2) (undo-tree-id864 . -2) (undo-tree-id865 . -2) (undo-tree-id866 . -2) (undo-tree-id867 . -2) (undo-tree-id868 . -2) (undo-tree-id869 . -2) (undo-tree-id870 . -2) (undo-tree-id871 . -2) (undo-tree-id872 . -2) (undo-tree-id873 . -2) (undo-tree-id874 . -2) (undo-tree-id875 . -2) (undo-tree-id876 . -2) (undo-tree-id877 . -2) (undo-tree-id878 . -2) (undo-tree-id879 . -2) (undo-tree-id880 . -2) (undo-tree-id881 . -2) (undo-tree-id882 . -2) (undo-tree-id883 . -2) (undo-tree-id884 . -2) (undo-tree-id885 . -2) (undo-tree-id886 . -2) (undo-tree-id887 . -2) (undo-tree-id888 . -2) (undo-tree-id889 . -2) (undo-tree-id890 . -2) (undo-tree-id891 . -2) (undo-tree-id892 . -2) (undo-tree-id893 . -2) (undo-tree-id894 . -2) (undo-tree-id895 . -2) (undo-tree-id896 . -2) (undo-tree-id897 . -2) (undo-tree-id898 . -2) (undo-tree-id899 . -2) (undo-tree-id900 . -2) (undo-tree-id901 . -2) (undo-tree-id902 . -2) (undo-tree-id903 . -2) (undo-tree-id904 . -2) (undo-tree-id905 . -2) (undo-tree-id906 . -2) (undo-tree-id907 . -2) (undo-tree-id908 . -2) (undo-tree-id909 . -2) (undo-tree-id910 . -2) (undo-tree-id911 . -2) (undo-tree-id912 . -2) (undo-tree-id913 . -2) (undo-tree-id914 . -2) (undo-tree-id915 . -2) (undo-tree-id916 . -2) (undo-tree-id917 . -2) (undo-tree-id918 . -2) (undo-tree-id919 . -2) (undo-tree-id920 . -2) (undo-tree-id921 . -2) (undo-tree-id922 . -2) (undo-tree-id923 . -2) (undo-tree-id924 . -2) (undo-tree-id925 . -2) (undo-tree-id926 . -2) (undo-tree-id927 . -2) (undo-tree-id928 . -2) (undo-tree-id929 . -2) (undo-tree-id930 . -2) (undo-tree-id931 . -2) (undo-tree-id932 . -2) (undo-tree-id933 . -2) (undo-tree-id934 . -2) (undo-tree-id935 . -2) (undo-tree-id936 . -2) (undo-tree-id937 . -2) (undo-tree-id938 . -2) (undo-tree-id939 . -2) (undo-tree-id940 . -2) (undo-tree-id941 . -2) (undo-tree-id942 . -2) (undo-tree-id943 . -2) (undo-tree-id944 . -2) (undo-tree-id945 . -2) (undo-tree-id946 . -2) (undo-tree-id947 . -2) (undo-tree-id948 . -2) (undo-tree-id949 . -2) (undo-tree-id950 . -2) (undo-tree-id951 . -2) (undo-tree-id952 . -2) (undo-tree-id953 . -2) (undo-tree-id954 . -2) (undo-tree-id955 . -2) (undo-tree-id956 . -2)) (25168 788 771815 0) 0 nil]) ([nil nil ((6353 . 6354)) nil (25168 895 987313 0) 0 nil]) ([nil nil ((6353 . 6354)) ((#(" " 0 1 (fontified t)) . 6353) (undo-tree-id428 . -1) (undo-tree-id429 . -1) (undo-tree-id430 . -1) (undo-tree-id431 . -1) (undo-tree-id432 . -1) (undo-tree-id433 . -1) (undo-tree-id434 . -1) (undo-tree-id435 . -1) (undo-tree-id436 . -1) (undo-tree-id437 . -1) (undo-tree-id438 . -1) (undo-tree-id439 . -1) (undo-tree-id440 . -1) (undo-tree-id441 . -1) (undo-tree-id442 . -1) (undo-tree-id443 . -1) (undo-tree-id444 . -1) (undo-tree-id445 . -1) (undo-tree-id446 . -1) (undo-tree-id447 . -1) (undo-tree-id448 . -1) (undo-tree-id449 . -1) (undo-tree-id450 . -1) (undo-tree-id451 . -1) (undo-tree-id452 . -1) (undo-tree-id453 . -1) (undo-tree-id454 . -1) (undo-tree-id455 . -1) (undo-tree-id456 . -1) (undo-tree-id457 . -1) (undo-tree-id458 . -1) (undo-tree-id459 . -1) (undo-tree-id460 . -1) (undo-tree-id461 . -1) (undo-tree-id462 . -1) (undo-tree-id463 . -1) (undo-tree-id464 . -1) (undo-tree-id465 . -1) (undo-tree-id466 . -1) (undo-tree-id467 . -1) (undo-tree-id468 . -1) (undo-tree-id469 . -1) (undo-tree-id470 . -1) (undo-tree-id471 . -1) (undo-tree-id472 . -1) (undo-tree-id473 . -1) (undo-tree-id474 . -1) (undo-tree-id475 . -1) (undo-tree-id476 . -1) (undo-tree-id477 . -1) (undo-tree-id478 . -1) (undo-tree-id479 . -1) (undo-tree-id480 . -1) (undo-tree-id481 . -1) (undo-tree-id482 . -1) (undo-tree-id483 . -1) (undo-tree-id484 . -1) (undo-tree-id485 . -1) (undo-tree-id486 . -1) (undo-tree-id487 . -1) (undo-tree-id488 . -1) (undo-tree-id489 . -1) (undo-tree-id490 . -1) (undo-tree-id491 . -1) (undo-tree-id492 . -1) (undo-tree-id493 . -1) (undo-tree-id494 . -1) (undo-tree-id495 . -1) (undo-tree-id496 . -1) (undo-tree-id497 . -1) (undo-tree-id498 . -1) (undo-tree-id499 . -1) (undo-tree-id500 . -1) (undo-tree-id501 . -1) (undo-tree-id502 . -1) (undo-tree-id503 . -1) (undo-tree-id504 . -1) (undo-tree-id505 . -1) (undo-tree-id506 . -1) (undo-tree-id507 . -1) (undo-tree-id508 . -1) (undo-tree-id509 . -1) (undo-tree-id510 . -1) (undo-tree-id511 . -1) (undo-tree-id512 . -1) (undo-tree-id513 . -1) (undo-tree-id514 . -1) (undo-tree-id515 . -1) (undo-tree-id516 . -1) (undo-tree-id517 . -1) (undo-tree-id518 . -1) (undo-tree-id519 . -1) (undo-tree-id520 . -1) (undo-tree-id521 . -1) (undo-tree-id522 . -1) (undo-tree-id523 . -1) (undo-tree-id524 . -1) (undo-tree-id525 . -1) (undo-tree-id526 . -1) (undo-tree-id527 . -1) (undo-tree-id528 . -1) (undo-tree-id529 . -1) (undo-tree-id530 . -1) (undo-tree-id531 . -1) (undo-tree-id532 . -1) (undo-tree-id533 . -1) (undo-tree-id534 . -1) (undo-tree-id535 . -1) (undo-tree-id536 . -1) (undo-tree-id537 . -1) (undo-tree-id538 . -1) (undo-tree-id539 . -1) (undo-tree-id540 . -1) (undo-tree-id541 . -1) (undo-tree-id542 . -1) (undo-tree-id543 . -1) (undo-tree-id544 . -1) (undo-tree-id545 . -1) (undo-tree-id546 . -1) (undo-tree-id547 . -1) (undo-tree-id548 . -1) (undo-tree-id549 . -1) (undo-tree-id550 . -1) (undo-tree-id551 . -1) (undo-tree-id552 . -1) (undo-tree-id553 . -1) (undo-tree-id554 . -1) (undo-tree-id555 . -1) (undo-tree-id556 . -1) (undo-tree-id557 . -1) (undo-tree-id558 . -1) (undo-tree-id559 . -1) (undo-tree-id560 . -1) (undo-tree-id561 . -1) (undo-tree-id562 . -1) (undo-tree-id563 . -1) (undo-tree-id564 . -1) (undo-tree-id565 . -1) (undo-tree-id566 . -1) (undo-tree-id567 . -1) (undo-tree-id568 . -1) (undo-tree-id569 . -1) (undo-tree-id570 . -1) (undo-tree-id571 . -1) (undo-tree-id572 . -1) (undo-tree-id573 . -1) (undo-tree-id574 . -1) (undo-tree-id575 . -1) (undo-tree-id576 . -1) (undo-tree-id577 . -1) (undo-tree-id578 . -1) (undo-tree-id579 . -1) (undo-tree-id580 . -1) (undo-tree-id581 . -1) (undo-tree-id582 . -1) (undo-tree-id583 . -1) (undo-tree-id584 . -1) (undo-tree-id585 . -1) (undo-tree-id586 . -1) (undo-tree-id587 . -1) (undo-tree-id588 . -1) (undo-tree-id589 . -1) (undo-tree-id590 . -1) (undo-tree-id591 . -1) (undo-tree-id592 . -1) (undo-tree-id593 . -1) (undo-tree-id594 . -1) (undo-tree-id595 . -1) (undo-tree-id596 . -1) (undo-tree-id597 . -1) (undo-tree-id598 . -1) (undo-tree-id599 . -1) (undo-tree-id600 . -1) (undo-tree-id601 . -1) (undo-tree-id602 . -1) (undo-tree-id603 . -1) (undo-tree-id604 . -1) (undo-tree-id605 . -1) (undo-tree-id606 . -1) (undo-tree-id607 . -1) (undo-tree-id608 . -1) (undo-tree-id609 . -1) (undo-tree-id610 . -1) (undo-tree-id611 . -1) (undo-tree-id612 . -1) (undo-tree-id613 . -1) (undo-tree-id614 . -1) (undo-tree-id615 . -1)) (25168 788 576066 0) 0 nil]) ([nil nil ((6355 . 6360) (6354 . 6356) (#("(" 0 1 (fontified nil)) . -6354) (6354 . 6355)) nil (25168 895 987305 0) 0 nil]) ([nil nil ((6355 . 6360) (6354 . 6356) (#("(" 0 1 (fontified nil)) . -6354) (6354 . 6355)) ((#("(" 0 1 (fontified nil)) . 6354) (6354 . 6355) (#("()" 0 1 (face (rainbow-delimiters-depth-1-face) fontified nil) 1 2 (face (rainbow-delimiters-depth-1-face) fontified nil)) . 6354) (undo-tree-id258 . -2) (undo-tree-id259 . -2) (undo-tree-id260 . -1) (undo-tree-id261 . -1) (undo-tree-id262 . -1) (undo-tree-id263 . -1) (undo-tree-id264 . -1) (undo-tree-id265 . -1) (undo-tree-id266 . -1) (undo-tree-id267 . -1) (undo-tree-id268 . -1) (undo-tree-id269 . -1) (undo-tree-id270 . -1) (undo-tree-id271 . -1) (undo-tree-id272 . -1) (undo-tree-id273 . -1) (undo-tree-id274 . -1) (undo-tree-id275 . -1) (undo-tree-id276 . -1) (undo-tree-id277 . -1) (undo-tree-id278 . -1) (undo-tree-id279 . -1) (undo-tree-id280 . -1) (undo-tree-id281 . -1) (undo-tree-id282 . -1) (undo-tree-id283 . -1) (undo-tree-id284 . -1) (undo-tree-id285 . -1) (undo-tree-id286 . -1) (undo-tree-id287 . -1) (undo-tree-id288 . -1) (undo-tree-id289 . -1) (undo-tree-id290 . -1) (undo-tree-id291 . -1) (undo-tree-id292 . -1) (undo-tree-id293 . -1) (undo-tree-id294 . -1) (undo-tree-id295 . -1) (undo-tree-id296 . -1) (undo-tree-id297 . -1) (undo-tree-id298 . -1) (undo-tree-id299 . -1) (undo-tree-id300 . -1) (undo-tree-id301 . -1) (undo-tree-id302 . -1) (undo-tree-id303 . -1) (undo-tree-id304 . -1) (undo-tree-id305 . -1) (undo-tree-id306 . -1) (undo-tree-id307 . -1) (undo-tree-id308 . -1) (undo-tree-id309 . -1) (undo-tree-id310 . -1) (undo-tree-id311 . -1) (undo-tree-id312 . -1) (undo-tree-id313 . -1) (undo-tree-id314 . -1) (undo-tree-id315 . -1) (undo-tree-id316 . -1) (undo-tree-id317 . -1) (undo-tree-id318 . -1) (undo-tree-id319 . -1) (undo-tree-id320 . -1) (undo-tree-id321 . -1) (undo-tree-id322 . -1) (undo-tree-id323 . -1) (undo-tree-id324 . -1) (undo-tree-id325 . -1) (undo-tree-id326 . -1) (undo-tree-id327 . -1) (undo-tree-id328 . -1) (undo-tree-id329 . -1) (undo-tree-id330 . -1) (undo-tree-id331 . -1) (undo-tree-id332 . -1) (undo-tree-id333 . -1) (undo-tree-id334 . -1) (undo-tree-id335 . -1) (undo-tree-id336 . -1) (undo-tree-id337 . -1) (undo-tree-id338 . -1) (undo-tree-id339 . -1) (undo-tree-id340 . -1) (undo-tree-id341 . -1) (undo-tree-id342 . -1) (undo-tree-id343 . -1) (#("print" 0 5 (fontified t)) . 6355) (undo-tree-id344 . -5) (undo-tree-id345 . -5) (undo-tree-id346 . -5) (undo-tree-id347 . -5) (undo-tree-id348 . -5) (undo-tree-id349 . -5) (undo-tree-id350 . -5) (undo-tree-id351 . -5) (undo-tree-id352 . -5) (undo-tree-id353 . -5) (undo-tree-id354 . -5) (undo-tree-id355 . -5) (undo-tree-id356 . -5) (undo-tree-id357 . -5) (undo-tree-id358 . -5) (undo-tree-id359 . -5) (undo-tree-id360 . -5) (undo-tree-id361 . -5) (undo-tree-id362 . -5) (undo-tree-id363 . -5) (undo-tree-id364 . -5) (undo-tree-id365 . -5) (undo-tree-id366 . -5) (undo-tree-id367 . -5) (undo-tree-id368 . -5) (undo-tree-id369 . -5) (undo-tree-id370 . -5) (undo-tree-id371 . -5) (undo-tree-id372 . -5) (undo-tree-id373 . -5) (undo-tree-id374 . -5) (undo-tree-id375 . -5) (undo-tree-id376 . -5) (undo-tree-id377 . -5) (undo-tree-id378 . -5) (undo-tree-id379 . -5) (undo-tree-id380 . -5) (undo-tree-id381 . -5) (undo-tree-id382 . -5) (undo-tree-id383 . -5) (undo-tree-id384 . -5) (undo-tree-id385 . -5) (undo-tree-id386 . -5) (undo-tree-id387 . -5) (undo-tree-id388 . -5) (undo-tree-id389 . -5) (undo-tree-id390 . -5) (undo-tree-id391 . -5) (undo-tree-id392 . -5) (undo-tree-id393 . -5) (undo-tree-id394 . -5) (undo-tree-id395 . -5) (undo-tree-id396 . -5) (undo-tree-id397 . -5) (undo-tree-id398 . -5) (undo-tree-id399 . -5) (undo-tree-id400 . -5) (undo-tree-id401 . -5) (undo-tree-id402 . -5) (undo-tree-id403 . -5) (undo-tree-id404 . -5) (undo-tree-id405 . -5) (undo-tree-id406 . -5) (undo-tree-id407 . -5) (undo-tree-id408 . -5) (undo-tree-id409 . -5) (undo-tree-id410 . -5) (undo-tree-id411 . -5) (undo-tree-id412 . -5) (undo-tree-id413 . -5) (undo-tree-id414 . -5) (undo-tree-id415 . -5) (undo-tree-id416 . -5) (undo-tree-id417 . -5) (undo-tree-id418 . -5) (undo-tree-id419 . -5) (undo-tree-id420 . -5) (undo-tree-id421 . -5) (undo-tree-id422 . -5) (undo-tree-id423 . -5) (undo-tree-id424 . -5) (undo-tree-id425 . -5) (undo-tree-id426 . -5) (undo-tree-id427 . -5)) (25168 788 236416 0) 0 nil]) ([nil nil ((6360 . 6361)) nil (25168 895 987295 0) 0 nil]) ([nil nil ((6360 . 6361)) ((#(" " 0 1 (fontified t)) . 6360) (undo-tree-id3 . -1) (undo-tree-id4 . -1) (undo-tree-id5 . -1) (undo-tree-id6 . -1) (undo-tree-id7 . -1) (undo-tree-id8 . -1) (undo-tree-id9 . -1) (undo-tree-id10 . -1) (undo-tree-id11 . -1) (undo-tree-id12 . -1) (undo-tree-id13 . -1) (undo-tree-id14 . -1) (undo-tree-id15 . -1) (undo-tree-id16 . -1) (undo-tree-id17 . -1) (undo-tree-id18 . -1) (undo-tree-id19 . -1) (undo-tree-id20 . -1) (undo-tree-id21 . -1) (undo-tree-id22 . -1) (undo-tree-id23 . -1) (undo-tree-id24 . -1) (undo-tree-id25 . -1) (undo-tree-id26 . -1) (undo-tree-id27 . -1) (undo-tree-id28 . -1) (undo-tree-id29 . -1) (undo-tree-id30 . -1) (undo-tree-id31 . -1) (undo-tree-id32 . -1) (undo-tree-id33 . -1) (undo-tree-id34 . -1) (undo-tree-id35 . -1) (undo-tree-id36 . -1) (undo-tree-id37 . -1) (undo-tree-id38 . -1) (undo-tree-id39 . -1) (undo-tree-id40 . -1) (undo-tree-id41 . -1) (undo-tree-id42 . -1) (undo-tree-id43 . -1) (undo-tree-id44 . -1) (undo-tree-id45 . -1) (undo-tree-id46 . -1) (undo-tree-id47 . -1) (undo-tree-id48 . -1) (undo-tree-id49 . -1) (undo-tree-id50 . -1) (undo-tree-id51 . -1) (undo-tree-id52 . -1) (undo-tree-id53 . -1) (undo-tree-id54 . -1) (undo-tree-id55 . -1) (undo-tree-id56 . -1) (undo-tree-id57 . -1) (undo-tree-id58 . -1) (undo-tree-id59 . -1) (undo-tree-id60 . -1) (undo-tree-id61 . -1) (undo-tree-id62 . -1) (undo-tree-id63 . -1) (undo-tree-id64 . -1) (undo-tree-id65 . -1) (undo-tree-id66 . -1) (undo-tree-id67 . -1) (undo-tree-id68 . -1) (undo-tree-id69 . -1) (undo-tree-id70 . -1) (undo-tree-id71 . -1) (undo-tree-id72 . -1) (undo-tree-id73 . -1) (undo-tree-id74 . -1) (undo-tree-id75 . -1) (undo-tree-id76 . -1) (undo-tree-id77 . -1) (undo-tree-id78 . -1) (undo-tree-id79 . -1) (undo-tree-id80 . -1) (undo-tree-id81 . -1) (undo-tree-id82 . -1) (undo-tree-id83 . -1) (undo-tree-id84 . -1) (undo-tree-id85 . -1) (undo-tree-id86 . -1) (undo-tree-id87 . -1) (undo-tree-id88 . -1) (undo-tree-id89 . -1) (undo-tree-id90 . -1) (undo-tree-id91 . -1) (undo-tree-id92 . -1) (undo-tree-id93 . -1) (undo-tree-id94 . -1) (undo-tree-id95 . -1) (undo-tree-id96 . -1) (undo-tree-id97 . -1) (undo-tree-id98 . -1) (undo-tree-id99 . -1) (undo-tree-id100 . -1) (undo-tree-id101 . -1) (undo-tree-id102 . -1) (undo-tree-id103 . -1) (undo-tree-id104 . -1) (undo-tree-id105 . -1) (undo-tree-id106 . -1) (undo-tree-id107 . -1) (undo-tree-id108 . -1) (undo-tree-id109 . -1) (undo-tree-id110 . -1) (undo-tree-id111 . -1) (undo-tree-id112 . -1) (undo-tree-id113 . -1) (undo-tree-id114 . -1) (undo-tree-id115 . -1) (undo-tree-id116 . -1) (undo-tree-id117 . -1) (undo-tree-id118 . -1) (undo-tree-id119 . -1) (undo-tree-id120 . -1) (undo-tree-id121 . -1) (undo-tree-id122 . -1) (undo-tree-id123 . -1) (undo-tree-id124 . -1) (undo-tree-id125 . -1) (undo-tree-id126 . -1) (undo-tree-id127 . -1) (undo-tree-id128 . -1) (undo-tree-id129 . -1) (undo-tree-id130 . -1) (undo-tree-id131 . -1) (undo-tree-id132 . -1) (undo-tree-id133 . -1) (undo-tree-id134 . -1) (undo-tree-id135 . -1) (undo-tree-id136 . -1) (undo-tree-id137 . -1) (undo-tree-id138 . -1) (undo-tree-id139 . -1) (undo-tree-id140 . -1) (undo-tree-id141 . -1) (undo-tree-id142 . -1) (undo-tree-id143 . -1) (undo-tree-id144 . -1) (undo-tree-id145 . -1) (undo-tree-id146 . -1) (undo-tree-id147 . -1) (undo-tree-id148 . -1) (undo-tree-id149 . -1) (undo-tree-id150 . -1) (undo-tree-id151 . -1) (undo-tree-id152 . -1) (undo-tree-id153 . -1) (undo-tree-id154 . -1) (undo-tree-id155 . -1) (undo-tree-id156 . -1) (undo-tree-id157 . -1) (undo-tree-id158 . -1) (undo-tree-id159 . -1) (undo-tree-id160 . -1) (undo-tree-id161 . -1) (undo-tree-id162 . -1) (undo-tree-id163 . -1) (undo-tree-id164 . -1) (undo-tree-id165 . -1) (undo-tree-id166 . -1) (undo-tree-id167 . -1) (undo-tree-id168 . -1) (undo-tree-id169 . -1) (undo-tree-id170 . -1) (undo-tree-id171 . -1) (undo-tree-id172 . -1) (undo-tree-id173 . -1) (undo-tree-id174 . -1) (undo-tree-id175 . -1) (undo-tree-id176 . -1) (undo-tree-id177 . -1) (undo-tree-id178 . -1) (undo-tree-id179 . -1) (undo-tree-id180 . -1) (undo-tree-id181 . -1) (undo-tree-id182 . -1) (undo-tree-id183 . -1) (undo-tree-id184 . -1) (undo-tree-id185 . -1) (undo-tree-id186 . -1) (undo-tree-id187 . -1) (undo-tree-id188 . -1) (undo-tree-id189 . -1) (undo-tree-id190 . -1) (undo-tree-id191 . -1) (undo-tree-id192 . -1) (undo-tree-id193 . -1) (undo-tree-id194 . -1) (undo-tree-id195 . -1) (undo-tree-id196 . -1) (undo-tree-id197 . -1) (undo-tree-id198 . -1) (undo-tree-id199 . -1) (undo-tree-id200 . -1) (undo-tree-id201 . -1) (undo-tree-id202 . -1) (undo-tree-id203 . -1) (undo-tree-id204 . -1) (undo-tree-id205 . -1) (undo-tree-id206 . -1) (undo-tree-id207 . -1) (undo-tree-id208 . -1) (undo-tree-id209 . -1) (undo-tree-id210 . -1) (undo-tree-id211 . -1) (undo-tree-id212 . -1) (undo-tree-id213 . -1) (undo-tree-id214 . -1) (undo-tree-id215 . -1) (undo-tree-id216 . -1) (undo-tree-id217 . -1) (undo-tree-id218 . -1) (undo-tree-id219 . -1) (undo-tree-id220 . -1) (undo-tree-id221 . -1) (undo-tree-id222 . -1) (undo-tree-id223 . -1) (undo-tree-id224 . -1) (undo-tree-id225 . -1) (undo-tree-id226 . -1) (undo-tree-id227 . -1) (undo-tree-id228 . -1) (undo-tree-id229 . -1) (undo-tree-id230 . -1) (undo-tree-id231 . -1) (undo-tree-id232 . -1) (undo-tree-id233 . -1) (undo-tree-id234 . -1) (undo-tree-id235 . -1) (undo-tree-id236 . -1) (undo-tree-id237 . -1) (undo-tree-id238 . -1) (undo-tree-id239 . -1) (undo-tree-id240 . -1) (undo-tree-id241 . -1) (undo-tree-id242 . -1) (undo-tree-id243 . -1) (undo-tree-id244 . -1) (undo-tree-id245 . -1) (undo-tree-id246 . -1) (undo-tree-id247 . -1) (undo-tree-id248 . -1) (undo-tree-id249 . -1) (undo-tree-id250 . -1) (undo-tree-id251 . -1) (undo-tree-id252 . -1) (undo-tree-id253 . -1) (undo-tree-id254 . -1) (undo-tree-id255 . -1) (undo-tree-id256 . -1) (undo-tree-id257 . -1)) (25168 787 746644 0) 0 nil]) ([nil nil ((6362 . 6364) (6361 . 6363) (#("(" 0 1 (fontified nil)) . -6361) (6361 . 6362)) nil (25168 895 987287 0) 0 nil]) ([nil nil ((6361 . 6364)) ((#("row" 0 3 (fontified t)) . 6361) (t 25168 731 792051 853000)) (25168 731 683602 0) 0 nil]) ([nil nil ((6364 . 6365)) nil (25168 895 987276 0) 0 nil]) nil ([nil nil ((6365 . 6366)) nil (25168 895 987266 0) 0 nil]) ([nil nil ((6366 . 6369)) nil (25168 895 987250 0) 0 nil]) ([nil nil ((#("car" 0 3 (fontified t)) . 6362) (undo-tree-id1330 . -3) (undo-tree-id1331 . -2) (undo-tree-id1332 . -2) (undo-tree-id1333 . -3) (t 25168 895 993848 529000)) nil (25168 936 95784 0) 0 nil]) ([nil nil ((6362 . 6368)) nil (25168 936 95741 0) 0 nil]) ([nil nil ((#(" do (print (second row))" 0 12 (fontified t) 12 13 (fontified t face (rainbow-delimiters-depth-1-face)) 13 19 (fontified t) 19 20 (fontified t face (rainbow-delimiters-depth-2-face)) 20 30 (fontified t) 30 31 (fontified t face (rainbow-delimiters-depth-2-face)) 31 32 (fontified t face (rainbow-delimiters-depth-1-face))) . 6342) (undo-tree-id0 . -1) (undo-tree-id1 . -1) (undo-tree-id2 . -32) (undo-tree-id3 . -32) (undo-tree-id4 . -32) (t 25168 936 101832 441000)) nil (25168 1657 423150 0) 0 nil]) ([nil nil ((6190 . 6193) (t 25168 1657 534701 533000)) nil (25168 1726 478392 0) 0 nil]) ([nil nil ((6194 . 6201) (6193 . 6195) (#("(" 0 1 (fontified nil)) . -6193) (6193 . 6194)) nil (25168 1726 478384 0) 0 nil]) ([nil nil ((#("p" 0 1 (fontified t)) . -6200) (undo-tree-id19 . -1) 6201) nil (25168 1726 478372 0) 0 nil]) ([nil nil ((6200 . 6205)) nil (25168 1726 478360 0) 0 nil]) ([nil nil ((6205 . 6206)) nil (25168 1726 478355 0) 0 nil]) ([nil nil ((6206 . 6210)) nil (25168 1726 478350 0) 0 nil]) ([nil nil ((6210 . 6211)) nil (25168 1726 478344 0) 0 nil]) ([nil nil ((6212 . 6215) (6211 . 6213) (#("\"" 0 1 (fontified nil)) . -6211) (6211 . 6212)) nil (25168 1726 478337 0) 0 nil]) ([nil nil ((6215 . 6216)) nil (25168 1726 478328 0) 0 nil]) ([nil nil ((6216 . 6221)) nil (25168 1726 478323 0) 0 nil]) ([nil nil ((6221 . 6222)) nil (25168 1726 478317 0) 0 nil]) ([nil nil ((6222 . 6224)) nil (25168 1726 478311 0) 0 nil]) ([nil nil ((6223 . 6227)) nil (25168 1726 478306 0) 0 nil]) ([nil nil ((6228 . 6229)) nil (25168 1726 478299 0) 0 nil]) ([nil nil ((#("l" 0 1 (fontified t face font-lock-string-face)) . -6228) (undo-tree-id18 . -1) 6229) nil (25168 1726 478292 0) 0 nil]) ([nil nil ((6228 . 6229)) nil (25168 1726 478282 0) 0 nil]) ([nil nil ((6231 . 6234)) nil (25168 1726 478277 0) 0 nil]) ([nil nil ((6235 . 6246) (6234 . 6236) (#("(" 0 1 (fontified nil)) . -6234) (6234 . 6235)) nil (25168 1726 478270 0) 0 nil]) ([nil nil ((6246 . 6247)) nil (25168 1726 478260 0) 0 nil]) ([nil nil ((#("(dbi:prepare conn \"SET names 'utf8';\")" 0 1 (fontified t face (rainbow-delimiters-depth-6-face)) 1 18 (fontified t) 18 36 (fontified t face font-lock-string-face) 36 37 (fontified t face font-lock-string-face) 37 38 (fontified t face (rainbow-delimiters-depth-6-face))) . 6193) (undo-tree-id12 . -38) (undo-tree-id13 . 38) (undo-tree-id14 . -1) (undo-tree-id15 . 1) (undo-tree-id16 . -38) (undo-tree-id17 . -38)) nil (25168 1726 478250 0) 0 nil]) ([nil nil ((#(" " 0 2 (fontified nil)) . 6190) (undo-tree-id5 . -2) (undo-tree-id6 . -2) (undo-tree-id7 . -2) (undo-tree-id8 . -2) (undo-tree-id9 . -2) (#(" " 0 1 (fontified t)) . -6190) (undo-tree-id10 . -1) (undo-tree-id11 . -1) 6193) nil (25168 1726 478218 0) 0 nil]) ([nil current ((nil rear-nonsticky nil 6243 . 6244) (nil fontified nil 6243 . 6244) (nil fontified nil 6242 . 6243) (nil fontified nil 6224 . 6242) (nil fontified nil 6207 . 6224) (nil fontified nil 6206 . 6207) (6206 . 6244)) nil (25168 1726 478164 0) 0 nil]) nil
36,435
Common Lisp
.lisp
51
713.019608
7,934
0.612672
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
33f3f2f46787cdf400eccafb2761a0a2ad2ba3a8176eea765fc1475f3618d573
20,501
[ -1 ]
20,502
time.lisp
jnc-nj_jack-tools/src/time.lisp
(in-package #:jack.tools.time) (defun universal-to-timestring (universal) (local-time:format-timestring nil (local-time:universal-to-timestamp universal))) (defun sec-now () (local-time:timestamp-to-universal (local-time:now))) (defun create-time (&key +time -time (unit :hour)) (let ((time (local-time:now))) (when +time (setf time (local-time:timestamp+ time +time unit))) (when -time (setf time (local-time:timestamp- time -time unit))) (local-time:format-timestring nil time))) (defun time-difference (time-1 time-2) (cond ((stringp time-1) (time-difference (local-time:parse-timestring time-1) time-2)) ((stringp time-2) (time-difference time-1 (local-time:parse-timestring time-2))) (t (- (local-time:timestamp-to-universal time-1) (local-time:timestamp-to-universal time-2))))) (defun year-difference (time-1 time-2) (cond ((stringp time-1) (year-difference (local-time:parse-timestring time-1) time-2)) ((stringp time-2) (year-difference time-1 (local-time:parse-timestring time-2))) (t (- (local-time:timestamp-year time-1) (local-time:timestamp-year time-2))))) (defun timestamp> (time-1 time-2) (cond ((null time-1) nil) ((null time-2) t) ((stringp time-1) (timestamp> (local-time:parse-timestring time-1) time-2)) ((stringp time-2) (timestamp> time-1 (local-time:parse-timestring time-2))) (t (local-time:timestamp> time-1 time-2)))) (defun timestamp>= (time-1 time-2) (cond ((null time-1) nil) ((null time-2) t) ((stringp time-1) (timestamp>= (local-time:parse-timestring time-1) time-2)) ((stringp time-2) (timestamp>= time-1 (local-time:parse-timestring time-2))) (t (local-time:timestamp>= time-1 time-2)))) (defun timed-index (timestamp interval objects &key return?) (let ((index (floor (mod (*/ (time-difference (create-time) timestamp) interval) (if (numberp objects) objects (length objects)))))) (cond ((and (not (numberp objects)) return?) (nth index objects)) (t index)))) (defun timeout (wheel timer interval) (tw:schedule-timer wheel timer :milliseconds interval)) (defun wait (lock condition-variable) (bt:with-lock-held (lock) (bt:condition-wait condition-variable lock))) (defun release (lock condition-variable) (bt:with-lock-held (lock) (bt:condition-notify condition-variable))) (defun subtract-time (time amount unit) (local-time:format-timestring nil (local-time:timestamp- (local-time:parse-timestring time) amount unit))) (defun add-time (time amount unit) (local-time:format-timestring nil (local-time:timestamp+ (local-time:parse-timestring time) amount unit)))
2,676
Common Lisp
.lisp
68
35.764706
83
0.701734
jnc-nj/jack-tools
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6ad814e5eb06ad97fc3449cda43d73491c921d1b0cfe4e8427fd9e15a2223349
20,502
[ -1 ]