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
22,662
data.lisp
persidastricl_persidastricl/src/core/data.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ------- ;;; -*- mode: Lisp; -*- ;;; ;;; data.lisp ;;; ;;; ----- (in-package :data) (named-readtables:in-readtable persidastricl:syntax) (defgeneric diff* (d1 d2)) (defun diff-atom (a b) (if (== a b) [nil nil b] [a b nil])) (defmethod diff* (a b) (diff-atom a b)) (defun as-set-value (s) (if (set? s) s (into #{} s))) (defun vectorize (m) "Convert an associative-by-numeric-index collection into an equivalent vector, with nil for any missing keys" (when (seq m) (reduce (lambda (result e) (dlet (([k v] (->list e))) (assoc result k v))) m :initial-value (vec (take (apply #'max (->list (keys m))) (repeat nil)))))) (defun diff-associative-key (a b k) "Diff associative things a and b, comparing only the key k." (dlet ((va (get a k)) (vb (get b k)) ([a* b* ab] (diff va vb)) (in-a (not (== (get a k :not-found) :not-found))) (in-b (not (== (get b k :not-found) :not-found))) (same (and in-a in-b (or (not (nil? ab)) (and (nil? va) (nil? vb)))))) [(when (and in-a (or (not (nil? a*)) (not same))) {k a*}) (when (and in-b (or (not (nil? b*)) (not same))) {k b*}) (when same {k ab})])) (defun diff-associative (a b ks) (vec (reduce (lambda (diff1 diff2) (doall (map #'merge diff1 diff2))) (map (partial #'diff-associative-key a b) ks) :initial-value [nil nil nil]))) (defun diff-sequential (a b) (vec (map #'vectorize (diff-associative (if (vector? a) a (vec a)) (if (vector? b) b (vec b)) (range (max (count a) (count b))))))) (defmethod diff* ((a1 p::hash-map) a2) (diff-associative a1 a2 (set:union (set (keys a1)) (set (keys a2))))) (defmethod diff* ((a1 hash-table) a2) (diff-associative a1 a2 (set:union (set (keys a1)) (set (keys a2))))) (defmethod diff* ((s1 string) (s2 string)) (diff-sequential s1 s2)) (defmethod diff* ((s1 p::hash-set) s2) (let ((s1 (as-set-value s1)) (s2 (as-set-value s2))) [(set:difference s1 s2) (set:difference s2 s1) (set:intersection s1 s2)])) (defmethod diff* ((s1 sequence) s2) (diff-sequential s1 s2)) (defmethod diff* ((s1 p::vector) s2) (diff-sequential s1 s2)) (defmethod diff* ((s1 p::lazy-sequence) s2) (diff-sequential s1 s2)) (defun diff-type (x) (typecase x (p::hash-map :associative) (hash-table :associative) (p::hash-set :set) (p::vector :sequential) (simple-array :sequential) (list :sequential) (string :string) (t :unknown))) (defun diff (a b) (if (== a b) [nil nil a] (if (== (diff-type a) (diff-type b)) (diff* a b) (diff-atom a b))))
3,099
Common Lisp
.lisp
95
27.621053
80
0.571907
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
35bcab23ad451c915f0484a0c70c49c989b01f30b8dbf3859f38c103bd038fb6
22,662
[ -1 ]
22,663
sub-vector.lisp
persidastricl_persidastricl/src/core/sub-vector.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ------- ;;; -*- mode: Lisp; -*- ;;; ;;; sub-vector.lisp ;;; ;;; ----- (in-package #:persidastricl) (named-readtables:in-readtable persidastricl:syntax) (define-immutable-class sub-vector (metadata collection seqable) ((v :initarg :v :reader v) (start :initarg :start :reader start) (end :initarg :end :reader end)) (:default-initargs :v [] :start 0 :end 0 :meta nil)) (defun subvec (v start &optional (end (count v))) (assert (vector? v)) (assert (> end start)) (make-instance 'sub-vector :v v :start start :end (min end (count v)))) (defmethod conj ((sv sub-vector) &rest items) (if items (with-slots (v start end meta) sv (let* ((items (vec items)) (n (count items)) (end (slot-value sv 'end)) (nv (reduce (lambda (v* i) (assoc v* (+ end i) (get items i))) (range n) :initial-value v))) (make-instance (type-of sv) :v nv :start start :end (+ end n) :meta meta))) sv)) (defmethod count ((sv sub-vector)) (- (slot-value sv 'end) (slot-value sv 'start))) (defmethod get ((sv sub-vector) index &optional (default nil)) (if (< index (count sv)) (get (slot-value sv 'v) (+ (slot-value sv 'start) index) default) default)) (defmethod first ((sv sub-vector)) (get (slot-value sv 'v) (slot-value sv 'start))) (defmethod peek ((sv sub-vector)) (get (slot-value sv 'v) (dec (slot-value sv 'end)))) (defmethod seq ((sv sub-vector)) (when (pos? (count sv)) (labels ((next* (i) (when (< i (count sv)) (let ((value (get sv i))) (lseq value (next* (1+ i))))))) (lseq (first sv) (next* 1))))) (defmethod rest ((sv sub-vector)) (drop 1 (seq sv))) (defmethod rseq ((sv sub-vector)) (with-slots (v start) sv (let ((count (count sv))) (when (pos? count) (let ((index (+ start (dec count)))) (labels ((next* (i) (when (>= i start) (let ((value (get v i))) (lseq value (next* (1- i))))))) (lseq (get v index) (next* (1- index))))))))) (defmethod nth ((sv sub-vector) n &optional (default nil)) (nth (seq sv) n default)) (defmethod next ((sv sub-vector)) (next (seq sv))) (defmethod head ((sv sub-vector)) (head (seq sv))) (defmethod tail ((sv sub-vector)) (tail (seq sv))) (defmethod ->list ((sv sub-vector)) (cl:map 'list (lambda (i) (get sv i)) (loop for i from 0 below (count sv) collect i))) (defmethod cons ((sv sub-vector) value) (conj sv value)) (defmethod pop ((sv sub-vector)) (with-slots (v start end meta) sv (make-instance (type-of sv) :v v :start start :end (max start (dec end)) :meta meta))) (defmethod assoc ((sv sub-vector) index item &rest kv-pairs) (with-slots (v start end meta) sv (let ((new-items (- (inc (count kv-pairs)) (- (dec end) index)))) (labels ((adjust (vr k v) (conj vr (+ start k) v))) (let* ((kv-pairs (reduce (lambda (v kv-pair) (apply #'adjust v kv-pair)) (partition kv-pairs 2) :initial-value (conj [] (+ start index) item))) (nv (apply #'assoc v (->list kv-pairs)))) (make-instance (type-of sv) :v nv :start start :end (+ end (max 0 new-items)) :meta meta)))))) (defun pprint-sub-vector (stream sv &rest other-args) (declare (ignore other-args)) (let ((*print-length* (min *print-bpvt-items* (or *print-lines* *print-bpvt-items*)))) (pprint-logical-block (stream (->list (take (inc *print-length*) (seq sv))) :prefix "[" :suffix "]") (pprint-exit-if-list-exhausted) (loop (write (pprint-pop) :stream stream) (pprint-exit-if-list-exhausted) (write-char #\space stream) (pprint-newline :fill stream))))) (defmethod print-object ((object sub-vector) stream) (format stream "~/persidastricl::pprint-sub-vector/" object)) (set-pprint-dispatch 'sub-vector 'pprint-sub-vector) (defmethod with-meta ((sv sub-vector) meta) (with-slots (v start end) sv (make-instance (type-of sv) :v v :start start :end end :meta meta))) ;; ;; equality with subvecs ;; (defmethod == ((s1 sub-vector) (s2 sequence)) (== (seq s1) (seq s2))) (defmethod == ((s1 sequence) (s2 sub-vector)) (== (seq s2) (seq s1))) (defmethod == ((s1 sub-vector) (s2 vector)) (== (seq s1) (seq s2))) (defmethod == ((s1 vector) (s2 sub-vector)) (== (seq s2) (seq s1))) (defmethod == ((s1 sub-vector) (s2 lazy-sequence)) (== (seq s1) (seq s2))) (defmethod == ((s1 lazy-sequence) (s2 sub-vector)) (== (seq s2) (seq s1))) (defmethod compare ((sv1 sub-vector) (sv2 sub-vector)) (compare (seq sv1) (seq sv2))) (defmethod compare ((sv1 sub-vector) (v1 vector)) (compare (seq sv1) (seq v1))) (defmethod compare ((v1 vector) (sv1 sub-vector)) (compare (seq v1) (seq sv1)))
5,321
Common Lisp
.lisp
133
34.067669
104
0.583608
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3ec4e6e563b18b5af189eeedb76807c58d220aff1803a5b7aa15ba993a9bca8d
22,663
[ -1 ]
22,664
walk.lisp
persidastricl_persidastricl/src/core/walk.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ------- ;;; -*- mode: Lisp; -*- ;;; ;;; walk.lisp ;;; ;;; ----- (in-package :walk) (named-readtables:in-readtable persidastricl:syntax) (defgeneric walk (inner outer form)) (defmethod walk (inner outer form) (funcall outer form)) (defmethod walk (inner outer (form (eql nil))) (funcall outer form)) (defmethod walk (inner outer (form list)) (funcall outer (->list (map inner form)))) (defmethod walk (inner outer (entry p::entry)) (funcall outer (p::map-entry (funcall inner (key entry)) (funcall inner (val entry))))) (defmethod walk (inner outer (seq p::lazy-sequence)) (funcall outer (doall (map inner seq)))) (defmethod walk (inner outer (m p::hash-map)) (funcall outer (into (empty m) (map inner m)))) (defmethod walk (inner outer (collection p::collection)) (funcall outer (into (empty collection) (map inner collection)))) (defun postwalk (f form) (walk (lambda (frm) (postwalk f frm)) f form)) (defun prewalk (f form) (walk (lambda (frm) (prewalk f frm)) #'identity (funcall f form))) (defun keywordize-keys (m) (labels ((keywordize-entry (e) (let ((k (key e)) (v (val e))) (if (string? k) (p::map-entry (keyword k) v) e)))) (postwalk (lambda (x) (if (map? x) (into {} (map #'keywordize-entry x)) x)) m))) (defun stringify-keys (m) (labels ((stringify-entry (e) (let ((k (key e)) (v (val e))) (if (keywordp k) (p::map-entry (name k) v) e)))) (postwalk (lambda (x) (if (map? x) (into {} (map #'stringify-entry x)) x)) m))) (defun prewalk-demo (form) (prewalk (lambda (x) (princ "Walked: ") (princ (format nil "~s~%" x)) x) form)) (defun postwalk-demo (form) (postwalk (lambda (x) (princ "Walked: ") (princ (format nil "~s~%" x)) x) form)) (defun prewalk-replace (smap form) (prewalk (lambda (x) (let ((v (get smap x))) (or v x))) form)) (defun postwalk-replace (smap form) (postwalk (lambda (x) (let ((v (get smap x))) (or v x))) form)) (defun macroexpand-all (form) (postwalk (lambda (x) (if (listp x) (macroexpand x) x)) form))
2,515
Common Lisp
.lisp
70
31.385714
89
0.604948
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e8fc7e8dd2e86506815714f3519310d76bf9bf991e8cf816c4a989dc586a2fbf
22,664
[ -1 ]
22,665
functions.lisp
persidastricl_persidastricl/src/core/functions.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ----- ;;; -*- mode: Lisp; -*- ;;; ;;; core/functions.lisp ;;; ;;; core (regular) functions ;;; ;;; ----- (in-package #:persidastricl) (named-readtables:in-readtable persidastricl:syntax) (defun memoize (f) (let ((mem (atom (persistent-hash-map)))) (lambda (&rest args) (let ((r (get (deref mem) args))) (or r (let ((ret (apply f args))) (swap! mem #'assoc args ret) ret)))))) (defmacro defmemoized (sym f) `(setf (fdefinition ',sym) ,(memoize f))) (defmacro fdef (sym f) `(setf (fdefinition ',sym) ,f)) (defun reduce (f s &key (initial-value nil initial-value-p)) (if s (let ((s (seq s))) (labels ((reduce* (current-value seq) (if seq (let* ((new-value (head seq)) (result (funcall f current-value new-value))) (reduce* result (tail seq))) current-value))) (reduce* (if initial-value-p initial-value (head s)) (if initial-value-p s (tail s))))) initial-value)) (defun reductions (f s &key (initial-value nil initial-value-p)) (if s (let ((s (seq s))) (labels ((reduce* (current-value seq accum) (if seq (let* ((new-value (head seq)) (result (funcall f current-value new-value))) (reduce* result (tail seq) (conj accum result))) accum))) (let ((init (if initial-value-p initial-value (head s))) (seq (if initial-value-p s (tail s)))) (reduce* init seq [init])))) [initial-value])) (defun frequencies (coll) (reduce (lambda (m target) (assoc m target (inc (get m target 0)))) coll :initial-value {})) (defun run! (f coll) (reduce (lambda (ign item) (declare (ignore ign)) (funcall f item)) coll :initial-value nil) nil) (defun reduce-kv (f s &key (initial-value nil initial-value-p)) (if s (let ((s (seq s))) (labels ((reduce* (seq current-value) (if seq (let ((new-value (head seq))) (reduce* (tail seq) (apply f current-value (->list new-value)))) current-value))) (reduce* (if initial-value-p s (tail s)) (if initial-value-p initial-value (head s))))) initial-value)) (defun get-in (obj path &optional (default nil)) (or (reduce (lambda (obj k) (get obj k)) path :initial-value obj) default)) (defun assoc-in (obj path v) (let* ((k (first path)) (more (rest path)) (next (or (get obj k) (empty obj)))) (if more (assoc obj k (assoc-in next more v)) (assoc obj k v)))) (defun update (m k f &rest args) (let ((current (get m k))) (assoc m k (apply f current args)))) (defun update-in (obj path f &rest args) (let* ((k (first path)) (more (rest path))) (if (first more) (assoc obj k (apply #'update-in (or (get obj k) (empty obj)) more f args)) (assoc obj k (apply f (get obj k) args))))) (defun filter (pred sequence) (when (keywordp pred) (make-funcallable-keyword pred)) (when-let ((seq (seq sequence))) (labels ((filter* (s) (when s (let ((v (head s))) (if (funcall pred v) (lseq v (filter* (tail s) )) (filter* (tail s))))))) (filter* seq)))) (defun map (f &rest seqs) (when (keywordp f) (make-funcallable-keyword f)) (when (every #'seq seqs) (let ((n (count seqs)) (seqs (cl:map 'list #'seq seqs))) (labels ((apply* (args) (apply f args)) (map* (ss) (let ((args (cl:map 'list #'head ss))) (when (= n (count args)) (let ((r (apply* args))) (lseq r (map* (remove-if #'nil? (cl:map 'list #'tail ss))))))))) (map* seqs))))) (defun every? (f &rest seqs) (when (keywordp f) (make-funcallable-keyword f)) (cond ((every (lambda (s) (nil? (seq s))) seqs) t) ((every #'seq seqs) (let ((n (count seqs)) (seqs (cl:map 'list #'seq seqs))) (labels ((apply* (args) (apply f args)) (every?* (ss) (let ((args (cl:map 'list #'head ss)) (rest-seqs (remove-if #'nil? (cl:map 'list #'tail ss)))) (when (= n (count args)) (let ((r (apply* args))) (when (true? r) (if (empty? rest-seqs) t (every?* rest-seqs)))))))) (every?* seqs)))))) (fdef not-every? (comp #'not #'every?)) (defun every-pred (&rest preds) (lambda (&rest args) (every? (lambda (pred) (every? pred args)) preds))) (defun mapv (f &rest seqs) (into (persistent-vector) (apply #'map f seqs))) (defun concat (&rest colls) (labels ((cat (s more) (if-let ((s (seq s))) (lseq (first s) (cat (rest s) more)) (when more (cat (first more) (rest more)))))) (cat (first colls) (rest colls)))) (defun mapcat (f s &rest seqs) (let ((xs (apply #'map f s seqs))) (apply #'concat (->list xs)))) ;; ;; TODO: can we figure out a way to do this without the 'eval'?? or does it even matter?? ;; (defmacro lazy-cat (&rest colls) `(let ((xs (map (lambda (x) (delay (eval x))) ',colls))) (labels ((cat (s more) (if-let ((s (seq s))) (lseq (first s) (cat (rest s) more)) (when more (cat (force (first more)) (rest more)))))) (cat (force (first xs)) (rest xs))))) (defun filterv (pred seq) (into (persistent-vector) (filter pred seq))) (defun keep (f &rest seqs) (when (keywordp f) (make-funcallable-keyword f)) (when seqs (let ((n (count seqs)) (seqs (cl:map 'list #'seq seqs))) (labels ((apply* (args) (apply f args)) (map* (ss) (let ((args (cl:map 'list #'head ss))) (when (= n (count args)) (let ((r (apply* args))) (if r (lseq r (map* (remove-if #'nil? (cl:map 'list #'tail ss)))) (map* (remove-if #'nil? (cl:map 'list #'tail ss))))))))) (map* seqs))))) (defun integers (&key (from 0) (step 1)) (lseq from (integers :from (+ from step) :step step))) (defun map-indexed (f &rest seqs) (apply #'map f (integers) seqs)) (defun keep-indexed (f &rest seqs) (apply #'keep f (integers) seqs)) (defun range (&optional n1 n2 n3) "returns a lazy sequence of numbers based on the following: (range) infinite sequence (0 1 2 ...) (range end) finite sequence (0 1 ... end) (range start end) and (< start end) finite sequence (start start+1 start+2 ... end) (range start end) and (> start end) finite sequence (start start-1 start-2 ... end) (range start end step) and (< start end) (pos? step) finite sequence (start start+step ... end) (range start end step) and (> start end) (neg? step) finite sequence (start start-step ... end) (range start nil step) infinite sequence (start start+step ...) returns nil when 1. (zero? step) or 2. (= start end) or 3. (< start stop) but (neg? step) or 4. (> start stop) but (pos? step)" (let* ((args (cond ((and n1 n2 n3) (list n1 n2 n3)) ((and n1 n2) (list n1 n2 (if (<= n1 n2) 1 -1))) ((and n1 n3) (list n1 nil n3)) ((and n1) (list 0 n1 (if (neg? n1) -1 1))) (t (list 0 nil 1)))) (start (nth args 0)) (end (nth args 1)) (step (nth args 2))) (if (or (zerop step) (and end start (= start end))) nil (labels ((finite-up* (end &key (start 0) (step 1)) (when (< start end) (lseq start (finite-up* end :start (+ start step) :step step)))) (finite-down* (end &key (start 0) (step 1)) (when (> start end) (lseq start (finite-down* end :start (+ start step) :step step)))) (infinite* (&key (start 0) (step 1)) (lseq start (infinite* :start (+ start step) :step step)))) (if end (cond ((and (> start end) (neg? step)) (finite-down* end :start start :step step)) ((and (< start end) (pos? step)) (finite-up* end :start start :step step))) (infinite* :start start :step step)))))) (defun nrange (n &key (start 0) (step 1)) (when (> n 0) (lseq start (nrange (1- n) :start (+ start step) :step step)))) (defun take-while (pred s) (when-let ((s (seq s))) (let ((v (head s))) (when (funcall pred v) (lseq v (take-while pred (tail s))))))) (defun take-nth (n s) (when-let ((s (seq s))) (lseq (head s) (take-nth n (drop n s))))) (defun drop-while (pred s) (when-let ((s (seq s))) (let ((v (head s))) (if (funcall pred v) (drop-while pred (tail s)) (lseq v (tail s)))))) (defun drop-last (n seq) (map (lambda (x y) (declare (ignore y)) x) (seq seq) (drop n seq))) (defun take-last (n seq) (labels ((take* (s lead) (if lead (take* (tail s) (tail lead)) s))) (take* (seq seq) (drop n seq)))) (defun split-at (n seq) (list (take n seq) (drop n seq))) (defun split-with (pred seq) (list (take-while pred seq) (drop-while pred seq))) (defun iterate (f x) (let ((v (funcall f x))) (lseq v (iterate f v)))) (defun partition (source n &optional (step n)) (when-let ((s (seq source))) (let ((v (->list (take n s))) (rest (drop step s))) (if rest (lseq v (partition rest n step)) (if (= n (length v)) (list v) '()))))) (defun partition-all (source n &optional (step n)) (when-let ((s (seq source))) (let ((v (->list (take n s))) (rest (drop step s))) (if rest (lseq v (partition-all rest n step)) (list v))))) (defun partition-by (f seq) (when-let ((s (seq seq))) (let* ((v (head s)) (fv (funcall f v)) (run (into (list v) (take-while (lambda (v) (== fv (funcall f v))) (tail s))))) (lseq run (partition-by f (drop (cl:length run) s)))))) (defun group-by (f coll) (when (keywordp f) (make-funcallable-keyword f)) (reduce (lambda (ret x) (let ((k (funcall f x))) (assoc ret k (conj (get ret k (persistent-vector)) x)))) coll :initial-value (persistent-hash-map))) (defun rand-nth (coll) (assert (collection? coll)) (nth (seq coll) (random (count coll)))) (defun cycle (coll) (labels ((more (c) (let ((v (head c)) (tail (or (tail c) coll))) (lseq v (more tail))))) (more coll))) (defun repeatedly (f) (lseq (funcall f) (repeatedly f))) (defun repeat (x) (repeatedly (constantly x))) (defun distinct (coll) (labels ((step* (xs seen) (when (seq xs) (let ((f (first xs))) (if (contains? seen f) (step* (rest xs) seen) (lseq f (step* (rest xs) (conj seen f)))))))) (when (seq coll) (step* (seq coll) #{})))) (defun dedup (seq) (labels ((next* (s prev) (when (seq s) (let ((v (first s))) (if (== v prev) (next* (rest s) prev) (lseq v (next* (rest s) v))))))) (when (seq seq) (let ((v (first seq))) (lseq v (next* (rest seq) v)))))) (defun distinct? (&rest items) (labels ((distinct* (s target others) (if target (if (contains? s target) nil (distinct* (conj s target) (first others) (rest others))) t))) (if (seq items) (distinct* #{} (first items) (rest items)) t))) (defun shuffle (coll) (assert (collection? coll)) (let* ((l (->list coll)) (n (count l))) (do ((tail (nthcdr 0 l) (cdr tail))) ((zerop n)) (rotatef (car tail) (car (nthcdr (random n) tail))) (decf n)) (vec l))) (defun zipmap (seq1 seq2) (labels ((zipmap* (m s1 s2) (let ((k (head s1)) (v (head s2))) (if (and k v) (zipmap* (assoc m k v) (tail s1) (tail s2)) m)))) (zipmap* (persistent-hash-map) seq1 seq2))) (defun interleave (seq1 seq2) (let ((e1 (first seq1)) (e2 (first seq2))) (when (and e1 e2) (lseq e1 (lseq e2 (interleave (rest seq1) (rest seq2))))))) (defun interpose (separator seq) (drop 1 (interleave (repeat separator) seq))) (defun line-seq (stream) (when stream (let ((line (read-line stream nil nil))) (when line (lseq line (line-seq stream)))))) (defun tree-seq (branch? children root) (labels ((walk (node) (lseq node (when (funcall branch? node) (mapcat #'walk (funcall children node)))))) (walk root))) (defun re-seq (re s) (let ((scanner (cl-ppcre:create-scanner re))) (labels ((scan* (pos) (let* ((match (multiple-value-list (cl-ppcre:scan scanner s :start pos))) (start (get match 0)) (end (get match 1))) (when start (let ((v (subs s start end))) (lseq v (scan* end))))))) (scan* 0)))) (defun random-seq (n &key (random-state *random-state*)) (labels ((rand* (n) (lseq (random n random-state) (rand* n)))) (lseq (random n random-state) (rand* n)))) (labels ((best (pred k c1 c2 &rest contestants) (labels ((best* (the-one the-value challengers) (let ((challenger (first challengers))) (if challenger (let ((challenger-value (get challenger k))) (if (funcall pred the-value challenger-value) (best* the-one the-value (rest challengers)) (best* challenger challenger-value (rest challengers)))) the-one)))) (let* ((v1 (get c1 k)) (v2 (get c2 k)) (c1? (funcall pred v1 v2)) (w (if c1? c1 c2)) (v (if c1? v1 v2))) (best* w v contestants))))) (defun min-key (k &rest challengers) (apply #'best #'< k challengers)) (defun max-key (k &rest challengers) (apply #'best #'> k challengers))) (defun replace (smap coll) (if (vector? coll) (reduce (lambda (v i) (let ((rep (get smap (nth v i)))) (if rep (assoc v i rep) v))) (range (count coll)) :initial-value coll) (map (lambda (x) (get smap x x)) coll))) (defun flatten (x) (filter (complement #'sequential?) (tail (tree-seq #'collection? #'seq x)))) (defun some (pred &rest seqs) (head (apply #'keep pred seqs))) (fdef not-any? (comp #'not #'some)) (defun some-fn (&rest fns) (lambda (&rest s) (some (lambda (f) (some f s)) fns))) (defvar emptyable? (some-fn #'string? #'sequential? #'collection? #'map?)) (defun mremove (pred m) (labels ((check (m k v) (let ((result (unwind-protect (funcall pred v)))) (if-not result (assoc m k v) m))) (collection? (x) (typep x 'persidastricl::collection)) (collection (v) (into (empty v) (map #'scrub v))) (scrub (item) (cond ((map? item) (mremove pred item)) ((collection? item) (collection item)) (t item)))) (when m (reduce-kv (lambda (m k v) (check m k (scrub v))) m :initial-value (persistent-hash-map))))) (defun has-no-value? (x) (or (null x) (and (funcall emptyable? x) (empty? x)))) (defun only-valid-values (x) (mremove #'has-no-value? x)) (defun juxt (&rest fns) (run! (lambda (f) (when (keywordp f) (make-funcallable-keyword f))) fns) (lambda (&rest args) (reduce (lambda (v f) (conj v (apply f args))) fns :initial-value (persistent-vector)))) (defun merge (&rest ms) (if (some #'identity ms) (reduce (lambda (m1 m2) (if m2 (into m1 (->plist m2)) m1)) (filter #'some? ms)))) (defun merge-with (f &rest ms) (labels ((merge-kv (m k v2) (let ((v1 (get m k :not-found))) (if (== v1 :not-found) (assoc m k v2) (assoc m k (funcall f v1 v2))))) (merge* (m1 m2) (reduce-kv #'merge-kv m2 :initial-value m1))) (reduce #'merge* (filter #'some? ms)))) (defun slurp (f) (with-open-file (is f :if-does-not-exist nil) (when is (str:join #\NEWLINE (->list (line-seq is)))))) (defun spit (f contents &key (if-exists :overwrite) (if-does-not-exist :create)) (with-open-file (os f :if-exists if-exists :if-does-not-exist if-does-not-exist :direction :output) (write-string contents os)) f) (defun trampoline (f &rest args) (if args (trampoline (lambda () (apply f args))) (let ((ret (funcall f))) (if (functionp ret) (trampoline ret) ret)))) (defun dorun (coll) (let ((s (seq coll))) (when s (dorun (next s))))) (defun dorun-n (n coll) (when (and (seq coll) (pos? n)) (dorun-n (dec n) (next coll)))) (defun doall (coll) (dorun coll) coll) (defun do-n (n coll) (dorun-n n coll) coll)
18,952
Common Lisp
.lisp
526
26.397338
101
0.495883
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
090293dbaaa24f447c093eaa4cd81bc8c345047aa3458e2e5e5ed229da6e2672
22,665
[ -1 ]
22,666
methods.lisp
persidastricl_persidastricl/src/core/methods.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ----- ;;; -*- mode: Lisp; -*- ;;; ;;; core/methods.lisp ;;; ;;; core (generic) functions ;;; ;;; ----- (in-package #:persidastricl) (defmethod conj ((l list) &rest items) (->list (concat (seq l) items))) (defgeneric into (obj sequence)) (defmethod into ((lst list) sequence) (if sequence (apply #'conj lst (->list sequence)) lst)) (defmethod into ((a array) sequence) (if sequence (let ((size (+ (length (->list a)) (length (->list sequence))))) (make-array size :initial-contents (->list (concat (->list a) sequence)))) a)) (defmethod into ((s1 string) (s2 string)) (concatenate 'string s1 s2)) (defmethod into ((col collection) sequence) (reduce #'conj (seq sequence) :initial-value col)) (labels ((twople? (item) (= (count item) 2)) (classify (s) (let ((item (first s))) (cond ((dotted-pair? item) :alist) ((and (or (typep item 'entry) (typep item 'simple-array) (typep item 'persistent-vector) (typep item 'list)) (twople? item)) :entries) (t :non-entries)))) (prepare-sequence (seq) (case (classify seq) (:alist (map (lambda (dp) (list (car dp) (cdr dp))) seq)) (:entries (map #'->list seq)) (otherwise (partition-all seq 2))))) (defmethod into ((obj hash-map) sequence) (let ((seq (seq sequence))) (reduce (lambda (m kv-pair) (apply #'assoc m kv-pair)) (prepare-sequence seq) :initial-value obj))) (defmethod into ((obj hash-table) sequence) (let ((seq (seq sequence))) (reduce (lambda (m kv-pair) (setf (gethash (first kv-pair) m) (second kv-pair)) m) (prepare-sequence seq) :initial-value obj)))) ;; ----- ;; more equality ;; ;; ----- ;; ;; lazy sequence equality with sequences and vectors (defmethod == ((s1 lazy-sequence) (s2 lazy-sequence)) (or (eq s1 s2) (and (= (count s1) (count s2)) (every? (lambda (e1 e2) (== e1 e2)) s1 s2)))) (defmethod == ((s1 sequence) (s2 lazy-sequence)) (== (seq s1) s2)) (defmethod == ((s1 lazy-sequence) (s2 sequence)) (== s1 (seq s2))) (defmethod == ((s1 vector) (s2 lazy-sequence)) (== (seq s1) s2)) (defmethod == ((s1 lazy-sequence) (s2 vector)) (== s1 (seq s2))) ;; ;; vectors ;; (defmethod == ((v1 vector) (v2 vector)) (and (= (count v1) (count v2)) (== (seq v1) (seq v2)))) (defmethod == ((s1 sequence) (s2 vector)) (when s1 (== (seq s2) (seq s1)))) (defmethod == ((s1 vector) (s2 sequence)) (when s2 (== (seq s1) (seq s2)))) ;; ;; NOTE: any standard-object CLOS object can be a subclass of ;; 'metadata and have a 'meta slot with data that is any sort of map ;; (hamt or hash-table) ;; ;; NOTE: any persistent-class CLOS object can only have meta that is a ;; persistent-hash-map (see their `with-meta` defmethod definitions ;; elsewhere) because it makes no sense (at least to me) to have a ;; persistent-class object with immutable meta data --mdp ;; (defmethod with-meta ((object metadata) (meta hash-map)) (setf (slot-value object 'meta) meta) object) (defmethod with-meta ((object metadata) (meta hash-table)) (setf (slot-value object 'meta) meta) object)
3,749
Common Lisp
.lisp
116
26.991379
82
0.582594
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
89b461e3e183f508fd6d44b0d34f29a2ac6b7ff2e21b497a1f4d4e31f15898b0
22,666
[ -1 ]
22,667
set.lisp
persidastricl_persidastricl/src/core/set.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ------- ;;; -*- mode: Lisp; -*- ;;; ;;; set.lisp ;;; ;;; ----- (in-package #:set) (named-readtables:in-readtable persidastricl:syntax) (defun union (&rest sets) (reduce #'into sets :initial-value #{})) (defun intersection (&rest sets) (assert (not (empty? sets))) (labels ((intersect* (s1 s2) (reduce (lambda (s item) (if (and (contains? s1 item) (contains? s2 item)) (conj s item) s)) (if (< (count s1) (count s2)) s1 s2) :initial-value #{}))) (if (every (lambda (s) (not (empty? s))) sets) (reduce #'intersect* sets) #{}))) (defun difference (&rest sets) (when (set? (first sets)) (labels ((difference* (s1 s2) (reduce (lambda (s1 item) (if (contains? s1 item) (disj s1 item) s1)) s2 :initial-value s1))) (reduce #'difference* sets)))) (defun index (xrel ks) (reduce (lambda (m x) (let ((ik (select-keys x ks))) (assoc m ik (conj (get m ik #{}) x)))) xrel :initial-value {})) (defun select (pred s) (reduce (lambda (s item) (if (funcall pred item) (conj s item) s)) s :initial-value #{})) (defun project (xrel ks) (with-meta (set (map (lambda (x) (select-keys x ks)) xrel)) (meta xrel))) (defun rename-keys (map kmap) (reduce-kv (lambda (m old new) (let ((v (get map old))) (if v (assoc m new v) m))) kmap :initial-value (apply #'dissoc map (->list (keys kmap))))) (defun rename (xrel kmap) (with-meta (set (map (lambda (x) (rename-keys x kmap)) xrel)) (meta xrel))) (defun map-invert (m) (reduce-kv (lambda (m k v) (assoc m v k)) m :initial-value {})) (defun join (xrel yrel &optional km) (labels ((natural-join (xrel yrel) (if (and (seq xrel) (seq yrel)) (let* ((ks (intersection (set (keys (first xrel))) (set (keys (first yrel))))) (rels (if (<= (count xrel) (count yrel)) [xrel yrel] [yrel xrel])) (r (get rels 0)) (s (get rels 1)) (idx (index r ks))) (reduce (lambda (ret x) (let ((found (get idx (select-keys x ks)))) (if found (reduce (lambda (inner-s m) (conj inner-s (merge m x))) found :initial-value ret) ret))) s :initial-value #{})) #{})) (key-join (xrel yrel km) (let* ((rels (if (<= (count xrel) (count yrel)) [xrel yrel (map-invert km)] [yrel xrel km])) (r (get rels 0)) (s (get rels 1)) (k (get rels 2)) (idx (index r (vals k)))) (reduce (lambda (ret x) (let ((found (get idx (rename-keys (select-keys x (keys k)) k)))) (if found (reduce (lambda (inner-s m) (conj inner-s (merge m x))) found :initial-value ret) ret))) s :initial-value #{})))) (if km (key-join xrel yrel km) (natural-join xrel yrel)))) (defun subset? (set1 set2) (assert (and (set? set1) (set? set2))) (cond ((empty? set1) t) (t (and (<= (count set1) (count set2)) (every? (lambda (item) (contains? set2 item)) set1))))) (defun superset? (set1 set2) (assert (and (set? set1) (set? set2))) (cond ((empty? set2) t) (t (and (>= (count set1) (count set2)) (every? (lambda (item) (contains? set1 item)) set2)))))
4,588
Common Lisp
.lisp
144
20.701389
95
0.44028
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
e98a2eb4b05e7d0d2d6f792cd8caea618f2cc928e8e9066647ed678b82a106c5
22,667
[ -1 ]
22,668
destructure.lisp
persidastricl_persidastricl/src/core/destructure.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ------- ;;; -*- mode: Lisp; -*- ;;; ;;; destructure.lisp ;;; ;;; ----- (in-package #:persidastricl) (named-readtables:in-readtable persidastricl:syntax) (defun destructure (bindings) (labels ((pb (bvec b val) (labels ((nnext (x) (next (next x))) (is-persistent-vector? (b) (== (first b) 'persistent-vector)) (is-persistent-map? (b) (== (first b) 'persistent-hash-map)) ;; processing vectors and lists (pvec (bvec b val) (let ((gvec (gentemp "V__")) (gseq (gentemp "S__")) (gfirst (gentemp "FIRST__")) (has-rest? (some (lambda (s) (contains? #{'&rest} s)) b))) (labels ((pvec* (ret n bs seen-rest?) (if (seq bs) (let ((firstb (first bs))) (cond ((== firstb '&rest) (pvec* (pb ret (second bs) gseq) n (nnext bs) t)) ((== firstb :as) (pb ret (second bs) gvec)) (:otherwise (if seen-rest? (error "Unsupported binding form, only :as can follow &rest parameter") (pvec* (pb (if has-rest? (conj ret gfirst `(first ,gseq) gseq `(next ,gseq)) ret) firstb (if has-rest? gfirst `(nth ,gvec ,n))) (inc n) (next bs) seen-rest?))))) ret))) (pvec* (let ((ret (conj bvec gvec val))) (if has-rest? (conj ret gseq (list `seq gvec)) ret)) 0 b nil)))) ;; processing maps (pmap (bvec b val) (let ((gmap (gentemp "M__")) (defaults (into {} (drop 1 (get b :or))))) (labels ((pmap* (ret bes) (if (seq bes) (let* ((bb (key (first bes))) (bk (value (first bes))) (local bb) (bv (if (and defaults (get defaults local)) (list `get gmap bk (get defaults local)) (list `get gmap bk)))) (pmap* (if (symbolp bb) (conj ret local bv) (pb ret bb bv)) (next bes))) ret))) (pmap* (-> (conj bvec gmap) (conj val) ;; (conj gmap) ;; (conj `(if (sequential? ,gmap) (into (persistent-hash-map) (seq ,gmap)) ,gmap)) (lambda (ret) (let ((vas (get b :as))) (if vas (conj ret vas gmap) ret)))) (let ((transforms (reduce (lambda (tfs mk) (if (keywordp mk) (let ((mkn (string-downcase (symbol-name mk)))) (cond ((string= mkn "keys") (assoc tfs mk #'keyword)) ((string= mkn "syms") (assoc tfs mk (lambda (s) `',s))) ((string= mkn "strs") (assoc tfs mk (lambda (s) (str s)))) (:otherwise tfs))) tfs)) (keys b) :initial-value (persistent-hash-map)))) (reduce (lambda (bes entry) (let* ((init (get bes (key entry))) (init (if (is-persistent-vector? init) (into [] (drop 1 init)) init))) (reduce (lambda (m k) (assoc m k (funcall (value entry) k) )) init :initial-value (dissoc bes (key entry))))) transforms :initial-value (dissoc b :as :or)))))))) (cond ((symbolp b) (-> bvec (conj b) (conj val))) ((is-persistent-map? b) (pmap bvec (into {} (drop 1 b)) val)) ((is-persistent-vector? b) (pvec bvec (into [] (drop 1 b)) val)) ((listp b) (pvec bvec (into '() b) val)) (:otherwise (error (str "Unsupported binding form" b)))))) (process-entry (bvec b) (pb bvec (first b) (second b)))) (if (every? #'symbolp (map #'first bindings)) bindings (->list (partition (reduce #'process-entry bindings :initial-value []) 2))))) (defmacro dlet (bindings &rest body) `(let* ,(destructure bindings) ,@body))
8,849
Common Lisp
.lisp
121
26.033058
149
0.234606
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9aae4d31b91c97da60f4b20a9bd0601676514aaa0b3951a2d9faa255650ec2c1
22,668
[ -1 ]
22,669
random.lisp
persidastricl_persidastricl/src/user/random.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;; ----- ;; random.lisp ;; ;; ----- (in-package #:persidastricl) (named-readtables:in-readtable syntax) (def multiplier #x5DEECE66D) (def addend #xB) (def mask (- (ash 1 48) 1)) (defclass random-generator () ((seed :initarg :seed))) (def seed-uniquifier 8682522807148012) (defun seed-uniquifier () (let* ((current seed-uniquifier) (next (* current 181783497276652981))) (if (= current (atomics:cas seed-uniquifier current next)) next (seed-uniquifier)))) (defun initial-scramble (seed) (logand (logxor seed multiplier) mask)) (defun random-generator (&optional (seed (logxor seed-uniquifier (get-universal-time)))) (make-instance 'random-generator :seed (initial-scramble seed))) (defun next-bits (rnd bits) (let* ((seed (slot-value rnd 'seed)) (next (logand (+ (* seed multiplier) addend) mask))) (cond ((= seed (atomics:cas (slot-value rnd 'seed) seed next)) (ash next (- 0 (- 48 bits)))) (t (next-bits rnd bits))))) (defun next-int (rnd n) (assert (> n 0)) (cond ((= n (logand n (- n))) (ash (* n (next-bits rnd 31)) -31)) (t (let* ((bits (next-bits rnd 31)) (val (mod bits n))) (if (< (+ (- bits val) (1- n)) 0) (next-int rnd n) val))))) (defun rand-seq (n &optional (rg (random-generator))) (lseq (next-int rg n) (rand-seq n rg)))
1,702
Common Lisp
.lisp
50
30.26
92
0.62561
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4135dd074bd6b648f63ef0b6ada4f162e3db5a0fd75ee6477539ed85d355ebc0
22,669
[ -1 ]
22,670
user.lisp
persidastricl_persidastricl/src/user/user.lisp
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;; ----- ;; user.lisp ;; ;; ----- (in-package #:user) (named-readtables:in-readtable syntax)
423
Common Lisp
.lisp
17
23.705882
65
0.657568
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
8861e7642dccf22ebf29af4f9a39f730d9feefb192249ae437c1e09f26eb115f
22,670
[ -1 ]
22,671
persidastricl.asd
persidastricl_persidastricl/persidastricl.asd
;;; ----- ;;; ;;; Copyright (c) 2019-2023 Michael D Pendergrass, pupcus.org ;;; ;;; This program and the accompanying materials are made ;;; available under the terms of the Eclipse Public License 2.0 ;;; which is available at https://www.eclipse.org/legal/epl-2.0/ ;;; ;;; SPDX-License-Identifier: EPL-2.0 ;;; ;;; ----- ;;; ----- ;;; -*- mode: Lisp; -*- ;;; ;;; persidastricl.asd ;;; ;;; persistent data structures in common lisp ;;; ;;; ----- (asdf:defsystem #:persidastricl :description "persistent data structures in common lisp 'per-si-DAS-trick-el" :author "Michael D. Pendergrass <[email protected]>" :license "Eclipse Public License 2.0" :version "0.3.0" :depends-on (#:arrow-macros #:babel #:cl-ppcre #:cl-murmurhash #:closer-mop #:json-streams #:named-readtables #:sip-hash #:random-state #:atomics) :serial t :components ((:module "packaging" :pathname "src" :serial t :components ((:file "package"))) (:module "init" :pathname "src/init" :serial t :components ((:file "bits") (:file "hash") (:file "vector") (:file "equality") (:file "macros") (:file "functions") (:file "methods") (:file "compare") (:file "entry"))) (:module "lazy-sequences" :pathname "src/lazy" :serial t :components ((:file "thunk") (:file "lazy-sequence"))) (:module "metaclass" :pathname "src/metaclass" :serial t :components ((:file "immutable-class"))) (:module "node" :pathname "src/node" :serial t :components ((:file "node") (:file "overflow-node") (:file "hash-set-overflow-node") (:file "hash-map-overflow-node") (:file "transient-hash-set-overflow-node") (:file "persistent-hash-set-overflow-node") (:file "transient-hash-map-overflow-node") (:file "persistent-hash-map-overflow-node") (:file "hamt-node") (:file "hash-map-node") (:file "hash-set-node") (:file "transient-hash-map-node") (:file "persistent-hash-map-node") (:file "transient-hash-set-node") (:file "persistent-hash-set-node") (:file "bpvt-node") (:file "vector-node") (:file "vector-leaf-node") (:file "transient-vector-node") (:file "persistent-vector-node") (:file "transient-vector-leaf-node") (:file "persistent-vector-leaf-node"))) (:module "mixins" :pathname "src/mixins" :serial t :components ((:file "associable") (:file "collection") (:file "counted") (:file "meta") (:file "seqable"))) (:module "structures" :pathname "src/impl" :serial t :components ((:file "hamt") (:module "map" :pathname "map" :serial t :components ((:file "hash-map") (:file "transient-hash-map") (:file "persistent-hash-map"))) (:module "set" :pathname "set" :serial t :components ((:file "hash-set") (:file "transient-hash-set") (:file "persistent-hash-set"))) (:file "bpvt") (:module "vector" :pathname "vector" :serial t :components ((:file "vector") (:file "transient-vector") (:file "persistent-vector"))) (:file "functions") (:file "methods") (:file "syntax"))) (:module "iterator" :pathname "src/iterator" :serial t :components ((:file "iterator") (:file "node-iterator") (:file "hamt-iterator") (:file "methods"))) (:module "stm" :pathname "src/stm" :serial t :components ((:file "atom"))) (:module "core" :pathname "src/core" :serial t :components ((:file "methods") (:file "functions") (:file "sub-vector") (:file "destructure") (:file "when-first") (:file "string") (:file "set") (:file "walk") (:file "data") (:file "json") (:file "combinatorics"))) (:module "sample-seqs" :pathname "src/lazy" :serial t :components ((:file "sequences"))) (:module "user" :pathname "src/user" :serial t :components ((:file "user") (:file "random")))) :in-order-to ((test-op (test-op #:persidastricl/test)))) (asdf:defsystem #:persidastricl/test :depends-on (#:persidastricl #:fiveam) :components ((:module "test" :serial t :components ((:file "master") (:file "immutable-class") (:file "bits") (:file "hash") (:file "entry") (:file "vector") (:file "atom") (:file "thunk") (:file "lazy-sequence") (:file "syntax") (:file "hash-map") (:file "hash-set") (:file "equality") (:file "string") (:file "set") (:file "walk") (:file "data") (:file "combinatorics")))) :perform (test-op (o s) (uiop:symbol-call :fiveam :run! (uiop:find-symbol* :master-suite :persidastricl))))
7,717
Common Lisp
.asd
179
21.949721
103
0.363382
persidastricl/persidastricl
2
0
2
EPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
1513dcb9af8794f1e375577ab96ade94bcc23f1cc3c99302f0a1d4e33ab1de58
22,671
[ -1 ]
22,780
monotri_sequencing.lsp
KedalionDaimon_monotri/monotri_sequencing.lsp
; CHECK MONOTRI.LSP FOR COMMENTS ; Comments below are "unclean" from the working version. ; Specialty of this version: planning is "sequencing", not "structural". (defvar *slidings* 5) (defvar *stop* 'SIG-TERM) (defvar *trigger-answer-length* 60) (defvar *elements-per-area* 1000) (defvar *number-of-areas* 2000) (defvar *history-length* 60) ; (X Y Z) is the only data structure - an implied X-Y-Z=X-triangle. ; turn observation into tristructures: (defun tristruct (observation) (cond ((null observation) nil) ((null (cdr observation)) nil) ((null (cddr observation)) nil) (t (cons (list (car observation) (cadr observation) (caddr observation)) (tristruct (cdr observation)))))) ; (tristruct '(A B C D E)) --> ((A B C) (B C D) (C D E)) ; STRICT VERSION OF BELOW, BUT HERE STRICTLY SAME ATOMS: ; (defun match-to-observation (el tri-observation) ; (cond ((null tri-observation) nil) ; ((equal el (car tri-observation)) 'POSITIVE) ; ((equal (reverse el) (car tri-observation)) 'POSITIVE) ; ((equal (list (cadr el) (car el) (caddr el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (reverse (list (cadr el) (car el) (caddr el))) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (list (cadr el) (caddr el) (car el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (reverse (list (cadr el) (caddr el) (car el))) ; (car tri-observation)) ; 'NEGATIVE) ; (t (match-to-observation el (cdr tri-observation))))) ; ; (match-to-observation '(A B C) '((A B C))) --> POSITIVE ; ; (match-to-observation '(B X C) '((A B C))) --> NIL ; ; (match-to-observation '(B A C) '((A B C))) --> NEGATIVE ; RELAXED VERSION OF ABOVE, WORKING WITH VARIABLES: (defun match-to-observation (el tri-observation) (cond ((null tri-observation) nil) ; PRINCIPLE: X Y Z ; EXACT MATCH (though I could do only with variable match, actually): ; + ; X Y Z ; Z Y X ; - ; Y X Z ; Z X Y ; Y Z X ; X Z Y ((equal el (car tri-observation)) 'POSITIVE) ((equal (reverse el) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (car el) (caddr el)) (car tri-observation)) 'NEGATIVE) ((equal (reverse (list (cadr el) (car el) (caddr el))) (car tri-observation)) 'NEGATIVE) ((equal (list (cadr el) (caddr el) (car el)) (car tri-observation)) 'NEGATIVE) ((equal (reverse (list (cadr el) (caddr el) (car el))) (car tri-observation)) 'NEGATIVE) ; VARIABLE MATCH: ; - ; ? X Z ; ? Z X ; X Z ? ; Z X ? ; + ; X ? Z ; Z ? X ((equal (list (caar tri-observation) (car el) (caddr el)) (car tri-observation)) 'NEGATIVE) ((equal (list (caar tri-observation) (caddr el) (car el)) (car tri-observation)) 'NEGATIVE) ((equal (list (car el) (caddr el) (caddar tri-observation)) (car tri-observation)) 'NEGATIVE) ((equal (list (caddr el) (car el) (caddar tri-observation)) (car tri-observation)) 'NEGATIVE) ((equal (list (car el) (cadar tri-observation) (caddr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caddr el) (cadar tri-observation) (car el)) (car tri-observation)) 'POSITIVE) ; + ; X Y ? ; Y X ? ; Y Z ? ; Z Y ? ; ? X Y ; ? Y X ; ? Y Z ; ? Z Y ((equal (list (car el) (cadr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (car el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (caddr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (caddr el) (cadr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (car el) (cadr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (cadr el) (car el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (cadr el) (caddr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (caddr el) (cadr el)) (car tri-observation)) 'POSITIVE) ; OTHERWISE: (t (match-to-observation el (cdr tri-observation))))) ; hierarchisation ALSO adjusts the knowledge - ; LEGAL style, not MATHEMATICS style logic: (defun proto-match-adjust-knowledge (knowledge tri-observation seen-knowledge rejection) (cond ((null tri-observation) (append '(()) knowledge)) ((null knowledge) (append '(()) ; INITIALLY, KNOWLEDGE CANNOT CONSIST OUT OF NILs. ; NO reverse priority: ; if you had seen anything, it would be the result (reverse seen-knowledge) (reverse rejection))) (t (let ((mch (match-to-observation (car knowledge) tri-observation))) (cond ((equal 'POSITIVE mch) (append '(t) (list (car knowledge)) (reverse seen-knowledge) (cdr knowledge) (reverse rejection))) ((equal 'NEGATIVE mch) (proto-match-adjust-knowledge (cdr knowledge) tri-observation seen-knowledge (cons (car knowledge) rejection))) (t ; i.e. (null mch) (proto-match-adjust-knowledge (cdr knowledge) tri-observation (cons (car knowledge) seen-knowledge) rejection))))))) ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (C B A) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (T (C B A) (R S X) (V M S) (U N X)) ; ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (B A C) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (NIL (R S X) (V M S) (U N X) (B A C)) ; ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (K L M) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (NIL (R S X) (V M S) (K L M) (U N X)) (defun match-adjust-knowledge (knowledge observation) (let ((tristrct (tristruct observation))) (let ((proto-result (proto-match-adjust-knowledge knowledge tristrct nil nil))) (cond ((null (car proto-result)) (cond ((null tristrct) proto-result) (t ; then create a hypothesis - you could put "T", but ; consing a HYPOTHESIS makes clear this is not really T: (cons 'HYPOTHESIS (cons (car (reverse tristrct)) (cdr (reverse (cdr (reverse proto-result))))))))) (t proto-result))))) ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A B C D)) ; --> ; (T (C B A) (R S X) (V M S) (U N X)) ; ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A B V D)) ; --> ; (HYPOTHESIS (B V D) (R S X) (V M S) (C B A)) ; ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A)) ; --> ; (NIL (R S X) (V M S) (C B A) (U N X)) ; NEXT: HIERERACHISE: ; Everywhere in the input where the first data structure of the knowledge ; is found, unless the knowledge starts with NIL: ; STRICT HIERARCHISATION VERSION: ; ; (defun hierarchise (triatoms observation) ; (cond ((null triatoms) observation) ; ((null observation) observation) ; ((null (cdr observation)) observation) ; ((null (cddr observation)) observation) ; ((or (equal triatoms ; (list (car observation) ; (cadr observation) ; (caddr observation))) ; ; I tried doing the below with REVERSE triatoms, and it FAILED in SBCL, ; ; but works with Clisp. ; (equal triatoms ; (list (caddr observation) ; (cadr observation) ; (car observation)))) ; (cons (list (car observation) ; (cadr observation) ; (caddr observation)) ; (hierarchise triatoms (cdddr observation)))) ; (t (cons (car observation) ; (hierarchise triatoms (cdr observation)))))) ; ; ; (hierarchise '(A B C) '(K L A B C B A E R T C B A B C X Y)) ; ; --> ; ; (K L (A B C) B A E R T (C B A) B C X Y) ; RELAXED HIERARCHISATION VERSION: (defun hierarchise (triatoms observation) (cond ((null triatoms) observation) ((null observation) observation) ((null (cdr observation)) observation) ((null (cddr observation)) observation) ((or (equal triatoms (list (car observation) (cadr observation) (caddr observation))) ; I tried doing the below with REVERSE triatoms, and it FAILED in SBCL, ; but works with Clisp. (equal triatoms (list (caddr observation) (cadr observation) (car observation))) ; NOW COME VARIABLES: (equal triatoms (list (car observation) (cadr triatoms) (caddr observation))) (equal triatoms (list (caddr observation) (cadr triatoms) (car observation))) (equal triatoms (list (car observation) (cadr observation) (caddr triatoms))) (equal triatoms (list (cadr observation) (car observation) (caddr triatoms))) (equal triatoms (list (caddr observation) (cadr observation) (caddr triatoms))) (equal triatoms (list (cadr observation) (caddr observation) (caddr triatoms))) (equal triatoms (list (car triatoms) (cadr observation) (caddr observation))) (equal triatoms (list (car triatoms) (caddr observation) (cadr observation))) (equal triatoms (list (car triatoms) (car observation) (cadr observation))) (equal triatoms (list (car triatoms) (cadr observation) (car observation)))) (cons (list (car observation) (cadr observation) (caddr observation)) (hierarchise triatoms (cdddr observation)))) (t (cons (car observation) (hierarchise triatoms (cdr observation)))))) ; (hierarchise '(A B C) '(K L A B C B A E R T C B A B C X Y)) ; --> ; (K (L A B) (C B A) E R (T C B) (A B C) X Y) ; NEXT: HYPOTHETISE & HIERARCHISE UNTIL TOP OR UNTIL HYPOTHESIS (defun single-adjust-knowledge-and-hierarchise (joint-knowledge-observation-list) (let ((kno (car joint-knowledge-observation-list)) (obs (cadr joint-knowledge-observation-list))) (cond ; if knowledge is null or the observation is too short, do not compute: ((or (null kno) (null obs)) (cons nil joint-knowledge-observation-list)) ((or (null (cdr obs))) (cons nil joint-knowledge-observation-list)) ((or (null (cddr obs))) (cons nil joint-knowledge-observation-list)) (t (let ((adjusted-kno (match-adjust-knowledge kno obs))) (cond ((null (car adjusted-kno)) (list (car adjusted-kno) (cdr adjusted-kno) obs)) (t (list (car adjusted-kno) (cdr adjusted-kno) (hierarchise (cadr adjusted-kno) obs))))))))) ; (single-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R T C B A B C X Y))) ; --> ; (T ((A B C) (R S X) (V M S) (I T S) (M V S) (U N X) (C P M) (D O S) (W N T)) ; (K L (A B C) B A E R T (C B A) B C X Y)) ; NEXT: RESLIDE (defun multi-adjust-knowledge-and-hierarchise (joint-knowledge-observation-list) (let ((adjustment (single-adjust-knowledge-and-hierarchise joint-knowledge-observation-list))) (cond ; HERE, I COULD CATCH HYPOTHESES IF I DISLIKED THEM. ; So far, I hierarchise till the top, creating hypotheses: ((or (null (car adjustment)) ; the below alternative is in case of lack of hierarchisation: (equal (caddr adjustment) (cadr joint-knowledge-observation-list))) joint-knowledge-observation-list) (t (multi-adjust-knowledge-and-hierarchise (cdr adjustment)))))) ; [Using the "strict" version above:] ; (multi-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y))) ; --> ; (((K L ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))))) ; ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y))))))) ; (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))) ; (R D (O (S T I) (T S ((C B A) B (C X Y))))) ; (O (S T I) (T S ((C B A) B (C X Y)))) (T S ((C B A) B (C X Y))) ; ((C B A) B (C X Y)) (C X Y) (A B C)) ; ((K L ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))))))) ; The reslider ONLY adjusts the knowledge several times, ; until after the final knowledge adjustment it undertakes hierarchisation ; "for real". (defun reslider (knowledge observation slide-count) (cond ((zerop slide-count) (multi-adjust-knowledge-and-hierarchise (list knowledge observation))) (t (let ((mutation (multi-adjust-knowledge-and-hierarchise (list knowledge observation)))) (reslider (car mutation) observation (- slide-count 1)))))) ; (reslider ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y) ; 3) ; --> STRICT VERSION: ; (((K L (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))))) ; (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y)))))))))) ; (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))) ; (A E (R D (O S (T I (T S (C B (A B (C X Y)))))))) ; (R D (O S (T I (T S (C B (A B (C X Y))))))) ; (O S (T I (T S (C B (A B (C X Y)))))) (T I (T S (C B (A B (C X Y))))) ; (T S (C B (A B (C X Y)))) (C B (A B (C X Y)))) ; ((K L (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))))))) ; --> FREE VERSION: ; (((K ((L A B) (C B A) (E R (D (O S T) (I T ((S C B) (A B C) X))))) Y) ; ((C B A) (E R (D (O S T) (I T ((S C B) (A B C) X)))) Y) ; (R (D (O S T) (I T ((S C B) (A B C) X))) Y) ; ((O S T) (I T ((S C B) (A B C) X)) Y) (I T S) ((A B C) X Y) (A B C) ; (K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y) ; ((C B A) (E R (D (O S T) (((I T S) C B) (A B C) X))) Y)) ; ((K ((L A B) (C B A) (E R (D (O S T) (I T ((S C B) (A B C) X))))) Y))) ; ; ONLY ONCE WOULD BE (FREE VERSION): ; (multi-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y))) ; --> ; (((K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y) ; ((C B A) (E R (D (O S T) (((I T S) C B) (A B C) X))) Y) ; (R (D (O S T) (((I T S) C B) (A B C) X)) Y) ; ((O S T) (((I T S) C B) (A B C) X) Y) ((A B C) X Y) (A B C) (I T S) (R S X) ; (V M S)) ; ((K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y))) ; NEXT: PLAN (defun two-seek-continuation (two-atoms knowledge) (cond ((null knowledge) nil) ((equal (list (caar knowledge) (cadar knowledge)) two-atoms) (caddar knowledge)) (t (two-seek-continuation two-atoms (cdr knowledge))))) ; (two-seek-continuation '(A B) ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> C ; (two-seek-continuation '(F G) ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> NIL (defun one-seek-continuation (one-atom knowledge) (cond ((null knowledge) nil) ((equal (caar knowledge) one-atom) (cadar knowledge)) ((equal (cadar knowledge) one-atom) (caddar knowledge)) (t (one-seek-continuation one-atom (cdr knowledge))))) ; (one-seek-continuation 'A ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> B ; (one-seek-continuation 'B ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> C ; (one-seek-continuation 'K ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> NIL (defun seek-continuation (present knowledge) (cond ((null knowledge) nil) ((null present) nil) ((null (cdr present)) ; that is, only ONE atom available: (let ((one-res (one-seek-continuation (car present) knowledge))) (cond ((not (null one-res)) one-res) ((and (null one-res) (not (listp (car present)))) nil) (t ; that is, we can de-compose: (seek-continuation (car present) knowledge))))) (t ; that is, the present is longer than one atom: (let ((revpres (reverse present))) (let ((two-result (two-seek-continuation (list (cadr revpres) (car revpres)) knowledge))) (cond ((not (null two-result)) two-result) (t (seek-continuation (list (car revpres)) knowledge)))))))) ; (seek-continuation ; '(K L (A (B C D) E)) '((P Q R) (E F G) ((B C D) E H) (I J K))) ; --> H ; (seek-continuation ; '(K L (A (B C D) E)) '((P Q R) (E F G) ((B C X) E H) (I J K))) ; --> F ; (seek-continuation ; '(K L (A (B C D) N)) '((P Q R) (E F G) ((B C X) E H) (I J K))) ; --> NIL (defun flatten-list (lis) (cond ((not (listp lis)) (list lis)) ((null lis) nil) ((listp (car lis)) (flatten-list (append (car lis) (cdr lis)))) (t (cons (car lis) (flatten-list (cdr lis)))))) ; (flatten-list '((a ((b c) (e f))))) --> (a b c e f) (defun mmb (x y) (cond ((null y) nil) ((equal x (car y)) y) (t (mmb x (cdr y))))) ; IT IS MORE SENSIBLE TO TURN ON THE SEQUENCING ALTERNATIVE ; IF YOU INTEND TO WORK WITH *stop* TO SIGNIFY STRUCTURE TERMINATION: ; ; simple alternative: ; ; THUNK ; (defun follow-till-termination (present knowledge general-plan) ; (let ((plan (seek-continuation present knowledge))) ; (let ((flat-plan (flatten-list plan))) ; (let ((new-gen-plan (append general-plan flat-plan))) ; (cond ; ((mmb *stop* new-gen-plan) ; (reverse (cdr (mmb *stop* (reverse new-gen-plan))))) ; (t new-gen-plan)))))) ; sequencing alternative: ; THUNK (defun follow-till-termination (present knowledge general-plan) (let ((plan (seek-continuation present knowledge))) (let ((flat-plan (flatten-list plan))) (let ((new-gen-plan (append general-plan flat-plan))) (cond ((mmb *stop* new-gen-plan) (reverse (cdr (mmb *stop* (reverse new-gen-plan))))) ((or (null plan) (< *trigger-answer-length* (length new-gen-plan))) new-gen-plan) (t (follow-till-termination (list plan) knowledge new-gen-plan))))))) (defun generate-plan (present knowledge) (follow-till-termination present knowledge nil)) ; (generate-plan '(K L (A (B C D) E)) ; '((P Q R) (E F G) ((B C D) E ((S T (U V W)) R (G H I))) (I J K))) ; --> (S T U V W R G H I) ; simple alternative ; --> (S T U V W R G H I J K) ; sequencing alternative, follows I into (I J K) ; ---------------------------------------------------------------------------- ; THE BELOW IS ADJUSTED STRAIGHT FROM LAIAN: ; KNOWLEDGE SELECTION AND GENERATION ; Now that you have everything needed to create a plan, ; define a function to select the knowledge area which shall be ; used for the analysis of the input substrate. For this, ; simply pick the area which is most similar to the "problem" ; at hand (i.e. the relevant section of input history). ; The "candidate" will be the car of the knowledge-areas, ; and what is called below as "knowledge-areas" is the ; cdr of the knowledge-areas. (defun set-intersection (set1 set2) (cond ((null set1) nil) ((and (not (mmb (car set1) (cdr set1))) (mmb (car set1) set2)) (cons (car set1) (set-intersection (cdr set1) set2))) (t (set-intersection (cdr set1) set2)))) ; (set-intersection '(A B C D E) '(X Y C D Z)) --> (C D) ; select knowledge area to use: (defun select-knowledge-area (problem candidate knowledge-areas) (cond ; car of candidate is the history, cadr of candidate - the knowledge ((null knowledge-areas) (cadr candidate)) ((< (length (set-intersection (car candidate) problem)) (length (set-intersection (caar knowledge-areas) problem))) (select-knowledge-area problem (car knowledge-areas) (cdr knowledge-areas))) (t (select-knowledge-area problem candidate (cdr knowledge-areas))))) ; (select-knowledge-area ; '(A B C D E) ; '((A B X Y Z) (KNOWLEDGE 1)) ; '(((B X Y Z Q) (KNOWLEDGE 2)) ; ((A B C Y Z) (KNOWLEDGE 3)) ; ((A B X C Z) (KNOWLEDGE 4)))) ; --> ; (KNOWLEDGE 3) ; Knowledge generation: ; Normally, you will load knowledge from a file. ; But if no file exists yet, knowledge may be generated: (defun gen-knowledge-area (cntr) (cond ((zerop cntr) nil) (t (cons (list nil nil nil) (gen-knowledge-area (- cntr 1)))))) (defun gen-multiple-knowledge-areas (cntr) (cond ((zerop cntr) nil) (t (cons (list nil (gen-knowledge-area *elements-per-area*)) (gen-multiple-knowledge-areas (- cntr 1)))))) (defun gen-knowledge () (gen-multiple-knowledge-areas *number-of-areas*)) (defun load-knowledge () (cond ((null (probe-file "monotri.txt")) (gen-knowledge)) (t (with-open-file (stream "./monotri.txt") (read stream))))) ; LOAD the knowledge: (defvar *knowledge-areas* (load-knowledge)) ; SAVE the knowledge: (defun save-knowledge () (with-open-file (stream "./monotri.txt" :direction :output :if-exists :supersede) (format stream (write-to-string *knowledge-areas*)))) ; You cannot use print or princ here. ; sample call: ; (save-knowledge) ; -------------------------------------------------------- ; EXECUTION PHASE: ; READ / HISTORISE ; HIERARCHISE ; ANALYSE NOTIONS ; PLAN / OUTPUT ; (defun eexxiitt () '()) (defun eexxiitt () (progn (terpri) (save-knowledge) (quit))) ; a few functions to take whole sections of lists, always counting from 1: (defun proto-takefirst (fromwhere howmany resultlist) (if (or (null fromwhere) (zerop howmany)) (reverse resultlist) (proto-takefirst (cdr fromwhere) (- howmany 1) (cons (car fromwhere) resultlist)))) ; take the front part of a list: (defun takefirst (fromwhere howmany) (proto-takefirst fromwhere howmany '())) ; take the final part of a list: (defun takelast (fromwhere howmany) (reverse (takefirst (reverse fromwhere) howmany))) ; setup instincts (defun word-instinct (word) (cond ((equal word 'I) 'YOU) ((equal word 'ME) 'YOU) ((equal word 'YOU) 'ME) ((equal word 'AM) 'ARE) ((equal word 'ARE) 'AM-ARE) ((equal word 'MINE) 'YOURS) ((equal word 'YOURS) 'MINE) ((equal word 'MY) 'YOUR) ((equal word 'YOUR) 'MY) ((equal word 'MYSELF) 'YOURSELF) ((equal word 'YOURSELF) 'MYSELF) ((equal word 'WAS) 'WAS-WERE) (T word))) (defun proto-apply-instincts (sentence checked-sentence) (cond ((null sentence) (reverse checked-sentence)) (T (proto-apply-instincts (cdr sentence) (cons (word-instinct (car sentence)) checked-sentence))))) (defun apply-instincts (sentence) (proto-apply-instincts sentence '())) ; sample call: (apply-instincts '(I WAS HERE TODAY)) ; --> (YOU WAS-WERE HERE TODAY) ; Even when you have a plan, talk only until as long as ; the interaction should not be terminated. The rest of ; the plan is NOT executed. ; THUNK using SIG-TERM: (defun until-terminator (lis) (cond ((null lis) nil) ((equal *stop* (car lis)) nil) (t (cons (car lis) (until-terminator (cdr lis)))))) ; (until-terminator '(A B C D SIG-TERM E F G H)) --> (A B C D) (defvar *knowledge* nil) (defvar *human* nil) (defvar *history* nil) (defvar *machine* nil) (defvar *hierarchy* nil) (defvar *hierarchy-and-knowledge* nil) (defvar *plan* nil) ; VARIANTS FOR USING *stop* AS WELL AS NOT USING IT ARE IMPLEMENTED ; - THE DEFAULT HERE IS NOT USING IT. (defun run () (progn (finish-output nil) (print '(HUMAN------)) (finish-output nil) (terpri) (finish-output nil) (setq *human* (read)) (finish-output nil) (cond ((null *human*) (eexxiitt)) (t ; WITH *stop*: (setq *history* (takelast (append *history* *human*) *history-length*)) ; WITHOUT *stop*: ; (setq *history* (takelast (append *history* *human*) ; *history-length*)) (setq *knowledge* (select-knowledge-area *history* (car *knowledge-areas*) (cdr *knowledge-areas*))) (setq *hierarchy-and-knowledge* (reslider *knowledge* *history* *slidings*)) (setq *knowledge* (car *hierarchy-and-knowledge*)) (setq *hierarchy* (cadr *hierarchy-and-knowledge*)) (setq *plan* (until-terminator (generate-plan *hierarchy* *knowledge*))) (setq *machine* (apply-instincts (takelast *plan* *trigger-answer-length*))) ; WITH *stop*: (cond ((null *machine*) (setq *history* *history*)) ; i.e. do nothing (t (setq *history* (takelast (append *history* (list *stop*) *machine* (list *stop*)) *history-length*)))) ; WITHOUT *stop*: ; (cond ((null *machine*) (setq *history* *history*)) ; i.e. do nothing ; (t (setq *history* (takelast (append *history* *machine*) ; *history-length*)))) (setq *knowledge-areas* (cons (list *history* *knowledge*) (reverse (cdr (reverse *knowledge-areas*))))) (finish-output nil) (print '(MACHINE----)) (finish-output nil) (print *machine*) (finish-output nil) (terpri) (finish-output nil) (run))))) (progn (print '(LOGICAL TRIANGULATION SYSTEM)) (print '(BASED ON IMPLICIT TRIANGULATION)) (print '(USING ONLY TRIANGLES AS DATA STRUCTURE)) (print '(ENTER NIL TO TERMINATE)) (print '(ENTER LIST OF SYMBOLS TO COMMUNICATE)) (terpri) (finish-output nil) (run) )
27,599
Common Lisp
.l
693
32.962482
100
0.546479
KedalionDaimon/monotri
2
1
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9c578c57b079ad5cd49805b6cfb50616eeaf249c4013b263cc2d30c3a43c32a2
22,780
[ -1 ]
22,781
monotri_positive.lsp
KedalionDaimon_monotri/monotri_positive.lsp
; CHECK MONOTRI.LSP FOR COMMENTS ; Comments below are "unclean" from the working version. ; Specialty of this version: Minimizes bistructure "punishment" ; by a NEGATIVE evaluation, keeps up POSITIVE judgement for ; evolutionary "winning" insect. (defvar *slidings* 5) (defvar *stop* 'SIG-TERM) (defvar *trigger-answer-length* 60) (defvar *elements-per-area* 1000) (defvar *number-of-areas* 2000) (defvar *history-length* 60) ; (X Y Z) is the only data structure - an implied X-Y-Z=X-triangle. ; turn observation into tristructures: (defun tristruct (observation) (cond ((null observation) nil) ((null (cdr observation)) nil) ((null (cddr observation)) nil) (t (cons (list (car observation) (cadr observation) (caddr observation)) (tristruct (cdr observation)))))) ; (tristruct '(A B C D E)) --> ((A B C) (B C D) (C D E)) ; STRICT VERSION OF BELOW, BUT HERE STRICTLY SAME ATOMS: ; (defun match-to-observation (el tri-observation) ; (cond ((null tri-observation) nil) ; ((equal el (car tri-observation)) 'POSITIVE) ; ((equal (reverse el) (car tri-observation)) 'POSITIVE) ; ((equal (list (cadr el) (car el) (caddr el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (reverse (list (cadr el) (car el) (caddr el))) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (list (cadr el) (caddr el) (car el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (reverse (list (cadr el) (caddr el) (car el))) ; (car tri-observation)) ; 'NEGATIVE) ; (t (match-to-observation el (cdr tri-observation))))) ; ; (match-to-observation '(A B C) '((A B C))) --> POSITIVE ; ; (match-to-observation '(B X C) '((A B C))) --> NIL ; ; (match-to-observation '(B A C) '((A B C))) --> NEGATIVE ; RELAXED VERSION OF ABOVE, WORKING WITH VARIABLES: (defun match-to-observation (el tri-observation) (cond ((null tri-observation) nil) ; PRINCIPLE: X Y Z ; EXACT MATCH (though I could do only with variable match, actually): ; + ; X Y Z ; Z Y X ; - ; Y X Z ; Z X Y ; Y Z X ; X Z Y ((equal el (car tri-observation)) 'POSITIVE) ((equal (reverse el) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (car el) (caddr el)) (car tri-observation)) 'NEGATIVE) ((equal (reverse (list (cadr el) (car el) (caddr el))) (car tri-observation)) 'NEGATIVE) ((equal (list (cadr el) (caddr el) (car el)) (car tri-observation)) 'NEGATIVE) ((equal (reverse (list (cadr el) (caddr el) (car el))) (car tri-observation)) 'NEGATIVE) ; VARIABLE MATCH: ; - ; ? X Z ; ? Z X ; X Z ? ; Z X ? ; + ; X ? Z ; Z ? X ; ((equal (list (caar tri-observation) (car el) (caddr el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (list (caar tri-observation) (caddr el) (car el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (list (car el) (caddr el) (caddar tri-observation)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (list (caddr el) (car el) (caddar tri-observation)) ; (car tri-observation)) ; 'NEGATIVE) ((equal (list (car el) (cadar tri-observation) (caddr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caddr el) (cadar tri-observation) (car el)) (car tri-observation)) 'POSITIVE) ; + ; X Y ? ; Y X ? ; Y Z ? ; Z Y ? ; ? X Y ; ? Y X ; ? Y Z ; ? Z Y ((equal (list (car el) (cadr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (car el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (caddr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (caddr el) (cadr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (car el) (cadr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (cadr el) (car el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (cadr el) (caddr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (caddr el) (cadr el)) (car tri-observation)) 'POSITIVE) ; OTHERWISE: (t (match-to-observation el (cdr tri-observation))))) ; hierarchisation ALSO adjusts the knowledge - ; LEGAL style, not MATHEMATICS style logic: (defun proto-match-adjust-knowledge (knowledge tri-observation seen-knowledge rejection) (cond ((null tri-observation) (append '(()) knowledge)) ((null knowledge) (append '(()) ; INITIALLY, KNOWLEDGE CANNOT CONSIST OUT OF NILs. ; NO reverse priority: ; if you had seen anything, it would be the result (reverse seen-knowledge) (reverse rejection))) (t (let ((mch (match-to-observation (car knowledge) tri-observation))) (cond ((equal 'POSITIVE mch) (append '(t) (list (car knowledge)) (reverse seen-knowledge) (cdr knowledge) (reverse rejection))) ((equal 'NEGATIVE mch) (proto-match-adjust-knowledge (cdr knowledge) tri-observation seen-knowledge (cons (car knowledge) rejection))) (t ; i.e. (null mch) (proto-match-adjust-knowledge (cdr knowledge) tri-observation (cons (car knowledge) seen-knowledge) rejection))))))) ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (C B A) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (T (C B A) (R S X) (V M S) (U N X)) ; ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (B A C) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (NIL (R S X) (V M S) (U N X) (B A C)) ; ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (K L M) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (NIL (R S X) (V M S) (K L M) (U N X)) (defun match-adjust-knowledge (knowledge observation) (let ((tristrct (tristruct observation))) (let ((proto-result (proto-match-adjust-knowledge knowledge tristrct nil nil))) (cond ((null (car proto-result)) (cond ((null tristrct) proto-result) (t ; then create a hypothesis - you could put "T", but ; consing a HYPOTHESIS makes clear this is not really T: (cons 'HYPOTHESIS (cons (car (reverse tristrct)) (cdr (reverse (cdr (reverse proto-result))))))))) (t proto-result))))) ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A B C D)) ; --> ; (T (C B A) (R S X) (V M S) (U N X)) ; ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A B V D)) ; --> ; (HYPOTHESIS (B V D) (R S X) (V M S) (C B A)) ; ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A)) ; --> ; (NIL (R S X) (V M S) (C B A) (U N X)) ; NEXT: HIERERACHISE: ; Everywhere in the input where the first data structure of the knowledge ; is found, unless the knowledge starts with NIL: ; STRICT HIERARCHISATION VERSION: ; ; (defun hierarchise (triatoms observation) ; (cond ((null triatoms) observation) ; ((null observation) observation) ; ((null (cdr observation)) observation) ; ((null (cddr observation)) observation) ; ((or (equal triatoms ; (list (car observation) ; (cadr observation) ; (caddr observation))) ; ; I tried doing the below with REVERSE triatoms, and it FAILED in SBCL, ; ; but works with Clisp. ; (equal triatoms ; (list (caddr observation) ; (cadr observation) ; (car observation)))) ; (cons (list (car observation) ; (cadr observation) ; (caddr observation)) ; (hierarchise triatoms (cdddr observation)))) ; (t (cons (car observation) ; (hierarchise triatoms (cdr observation)))))) ; ; ; (hierarchise '(A B C) '(K L A B C B A E R T C B A B C X Y)) ; ; --> ; ; (K L (A B C) B A E R T (C B A) B C X Y) ; RELAXED HIERARCHISATION VERSION: (defun hierarchise (triatoms observation) (cond ((null triatoms) observation) ((null observation) observation) ((null (cdr observation)) observation) ((null (cddr observation)) observation) ((or (equal triatoms (list (car observation) (cadr observation) (caddr observation))) ; I tried doing the below with REVERSE triatoms, and it FAILED in SBCL, ; but works with Clisp. (equal triatoms (list (caddr observation) (cadr observation) (car observation))) ; NOW COME VARIABLES: (equal triatoms (list (car observation) (cadr triatoms) (caddr observation))) (equal triatoms (list (caddr observation) (cadr triatoms) (car observation))) (equal triatoms (list (car observation) (cadr observation) (caddr triatoms))) (equal triatoms (list (cadr observation) (car observation) (caddr triatoms))) (equal triatoms (list (caddr observation) (cadr observation) (caddr triatoms))) (equal triatoms (list (cadr observation) (caddr observation) (caddr triatoms))) (equal triatoms (list (car triatoms) (cadr observation) (caddr observation))) (equal triatoms (list (car triatoms) (caddr observation) (cadr observation))) (equal triatoms (list (car triatoms) (car observation) (cadr observation))) (equal triatoms (list (car triatoms) (cadr observation) (car observation)))) (cons (list (car observation) (cadr observation) (caddr observation)) (hierarchise triatoms (cdddr observation)))) (t (cons (car observation) (hierarchise triatoms (cdr observation)))))) ; (hierarchise '(A B C) '(K L A B C B A E R T C B A B C X Y)) ; --> ; (K (L A B) (C B A) E R (T C B) (A B C) X Y) ; NEXT: HYPOTHETISE & HIERARCHISE UNTIL TOP OR UNTIL HYPOTHESIS (defun single-adjust-knowledge-and-hierarchise (joint-knowledge-observation-list) (let ((kno (car joint-knowledge-observation-list)) (obs (cadr joint-knowledge-observation-list))) (cond ; if knowledge is null or the observation is too short, do not compute: ((or (null kno) (null obs)) (cons nil joint-knowledge-observation-list)) ((or (null (cdr obs))) (cons nil joint-knowledge-observation-list)) ((or (null (cddr obs))) (cons nil joint-knowledge-observation-list)) (t (let ((adjusted-kno (match-adjust-knowledge kno obs))) (cond ((null (car adjusted-kno)) (list (car adjusted-kno) (cdr adjusted-kno) obs)) (t (list (car adjusted-kno) (cdr adjusted-kno) (hierarchise (cadr adjusted-kno) obs))))))))) ; (single-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R T C B A B C X Y))) ; --> ; (T ((A B C) (R S X) (V M S) (I T S) (M V S) (U N X) (C P M) (D O S) (W N T)) ; (K L (A B C) B A E R T (C B A) B C X Y)) ; NEXT: RESLIDE (defun multi-adjust-knowledge-and-hierarchise (joint-knowledge-observation-list) (let ((adjustment (single-adjust-knowledge-and-hierarchise joint-knowledge-observation-list))) (cond ; HERE, I COULD CATCH HYPOTHESES IF I DISLIKED THEM. ; So far, I hierarchise till the top, creating hypotheses: ((or (null (car adjustment)) ; the below alternative is in case of lack of hierarchisation: (equal (caddr adjustment) (cadr joint-knowledge-observation-list))) joint-knowledge-observation-list) (t (multi-adjust-knowledge-and-hierarchise (cdr adjustment)))))) ; [Using the "strict" version above:] ; (multi-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y))) ; --> ; (((K L ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))))) ; ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y))))))) ; (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))) ; (R D (O (S T I) (T S ((C B A) B (C X Y))))) ; (O (S T I) (T S ((C B A) B (C X Y)))) (T S ((C B A) B (C X Y))) ; ((C B A) B (C X Y)) (C X Y) (A B C)) ; ((K L ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))))))) ; The reslider ONLY adjusts the knowledge several times, ; until after the final knowledge adjustment it undertakes hierarchisation ; "for real". (defun reslider (knowledge observation slide-count) (cond ((zerop slide-count) (multi-adjust-knowledge-and-hierarchise (list knowledge observation))) (t (let ((mutation (multi-adjust-knowledge-and-hierarchise (list knowledge observation)))) (reslider (car mutation) observation (- slide-count 1)))))) ; (reslider ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y) ; 3) ; --> STRICT VERSION: ; (((K L (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))))) ; (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y)))))))))) ; (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))) ; (A E (R D (O S (T I (T S (C B (A B (C X Y)))))))) ; (R D (O S (T I (T S (C B (A B (C X Y))))))) ; (O S (T I (T S (C B (A B (C X Y)))))) (T I (T S (C B (A B (C X Y))))) ; (T S (C B (A B (C X Y)))) (C B (A B (C X Y)))) ; ((K L (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))))))) ; --> FREE VERSION: ; (((K ((L A B) (C B A) (E R (D (O S T) (I T ((S C B) (A B C) X))))) Y) ; ((C B A) (E R (D (O S T) (I T ((S C B) (A B C) X)))) Y) ; (R (D (O S T) (I T ((S C B) (A B C) X))) Y) ; ((O S T) (I T ((S C B) (A B C) X)) Y) (I T S) ((A B C) X Y) (A B C) ; (K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y) ; ((C B A) (E R (D (O S T) (((I T S) C B) (A B C) X))) Y)) ; ((K ((L A B) (C B A) (E R (D (O S T) (I T ((S C B) (A B C) X))))) Y))) ; ; ONLY ONCE WOULD BE (FREE VERSION): ; (multi-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y))) ; --> ; (((K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y) ; ((C B A) (E R (D (O S T) (((I T S) C B) (A B C) X))) Y) ; (R (D (O S T) (((I T S) C B) (A B C) X)) Y) ; ((O S T) (((I T S) C B) (A B C) X) Y) ((A B C) X Y) (A B C) (I T S) (R S X) ; (V M S)) ; ((K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y))) ; NEXT: PLAN (defun two-seek-continuation (two-atoms knowledge) (cond ((null knowledge) nil) ((equal (list (caar knowledge) (cadar knowledge)) two-atoms) (caddar knowledge)) (t (two-seek-continuation two-atoms (cdr knowledge))))) ; (two-seek-continuation '(A B) ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> C ; (two-seek-continuation '(F G) ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> NIL (defun one-seek-continuation (one-atom knowledge) (cond ((null knowledge) nil) ((equal (caar knowledge) one-atom) (cadar knowledge)) ((equal (cadar knowledge) one-atom) (caddar knowledge)) (t (one-seek-continuation one-atom (cdr knowledge))))) ; (one-seek-continuation 'A ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> B ; (one-seek-continuation 'B ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> C ; (one-seek-continuation 'K ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> NIL (defun seek-continuation (present knowledge) (cond ((null knowledge) nil) ((null present) nil) ((null (cdr present)) ; that is, only ONE atom available: (let ((one-res (one-seek-continuation (car present) knowledge))) (cond ((not (null one-res)) one-res) ((and (null one-res) (not (listp (car present)))) nil) (t ; that is, we can de-compose: (seek-continuation (car present) knowledge))))) (t ; that is, the present is longer than one atom: (let ((revpres (reverse present))) (let ((two-result (two-seek-continuation (list (cadr revpres) (car revpres)) knowledge))) (cond ((not (null two-result)) two-result) (t (seek-continuation (list (car revpres)) knowledge)))))))) ; (seek-continuation ; '(K L (A (B C D) E)) '((P Q R) (E F G) ((B C D) E H) (I J K))) ; --> H ; (seek-continuation ; '(K L (A (B C D) E)) '((P Q R) (E F G) ((B C X) E H) (I J K))) ; --> F ; (seek-continuation ; '(K L (A (B C D) N)) '((P Q R) (E F G) ((B C X) E H) (I J K))) ; --> NIL (defun flatten-list (lis) (cond ((not (listp lis)) (list lis)) ((null lis) nil) ((listp (car lis)) (flatten-list (append (car lis) (cdr lis)))) (t (cons (car lis) (flatten-list (cdr lis)))))) ; (flatten-list '((a ((b c) (e f))))) --> (a b c e f) (defun mmb (x y) (cond ((null y) nil) ((equal x (car y)) y) (t (mmb x (cdr y))))) ; IT IS MORE SENSIBLE TO TURN ON THE SEQUENCING ALTERNATIVE ; IF YOU INTEND TO WORK WITH *stop* TO SIGNIFY STRUCTURE TERMINATION: ; ; simple alternative: ; ; THUNK (defun follow-till-termination (present knowledge general-plan) (let ((plan (seek-continuation present knowledge))) (let ((flat-plan (flatten-list plan))) (let ((new-gen-plan (append general-plan flat-plan))) (cond ((mmb *stop* new-gen-plan) (reverse (cdr (mmb *stop* (reverse new-gen-plan))))) (t new-gen-plan)))))) ; sequencing alternative: ; THUNK ; (defun follow-till-termination (present knowledge general-plan) ; (let ((plan (seek-continuation present knowledge))) ; (let ((flat-plan (flatten-list plan))) ; (let ((new-gen-plan (append general-plan flat-plan))) ; (cond ; ((mmb *stop* new-gen-plan) ; (reverse (cdr (mmb *stop* (reverse new-gen-plan))))) ; ((or (null plan) ; (< *trigger-answer-length* (length new-gen-plan))) ; new-gen-plan) ; (t ; (follow-till-termination (list plan) knowledge new-gen-plan))))))) (defun generate-plan (present knowledge) (follow-till-termination present knowledge nil)) ; (generate-plan '(K L (A (B C D) E)) ; '((P Q R) (E F G) ((B C D) E ((S T (U V W)) R (G H I))) (I J K))) ; --> (S T U V W R G H I) ; simple alternative ; --> (S T U V W R G H I J K) ; sequencing alternative, follows I into (I J K) ; ---------------------------------------------------------------------------- ; THE BELOW IS ADJUSTED STRAIGHT FROM LAIAN: ; KNOWLEDGE SELECTION AND GENERATION ; Now that you have everything needed to create a plan, ; define a function to select the knowledge area which shall be ; used for the analysis of the input substrate. For this, ; simply pick the area which is most similar to the "problem" ; at hand (i.e. the relevant section of input history). ; The "candidate" will be the car of the knowledge-areas, ; and what is called below as "knowledge-areas" is the ; cdr of the knowledge-areas. (defun set-intersection (set1 set2) (cond ((null set1) nil) ((and (not (mmb (car set1) (cdr set1))) (mmb (car set1) set2)) (cons (car set1) (set-intersection (cdr set1) set2))) (t (set-intersection (cdr set1) set2)))) ; (set-intersection '(A B C D E) '(X Y C D Z)) --> (C D) ; select knowledge area to use: (defun select-knowledge-area (problem candidate knowledge-areas) (cond ; car of candidate is the history, cadr of candidate - the knowledge ((null knowledge-areas) (cadr candidate)) ((< (length (set-intersection (car candidate) problem)) (length (set-intersection (caar knowledge-areas) problem))) (select-knowledge-area problem (car knowledge-areas) (cdr knowledge-areas))) (t (select-knowledge-area problem candidate (cdr knowledge-areas))))) ; (select-knowledge-area ; '(A B C D E) ; '((A B X Y Z) (KNOWLEDGE 1)) ; '(((B X Y Z Q) (KNOWLEDGE 2)) ; ((A B C Y Z) (KNOWLEDGE 3)) ; ((A B X C Z) (KNOWLEDGE 4)))) ; --> ; (KNOWLEDGE 3) ; Knowledge generation: ; Normally, you will load knowledge from a file. ; But if no file exists yet, knowledge may be generated: (defun gen-knowledge-area (cntr) (cond ((zerop cntr) nil) (t (cons (list nil nil nil) (gen-knowledge-area (- cntr 1)))))) (defun gen-multiple-knowledge-areas (cntr) (cond ((zerop cntr) nil) (t (cons (list nil (gen-knowledge-area *elements-per-area*)) (gen-multiple-knowledge-areas (- cntr 1)))))) (defun gen-knowledge () (gen-multiple-knowledge-areas *number-of-areas*)) (defun load-knowledge () (cond ((null (probe-file "monotri.txt")) (gen-knowledge)) (t (with-open-file (stream "./monotri.txt") (read stream))))) ; LOAD the knowledge: (defvar *knowledge-areas* (load-knowledge)) ; SAVE the knowledge: (defun save-knowledge () (with-open-file (stream "./monotri.txt" :direction :output :if-exists :supersede) (format stream (write-to-string *knowledge-areas*)))) ; You cannot use print or princ here. ; sample call: ; (save-knowledge) ; -------------------------------------------------------- ; EXECUTION PHASE: ; READ / HISTORISE ; HIERARCHISE ; ANALYSE NOTIONS ; PLAN / OUTPUT ; (defun eexxiitt () '()) (defun eexxiitt () (progn (terpri) (save-knowledge) (quit))) ; a few functions to take whole sections of lists, always counting from 1: (defun proto-takefirst (fromwhere howmany resultlist) (if (or (null fromwhere) (zerop howmany)) (reverse resultlist) (proto-takefirst (cdr fromwhere) (- howmany 1) (cons (car fromwhere) resultlist)))) ; take the front part of a list: (defun takefirst (fromwhere howmany) (proto-takefirst fromwhere howmany '())) ; take the final part of a list: (defun takelast (fromwhere howmany) (reverse (takefirst (reverse fromwhere) howmany))) ; setup instincts (defun word-instinct (word) (cond ((equal word 'I) 'YOU) ((equal word 'ME) 'YOU) ((equal word 'YOU) 'ME) ((equal word 'AM) 'ARE) ((equal word 'ARE) 'AM-ARE) ((equal word 'MINE) 'YOURS) ((equal word 'YOURS) 'MINE) ((equal word 'MY) 'YOUR) ((equal word 'YOUR) 'MY) ((equal word 'MYSELF) 'YOURSELF) ((equal word 'YOURSELF) 'MYSELF) ((equal word 'WAS) 'WAS-WERE) (T word))) (defun proto-apply-instincts (sentence checked-sentence) (cond ((null sentence) (reverse checked-sentence)) (T (proto-apply-instincts (cdr sentence) (cons (word-instinct (car sentence)) checked-sentence))))) (defun apply-instincts (sentence) (proto-apply-instincts sentence '())) ; sample call: (apply-instincts '(I WAS HERE TODAY)) ; --> (YOU WAS-WERE HERE TODAY) ; Even when you have a plan, talk only until as long as ; the interaction should not be terminated. The rest of ; the plan is NOT executed. ; THUNK using SIG-TERM: (defun until-terminator (lis) (cond ((null lis) nil) ((equal *stop* (car lis)) nil) (t (cons (car lis) (until-terminator (cdr lis)))))) ; (until-terminator '(A B C D SIG-TERM E F G H)) --> (A B C D) (defvar *knowledge* nil) (defvar *human* nil) (defvar *history* nil) (defvar *machine* nil) (defvar *hierarchy* nil) (defvar *hierarchy-and-knowledge* nil) (defvar *plan* nil) ; VARIANTS FOR USING *stop* AS WELL AS NOT USING IT ARE IMPLEMENTED ; - THE DEFAULT HERE IS NOT USING IT. (defun run () (progn (finish-output nil) (print '(HUMAN------)) (finish-output nil) (terpri) (finish-output nil) (setq *human* (read)) (finish-output nil) (cond ((null *human*) (eexxiitt)) (t ; WITH *stop*: ; (setq *history* (takelast (append *history* *human* (list *stop*)) ; *history-length*)) ; WITHOUT *stop*: (setq *history* (takelast (append *history* *human*) *history-length*)) (setq *knowledge* (select-knowledge-area *history* (car *knowledge-areas*) (cdr *knowledge-areas*))) (setq *hierarchy-and-knowledge* (reslider *knowledge* *history* *slidings*)) (setq *knowledge* (car *hierarchy-and-knowledge*)) (setq *hierarchy* (cadr *hierarchy-and-knowledge*)) (setq *plan* (until-terminator (generate-plan *hierarchy* *knowledge*))) (setq *machine* (apply-instincts (takelast *plan* *trigger-answer-length*))) ; WITH *stop*: ; (cond ((null *machine*) (setq *history* *history*)) ; i.e. do nothing ; (t (setq *history* (takelast (append *history* *machine* (list *stop*)) ; *history-length*)))) ; WITHOUT *stop*: (cond ((null *machine*) (setq *history* *history*)) ; i.e. do nothing (t (setq *history* (takelast (append *history* *machine*) *history-length*)))) (setq *knowledge-areas* (cons (list *history* *knowledge*) (reverse (cdr (reverse *knowledge-areas*))))) (finish-output nil) (print '(MACHINE----)) (finish-output nil) (print *machine*) (finish-output nil) (terpri) (finish-output nil) (run))))) (progn (print '(LOGICAL TRIANGULATION SYSTEM)) (print '(BASED ON IMPLICIT TRIANGULATION)) (print '(USING ONLY TRIANGLES AS DATA STRUCTURE)) (print '(ENTER NIL TO TERMINATE)) (print '(ENTER LIST OF SYMBOLS TO COMMUNICATE)) (terpri) (finish-output nil) (run) )
27,715
Common Lisp
.l
695
33.260432
100
0.546765
KedalionDaimon/monotri
2
1
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
698d0206e72f3514adc9f3518c83e1320f77b5c1a78cfbb7f3fd959b3fb5633f
22,781
[ -1 ]
22,782
monotri.lsp
KedalionDaimon_monotri/monotri.lsp
; MONOTRI ; INTRODUCTION AND EXPLANATION ; This is an artificial intelligence operating on lists of symbols. ; It employs Logical Triangulation. The point of this experiment ; is to demonstrate an intelligent entity with ONLY triangles as a ; data structure. As opposed to earlier experiments, here, individual ; relations between pairs of atoms are not considered: instead, everything ; is handled by means of logical triangles, including the structuring of ; input. ; Everything consists thereby out of symbols. Sequences of three symbols, ; e.g. "A B C", are taken to symbolise a positive logical triangle of ; type vic-vic-ana, namely + A-B-C=A. If such a "triangle" is recognised ; in the input, it is "hierarchised" (i.e. it is replaced by another ; "symbol" within the input, say "X", in the input). So an input sequence as ; "K L A B C M N" would become "K L X M N". Then, the next hierarchisation ; is attempted, and so forth recursively, until finally only one or two ; symbols remain. - In the actual implementation, as the name of the "higher" ; symbol is unimportant, it is just expressed as a sub-list, i.e. actually, ; the hierarchisation is expressed as "K L (A B C) M N". ; (In the below program, the word "atom" does NOT signify a "Lisp atom", but ; such an "atom of knowledge", i.e. A, B, and C are ATOMS, and X (or (A B C)) ; is an ATOM as well.) ; Observations may be congruent with a knowledge element - thus giving it ; priority, or incongruent - thus decreasing its priority, or neutral - ; leaving the knowledge element unchanged. "C B A" is congruent to "A B C", ; as both express the same logical triangle, namely + A-B-C=A; but "A C B" ; would be incongruent, expressing + A-C-B=A and contradicting thereby the ; relations of "A B C"; whereas "X Y Z", expressing + X-Y-Z=X, is entirely ; without relation to A B C and therefore considered neutral. ; The reply given to the user is the "continuation" of the present into the ; future according to experience. ; Knowledge is treated as an internal "swarm" of knowledge bases; in each ; exchange with the human a suitable "insect" for the situation is selected ; to handle the challenge. - To ensure in this some "situational awareness", ; the system also has some history of the most recently handled symbols. ; Most knowledge bases (or "insects") overlap in the "history", so the ; exchange appears to the user as an exchange with one single central ; intelligent entity. ; ---------------------------------------------------------------------------- ; NEXT: VARIABLES. ; Count of re-considerations of the input - the higher the count, ; the smarter the system - and the slower its operation. (defvar *slidings* 5) ; Which signal shows termination of a sequence of symbols. (defvar *stop* 'SIG-TERM) ; What is the maximum count of symbols in an answer. (defvar *trigger-answer-length* 60) ; How many chains of three symbols each can be known per knowledge area. (defvar *elements-per-area* 1000) ; How many insects are there. (defvar *number-of-areas* 2000) ; What is the length of the situational history... should be ; greater or equal to *trigger-answer-length*. (defvar *history-length* 60) ; ---------------------------------------------------------------------------- ; NEXT: STRUCTURING OF KNOWLEDGE AND INPUT. ; (X Y Z) is the only data, a tristructure - an implied X-Y-Z=X-triangle. ; Turn observation into tristructures - these are possibilities ; of input structuring, and in the end, one such possibility will ; be selected for the given hierarchisation step. (defun tristruct (observation) (cond ((null observation) nil) ((null (cdr observation)) nil) ((null (cddr observation)) nil) (t (cons (list (car observation) (cadr observation) (caddr observation)) (tristruct (cdr observation)))))) ; (tristruct '(A B C D E)) --> ((A B C) (B C D) (C D E)) ; Now, given a knowledge element and the list of tristructures, ; decide whether the "perceived reality" is either SUPPORTING the ; known element, i.e. being POSITIVE to it, or CONTRADICTING it, ; i.e. being NEGATIVE to it, or whether reality is NEUTRAL regarding ; the present knowledge element at hand. The knowledge element is the ; first argument, the observed reality - the list of tristructures ; in the second argument. The decision whether the reaction is ; POSITIVE, NEGATIVE or NEUTRAL will influence whether the knowledge ; element will receive priority, be de-prioritised, or just left where ; it currently is within the knowledge base of the presently used insect. ; STRICT VERSION OF BELOW, BUT HERE STRICTLY "SAME" ATOMS, i.e. ; A B C may only be measured against tristructures consisting out of ; exactly A, B and C. This provides the greatest "certainty" of the ; conclusions, but the conclusions are more narrow, too, as you must ; hope to actually "catch" exactly these three symbols. ; (defun match-to-observation (el tri-observation) ; (cond ((null tri-observation) nil) ; ((equal el (car tri-observation)) 'POSITIVE) ; ((equal (reverse el) (car tri-observation)) 'POSITIVE) ; ((equal (list (cadr el) (car el) (caddr el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (reverse (list (cadr el) (car el) (caddr el))) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (list (cadr el) (caddr el) (car el)) ; (car tri-observation)) ; 'NEGATIVE) ; ((equal (reverse (list (cadr el) (caddr el) (car el))) ; (car tri-observation)) ; 'NEGATIVE) ; (t (match-to-observation el (cdr tri-observation))))) ; ; (match-to-observation '(A B C) '((A B C))) --> POSITIVE ; ; (match-to-observation '(B X C) '((A B C))) --> NIL ; ; (match-to-observation '(B A C) '((A B C))) --> NEGATIVE ; RELAXED VERSION OF ABOVE, WORKING WITH "VARIABLES"; ; that is, not only A, B, and C lead to conclusions, but also ; A B M, B N C etc. - i.e. any triangle where at least one side ; is in common with the evaluated tristructure. This makes conclusions ; less certain - but far more likely to be found, and it allows for ; hypothetical reasoning. As it is unimportant exactly which "foreign" ; symbol is used in the triangle, it is symbolised with "?" in the comments. (defun match-to-observation (el tri-observation) (cond ((null tri-observation) nil) ; PRINCIPLE: X Y Z ; EXACT MATCH (though I could do only with variable match, actually): ; + ; X Y Z ; Z Y X ; - ; Y X Z ; Z X Y ; Y Z X ; X Z Y ((equal el (car tri-observation)) 'POSITIVE) ((equal (reverse el) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (car el) (caddr el)) (car tri-observation)) 'NEGATIVE) ((equal (reverse (list (cadr el) (car el) (caddr el))) (car tri-observation)) 'NEGATIVE) ((equal (list (cadr el) (caddr el) (car el)) (car tri-observation)) 'NEGATIVE) ((equal (reverse (list (cadr el) (caddr el) (car el))) (car tri-observation)) 'NEGATIVE) ; VARIABLE MATCH: ; - ; ? X Z ; ? Z X ; X Z ? ; Z X ? ; + ; X ? Z ; Z ? X ((equal (list (caar tri-observation) (car el) (caddr el)) (car tri-observation)) 'NEGATIVE) ((equal (list (caar tri-observation) (caddr el) (car el)) (car tri-observation)) 'NEGATIVE) ((equal (list (car el) (caddr el) (caddar tri-observation)) (car tri-observation)) 'NEGATIVE) ((equal (list (caddr el) (car el) (caddar tri-observation)) (car tri-observation)) 'NEGATIVE) ((equal (list (car el) (cadar tri-observation) (caddr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caddr el) (cadar tri-observation) (car el)) (car tri-observation)) 'POSITIVE) ; + ; X Y ? ; Y X ? ; Y Z ? ; Z Y ? ; ? X Y ; ? Y X ; ? Y Z ; ? Z Y ((equal (list (car el) (cadr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (car el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (cadr el) (caddr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (caddr el) (cadr el) (caddar tri-observation)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (car el) (cadr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (cadr el) (car el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (cadr el) (caddr el)) (car tri-observation)) 'POSITIVE) ((equal (list (caar tri-observation) (caddr el) (cadr el)) (car tri-observation)) 'POSITIVE) ; OTHERWISE: (t (match-to-observation el (cdr tri-observation))))) ; Hierarchisation, i.e. the structuring of input, ALSO adjusts the knowledge ; of the system which is trying to structure the input, as it decides which ; structures are appropriate, thus raising or destroying priority. (This is ; LEGAL style, not MATHEMATICS style logic.) I.e. the application of a ; conclusion on a real-world problem ALSO adjusts the knowledge base of the ; agent reasoning on the problem. (defun proto-match-adjust-knowledge (knowledge tri-observation seen-knowledge rejection) (cond ((null tri-observation) (append '(()) knowledge)) ((null knowledge) (append '(()) ; INITIALLY, KNOWLEDGE CANNOT CONSIST OUT OF NILs. ; NO "(reverse priority)": ; if you had seen anything, it would be the RESULT of this ; function! (reverse seen-knowledge) (reverse rejection))) (t (let ((mch (match-to-observation (car knowledge) tri-observation))) (cond ((equal 'POSITIVE mch) (append '(t) (list (car knowledge)) (reverse seen-knowledge) (cdr knowledge) (reverse rejection))) ((equal 'NEGATIVE mch) (proto-match-adjust-knowledge (cdr knowledge) tri-observation seen-knowledge (cons (car knowledge) rejection))) (t ; i.e. (null mch) (proto-match-adjust-knowledge (cdr knowledge) tri-observation (cons (car knowledge) seen-knowledge) rejection))))))) ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (C B A) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (T (C B A) (R S X) (V M S) (U N X)) ; ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (B A C) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (NIL (R S X) (V M S) (U N X) (B A C)) ; ; (proto-match-adjust-knowledge ; '((R S X) (V M S) (K L M) (U N X)) '((Z A B) (A B C) (B C D)) nil nil) ; --> ; (NIL (R S X) (V M S) (K L M) (U N X)) (defun match-adjust-knowledge (knowledge observation) (let ((tristrct (tristruct observation))) (let ((proto-result (proto-match-adjust-knowledge knowledge tristrct nil nil))) (cond ((null (car proto-result)) (cond ((null tristrct) proto-result) (t ; then create a hypothesis - you could put "T", but ; consing a HYPOTHESIS makes clear this is not really T: (cons 'HYPOTHESIS (cons (car (reverse tristrct)) (cdr (reverse (cdr (reverse proto-result))))))))) (t proto-result))))) ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A B C D)) ; --> ; (T (C B A) (R S X) (V M S) (U N X)) ; ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A B V D)) ; --> ; (HYPOTHESIS (B V D) (R S X) (V M S) (C B A)) ; ; (match-adjust-knowledge '((R S X) (V M S) (C B A) (U N X)) '(Z A)) ; --> ; (NIL (R S X) (V M S) (C B A) (U N X)) ; ---------------------------------------------------------------------------- ; NEXT: HIERERACHISE. ; Replace tristructures in the input with a super-symbol ; (i.e., sub-list them) where the first data structure of the ; knowledge is found, unless the knowledge starts with NIL: ; ; STRICT HIERARCHISATION VERSION - hierarchising with regard to the ; ; tristructure A B C only this tristructure A B C, thus being "narrow", ; ; but "certain": ; ; (defun hierarchise (triatoms observation) ; (cond ((null triatoms) observation) ; ((null observation) observation) ; ((null (cdr observation)) observation) ; ((null (cddr observation)) observation) ; ((or (equal triatoms ; (list (car observation) ; (cadr observation) ; (caddr observation))) ; ; I tried doing the below with REVERSE triatoms, and it FAILED in SBCL, ; ; but worked with Clisp. For compatibility, this is without REVERSE. ; (equal triatoms ; (list (caddr observation) ; (cadr observation) ; (car observation)))) ; (cons (list (car observation) ; (cadr observation) ; (caddr observation)) ; (hierarchise triatoms (cdddr observation)))) ; (t (cons (car observation) ; (hierarchise triatoms (cdr observation)))))) ; ; ; (hierarchise '(A B C) '(K L A B C B A E R T C B A B C X Y)) ; ; --> ; ; (K L (A B C) B A E R T (C B A) B C X Y) ; RELAXED HIERARCHISATION VERSION - this structures NOT ONLY A B C, ; i.e. the structurisation is a more "daring" and less "certain", but ; also "faster" and "more likely applicable". (defun hierarchise (triatoms observation) (cond ((null triatoms) observation) ((null observation) observation) ((null (cdr observation)) observation) ((null (cddr observation)) observation) ((or (equal triatoms (list (car observation) (cadr observation) (caddr observation))) ; I tried doing the below with REVERSE triatoms, and it FAILED in SBCL, ; but works with Clisp. Here, it is without REVERSE for compatibility: (equal triatoms (list (caddr observation) (cadr observation) (car observation))) ; NOW COME VARIABLES: (equal triatoms (list (car observation) (cadr triatoms) (caddr observation))) (equal triatoms (list (caddr observation) (cadr triatoms) (car observation))) (equal triatoms (list (car observation) (cadr observation) (caddr triatoms))) (equal triatoms (list (cadr observation) (car observation) (caddr triatoms))) (equal triatoms (list (caddr observation) (cadr observation) (caddr triatoms))) (equal triatoms (list (cadr observation) (caddr observation) (caddr triatoms))) (equal triatoms (list (car triatoms) (cadr observation) (caddr observation))) (equal triatoms (list (car triatoms) (caddr observation) (cadr observation))) (equal triatoms (list (car triatoms) (car observation) (cadr observation))) (equal triatoms (list (car triatoms) (cadr observation) (car observation)))) (cons (list (car observation) (cadr observation) (caddr observation)) (hierarchise triatoms (cdddr observation)))) (t (cons (car observation) (hierarchise triatoms (cdr observation)))))) ; (hierarchise '(A B C) '(K L A B C B A E R T C B A B C X Y)) ; --> ; (K (L A B) (C B A) E R (T C B) (A B C) X Y) ; ---------------------------------------------------------------------------- ; NEXT: HYPOTHETISE & HIERARCHISE UNTIL TOP (OR UNTIL HYPOTHESIS). ; That is, you know how to do ONE hierarchisation step - now recursively ; do MANY hierarchisation steps, repeatedly structuring the knowledge. I ; chose to structure it to the "top", but if you want to avoid too many ; purely "hypothetical" data structures, you may adjust the code to only ; hierarchise up to (and including) the first tristrcuture hypothesis. ; You NEED to create hypotheses, however, or the system cannot LEARN. (defun single-adjust-knowledge-and-hierarchise (joint-knowledge-observation-list) (let ((kno (car joint-knowledge-observation-list)) (obs (cadr joint-knowledge-observation-list))) (cond ; if knowledge is null or the observation is too short, do not compute: ((or (null kno) (null obs)) (cons nil joint-knowledge-observation-list)) ((or (null (cdr obs))) (cons nil joint-knowledge-observation-list)) ((or (null (cddr obs))) (cons nil joint-knowledge-observation-list)) (t (let ((adjusted-kno (match-adjust-knowledge kno obs))) (cond ((null (car adjusted-kno)) (list (car adjusted-kno) (cdr adjusted-kno) obs)) (t (list (car adjusted-kno) (cdr adjusted-kno) (hierarchise (cadr adjusted-kno) obs))))))))) ; (single-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R T C B A B C X Y))) ; --> ; (T ((A B C) (R S X) (V M S) (I T S) (M V S) (U N X) (C P M) (D O S) (W N T)) ; (K L (A B C) B A E R T (C B A) B C X Y)) ; HIERARCHISE ALL THE WAY UP. ; The joint-knowledge-observation-list consists of a list of the KNOWLEDGE ; and the HISTORY (i.e. the input to the system). The output is the MODIFIED ; knowledge and the STRUCTURED input. (defun multi-adjust-knowledge-and-hierarchise (joint-knowledge-observation-list) (let ((adjustment (single-adjust-knowledge-and-hierarchise joint-knowledge-observation-list))) (cond ; HERE, I COULD CATCH HYPOTHESES IF I DISLIKED THEM. ; So far, I hierarchise till the top, creating hypotheses: ((or (null (car adjustment)) ; the below alternative is in case of lack of hierarchisation: (equal (caddr adjustment) (cadr joint-knowledge-observation-list))) joint-knowledge-observation-list) (t (multi-adjust-knowledge-and-hierarchise (cdr adjustment)))))) ; [Using the "strict" version above:] ; (multi-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y))) ; --> ; (((K L ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))))) ; ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y))))))) ; (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))) ; (R D (O (S T I) (T S ((C B A) B (C X Y))))) ; (O (S T I) (T S ((C B A) B (C X Y)))) (T S ((C B A) B (C X Y))) ; ((C B A) B (C X Y)) (C X Y) (A B C)) ; ((K L ((A B C) B (A E (R D (O (S T I) (T S ((C B A) B (C X Y)))))))))) ; ---------------------------------------------------------------------------- ; NEXT: RESLIDE. ; Re-sliding means to "re-consider the input several times". The structuring ; of the input is dropped each time - but the ADJUSTED KNOWLEDGE BASE is ; kept - which, done several times, makes the system structure the knowledge ; in a more generally congruent way (i.e. "more intelligently"), as early ; mis-structures become de-prioritised upon reconsideration and are replaced ; by "better" structures of more reliable priority in the knowledge. ; The reslider ONLY adjusts the knowledge several times, ; until after the final knowledge adjustment it undertakes hierarchisation ; "for real". (defun reslider (knowledge observation slide-count) (cond ((zerop slide-count) (multi-adjust-knowledge-and-hierarchise (list knowledge observation))) (t (let ((mutation (multi-adjust-knowledge-and-hierarchise (list knowledge observation)))) (reslider (car mutation) observation (- slide-count 1)))))) ; (reslider ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y) ; 3) ; --> STRICT VERSION: ; (((K L (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))))) ; (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y)))))))))) ; (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))) ; (A E (R D (O S (T I (T S (C B (A B (C X Y)))))))) ; (R D (O S (T I (T S (C B (A B (C X Y))))))) ; (O S (T I (T S (C B (A B (C X Y)))))) (T I (T S (C B (A B (C X Y))))) ; (T S (C B (A B (C X Y)))) (C B (A B (C X Y)))) ; ((K L (A B (C B (A E (R D (O S (T I (T S (C B (A B (C X Y))))))))))))) ; --> FREE VERSION: ; (((K ((L A B) (C B A) (E R (D (O S T) (I T ((S C B) (A B C) X))))) Y) ; ((C B A) (E R (D (O S T) (I T ((S C B) (A B C) X)))) Y) ; (R (D (O S T) (I T ((S C B) (A B C) X))) Y) ; ((O S T) (I T ((S C B) (A B C) X)) Y) (I T S) ((A B C) X Y) (A B C) ; (K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y) ; ((C B A) (E R (D (O S T) (((I T S) C B) (A B C) X))) Y)) ; ((K ((L A B) (C B A) (E R (D (O S T) (I T ((S C B) (A B C) X))))) Y))) ; ; ONLY ONCE WITHOUT RESLIDING WOULD BE (FREE VERSION): ; (multi-adjust-knowledge-and-hierarchise ; (list ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T)) ; '(K L A B C B A E R D O S T I T S C B A B C X Y))) ; --> ; (((K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y) ; ((C B A) (E R (D (O S T) (((I T S) C B) (A B C) X))) Y) ; (R (D (O S T) (((I T S) C B) (A B C) X)) Y) ; ((O S T) (((I T S) C B) (A B C) X) Y) ((A B C) X Y) (A B C) (I T S) ; (R S X) (V M S)) ; ((K ((L A B) (C B A) (E R (D (O S T) (((I T S) C B) (A B C) X)))) Y))) ; ---------------------------------------------------------------------------- ; NEXT: PLAN ; Planning means extending the "present". The "present" may consist out of ; one or two symbols, at its top level. (If it consists out of more, e.g. ; because hierarchisation was terminated at a certain level of hypotheses, ; this still can be treated as "two symobols" as the last two are taken.) ; Basically, if you have "A B", you seek a "C" such as expressed by some ; tristructure "A B C" (i.e. C follows on A and B). If you have only "B", ; that is only ONE symbol is known, you try to find a "C" according to ; "A B C" or "B C D". (I.e. with one symbol, you have a better chance for ; a "hit".) If two top symbols are available, but yield not plan, you try ; then only with the last symbol again. If you CANNOT find a continuation ; even with the last atom, you DECOMPOSE it (if it is not elementary), e.g. ; "B" into "I J K", and then you try to find an "L" for either "J K" or "K". ; This you do recursively until the last symbol becomes elementary. If then ; still no continuation can be found - well, then the system replies NIL ; as it has no plan. (defun two-seek-continuation (two-atoms knowledge) (cond ((null knowledge) nil) ((equal (list (caar knowledge) (cadar knowledge)) two-atoms) (caddar knowledge)) (t (two-seek-continuation two-atoms (cdr knowledge))))) ; (two-seek-continuation '(A B) ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> C ; (two-seek-continuation '(F G) ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> NIL (defun one-seek-continuation (one-atom knowledge) (cond ((null knowledge) nil) ((equal (caar knowledge) one-atom) (cadar knowledge)) ((equal (cadar knowledge) one-atom) (caddar knowledge)) (t (one-seek-continuation one-atom (cdr knowledge))))) ; (one-seek-continuation 'A ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> B ; (one-seek-continuation 'B ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> C ; (one-seek-continuation 'K ; '((R S X) (V M S) (I T S) (M V S) (A B C) (U N X) (C P M) (D O S) (W N T))) ; --> NIL (defun seek-continuation (present knowledge) (cond ((null knowledge) nil) ((null present) nil) ((null (cdr present)) ; that is, only ONE atom available: (let ((one-res (one-seek-continuation (car present) knowledge))) (cond ((not (null one-res)) one-res) ((and (null one-res) (not (listp (car present)))) nil) (t ; that is, we can de-compose: (seek-continuation (car present) knowledge))))) (t ; that is, the present is longer than one atom: (let ((revpres (reverse present))) (let ((two-result (two-seek-continuation (list (cadr revpres) (car revpres)) knowledge))) (cond ((not (null two-result)) two-result) (t (seek-continuation (list (car revpres)) knowledge)))))))) ; (seek-continuation ; '(K L (A (B C D) E)) '((P Q R) (E F G) ((B C D) E H) (I J K))) ; --> H ; (seek-continuation ; '(K L (A (B C D) E)) '((P Q R) (E F G) ((B C X) E H) (I J K))) ; --> F ; (seek-continuation ; '(K L (A (B C D) N)) '((P Q R) (E F G) ((B C X) E H) (I J K))) ; --> NIL ; The continuation of the present will be possibly a "structured" ; symbol, but in order to give a decent reply to the user, the ; internal knowledge structure of the reply should be removed. (defun flatten-list (lis) (cond ((not (listp lis)) (list lis)) ((null lis) nil) ((listp (car lis)) (flatten-list (append (car lis) (cdr lis)))) (t (cons (car lis) (flatten-list (cdr lis)))))) ; (flatten-list '((a ((b c) (e f))))) --> (a b c e f) ; This is like the member function with test "equal"; I do this ; in case I want to use it elswhere than Common Lisp. It shows ; whether x is a member of the list y. (defun mmb (x y) (cond ((null y) nil) ((equal x (car y)) y) ; NOT (cdr y), as (x) would be nil! (t (mmb x (cdr y))))) ; When do you STOP replying? Well, either you handle I/O as ; "structures" of understanding, and then you reply simply with ; the "continuation structure" found, that is, if "L" was the ; reply to "J K", you answer with "L". OR you say - you insist ; on termination signals from I/O, in which case you try to extend ; L by M, N, O and so forth, until you reach a *stop*. To do this, ; you give the system L as hypothetical present and demand that L ; be continued. The "simple" alternative is just saying "L", the ; "sequencing" alternative tries to "sequence" structures until ; it hits *stop*. ; IT IS MORE SENSIBLE TO TURN ON THE SEQUENCING ALTERNATIVE ; IF YOU INTEND TO WORK WITH *stop* TO SIGNIFY STRUCTURE TERMINATION. ; Simple alternative. ; THUNK (defun follow-till-termination (present knowledge general-plan) (let ((plan (seek-continuation present knowledge))) (let ((flat-plan (flatten-list plan))) (let ((new-gen-plan (append general-plan flat-plan))) (cond ((mmb *stop* new-gen-plan) (reverse (cdr (mmb *stop* (reverse new-gen-plan))))) (t new-gen-plan)))))) ; ; Sequencing alternative. ; ; THUNK ; (defun follow-till-termination (present knowledge general-plan) ; (let ((plan (seek-continuation present knowledge))) ; (let ((flat-plan (flatten-list plan))) ; (let ((new-gen-plan (append general-plan flat-plan))) ; (cond ; ((mmb *stop* new-gen-plan) ; (reverse (cdr (mmb *stop* (reverse new-gen-plan))))) ; ((or (null plan) ; (< *trigger-answer-length* (length new-gen-plan))) ; new-gen-plan) ; (t ; (follow-till-termination (list plan) ; knowledge ; new-gen-plan))))))) (defun generate-plan (present knowledge) (follow-till-termination present knowledge nil)) ; (generate-plan '(K L (A (B C D) E)) ; '((P Q R) (E F G) ((B C D) E ((S T (U V W)) R (G H I))) (I J K))) ; --> (S T U V W R G H I) ; simple alternative ; --> (S T U V W R G H I J K) ; sequencing alternative, follows I into (I J K) ; ---------------------------------------------------------------------------- ; NEXT: KNOWLEDGE SELECTION AND GENERATION ; THE BELOW IS ADJUSTED STRAIGHT FROM THE SYSTEM LAIAN: ; Now that you have everything needed to create a plan, ; define a function to select the knowledge area which shall be ; used for the analysis of the input substrate. For this, ; simply pick the area which is most similar to the "problem" ; at hand (i.e. the relevant section of input history). ; The "candidate" will be the car of the knowledge-areas, ; and what is called below as "knowledge-areas" is the ; cdr of the knowledge-areas. (defun set-intersection (set1 set2) (cond ((null set1) nil) ((and (not (mmb (car set1) (cdr set1))) (mmb (car set1) set2)) (cons (car set1) (set-intersection (cdr set1) set2))) (t (set-intersection (cdr set1) set2)))) ; (set-intersection '(A B C D E) '(X Y C D Z)) --> (C D) ; select knowledge area to use: (defun select-knowledge-area (problem candidate knowledge-areas) (cond ; car of candidate is the history, cadr of candidate - the knowledge ((null knowledge-areas) (cadr candidate)) ((< (length (set-intersection (car candidate) problem)) (length (set-intersection (caar knowledge-areas) problem))) (select-knowledge-area problem (car knowledge-areas) (cdr knowledge-areas))) (t (select-knowledge-area problem candidate (cdr knowledge-areas))))) ; (select-knowledge-area ; '(A B C D E) ; '((A B X Y Z) (KNOWLEDGE 1)) ; '(((B X Y Z Q) (KNOWLEDGE 2)) ; ((A B C Y Z) (KNOWLEDGE 3)) ; ((A B X C Z) (KNOWLEDGE 4)))) ; --> ; (KNOWLEDGE 3) ; Knowledge generation: ; Normally, you will load knowledge from a file. ; But if no file exists yet, knowledge may be generated: (defun gen-knowledge-area (cntr) (cond ((zerop cntr) nil) (t (cons (list nil nil nil) (gen-knowledge-area (- cntr 1)))))) (defun gen-multiple-knowledge-areas (cntr) (cond ((zerop cntr) nil) (t (cons (list nil (gen-knowledge-area *elements-per-area*)) (gen-multiple-knowledge-areas (- cntr 1)))))) (defun gen-knowledge () (gen-multiple-knowledge-areas *number-of-areas*)) (defun load-knowledge () (cond ((null (probe-file "monotri.txt")) (gen-knowledge)) (t (with-open-file (stream "./monotri.txt") (read stream))))) ; LOAD the knowledge: (defvar *knowledge-areas* (load-knowledge)) ; SAVE the knowledge: (defun save-knowledge () (with-open-file (stream "./monotri.txt" :direction :output :if-exists :supersede) (format stream (write-to-string *knowledge-areas*)))) ; You cannot use print or princ here. ; sample call: ; (save-knowledge) ; ---------------------------------------------------------------------------- ; NEXT: PUT IT ALL TOGETHER. ; I.e. create a system that takes input, evaluates it, structures it ; according to the evaluation, changes knoweldge according to the ; evaluation, seeks a plan, and finally replies to the user. ; FIRST, A FEW AUXILIARY FUNCTIONS AND VARIABLES: ; (defun eexxiitt () '()) ; USE THIS IF YOU WANT TO DO A POST-MORTEM IN LISP. (defun eexxiitt () (progn (terpri) (save-knowledge) (quit))) ; a few functions to take whole sections of lists, always counting from 1: (defun proto-takefirst (fromwhere howmany resultlist) (if (or (null fromwhere) (zerop howmany)) (reverse resultlist) (proto-takefirst (cdr fromwhere) (- howmany 1) (cons (car fromwhere) resultlist)))) ; take the front part of a list: (defun takefirst (fromwhere howmany) (proto-takefirst fromwhere howmany '())) ; take the final part of a list: (defun takelast (fromwhere howmany) (reverse (takefirst (reverse fromwhere) howmany))) ; setup instincts (defun word-instinct (word) (cond ((equal word 'I) 'YOU) ((equal word 'ME) 'YOU) ((equal word 'YOU) 'ME) ((equal word 'AM) 'ARE) ((equal word 'ARE) 'AM-ARE) ((equal word 'MINE) 'YOURS) ((equal word 'YOURS) 'MINE) ((equal word 'MY) 'YOUR) ((equal word 'YOUR) 'MY) ((equal word 'MYSELF) 'YOURSELF) ((equal word 'YOURSELF) 'MYSELF) ((equal word 'WAS) 'WAS-WERE) (T word))) (defun proto-apply-instincts (sentence checked-sentence) (cond ((null sentence) (reverse checked-sentence)) (T (proto-apply-instincts (cdr sentence) (cons (word-instinct (car sentence)) checked-sentence))))) (defun apply-instincts (sentence) (proto-apply-instincts sentence '())) ; sample call: (apply-instincts '(I WAS HERE TODAY)) ; --> (YOU WAS-WERE HERE TODAY) ; Even when you have a plan, talk only until as long as ; the interaction should not be terminated. The rest of ; the plan is NOT executed. ; THUNK using SIG-TERM: (defun until-terminator (lis) (cond ((null lis) nil) ((equal *stop* (car lis)) nil) (t (cons (car lis) (until-terminator (cdr lis)))))) ; (until-terminator '(A B C D SIG-TERM E F G H)) --> (A B C D) (defvar *knowledge* nil) (defvar *human* nil) (defvar *history* nil) (defvar *machine* nil) (defvar *hierarchy* nil) (defvar *hierarchy-and-knowledge* nil) (defvar *plan* nil) ; VARIANTS FOR USING *stop* AS WELL AS NOT USING IT ARE IMPLEMENTED ; - THE DEFAULT HERE IS NOT USING IT. (defun run () ; READ HUMAN INPUT: (progn (finish-output nil) (print '(HUMAN------)) (finish-output nil) (terpri) (finish-output nil) (setq *human* (read)) (finish-output nil) (cond ((null *human*) (eexxiitt)) (t ; WITH *stop*: - consider placing the (list *stop*) actually NOT HERE... ; (setq *history* (takelast (append *history* *human* (list *stop*)) ; *history-length*)) ; ; ... SO THEN JUST DO THE "WITHOUT STOP" VERSION IN ALL CASES, ; BUT SEE BELOW... ; ; WITHOUT *stop*: (setq *history* (takelast (append *history* *human*) *history-length*)) ; SELECT EXECUTING INSECT: (setq *knowledge* (select-knowledge-area *history* (car *knowledge-areas*) (cdr *knowledge-areas*))) ; PERFORM EVALUATION, STRUCTURING BOTH INPUT AND KNOWLEDGE: (setq *hierarchy-and-knowledge* (reslider *knowledge* *history* *slidings*)) (setq *knowledge* (car *hierarchy-and-knowledge*)) (setq *hierarchy* (cadr *hierarchy-and-knowledge*)) ; FIND PLAN / REPLY TO THE USER: (setq *plan* (until-terminator (generate-plan *hierarchy* *knowledge*))) (setq *machine* (apply-instincts (takelast *plan* *trigger-answer-length*))) ; WITH *stop*: ; (cond ((null *machine*) (setq *history* *history*)) ; i.e. do nothing ; (t (setq *history* (takelast (append *history* *machine* (list *stop*)) ; *history-length*)))) ; ; ... YET INSTEAD OF THE ABOVE, PLACE THE STOP FOR THE HUMAN HERE, LIKE THIS: ; ; (cond ((null *machine*) (setq *history* *history*)) ; i.e. do nothing ; (t (setq *history* (takelast (append *history* (list *stop*) ; *machine* (list *stop*)) ; *history-length*)))) ; ; WITHOUT *stop*: (cond ((null *machine*) (setq *history* *history*)) ; i.e. do nothing (t (setq *history* (takelast (append *history* *machine*) *history-length*)))) ; UPDATE KNOWLEDGE AREAS / INSECTS OF THE KNOWLEDGE SWARM: (setq *knowledge-areas* (cons (list *history* *knowledge*) (reverse (cdr (reverse *knowledge-areas*))))) ; REPLY TO THE USER: (finish-output nil) (print '(MACHINE----)) (finish-output nil) (print *machine*) (finish-output nil) (terpri) (finish-output nil) (run))))) ; "I ASSUME I NEED NO INTRODUCTION." - Lestat (progn (print '(LOGICAL TRIANGULATION SYSTEM)) (print '(BASED ON IMPLICIT TRIANGULATION)) (print '(USING ONLY TRIANGLES AS DATA STRUCTURE)) (print '(ENTER NIL TO TERMINATE)) (print '(ENTER LIST OF SYMBOLS TO COMMUNICATE)) (terpri) (finish-output nil) (run) ; COMMENT THIS OUT IF YOU WANT TO PREVENT AUTOMATIC LAUNCH ON LOADING. ) ; Side-note concerning SAINT: ; http://www.softwarepreservation.org/projects/LISP/lisp15_family/ ; Side-note - paper suggested by Peter Voss, very good: ; http://www.cogsys.org/pdf/paper-1-2.pdf
37,777
Common Lisp
.l
850
38.638824
80
0.589111
KedalionDaimon/monotri
2
1
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
2424dac322927299c541952be3aa71272b847c6e5f8ccf1c7e8f1f7b6058d609
22,782
[ -1 ]
22,800
bullet.lisp
kiskami_tubegame/bullet.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; bullet.lisp (in-package #:tubegame) (defun create-bullet (type billbset x y z orinode owner) (let* ((startpos (calc-bullet-startpos x y z)) (physobj (llgs-engine-cl:colldet-addbox (first startpos) (second startpos) (third startpos) *BULLETBOX-HALFEXT1* *BULLETBOX-HALFEXT2* *BULLETBOX-HALFEXT3* *BULLET-PHYS-GRP* *BULLET-PHYS-MASK*)) (bulletent (make-bulletdata :type type :owner owner :physobj physobj :updatefunc #'bullet-update :collfunc #'bullet-collfunc :energy *BULLET-ENERGY* :pos startpos :flydir (llgs-engine-cl:render-getscenenodeorientation orinode) :flydist 0 :billset billbset :billboard (llgs-engine-cl:billboard-create billbset (first startpos) (second startpos) (third startpos) 1.0 1.0 1.0)))) ; (format t "create-bullet: startpos: ~A, phsyobj: ~A~%" startpos physobj) (llgs-engine-cl:billboard-updatebounds billbset) (llgs-engine-cl:colldet-setcolobjpos physobj (first startpos) (second startpos) (third startpos)) (add-to-physobjmap physobj bulletent) bulletent)) (defun blow-bullet (bullet) (llgs-engine-cl:billboard-remove (bulletdata-billset bullet) (bulletdata-billboard bullet)) (remove-entity bullet) (del-from-physobjmap (bulletdata-physobj bullet)) (del-physobj (bulletdata-physobj bullet))) (defun bullet-update (bullet elapsedt) (let ((distdelta (* elapsedt *BULLETSPEED*))) (incf (bulletdata-flydist bullet) distdelta) (cond ((<= *BULLET-MAXDIST* (bulletdata-flydist bullet)) (blow-bullet bullet)) (t (bullet-flystep bullet distdelta))))) (defun bullet-collfunc (bullet otherobj) (when otherobj (cond ((eq 'cube (entitydata-type otherobj)) ; (format t "collision with cube, destroying~%") ) ((eq 'asteroid (entitydata-type otherobj)) ; (format t "collision with asteroid, damageing and destroying ~%") (add-points-to-owner (bulletdata-owner bullet) (bulletdata-energy bullet)) (damage-asteroid otherobj (bulletdata-energy bullet)))) (blow-bullet bullet))) (defun calc-bullet-startpos (x y z) (list x y z)) (defun bullet-flystep (bullet delta) (let ((dir (bulletdata-flydir bullet)) (billb (bulletdata-billboard bullet)) (billset (bulletdata-billset bullet))) ; (format t "bullet-flystep: delta: ~A oripos: ~A flydir: ~A~%" delta (llgs-engine-cl:billboard-getpos billset billb) dir) (llgs-engine-cl:billboard-move billset billb (first dir) (second dir) (third dir) (fourth dir) delta) (llgs-engine-cl:billboard-updatebounds billset) ; (format t "bullet-flystep: newpos: ~A~%" (llgs-engine-cl:billboard-getpos billset billb)) (let ((pos (llgs-engine-cl:billboard-getpos billset billb))) (llgs-engine-cl:colldet-setcolobjpos (bulletdata-physobj bullet) (first pos) (second pos) (third pos))) )) (defun add-points-to-owner (player points) (incf (playerdata-levelpoints player) points))
3,920
Common Lisp
.lisp
86
40.313953
126
0.691985
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
873d3204ac44a40ee91947895831bc2c9e8a6ea466b059907ce5bb7dfb964fe0
22,800
[ -1 ]
22,801
globals.lisp
kiskami_tubegame/globals.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; globals.lisp (in-package #:tubegame) (defconstant *GAMELABEL* "tubegame") (defconstant *GAMELABEL2* "a 3D space shoot'em up") (defconstant *COPYRIGHT* "Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Source code is at http://code.google.com/p/tubegame Github mirror at https://github.com/kiskami/tubegame ") (defconstant *RIGHTS* "All rights reserved.") (defconstant *CONTROLS* "Control your ship with mouselook, left mouse button shoots, ESC quits, screenshot with F11.") (defconstant *PRESS-ANY-KEY* "Press any key to start!") (defconstant *PRESS-ANY-KEY2* "Press any key to quit!") (defconstant *GAME-OVER* "G A M E O V E R") (defconstant *GAME-OVER-TIMEOUT* 5.0) (defconstant *CONGRAT-MSG* "Congratulations!") (defconstant *DESTROYED-POINTS-MSG1* "You destroyed ~A of energy of stuff") (defconstant *DESTROYED-POINTS-MSG2* "on this level in ~A mins and ~A secs.") ; ------------------------------------------------ (defconstant *LABELCOLOR* '(0.24 0.61 0.83) "Skyblue color r,g,b") (defparameter *game-should-exit* nil "Game loop ends when t.") (defparameter *in-game* nil "Player is playing on a map when t, startscreen is displayed othervise.") (defparameter *main-camera* nil "Main game camera.") (defparameter *main-camera-node* nil "Main game camera scenenode") (defconstant *MAIN-CAMERA-SCENENODE-NAME* "main cam scenenode") (defconstant *MAIN-CAMERA-INITIAL-POS* '(-1.0 1.0 0.0)) (defconstant *MAIN-CAMERA-INITIAL-LOOKAT* '(0.0 0.0 0.0)) (defconstant *STARTSCREEN-CAMROT-SPEED* 0.005) (defconstant *ONEDEGREE* (/ pi 180.0) "One degree in radians.") (defconstant *PLAYER-INITIAL-POS* '(0.0 0.0 0.0)) (defconstant *PLAYER-NODE-SCALE* '(0.01 0.01 0.01)) (defconstant *PLAYER-MAX-ROT* (* 45 *ONEDEGREE*)) (defconstant *PlAYER-BACK-ROT-SPEED* 3.2) (defconstant *TURNSPEED* (* *ONEDEGREE* 15.0)) (defconstant *ROLLSPEED* (* *ONEDEGREE* 15.0)) (defconstant *FLYSPEED* 0.6) (defconstant *BULLETSPEED* 1.75) (defconstant *SKYBOX-MAT* "backgrounds/FirstSimpleStarField" "Skybox material name.") (defconstant *LEVEL1-FILE* "../data/level1.lisp" "Game level 1 file.") (defconstant *ESC-KEY* 1 "OIS scan code for ESC key.") (defconstant *F10-KEY* #x44 "OIS scan code for F10 key.") (defconstant *F11-KEY* #x57 "OIS scan code for F11 key.") (defconstant *F12-KEY* #x58 "OIS scan code for F12 key.") (defconstant *W-key* #x11) (defconstant *S-key* #x1F) (defconstant *A-key* #x1E) (defconstant *D-key* #x20) (defconstant *FPSDISPTIME* 2) (defconstant *COLLDET-DEBUGDRAWER-TIMEOUT* 1.5) (defconstant *COLLDET-TIMEOUT* 0.05 "Collision detection frequency.") (defconstant *FLYMODE-SWITCH-TIMEOUT* 1.5) ; ------------------------------------------------ (defconstant *PLAYER-MESH* "Playership.mesh" "Player ship Ogre mesh resource name") (defconstant *PLAYER-MESH-NAME* "playermesh") (defconstant *PLAYER-NODE-NAME* "playernode") (defconstant *PLAYER-PITCHNODE-NAME* "player_pitchnode") (defconstant *CUBE1-MESH* "Cube1.mesh" "Cube 1 Ogre mesh resource name") (defconstant *CUBE2-MESH* "Cube2.mesh" "Cube 2 Ogre mesh resource name") (defconstant *CUBE-2-MESH* "Cube-2.mesh" "Cube -2 Ogre mesh resource name") (defconstant *CUBE3-MESH* "Cube3.mesh" "Cube 3 Ogre mesh resource name") (defconstant *CUBE-3-MESH* "Cube-3.mesh" "Cube -3 Ogre mesh resource name") (defconstant *CUBE4-MESH* "Cube4.mesh" "Cube 4 Ogre mesh resource name") (defconstant *CUBE-4-MESH* "Cube-4.mesh" "Cube 4 Ogre mesh resource name") (defconstant *CUBE5-MESH* "Cube5.mesh" "Cube 5 Ogre mesh resource name") (defconstant *CUBE6-MESH* "Cube6.mesh" "Cube 6 Ogre mesh resource name") (defconstant *ASTEROID1-MESH* "Asteroida1.mesh" "Asteroid 1 Ogre mesh resource name") (defconstant *ASTEROID2-MESH* "Asteroida2.mesh" "Asteroid 2 Ogre mesh resource name") (defconstant *ASTEROID3-MESH* "Asteroida3.mesh" "Asteroid 3 Ogre mesh resource name") (defconstant *CEL-MESH* "Cel.mesh" "Level end object mesh resource name") (defconstant *ASTEROID1-SCALE* 0.2) (defconstant *ASTEROID2-SCALE* 0.12) (defconstant *ASTEROID3-SCALE* 0.05) (defconstant *EXPLOSION-AST1-W* 1.0) (defconstant *EXPLOSION-AST1-H* 1.0) (defconstant *EXPLOSION-AST2-W* 0.5) (defconstant *EXPLOSION-AST2-H* 0.5) (defconstant *EXPLOSION-AST3-W* 0.2) (defconstant *EXPLOSION-AST3-H* 0.2) (defconstant *CELCIL-HALFEXT1* 0.33) (defconstant *CELCIL-HALFEXT2* 0.01) (defconstant *CELCIL-HALFEXT3* 0.33) (defconstant *CELNODE-SCALE* '(0.4 0.4 0.4)) (defconstant *CEL-ROT-SPEED* 0.05) ; ------------------------------------------------ (defconstant *PLAYER-PHYS-GRP* 1) (defconstant *PLAYER-PHYS-MASK* (+ 2 4 8 16 32 64 128 256)) (defconstant *BULLET-PHYS-GRP* 2) (defconstant *BULLET-PHYS-MASK* (+ 4 8 32 128)) (defconstant *CUBE-PHYS-GRP* 4) (defconstant *CUBE-PHYS-MASK* (+ 1 2 64 128)) (defconstant *ASTEROIDA-PHYS-GRP* 8) (defconstant *ASTEROIDA-PHYS-MASK* (+ 1 2 64 128)) (defconstant *CEL-PHYS-GRP* 256) (defconstant *CEL-PHYS-MASK* 1) ; ------------------------------------------------ (defconstant *ASTEROID-BOUNCE-PENALTY* 5) (defconstant *CUBE-BOUNCE-PENALTY* 3) (defconstant *PLAYER-BOUNCE-TIMEOUT* 0.8) (defconstant *PLAYER-FIRE-TIMEOUT* 0.6) (defconstant *ASTEROID1-ENERGY* 100) (defconstant *ASTEROID2-ENERGY* 60) (defconstant *ASTEROID3-ENERGY* 20) (defconstant *BULLET-ENERGY* 20) (defconstant *BULLET-MAXDIST* 5) (defconstant *PLAYER-BULLET-W* 0.2) (defconstant *PLAYER-BULLET-H* 0.2) (defconstant *PLAYER-BULLET-MAT* "Examples/Flare") (defconstant *BULLETBOX-HALFEXT1* 0.015 "Player bullet colldet box size") (defconstant *BULLETBOX-HALFEXT2* 0.015) (defconstant *BULLETBOX-HALFEXT3* 0.015) (defconstant *EXPLOSION-MAT* "Explosion33") (defconstant *EXPBILLSET-STACKS* 8) (defconstant *EXPBILLSET-SLICES* 8) (defconstant *EXPLOSION-LIFETIME* 1.2) (defconstant *AST1-EXPLOSION-DIST* 0.0) (defconstant *AST2-EXPLOSION-DIST* 0.0) (defconstant *AST3-EXPLOSION-DIST* 0.0) ; ------------------------------------------------ (defconstant *POINTSPANELID* "player_points") (defconstant *INTEGPANELID* "player_integrity") (defconstant *WEAPONPANELID* "player_weapon_energy") (defconstant *SHIELDPANELID* "player_shield_energy") (defconstant *RETICLEPANELID* "player_reticle") (defconstant *GREEN-COLOR* '(0.0 1.0 0.0)) (defconstant *ORANGE-COLOR* '(1.0 0.546 0.0)) (defconstant *RED-COLOR* '(1.0 0.0 0.0)) ; ------------------------------------------------ (defparameter *PHYSOBJMAP* nil "Physics objects pointer->entity map.") (defparameter *PHYSOBJMAP-TRASH* nil) (defparameter *ENTITIES* '() "Game entities list.") (defparameter *EXPBILLBSET* nil "Explosions BillboardSet pointer") (defparameter *EXPBILLBSETNODE* nil) (defstruct leveldata levelfile levelpointmargin playershieldenergystart playerstructintegritystart playerweaponenergystart startposlist) (defstruct entitydata type mesh node physobj updatefunc collfunc) (defstruct (playerdata (:include entitydata)) levelpoints leveldonepoints integrity startweaponenergy weaponenergy shieldenergy bouncetime bouncing bouncepenalty firetime firing movementdir relx rely bulletbillbnode bulletbillbset flymode pitchnode playerrot speed difficulty playtimer) (defstruct (asteroiddata (:include entitydata)) subtype rotx roty rotz energy) (defstruct (bulletdata (:include entitydata)) owner billboard billset energy lifetime flydist pos flydir) (defstruct (explosiondata (:include entitydata)) billboard lifetime texindex pos)
9,242
Common Lisp
.lisp
217
39.589862
102
0.717555
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
57e76a28ff3e4c61110a03f6ad29ddfe29d28eba5849f114f62854833ea9dc02
22,801
[ -1 ]
22,802
make-exe.lisp
kiskami_tubegame/make-exe.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; make-exe.lisp (unless (find-package :asdf) (require :asdf)) ;;; Saving Executables (require "tubegame") (defparameter name #+unix "tubegame" #+windows "tubegame.exe") ;;; Only Clozure CL (on Windows) is supported atm #+ccl (save-application name :toplevel-function #'tubegame:game-run :prepend-kernel t)
1,177
Common Lisp
.lisp
25
44.2
87
0.711909
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
0fb956ffcbbd1bc8402a035720766af680dfdede1b09a4f973241756d94c8b69
22,802
[ -1 ]
22,803
package.lisp
kiskami_tubegame/package.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; package.lisp (in-package :cl-user) (defpackage #:tubegame (:use #:cl #:llgs-engine-cl) (:export :game-run))
943
Common Lisp
.lisp
22
41.454545
78
0.721436
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d3e6365d287ad0b5051ecc7e76bd37f5f9b0948afcb600491a09ec88c5d8c8b6
22,803
[ -1 ]
22,804
player.lisp
kiskami_tubegame/player.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; player.lisp (in-package #:tubegame) (defun load-player (level) (format t "Loading player data...~%") (let* ((mesh (llgs-engine-cl:mesh-load *PLAYER-MESH-NAME* *PLAYER-MESH*)) (node (llgs-engine-cl:render-createscenenode *PLAYER-NODE-NAME*)) (pitchnode (llgs-engine-cl:render-createchildscenenode node *PLAYER-PITCHNODE-NAME*)) (plyent (make-playerdata :type 'player :mesh mesh :node node :pitchnode pitchnode :physobj (llgs-engine-cl:colldet-addmeshgeom (first *PLAYER-INITIAL-POS*) (second *PLAYER-INITIAL-POS*) (third *PLAYER-INITIAL-POS*) mesh *PLAYER-PHYS-GRP* *PLAYER-PHYS-MASK*) :levelpoints 0 :leveldonepoints (leveldata-levelpointmargin level) :integrity (leveldata-playerstructintegritystart level) :startweaponenergy (leveldata-playerweaponenergystart level) :weaponenergy (leveldata-playerweaponenergystart level) :shieldenergy (leveldata-playershieldenergystart level) :updatefunc #'update-player :collfunc #'collision-player :bouncetime 0 :bouncing nil :bouncepenalty 0 :firetime *PLAYER-FIRE-TIMEOUT* :firing nil :movementdir 'forward :relx 0 :rely 0 :bulletbillbnode (llgs-engine-cl:render-createchildscenenode node "player_billboardset" :inheritori 1 :inheritscale 0) :bulletbillbset (llgs-engine-cl:billboardset-create) :flymode nil :playerrot 0 :speed *FLYSPEED* :difficulty 0 :playtimer 0))) (llgs-engine-cl:render-attachmoveable pitchnode mesh) (llgs-engine-cl:render-attachmoveable (playerdata-bulletbillbnode plyent) (playerdata-bulletbillbset plyent)) (llgs-engine-cl:render-setscenenodepos node (first *PLAYER-INITIAL-POS*) (second *PLAYER-INITIAL-POS*) (third *PLAYER-INITIAL-POS*)) (llgs-engine-cl:render-setscenenodescale pitchnode (first *PLAYER-NODE-SCALE*) (second *PLAYER-NODE-SCALE*) (third *PLAYER-NODE-SCALE*)) (llgs-engine-cl:render-rotatescenenodez node (adjust-float (deg-to-rad 90))) (llgs-engine-cl:render-rotatescenenodey node (adjust-float (deg-to-rad 90))) (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj plyent) node) (llgs-engine-cl:colldet-setscale (entitydata-physobj plyent) (first *PLAYER-NODE-SCALE*) (second *PLAYER-NODE-SCALE*) (third *PLAYER-NODE-SCALE*)) (llgs-engine-cl:billboardset-setdefdims (playerdata-bulletbillbset plyent) *PLAYER-BULLET-W* *PLAYER-BULLET-H*) (llgs-engine-cl:billboardset-setmaterial (playerdata-bulletbillbset plyent) *PLAYER-BULLET-MAT*) plyent)) (defun reset-player (player level) (setf (playerdata-levelpoints player) 0) (setf (playerdata-integrity player) (leveldata-playerstructintegritystart level)) (setf (playerdata-weaponenergy player) (leveldata-playerweaponenergystart level)) (setf (playerdata-shieldenergy player) (leveldata-playershieldenergystart level))) (defun show-player (player camnode level) (llgs-engine-cl:render-setscenenodepos camnode 0.0 0.3 0.1) (llgs-engine-cl:render-addchild (entitydata-node player) camnode) (llgs-engine-cl:render-cameralookat *main-camera* (+ 2.0 (first *PLAYER-INITIAL-POS*)) (second *PLAYER-INITIAL-POS*) (third *PLAYER-INITIAL-POS*)) (let ((startpos (first (leveldata-startposlist level)))) ; (format t "First startpos from level: ~A~%" startpos) (if (null startpos) (setf startpos *PLAYER-INITIAL-POS*)) (format t "Player startpos: ~A~%" startpos) (llgs-engine-cl:render-setscenenodepos (playerdata-node player) (first startpos) (second startpos) (third startpos)) (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj player) (entitydata-node player))) (llgs-engine-cl:render-addchild (llgs-engine-cl:render-rootscenenode) (entitydata-node player)) (llgs-engine-cl:render-setscenenodevis (entitydata-node player) t) (add-entity player) (add-to-physobjmap (entitydata-physobj player) player) (show-hud player)) (defun hide-player (player camnode) (llgs-engine-cl:render-setscenenodevis (entitydata-node player) nil) (llgs-engine-cl:render-removechild (entitydata-node player) camnode) (llgs-engine-cl:render-removechild (llgs-engine-cl:render-rootscenenode) (entitydata-node player)) (remove-entity player) (del-from-physobjmap (entitydata-physobj player)) (hide-hud)) (defun go-forward (player elapsedt) (llgs-engine-cl:render-translatescenenode (entitydata-node player) 0.0 (adjust-float (* -1.0 (playerdata-speed player) elapsedt)) 0.0 t) (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj player) (entitydata-node player))) (defun go-backward (player elapsedt) (llgs-engine-cl:render-translatescenenode (entitydata-node player) 0.0 (adjust-float (* (playerdata-speed player) elapsedt)) 0.0 t) (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj player) (entitydata-node player))) (defun handle-turn (player elapsedt) (let ((rad (* -1.0 (playerdata-relx player) (adjust-float (* *TURNSPEED* elapsedt))))) (cond ((not (zerop (playerdata-relx player))) (llgs-engine-cl:render-rotatescenenodez (entitydata-node player) rad) (cond ((<= *PLAYER-MAX-ROT* (+ rad (playerdata-playerrot player))) (setf rad (- *PLAYER-MAX-ROT* (playerdata-playerrot player))) ; (format t "handle-turn: rad1=~A~%" rad) ) ((>= (* -1 *PLAYER-MAX-ROT*) (+ rad (playerdata-playerrot player))) (setf rad (- (* -1 *PLAYER-MAX-ROT*) (playerdata-playerrot player))) ; (format t "handle-turn: rad2=~A~%" rad) ))) (t (when (not (zerop (playerdata-playerrot player))) ; rotate back ship after turns (setf rad (* (if (> (playerdata-playerrot player) 0) -1.0 1.0) *PlAYER-BACK-ROT-SPEED* (adjust-float (* *TURNSPEED* elapsedt))))))) (incf (playerdata-playerrot player) rad) (llgs-engine-cl:render-rotatescenenodey (playerdata-pitchnode player) (adjust-float rad))) (if (not (zerop (playerdata-rely player))) (llgs-engine-cl:render-rotatescenenodex (entitydata-node player) (* (playerdata-rely player) (adjust-float (* *ROLLSPEED* elapsedt))))) (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj player) (entitydata-node player)) ) (defun handle-flymode (player elapsedt) (cond ((playerdata-flymode player) ; freefly mode? (cond ((eq (playerdata-movementdir player) 'forward) (go-forward player elapsedt)) ((eq (playerdata-movementdir player) 'backward) (go-backward player elapsedt))) (setf (playerdata-movementdir player) nil) (setf (playerdata-bouncetime player) 0)) (t (cond ((playerdata-bouncing player) (incf (playerdata-bouncetime player) elapsedt) (cond ((>= (playerdata-bouncetime player) *PLAYER-BOUNCE-TIMEOUT*) ; (format t "Bouncing penalty to player ~A~%" (playerdata-bouncepenalty player)) (setf (playerdata-bouncetime player) 0) (decf (playerdata-integrity player) (playerdata-bouncepenalty player)) (when (>= 0 (playerdata-integrity player)) (setf (playerdata-integrity player) 0) (game-over player)) (update-integrity-hud player)) ; (cond ((eq (playerdata-movementdir player) 'forward) ; (setf (playerdata-movementdir player) 'backward) ;; (go-backward player elapsedt) ; ) ; ((eq (playerdata-movementdir player) 'backward) ; (setf (playerdata-movementdir player) 'forward) ;; (go-forward player elapsedt))) )) (t (setf (playerdata-movementdir player) 'forward) (setf (playerdata-bouncetime player) 0) (go-forward player elapsedt))))) ) (defun handle-firing (player elapsedt) (cond ((playerdata-firing player) (cond ((>= (+ (playerdata-firetime player) elapsedt) *PLAYER-FIRE-TIMEOUT*) (decf (playerdata-weaponenergy player) *BULLET-ENERGY*) (cond ((< 0 (playerdata-weaponenergy player)) ; (format t "FIRE!~%") (let ((pos (llgs-engine-cl:render-getscenenodepos (playerdata-node player)))) (add-entity (apply #'create-bullet 'playerbullet (list (playerdata-bulletbillbset player) (first pos) (second pos) (third pos) (playerdata-node player) player))))) (t (setf (playerdata-weaponenergy player) 0))) (update-weapon-hud player) (setf (playerdata-firetime player) 0)) (t (incf (playerdata-firetime player) elapsedt))) (setf (playerdata-firing player) nil)) (t (incf (playerdata-firetime player) elapsedt))) ) (defun update-player (player elapsedt) "Update player state according to input and collision events" (incf (playerdata-playtimer player) elapsedt) (handle-turn player elapsedt) (handle-flymode player elapsedt) (handle-firing player elapsedt) (raise-gamedifficulty player) (update-points-hud player) (setf (playerdata-relx player) 0) (setf (playerdata-rely player) 0) ) (defun raise-gamedifficulty (player) (when (and (= (playerdata-difficulty player) 0) (>= (playerdata-levelpoints player) (* (playerdata-leveldonepoints player) 0.6))) (setf (playerdata-speed player) (* (playerdata-speed player) 1.2)) (incf (playerdata-difficulty player)) (format t "Raised game difficulty to ~A.~%" (playerdata-difficulty player))) (when (and (= (playerdata-difficulty player) 1) (>= (playerdata-levelpoints player) (* (playerdata-leveldonepoints player) 0.8))) (setf (playerdata-speed player) (* (playerdata-speed player) 1.2)) (incf (playerdata-difficulty player)) (format t "Raised game difficulty to ~A.~%" (playerdata-difficulty player)))) (defun player-reset-collinfo (player) (setf (playerdata-bouncing player) nil)) (defun collision-player (player otherentity) ; (format t "Player collided with entity type ~A~%" (entitydata-type otherentity)) (cond ((eq 'asteroid (entitydata-type otherentity)) (player-bounce player otherentity *ASTEROID-BOUNCE-PENALTY*)) ((eq 'cube (entitydata-type otherentity)) (player-bounce player otherentity *CUBE-BOUNCE-PENALTY*))) ;TODO: powerups colldet! ) (defun player-bounce (player otherent penalty) (declare (ignore otherent)) (setf (playerdata-bouncepenalty player) penalty) (setf (playerdata-bouncing player) t)) (defun player-rightturn (player relx) (setf (playerdata-relx player) relx)) (defun player-leftturn (player relx) (setf (playerdata-relx player) relx)) (defun player-downturn (player rely) (setf (playerdata-rely player) rely)) (defun player-upturn (player rely) (setf (playerdata-rely player) rely)) (defun player-fire (player elapsedt) (declare (ignore elapsedt)) ; (format t "Player fire~%") (setf (playerdata-firing player) t)) (defun player-forward (player) (when (playerdata-flymode player) (setf (playerdata-movementdir player) 'forward))) (defun player-backward (player) (when (playerdata-flymode player) (setf (playerdata-movementdir player) 'backward))) (defun show-hud (player) ;points (llgs-engine-cl:render-createsimpletext *POINTSPANELID* (make-hud-string "Points: " (playerdata-levelpoints player)) "DroidSans" 32.0 10.0 10.0 1.0 1.0 1) ;integrity (llgs-engine-cl:render-createsimpletext *INTEGPANELID* (make-hud-string "Ship integrity: " (playerdata-integrity player)) "DroidSans" 24.0 10.0 45.0 1.0 1.0 1) ;weapon energy (llgs-engine-cl:render-createsimpletext *WEAPONPANELID* (make-hud-string "Weapon energy: " (playerdata-weaponenergy player)) "DroidSans" 24.0 10.0 71.0 1.0 1.0 1) (llgs-engine-cl:render-createsimpletext *RETICLEPANELID* "[ ]" "DroidSans" 0.04 0.485 0.482 1.0 1.0 0) (llgs-engine-cl:render-simpletextcolor *WEAPONPANELID* (first *GREEN-COLOR*) (second *GREEN-COLOR*) (third *GREEN-COLOR*)) (llgs-engine-cl:render-simpletextcolor *INTEGPANELID* (first *GREEN-COLOR*) (second *GREEN-COLOR*) (third *GREEN-COLOR*)) ; TODO shield, powerups ) (defun update-integrity-hud (player) (let ((swep (/ (playerdata-startweaponenergy player) 100))) (if (< (playerdata-weaponenergy player) (* 35 swep)) (llgs-engine-cl:render-simpletextcolor *INTEGPANELID* (first *ORANGE-COLOR*) (second *ORANGE-COLOR*) (third *ORANGE-COLOR*))) (if (< (playerdata-weaponenergy player) (* 5 swep)) (llgs-engine-cl:render-simpletextcolor *INTEGPANELID* (first *ORANGE-COLOR*) (second *ORANGE-COLOR*) (third *ORANGE-COLOR*)))) (llgs-engine-cl:render-simpletextsettext *INTEGPANELID* (make-hud-string "Ship integrity: " (playerdata-integrity player)))) (defun update-weapon-hud (player) (let ((swep (/ (playerdata-startweaponenergy player) 100))) (if (< (playerdata-weaponenergy player) (* 35 swep)) (llgs-engine-cl:render-simpletextcolor *WEAPONPANELID* (first *ORANGE-COLOR*) (second *ORANGE-COLOR*) (third *ORANGE-COLOR*))) (if (< (playerdata-weaponenergy player) (* 5 swep)) (llgs-engine-cl:render-simpletextcolor *WEAPONPANELID* (first *RED-COLOR*) (second *RED-COLOR*) (third *RED-COLOR*)))) (llgs-engine-cl:render-simpletextsettext *WEAPONPANELID* (make-hud-string "Weapon energy: " (playerdata-weaponenergy player)))) (defun update-points-hud (player) (llgs-engine-cl:render-simpletextsettext *POINTSPANELID* (make-hud-string "Points: " (playerdata-levelpoints player)))) (defun hide-hud ()) (defun game-over (player) ; (format t "*** GAME OVER ***~%") (llgs-engine-cl:render-createsimpletext "game_over" *GAME-OVER* "DroidSans-Bold" 0.10 0.2 0.4 1.0 1.0 0) (llgs-engine-cl:render-createsimpletext "st_pressany2" *PRESS-ANY-KEY2* "DroidSans-Bold" 0.05 0.33 0.5 1.0 1.0 0) ; level done? (when (<= (playerdata-leveldonepoints player) (playerdata-levelpoints player)) (llgs-engine-cl:render-createsimpletext "st_congrats" *CONGRAT-MSG* "DroidSans-Bold" 0.10 0.25 0.56 1.0 1.0 0) (llgs-engine-cl:render-simpletextcolor "st_congrats" 0.851 0.644 0.125)) (llgs-engine-cl:render-createsimpletext "st_destroyedmsg1" (make-formatted-string *DESTROYED-POINTS-MSG1* (playerdata-levelpoints player) nil) "DroidSans" 0.05 0.22 0.65 1.0 1.0 0) (let ((mins (floor (/ (playerdata-playtimer player) 60))) (secs (floor (mod (playerdata-playtimer player) 60)))) (format t "Level done in ~A mins and ~A secs (~A).~%" mins secs (playerdata-playtimer player)) (llgs-engine-cl:render-createsimpletext "st_destroyedmsg2" (make-formatted-string *DESTROYED-POINTS-MSG2* mins secs) "DroidSans" 0.05 0.22 0.70 1.0 1.0 0)) (setf *ENTITIES* nil) (setf *PHYSOBJMAP* (make-hash-table)) (add-entity (make-explosiondata :type 'game-over :lifetime 0 :updatefunc #'game-over-update))) (defun game-over-update (ent elapsedt) (incf (explosiondata-lifetime ent) elapsedt) (when (and (< *GAME-OVER-TIMEOUT* (explosiondata-lifetime ent)) (= 1 (llgs-engine-cl:i-anykeypressed))) (setf *game-should-exit* t))) (defun player-toggle-flymode (player) (setf (playerdata-flymode player) (not (playerdata-flymode player))) (format t "Switched player flymode to ~A~%" (playerdata-flymode player)))
16,484
Common Lisp
.lisp
341
42.659824
142
0.694699
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
27a7902c0c649e625e9ed412a650dcd271f74502a84872e35204028fa5d46bbe
22,804
[ -1 ]
22,805
startscreen.lisp
kiskami_tubegame/startscreen.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; startscreen.lisp (in-package #:tubegame) (defparameter *STARTSCREEN-STATE* 'none) (defun one-startscreen-frame (elapsedt) "Render one scrartscreen frame." (cond ((equal 'none *STARTSCREEN-STATE*) (format t "Startscreen init...~%") ; load startscreen assets (llgs-engine-cl:render-createsimpletext "st_gamelabel" *GAMELABEL* "DroidSans-Bold" 48.0 10.0 10.0 1.0 1.0 1) (llgs-engine-cl:render-createsimpletext "st_gamelabel2" *GAMELABEL2* "DroidSans-Bold-14" 14.0 10.0 60.0 1.0 1.0 1) (llgs-engine-cl:render-simpletextcolor "st_gamelabel" (first *LABELCOLOR*) (second *LABELCOLOR*) (third *LABELCOLOR*)) (llgs-engine-cl:render-createsimpletext "st_copylabel" *COPYRIGHT* "DroidSans-14" 14.0 10.0 80.0 1.0 1.0 1) (llgs-engine-cl:render-createsimpletext "st_pressany" *PRESS-ANY-KEY* "DroidSans-Bold" 16.0 10.0 380.0 1.0 1.0 1) (llgs-engine-cl:render-createsimpletext "st_controls" *CONTROLS* "DroidSans" 14.0 10.0 350.0 1.0 1.0 1) (llgs-engine-cl:render-createsimpleimage "si_3dlogo" "3DLogo" 0.0 0.83 0.105 0.1667 0) ; then run (setq *STARTSCREEN-STATE* 'run)) ((equal 'run *STARTSCREEN-STATE*) ; (format t "Startscreen run~%") (cond ((< 0 (llgs-engine-cl:i-anykeypressed)) ; start playing? (setq *in-game* t) (llgs-engine-cl:render-simpletexthide "st_gamelabel") (llgs-engine-cl:render-simpletexthide "st_gamelabel2") (llgs-engine-cl:render-simpletexthide "st_copylabel") (llgs-engine-cl:render-simpletexthide "st_pressany") (llgs-engine-cl:render-simpletexthide "st_controls") (llgs-engine-cl:render-simpletexthide "si_3dlogo") ) (t (if (< 0 elapsedt) ; update startscreen (llgs-engine-cl:render-rotatescenenodey *main-camera-node* (adjust-float (* *STARTSCREEN-CAMROT-SPEED* elapsedt))) ))))))
2,788
Common Lisp
.lisp
66
37.19697
79
0.678203
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c5b93e502cc1880aa8c51a404fd59f38b493b3627e155150f9a6e4d973e5c07e
22,805
[ -1 ]
22,806
powerups.lisp
kiskami_tubegame/powerups.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; powerups.lisp (in-package #:tubegame)
888
Common Lisp
.lisp
19
44.473684
79
0.712803
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d20a6304758debebdbd393fab1a74799963f73c6654788dbb2256c4def6414a1
22,806
[ -1 ]
22,807
asteroid.lisp
kiskami_tubegame/asteroid.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; asdteroid.lisp (in-package #:tubegame) (defun create-asteroid (x y z type n) (dotimes (i n) (create-1asteroid x y z type))) (defun create-1asteroid (x y z type) (let* ((mesh (llgs-engine-cl:mesh-load (gen-name "ast_mesh" type x y z) (get-ast-meshfile-name type))) (node (llgs-engine-cl:render-createscenenode (gen-name "ast" type x y z))) (pos (list (+ (* 2 x) (get-rnd-coord 0.62)) (+ (* 2 y) (get-rnd-coord 0.62)) (+ (* 2 z) (get-rnd-coord 0.62)))) (astent (make-asteroiddata :type 'asteroid :subtype type :mesh mesh :node node :physobj (llgs-engine-cl:colldet-addmeshgeom (first pos) (second pos) (third pos) mesh *ASTEROIDA-PHYS-GRP* *ASTEROIDA-PHYS-MASK*) :updatefunc #'update-asteroid :collfunc #'collision-asteroid :rotx 0 :roty 0 :rotz 0 :energy (get-asteroid-energy type))) (scale (get-asteroid-scale type))) (llgs-engine-cl:render-attachmoveable node mesh) (llgs-engine-cl:render-addchild (llgs-engine-cl:render-rootscenenode) node) (llgs-engine-cl:render-setscenenodepos node (first pos) (second pos) (third pos)) (llgs-engine-cl:render-setscenenodescale node (first scale) (second scale) (third scale)) (llgs-engine-cl:colldet-syncolobjtoscenenode (asteroiddata-physobj astent) node) (llgs-engine-cl:colldet-setscale (asteroiddata-physobj astent) (first scale) (second scale) (third scale)) (add-to-physobjmap (asteroiddata-physobj astent) astent))) (defun get-ast-meshfile-name (type) (cond ((eq type 'ast2) *ASTEROID2-MESH*) ((eq type 'ast3) *ASTEROID3-MESH*) (t *ASTEROID1-MESH*))) (defun get-asteroid-energy (type) (cond ((eq type 'ast2) *ASTEROID2-ENERGY*) ((eq type 'ast3) *ASTEROID3-ENERGY*) (t *ASTEROID1-ENERGY*))) (defun get-asteroid-scale (type) (cond ((eq type 'ast2) (list *ASTEROID2-SCALE* *ASTEROID2-SCALE* *ASTEROID2-SCALE*)) ((eq type 'ast3) (list *ASTEROID3-SCALE* *ASTEROID3-SCALE* *ASTEROID3-SCALE*)) (t (list *ASTEROID1-SCALE* *ASTEROID1-SCALE* *ASTEROID1-SCALE*)))) (defun update-asteroid (ast elapsedt) (declare (ignore ast elapsedt))) (defun collision-asteroid (ast otherobj) (declare (ignore ast otherobj))) (defun damage-asteroid (ast energy) (decf (asteroiddata-energy ast) energy) (cond ((<= (asteroiddata-energy ast) 0) (setf (asteroiddata-energy ast) 0) (blow-asteroid ast)) (t ; (format t "damaged asteroid with energy ~A - ~A~%" (asteroiddata-energy ast) energy ) nil))) (defun blow-asteroid (ast) ; (format t "asteroid blowup ~A~%" ast) (remove-entity ast) (del-physobj (asteroiddata-physobj ast)) (del-from-physobjmap (asteroiddata-physobj ast)) (add-entity (create-asteroid-explosion ast)) (llgs-engine-cl:render-destroyscenenode (asteroiddata-node ast))) (defun create-asteroid-explosion (ast) (create-explosion (llgs-engine-cl:render-getscenenodepos (asteroiddata-node ast)) (asteroiddata-subtype ast)))
3,834
Common Lisp
.lisp
83
42.144578
111
0.698579
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fa7d2f6e49bbfa0d7f898bc3b1230a836c3578a6a0d07e7e53fb4fb5c1de6d13
22,807
[ -1 ]
22,808
explosion.lisp
kiskami_tubegame/explosion.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; explosion.lisp (in-package #:tubegame) (defun init-explosions (parentnode) "Initialize global BillboardSet for explosions." (setf *EXPBILLBSET* (llgs-engine-cl:billboardset-create)) (setf *EXPBILLBSETNODE* (llgs-engine-cl:render-createchildscenenode ; (llgs-engine-cl:render-rootscenenode) parentnode "explosion_billboard" :inheritori 1 :inheritscale 0)) (llgs-engine-cl:billboardset-setdefdims *EXPBILLBSET* *EXPLOSION-AST1-W* *EXPLOSION-AST1-H*) (llgs-engine-cl:billboardset-setmaterial *EXPBILLBSET* *EXPLOSION-MAT*) (llgs-engine-cl:billboardset-stacksandslices *EXPBILLBSET* *EXPBILLSET-STACKS* *EXPBILLSET-SLICES*) (llgs-engine-cl:render-attachmoveable *EXPBILLBSETNODE* *EXPBILLBSET*) ; (format t "Initialized node and billboardset for explosions. ~A at ~A, ~A~%" ; *EXPBILLBSETNODE* ; (llgs-engine-cl:render-getscenenodepos *EXPBILLBSETNODE*) ; *EXPBILLBSET*) ) (defun reset-explosions () (llgs-engine-cl:billboardset-clear *EXPBILLBSET*)) (defun create-explosion (entpos enttype) (let* ((pos (calc-explosion-pos (llgs-engine-cl:render-getscenenodepos *main-camera-node*) entpos enttype)) (dims (calc-explosion-dims enttype)) (expent (make-explosiondata :type 'explosion :updatefunc #'update-explosion :billboard (llgs-engine-cl:billboard-create *EXPBILLBSET* (first pos) (second pos) (third pos) 1.0 1.0 1.0) :lifetime 0 :texindex 0 :pos pos))) (llgs-engine-cl:billboard-settexcoordind *EXPBILLBSET* (explosiondata-billboard expent) (explosiondata-texindex expent)) ; (format t "create-explosion: campos ~A, entpos ~A, exppos ~A~%" ; (llgs-engine-cl:render-getscenenodepos *main-camera-node*) ; entpos ; pos) (if dims (llgs-engine-cl:billboard-setdims *EXPBILLBSET* (explosiondata-billboard expent) (first dims) (second dims))) (llgs-engine-cl:billboard-updatebounds *EXPBILLBSET*) expent)) ;(defun calc-explosion-pos_ (campos entpos enttype) ; (list (first entpos) (second entpos) (third entpos))) (defun calc-explosion-pos (campos entpos enttype) (let ((dirvec (vec3_normalize (vec3- entpos campos)))) (cond ((eq 'ast1 enttype) (vec3- entpos (vec3* dirvec *AST1-EXPLOSION-DIST*))) ((eq 'ast2 enttype) (vec3- entpos (vec3* dirvec *AST2-EXPLOSION-DIST*))) ((eq 'ast3 enttype) (vec3- entpos (vec3* dirvec *AST3-EXPLOSION-DIST*))) (t (format t "calc-explosion-pos: unknown entity type: ~A~%" enttype) entpos)))) (defun calc-explosion-dims (enttype) (cond ((eq 'ast1 enttype) nil) ((eq 'ast2 enttype) (list *EXPLOSION-AST2-W* *EXPLOSION-AST2-H*)) ((eq 'ast3 enttype) (list *EXPLOSION-AST3-W* *EXPLOSION-AST3-H*)) (t (format t "calc-explosion-dims: unknown entity type: ~A~%" enttype)))) (defun update-explosion (exp elapsedt) (incf (explosiondata-lifetime exp) elapsedt) (when (explosion-needs-next-tex exp) (when (< (explosiondata-texindex exp) (1-(* *EXPBILLSET-SLICES* *EXPBILLSET-STACKS*))) (incf (explosiondata-texindex exp)) (llgs-engine-cl:billboard-settexcoordind *EXPBILLBSET* (explosiondata-billboard exp) (explosiondata-texindex exp)))) (when (<= *EXPLOSION-LIFETIME* (explosiondata-lifetime exp)) ; (format t "update-explosion: end of lifetime~%") (llgs-engine-cl:billboard-remove *EXPBILLBSET* (explosiondata-billboard exp)) (remove-entity exp))) (defun explosion-needs-next-tex (exp) (let ((timeperslice (/ *EXPLOSION-LIFETIME* (* *EXPBILLSET-SLICES* *EXPBILLSET-STACKS*)))) (<= (* (explosiondata-texindex exp) timeperslice) (explosiondata-lifetime exp))))
4,688
Common Lisp
.lisp
106
38.933962
93
0.684926
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
a095fa4c9456a0e858d5a7007806722334fad22116d72343b31f598a90210af4
22,808
[ -1 ]
22,809
tubegame.lisp
kiskami_tubegame/tubegame.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; tubegame.lisp (in-package :cl-user) (unless (find-package :asdf) (require :asdf)) (asdf:oos 'asdf:load-op :llgs-engine-cl) (in-package #:tubegame) (defun disp-name-and-license () (format t "~A~%~A~%~A~%" *GAMELABEL* *COPYRIGHT* *RIGHTS*)) (defun conv-to-int (str) (parse-integer str :junk-allowed t)) (defun parse-cmdargs (args) "Parse command line and return game initialization parameters." (format t "parse-cmdargs: ~A~%" args) (let ((pluginsfile "plugins.cfg") (cfgfile "tubegame.cfg") (logfile "tubegame.log") (rendersys 'opengl) ;'directx) (resfile "resources.cfg") (w 800) (h 600) (fullscreen 0) (help nil) (debug nil) (wp (member "-w" args :test #'equal)) (hp (member "-h" args :test #'equal)) (fp (member "-f" args :test #'equal)) (?p (member "-?" args :test #'equal))) ; (break) (if (and wp (conv-to-int (second wp))) (setf w (conv-to-int (second wp)))) (if (and hp (conv-to-int (second hp))) (setf h (conv-to-int (second hp)))) (if fp (setf fullscreen 1)) (if ?p (setf help t)) (list pluginsfile cfgfile logfile rendersys resfile w h fullscreen help debug))) (defun debugmodep (params) (first (last params))) (defun init-game (params) (let ((indebugmode (debugmodep params))) (format t "Initializing game in ~A mode.~%Params: ~A\%" (if indebugmode "DEBUG" "RELEASE") params) (format t "Loading llgs engine...~A~%" (llgs-engine-cl:load-llgsengine indebugmode)) (format t "Initialize rendering...~A~%" (llgs-engine-cl:render-init (first params) (second params) (third params) (fourth params) (fifth params))) (format t "Creating renderwindow (~Ax~A.~A)...~A~%" (sixth params) (seventh params) (eighth params) (llgs-engine-cl:render-createrenderwindow "tubegame" :w (sixth params) :h (seventh params) :fullscreen (eighth params))) (format t "Creating scenemanager...~A~%" (llgs-engine-cl:render-createscenemanager "INTERIOR" "tubescene")) (format t "Initializing camera and scene...~%") (setq *main-camera* (llgs-engine-cl:render-createcamera "main camera")) (setq *main-camera-node* (llgs-engine-cl:render-createscenenode *MAIN-CAMERA-SCENENODE-NAME*)) (llgs-engine-cl:render-attachmoveable *main-camera-node* *main-camera*) (llgs-engine-cl:render-setscenenodepos *main-camera-node* (first *MAIN-CAMERA-INITIAL-POS*) (second *MAIN-CAMERA-INITIAL-POS*) (third *MAIN-CAMERA-INITIAL-POS*)) (llgs-engine-cl:render-cameralookat *main-camera* (first *MAIN-CAMERA-INITIAL-LOOKAT*) (second *MAIN-CAMERA-INITIAL-LOOKAT*) (third *MAIN-CAMERA-INITIAL-LOOKAT*)) (llgs-engine-cl:render-setcameranearclipdist *main-camera* 0.01) (llgs-engine-cl:render-setcamerafarclipdist *main-camera* 10000.0) (llgs-engine-cl:render-setcameraasviewport *main-camera*) (llgs-engine-cl:render-setviewportbackground 0.5 1.0 0.5) (llgs-engine-cl:render-setambientlight 0.15 0.15 0.15) (llgs-engine-cl:render-setskybox *SKYBOX-MAT*) (let ((light (llgs-engine-cl:render-createlight "mainlight"))) (llgs-engine-cl:render-setlighttype light "POINT") (llgs-engine-cl:render-lightdiffcolor light 0.4 0.4 0.4) (llgs-engine-cl:render-setlightpos light 100.0 -100.0 0.0)) (let ((light (llgs-engine-cl:render-createlight "mainlight2"))) (llgs-engine-cl:render-setlighttype light "POINT") (llgs-engine-cl:render-lightdiffcolor light 0.4 0.4 0.4) (llgs-engine-cl:render-setlightpos light 100.0 100.0 0.0)) )) (defun game-run () "Call this to start and run the game." (disp-name-and-license) (let ((params (parse-cmdargs CCL:*UNPROCESSED-COMMAND-LINE-ARGUMENTS*)) ; not working!? (maintimer nil) ; measuring time between frames (deltatime 0) (fpsdisptime 0)) (when (car (last params 2)) (format t "Command line params: -- [-w <res_width>] [-h <res_height> [-f] [-d] [-?] -- - mandatory separator -w -h - renderwindow resolution - width, height in pixels -f - run on fullscreen -d - debug mode, always on atm -? - this help~%") (return-from game-run)) (init-game params) (format t "Initializing input...~A~%" (llgs-engine-cl:input-init)) (format t "Initializing colldet...~A~%" (llgs-engine-cl:colldet-init)) (setq maintimer (llgs-engine-cl:timer-create)) ; gameloop (loop until *game-should-exit* do (llgs-engine-cl:input-capture) ; simple gamestate :) (if *in-game* (one-game-frame deltatime) (one-startscreen-frame deltatime)) ; render one frame (llgs-engine-cl:render-oneframe) (setq deltatime (/ (llgs-engine-cl:timer-getmicroseconds maintimer) 1000000.0)) (llgs-engine-cl:timer-reset maintimer) (if (llgs-engine-cl:input-keypressed *F11-KEY*) ; screenshot (llgs-engine-cl:render-screenshottofile "tubegame-screenshot-")) (if (llgs-engine-cl:input-keypressed *ESC-KEY*) ; end playing game (setq *game-should-exit* t)) (incf fpsdisptime deltatime) (when (>= fpsdisptime *FPSDISPTIME*) (format t "FPS act: ~A, min: ~A, max: ~A~%Tris: ~A, batches: ~A~%" (llgs-engine-cl:render-actfps) (llgs-engine-cl:render-minfps) (llgs-engine-cl:render-maxfps) (llgs-engine-cl:render-trianglecount) (llgs-engine-cl:render-batchcount)) (setf fpsdisptime 0)))) (format t "Shutdown input...~A~%" (llgs-engine-cl:input-shutdown)) (format t "Shutdown colldet...~A~%" (llgs-engine-cl:colldet-shutdown)) (format t "Shutdown renderer...~A~%" (llgs-engine-cl:render-shutdown)) (llgs-engine-cl:close-llgsengine) (format t "Game end.~%"))
6,455
Common Lisp
.lisp
134
43.962687
103
0.685012
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
17ffd739e2a418aba64e4852924000d75d3138591afd0d2c51a40f0c91f2550c
22,809
[ -1 ]
22,810
game.lisp
kiskami_tubegame/game.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; game.lisp (in-package #:tubegame) (defparameter *GAME-STATE* 'none) (defparameter *LEVEL* nil) (defparameter *PLAYER* nil) (defparameter *colldet-debugdrawer-time* 1.5) (defparameter *colldet-debugdrawer-enabled* nil) (defparameter *colldet-time* 0) (defparameter *flymode-switch-time* 1.5) (defun toggle-debugdrawer () (when (<= *COLLDET-DEBUGDRAWER-TIMEOUT* *colldet-debugdrawer-time*) (setq *colldet-debugdrawer-time* 0) (setq *colldet-debugdrawer-enabled* (not *colldet-debugdrawer-enabled*)) (format t "Setting physics debugdraw to ~A~%" *colldet-debugdrawer-enabled*) (llgs-engine-cl:colldet-setdebugdrawmode (if *colldet-debugdrawer-enabled* 10 0)))) (defun toggle-flymode (player) (when (<= *FLYMODE-SWITCH-TIMEOUT* *flymode-switch-time*) (setq *flymode-switch-time* 0) ; (format t "Switching fly mode.~%") (player-toggle-flymode player))) (defun one-game-frame (elapsedt) "Update state and render one game playing frame." (cond ((equal *GAME-STATE* 'none) ; first time or a new try? (setf *ENTITIES* nil) (setf *PHYSOBJMAP* (make-hash-table)) (if (not *LEVEL*) (setq *LEVEL* (load-level1)) (reset-level *LEVEL*)) (if (not *PLAYER*) (setq *PLAYER* (load-player *LEVEL*)) (reset-player *PLAYER* *LEVEL*)) (if (not *EXPBILLBSET*) (init-explosions (playerdata-node *PLAYER*)) (reset-explosions)) (show-level-and-player *LEVEL* *PLAYER*) (setq *GAME-STATE* 'loaded) ) (t ;running ; ESC pressed? (if (llgs-engine-cl:input-keypressed *ESC-KEY*) ; end playing game (end-game *LEVEL*) (when (< 0 elapsedt) ; input (incf *colldet-debugdrawer-time* elapsedt) (if (llgs-engine-cl:input-keypressed *F12-KEY*) (toggle-debugdrawer)) (incf *flymode-switch-time* elapsedt) (if (llgs-engine-cl:input-keypressed *F10-KEY*) (toggle-flymode *PLAYER*)) ; move player (if (llgs-engine-cl:input-keypressed *W-KEY*) (player-forward *PLAYER*)) (if (llgs-engine-cl:input-keypressed *S-KEY*) (player-backward *PLAYER*)) (let ((relx (llgs-engine-cl:input-mouserelx)) (rely (llgs-engine-cl:input-mouserely))) (cond ((< 0 relx) (player-rightturn *PLAYER* relx)) ((>= 0 relx) (player-leftturn *PLAYER* relx))) (cond ((< 0 rely) (player-downturn *PLAYER* rely)) ((>= 0 rely) (player-upturn *PLAYER* rely)))) ; fire (if (llgs-engine-cl:input-leftmousebutton) (player-fire *PLAYER* elapsedt)) (incf *colldet-time* elapsedt) ; perform colldet and entity update (when (>= *colldet-time* *COLLDET-TIMEOUT*) (setf *colldet-time* 0) (player-reset-collinfo *PLAYER*) (let ((collnum (llgs-engine-cl:colldet-perform))) (when (< 0 collnum) ; (format t "There are ~A collisions atm.~%" collnum) ; update entities (and player) on colldet (dotimes (i collnum) (let* ((collpair (llgs-engine-cl:colldet-getcollpair i)) (entA (get-from-physobjmap (car collpair))) (entB (get-from-physobjmap (cdr collpair)))) (if entA (funcall (entitydata-collfunc entA) entA entB)) (if entB (funcall (entitydata-collfunc entB) entB entA))))))) (clean-colldet-trash) ; update entities (and player) (map nil #'(lambda (e) (funcall (entitydata-updatefunc e) e elapsedt)) *ENTITIES*) ))))) (defun load-level1 () "Read in level data file and create leveldata structure with initial values." (format t "Loading level1...~%") (let ((level (make-leveldata))) (with-open-file (l *LEVEL1-FILE* :direction :input :if-does-not-exist :error) (setf (leveldata-levelfile level) (read l))) (setf (leveldata-levelpointmargin level) (first (third (leveldata-levelfile level)))) (setf (leveldata-playerstructintegritystart level) (second (third (leveldata-levelfile level)))) (setf (leveldata-playerweaponenergystart level) (third (third (leveldata-levelfile level)))) (setf (leveldata-playershieldenergystart level) (fourth (third (leveldata-levelfile level)))) level)) (defun end-game (level) (hide-level-and-player level) (setq *GAME-STATE* 'none) (setq *in-game* nil)) (defun show-level-and-player (level player) (show-level level) (show-player player *main-camera-node* level)) (defun dimX (level) (first (first level))) (defun dimY (level) (second (first level))) (defun dimZ (level) (third (first level))) (defun show-level (level) "Process level data and create entities and scene objects." (let ((l (leveldata-levelfile level))) (loop for y from 0 to (1- (dimY l)) do (leveldata-yplane level y (dimZ l) (dimX l) (nth y (second l)))))) (defun leveldata-yplane (level y dimz dimx ypl) (loop for z from 0 to (1- dimz) do (leveldata-row level y z dimx (nth z ypl)))) (defun leveldata-row (level y z dimx row) (loop for x from 0 to (1- dimx) do ; (format t "leveldata-row: ~A ~A ~A ~A~%" x y z (nth x row)) (apply #'apply-rowdata level x y z (nth x row)))) (defun apply-rowdata (level x y z &optional cube &key (rotx 0) (roty 0) (rotz 0) sta cel (ast1 0) (ast2 0) (ast3 0) (ss 0) (pa 0) (wea 0) (spe 0) (tur 0) (ene 0)) "Create game entities within 1 cube and add them to scene." (when cube (add-entity (create-cube x y z cube rotx roty rotz)) (when sta (add-entity (create-startpoint x y z)) (let ((pos (calc-cube-pos (adjust-float x) (adjust-float y) (adjust-float z)))) (pushnew pos (leveldata-startposlist level)) (format t "Registered startpoint at ~A~%" pos))) (if cel (add-entity (create-endpoint x y z))) (if (> ast1 0) (add-entity (create-asteroid x y z 'ast1 ast1))) (if (> ast2 0) (add-entity (create-asteroid x y z 'ast2 ast2))) (if (> ast3 0) (add-entity (create-asteroid x y z 'ast3 ast3))) (if (> ss 0) (add-entity (create-strinteg-powerup x y z ss))) (if (> pa 0) (add-entity (create-shield-powerup x y z pa))) (if (> wea 0) (add-entity (create-weapon-powerup x y z wea))) (if (> spe 0) (add-entity (create-speed-powerup x y z spe))) (if (> tur 0) (add-entity (create-turret x y z tur))) (if (> ene 0) (add-entity (create-enemy x y z ene))))) (defun hide-level (level) (declare (ignore level)) nil) (defun hide-level-and-player (level) (hide-player *PLAYER* *main-camera-node*) (hide-level level)) (defun reset-level (level) (declare (ignore level)) nil) (defun create-cube (x y z cube rotx roty rotz) "Create cube mesh and scenenode, position it and rotate around its local x, then y, then z axis." ; (format t "Creating cube ~A at(~A,~A,~A), rot(~A,~A,~A)~%" cube x y z rotx roty rotz) (let* ((pos (calc-cube-pos (adjust-float x) (adjust-float y) (adjust-float z))) (mesh (llgs-engine-cl:mesh-load (gen-name "cube" cube x y z) (get-cube-meshfile-name cube))) (node (llgs-engine-cl:render-createscenenode (gen-name "cube" x y z))) (cubeent (make-entitydata :type 'cube :mesh mesh :node node :physobj (llgs-engine-cl:colldet-addmeshgeom (first pos) (second pos) (third pos) mesh *CUBE-PHYS-GRP* *CUBE-PHYS-MASK*) :updatefunc #'update-null :collfunc #'colldet-null))) (llgs-engine-cl:render-attachmoveable node mesh) (llgs-engine-cl:render-addchild (llgs-engine-cl:render-rootscenenode) node) (llgs-engine-cl:render-setscenenodepos node (first pos) (second pos) (third pos)) ; (llgs-engine-cl:render-setscenenodescale node 0.5 0.5 0.5) (if (and rotx (> rotx 0)) (llgs-engine-cl:render-rotatescenenodex node (adjust-float (deg-to-rad rotx)))) (if (and roty (> roty 0)) (llgs-engine-cl:render-rotatescenenodey node (adjust-float (deg-to-rad roty)))) (if (and rotz (> rotz 0)) (llgs-engine-cl:render-rotatescenenodez node (adjust-float (deg-to-rad rotz)))) (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj cubeent) (entitydata-node cubeent)) (add-to-physobjmap (entitydata-physobj cubeent) cubeent) cubeent)) (defun update-null (e elapsedt) "No op update function for cubes." (declare (ignore e elapsedt))) (defun colldet-null (cube otherobj) "No op colldet function for cubes." (declare (ignore cube otherobj))) (defun get-cube-meshfile-name (cube) (cond ((= cube 1) *CUBE1-MESH*) ((= cube 2) *CUBE2-MESH*) ((= cube -2) *CUBE-2-MESH*) ((= cube 3) *CUBE3-MESH*) ((= cube -3) *CUBE-3-MESH*) ((= cube 4) *CUBE4-MESH*) ((= cube -4) *CUBE-4-MESH*) ((= cube 5) *CUBE5-MESH*) ((= cube 6) *CUBE6-MESH*) (t *CUBE1-MESH*))) (defun calc-cube-pos (x y z) (list (* 2 x) (* 2 y) (* 2 z))) (defun create-startpoint (x y z) (declare (ignore x y z)) nil) (defun create-endpoint (x y z) (let* ((pos (calc-cube-pos (adjust-float x) (adjust-float y) (adjust-float z))) (mesh (llgs-engine-cl:mesh-load (gen-name "cel" x y z) *CEL-MESH*)) (node (llgs-engine-cl:render-createscenenode (gen-name "cel" x y z))) (celent (make-entitydata :type 'cel :mesh mesh :node node :physobj (llgs-engine-cl:colldet-addcylinder (first pos) (second pos) (third pos) *CELCIL-HALFEXT1* *CELCIL-HALFEXT2* *CELCIL-HALFEXT3* *CEL-PHYS-GRP* *CEL-PHYS-MASK*) :updatefunc #'cel-update :collfunc #'cel-colldet))) (llgs-engine-cl:render-attachmoveable node mesh) (llgs-engine-cl:render-addchild (llgs-engine-cl:render-rootscenenode) node) (llgs-engine-cl:render-setscenenodepos node (first pos) (second pos) (third pos)) (llgs-engine-cl:render-setscenenodescale node (first *CELNODE-SCALE*) (second *CELNODE-SCALE*) (third *CELNODE-SCALE*)) (llgs-engine-cl:render-rotatescenenodez node (adjust-float (/ pi 2))) (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj celent) (entitydata-node celent)) (add-to-physobjmap (entitydata-physobj celent) celent) celent)) (defun create-strinteg-powerup (x y z ss) (declare (ignore x y z ss)) nil) (defun create-shield-powerup (x y z pa) (declare (ignore x y z pa)) nil) (defun create-weapon-powerup (x y z wea) (declare (ignore x y z wea)) nil) (defun create-speed-powerup (x y z spe) (declare (ignore x y z spe)) nil) (defun create-turret (x y z tur) (declare (ignore x y z tur)) nil) (defun create-enemy (x y z ene) (declare (ignore x y z ene)) nil) (defun cel-colldet (cel otherobj) (declare (ignore cel)) ; (format t "cel-colldet: collision with ~A~%" otherobj) (game-over otherobj)) (defun cel-update (e elapsedt) (when (< 0 elapsedt) (llgs-engine-cl:render-rotatescenenodey (entitydata-node e) (* *CEL-ROT-SPEED* elapsedt)) ; (llgs-engine-cl:colldet-syncolobjtoscenenode (entitydata-physobj e) ; (entitydata-node e)) ))
11,970
Common Lisp
.lisp
273
38.347985
110
0.654393
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
b21a725e92d52599d39ebd4e9a342c557cff04f44793609b16b0b9b35d946187
22,810
[ -1 ]
22,811
startdest.lisp
kiskami_tubegame/startdest.lisp
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; startdest.lisp (in-package #:tubegame)
889
Common Lisp
.lisp
19
44.526316
79
0.713134
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
c2eb68d90c22197d0ac53d43a779056069de3515cd56ce38e47ef3162d615644
22,811
[ -1 ]
22,812
tubegame.asd
kiskami_tubegame/tubegame.asd
;;;; tubegame ;;;; Copyright (c) 2013 Kalman Kiss, Zalaegerszeg Hungary ;;;; ;;;; This program is free software; you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation; either version 2 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This program 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this program; if not, write to the Free Software ;;;; Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ;;;; ;;;; tubegame.asd (asdf:defsystem #:tubegame ; :serial t :description "tubegame is a simple game using llgs-engine-cl interface" :author "Kalman Kiss <[email protected]>" :version "0.0.1" :license "GPL2" :depends-on (#:llgs-engine-cl) :components ((:file "package") (:file "globals" :depends-on ("package")) (:file "utils" :depends-on ("globals")) (:file "startdest" :depends-on ("package" "globals")) (:file "explosion" :depends-on ("package" "globals" "utils")) (:file "asteroid" :depends-on ("package" "globals" "utils" "explosion")) (:file "bullet" :depends-on ("package" "globals" "utils")) (:file "player" :depends-on ("package" "globals" "utils" "bullet" "explosion")) (:file "game" :depends-on ("package" "globals" "utils" "player" "startdest" "asteroid" "explosion")) (:file "startscreen" :depends-on ("package")) (:file "tubegame" :depends-on ("package" "globals" "game" "startscreen"))))
1,891
Common Lisp
.asd
42
40.02381
90
0.649351
kiskami/tubegame
2
0
0
GPL-2.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
d1981eefe7d7bdae78390df4ae2052b55d2475b1879c2d8e3edf881067fa4746
22,812
[ -1 ]
22,840
strings.lisp
TralahM_trtek/src/strings.lisp
(in-package :trtek) (defun chars (str) (loop for c across str collect c))
75
Common Lisp
.lisp
2
36
53
0.722222
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
328b6df1c690c7b0f1d7b16e04e9878a44be65d38de5d6f99d32a2a7248d93ec
22,840
[ -1 ]
22,841
utils.lisp
TralahM_trtek/src/utils.lisp
(in-package :trtek) (defvar *epsilon* 1.0e-6) (defun chars (str) "Get a list of all the characters in a string." (loop for c across str collect c)) ; (chars "Get a list of all the characters in a string.") (defun approx-equal (x y &optional (*epsilon* *epsilon*)) "Check whether x and y are approximately equal. Useful for floating point numbers." (or (= x y) (< (/ (abs (- x y)) (max (abs x) (abs y))) *epsilon*))) (defun fact (x) (if (= x 0) 1 (* x (fact (- x 1))))) ;; (fact 6) => 720 (defun choose (n r) (/ (fact n) (fact (- n r)) (fact r))) ;; (choose 4 2) => 6 ;; (choose 6 2) => 15 (defun deg-to-rad (deg) "Convert `deg` degrees to radians" (* deg pi 1/180)) ;; (deg-to-rad 180) => 3.141592653589793d0 ;; (deg-to-rad 90) => 1.5707963267948966d0 ;; (deg-to-rad 45) => 0.7853981633974483d0 (defun rad-to-deg (rad) "Convert `rad` radians to degrees" (* rad (/ 180 pi))) ;; (rad-to-deg pi) => 180.0d0 ;; (rad-to-deg (* pi 2)) => 360.0d0 ;; (rad-to-deg (* pi .5)) => 90.0d0 (defun cos-deg (angle) "Cosine of `angle` in Degrees" (cos (deg-to-rad angle))) ;; (cos-deg 60) => 0.5 ;; (cos-deg 90) => 0.0 ;; (cos-deg 30) => 0.866 ;; (cos-deg 0) => 1.0d0 ;; (cos-deg 45) => 0.7071 (defun acos-deg (x) "Arc-Cosine of `x` in Degrees" (rad-to-deg (acos x))) ;; (acos-deg .5) => 60.0 ;; (acos-deg 0) => 90.0 ;; (acos-deg 1) => 0.0d0 ;; (acos-deg -1) => 180.0 (defun sin-deg (angle) "Sine of `angle` in Degrees" (sin (deg-to-rad angle))) ;; (sin-deg 60) => 0.866 ;; (sin-deg 90) => 1.0d0 ;; (sin-deg 30) => 0.5 ;; (sin-deg 0) => 0.0d0 ;; (sin-deg 45) => 0.7071 (defun asin-deg (x) "Arc-Sine of `x` in Degrees" (rad-to-deg (asin x))) ;; (asin-deg .5) => 30.0 ;; (asin-deg 0) => 0.0d0 ;; (asin-deg 1) => 90.0 ;; (asin-deg -1) => -90.0 (defun tan-deg (angle) "Tangent of `angle` in Degrees" (tan (deg-to-rad angle))) ;; (tan-deg 45) => 1 ;; (tan-deg 60) => 1.732 ;; (tan-deg 30) => 0.577 (defun atan-deg (x) "Arc-Tangent of `x` in Degrees" (rad-to-deg (atan x))) ;; (atan-deg .5) => 26.5651 ;; (atan-deg 0) => 0.0d0 ;; (atan-deg 1.0) => 45.0 ; (defun lrec (rec &optional base) ; "Function to define flat list recursers. ; The first argument to lrec must be a function of two arguments, ; the current car of the list,and a function which can be called to continue the ; recursion." ; (labels ((self (lst) ; (if (null lst) ; (if (functionp base) ; (funcall base) ; base) ; (funcall rec (car lst) ; #'(lambda () (self (cdr lst))))))) ; #'self)) ;; Using lrec we coul express our-length as: ;; (funcall (lrec #'(lambda (x f) (1+ (funcall f))) 0) '(1 2 3 4 5 6 7)) ;; Or Our-every as: ;; (funcall (lrec #'(lambda (x f) (and (oddp x) (funcall f))) t) '(1 2 3 4 5 6 7 8)) ;; (funcall (lrec #'(lambda (x f) (and (oddp x) (funcall f))) t) '(1 3 5 7 9)) ;; Functions Built Using Lrec ;;;; copy-list ; (lrec #'(lambda (x f) (cons x (funcall f)))) ;;remove-duplicates ; (lrec #'(lambda (x f) (adjoin x (funcall f)))) ;; find-if for some function fn ; (lrec #'(lambda (x f) (if (fn x) x (funcall f)))) ;;some, for some function fn ; (lrec #'(lambda (x f) (or (fn x) (funcall f)))) (defun rfind-if (fn tree) "Recursive version of find-if which works on trees as well as flat lists." (if (atom tree) (and (funcall fn tree) tree) (or (rfind-if fn (car tree)) (if (cdr tree) (rfind-if fn (cdr tree)))))) ;; (rfind-if #'oddp '(2 (3 4) 5)) ;;Function for recursion on trees ;; tree traverser to build a wider range of tree recursive functions (defun ttrav (rec &optional (base #'identity)) (labels ((self (tree) (if (atom tree) (if (functionp base) (funcall base tree) base) (funcall rec (self (car tree)) (if (cdr tree) (self (cdr tree))))))) #'self)) ;; Functions built with ttrav always traverse a whole tree. ;; our-copy-tree ;; (ttrav #'cons) ;; count-leaves ;; (ttrav #'(lambda (l r) (+ 1 (or r 1))) 1) ;; flatten ;; (ttrav #'nconc #'mklist) (defun trec (rec &optional (base #'identity)) "General function trec which taakes three objects: the currect object and two recursers which are closures representing recursions down the left and right subtrees." (labels ((self (tree) (if (atom tree) (if (functionp base) (funcall base tree) base) (funcall rec tree #'(lambda () (self (car tree))) #'(lambda () (if (cdr tree) (self (cdr tree)))))))))) ; Expressing functions by calls to constructors instead of sharp-quoted lambdaexpressions could, unfortunately, entail unnecessary work at runtime. A sharpquoted lambda-expression is a constant, but a call to a constructor function will be ; evaluated at runtime. If we really have to make this call at runtime, it might not ; be worth using constructor functions. However, at least some of the time we can ; call the constructor beforehand. By using #., the sharp-dot read macro, we can ; have the new functions built at read-time. So long as compose and its arguments ; are defined when this expression is read, we could say, for example, ;; (find-if #.(compose #’oddp #’truncate) lst) ; Then the call to compose would be evaluated by the reader, and the resulting ; function inserted as a constant into our code. Since both oddp and truncate are ; built-in, it would safe to assume that we can evaluate the compose at read-time, ; so long as compose itself were already loaded. ; In general, composing and combining functions is more easily and efficiently ; done with macros. This is particularly true in Common Lisp, with its separate ; name-space for functions.
5,936
Common Lisp
.lisp
154
34.811688
239
0.610403
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
905588c06a11b9723a2ffbc046a5fc1f0d62b4e6549b90f0f40611a32dc17033
22,841
[ -1 ]
22,842
main.lisp
TralahM_trtek/src/main.lisp
; Author: Tralah M Brian ; ; Copyright © 2020 Tralah M Brian ; Permission is hereby granted, free of charge, to any person obtaining ; a copy of this software and associated documentation files (the "Software"), ; to deal in the Software without restriction, including without limitation ; the rights to use, copy, modify, merge, publish, distribute, sublicense, ; and/or sell copies of the Software, and to permit persons to whom the ; Software is furnished to do so, subject to the following conditions: ; The above copyright notice and this permission notice shall be included ; in all copies or substantial portions of the Software. ; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES ; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. ; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, ; DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, ; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE ; OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (in-package :trtek) (defun package-internal-symbols (package) (let ((rslt nil)) (do-symbols (s package) (when (eq (second (multiple-value-list (find-symbol (symbol-name s) package))) :internal) (push s rslt))) rslt)) ;; (package-internal-symbols :trtek) (defun package-external-symbols (package) (let ((rslt nil)) (do-symbols (s package) (when (eq (second (multiple-value-list (find-symbol (symbol-name s) package))) :external) (push s rslt))) rslt)) ;; (package-external-symbols :trtek) (defun sigmoid (x) "The sigmoid function " (/ 1.0 (+ 1.0 (exp (- x))))) ;; (sigmoid 2) ;; (sigmoid 1) ;; (sigmoid 0) ;; (sigmoid 0.25) ;; (sigmoid (/ 22.0 7)) (defun sigmoid* (x) "Integral of the sigmoid function " (let ((temp (sigmoid x))) (* temp (- 1.0 temp)))) ;; (sigmoid* 2) ;; (sigmoid* 1) ;; (sigmoid* 0) ;; (sigmoid* (/ 22.0 7)) ;; (sigmoid* 0.625) ;; (sigmoid* (sigmoid 2)) ;; (sigmoid (sigmoid* 2)) ;; (sigmoid* (sigmoid 0)) ;; (sigmoid (sigmoid* 0)) (defun cmplmnt (fn) "complement of a function `fn' i.e not fn" #'(lambda (&rest args) (not (apply fn args)))) ;; (remove-if (cmplmnt #'oddp) '(1 2 3 4 5 6)) ;=> (1 3 5) ;; (remove-if (cmplmnt #'evenp) '(1 2 3 4 5 6)) ;=> (2 4 6) ;; ; # Returning Destructive Elements ;; (defvar *!equivs* (make-hash-table)) ;; (defun ! (fn) ;; (or (gethash fn *!equivs*) fn)) ;; (defun def! (fn fn!) ;; (setf (gethash fn *!equivs*) fn!)) ;; (def! #'remove-if #'delete-if) ;; instead of (delete-if #'oddp lst) ;; we would say (funcall (! #'remove-if) #'oddp lst) ;Memoizing utility (defun memoize (fn) "Memoizing utility for expensive function calls" (let ((cache (make-hash-table :test #'equal))) #'(lambda (&rest args) (multiple-value-bind (val win) (gethash args cache) (if win val (setf (gethash args cache) (apply fn args))))))) ;; (defvar slowid nil) ;; (setq slowid (memoize #'(lambda (x) (sleep 5) x))) ;; (time (funcall slowid 1));; 5.15 seconds ;; (time (funcall slowid 1));; 0.00 seconds ;; Composing Functions (defun compose (&rest fns) "Composing Functions takes a list of functions and returns a composed function in order of specification" (if fns (let ((fn1 (car (last fns))) (fns (butlast fns))) #'(lambda (&rest args) (reduce #'funcall fns :from-end t :initial-value (apply fn1 args)))) #'identity)) ;; eg (compose #'list #'1+) returns a fx equivalent to #'(lambda (x) (list (1+ x))) ;; (funcall (compose #'1+ #'find-if) #'oddp '(2 3 4)) ;==> 4 ; More function builders (defun fif (if then &optional else) #'(lambda (x) (if (funcall if x) (funcall then x) (if else (funcall else x))))) ;;(funcall (fif #'(lambda (x) (evenp x)) #'print #'(lambda (x) (format t "~a is not divisible by 2 ~%" x))) 3) ;;(funcall (fif #'(lambda (x) (evenp x)) #'(lambda (x) (format t "~a is divisible by 2" x) ) #'(lambda (x) (format t "~a is not divisible by 2 ~%" x))) 8) (defun fint (fn &rest fns) "Function Intersection for cases where we want an intersection of some n `fns' predicates: Instead of (find-if #'(lambda (x) (and (signed x) (sealed x) (delivered x))) docs) we can say: (find-if (fint #'signed #'sealed #'delivered) docs)" fn (let ((chain (apply #'fint fns))) #'(lambda (x) (and (funcall fn x) (funcall chain x)))) ) (defun fun (fn &rest fns) "Function union similar to `fint` except it uses or instead of and." (if (null fns) fn) (let ((chain (apply #'fun fns))) #'(lambda (x) (or (funcall fn x) (funcall chain x))))) ;;For the case where you want users to be able to type in expressions without ;;parenthenses; it reads a line of input and returns it as a list (defun readlist (&rest args) (values (read-from-string (concatenate 'string "(" (apply #'read-line args) ")")))) ;; (readlist) ;;; call me "Ed" ;;;=> (CALL ME "Ed") ;; The function prompt combines printing a question and reading the answer.It ;; takes the arguments of format,except the initial stream argument (defun prompt (&rest args) "The function prompt combines printing a question and reading the answer.It takes the arguments of format,except the initial stream argument " (apply #'format *query-io* args) (read *query-io*)) ;; (prompt "Enter a number between ~A and ~A. ~%>> " 1 10) ;;;>>> 3 ;;; => 3 ;; break-loop is for situations where you want to imitate the Lisp toplevel. ;;It takes 2 functions and an &rest argument,which is repeatedly given to ;;prompt. As long as the second function returns false for the input, the first ;;function is aplied to it (defun break-loop (fn quit &rest args) (format *query-io* "Entering break-loop ~%") (loop (let ((in (apply #'prompt args))) (if (funcall quit in) (return) (format *query-io* "~A~%" (funcall fn in)))))) ; (break-loop #'eval #'(lambda (x) (eq x :q)) ">> ") ;;=> Entering break-loop. ;;;>> (+ 2 3) ;;;=> 5 ;;; >> :q ;;;=> :Q ; Utility Functions for Operations on Lists ; Small Functions which operate on lists (proclaim '(inline last1 single append1 conc1 mklist)) ;; last element in a list (defun last1 (lst) "get last element in a list `lst'" (car (last lst))) ;;;; (last '(1 2 3 4)) ;;;; (last1 '(1 2 3 4)) ;; test whether lst is a list of one element (defun single (lst) "test whether `lst' is a list of one element" (and (consp lst) (not (cdr lst)))) ;;;; (single '(1 2 3 4)) ;;;; (single '(1)) ;; attach a new element to end of a list non-destructively (defun append1 (lst obj) "attach a new element `obj' to end of a list `lst' non-destructively" (append lst (list obj))) ;; attach a new element to end of a list destructively (defun conc1 (lst obj) "attach a new element `obj' to end of a list `lst' destructively" (nconc lst (list obj))) ;; Ensure obj is a list (defun mklist (obj) "Ensure `obj' is a list" (if (listp obj) obj (list obj))) ;;;; (mklist '(1 2));;==> (1 2) ;;;; (mklist '12) ;;==> (12) ; Longer Functions That Operate on Lists ;; Check whether a list x is longer than a list y (defun longer (x y) "Check whether a list `x' is longer than a list `y'" (labels ((compare (x y) (and (consp x) (or (null y) (compare (cdr x) (cdr y)))))) (if (and (listp x) (listp y)) (compare x y) (> (length x) (length y))))) ;;;; (longer '(1 2 3 45) '(1 5)) ;; ==> T ;;;; (longer '(1 2 3 45) '(1 5 4 5 6 7)) ;; ==> NIL ;; Apply filter function fn to list lst (defun filter (fn lst) "Apply filter function `fn' to list `lst'" (let ((acc nil)) (dolist (x lst) (let ((val (funcall fn x))) (if val (push val acc)))) (nreverse acc))) ;;;; (filter #'(lambda (x) (if (evenp x) x)) '(1 2 3 4 5 6 7 8)) ;;;; (filter #'(lambda (x) (if (oddp x) x)) '(1 2 3 4 5 6 7 8)) ;;;; (filter #'oddp '(1 2 3 4 5 6 7 8)) ;; Groups List into Sublists of Length n, remainder stored in last sublist (defun group (source n) "Groups List `source' into Sublists of Length `n', remainder stored in a last sublist" (if (zerop n) (error "Zero length")) (labels ((rec (source acc) (let ((rest (nthcdr n source))) (if (consp rest) (rec rest (cons (subseq source 0 n) acc)) (nreverse (cons source acc)))))) (if source (rec source nil) nil))) ;;;; (group '(1 2 3 4 5 6 7 8) 2) ;;;; (group '(1 2 3 4 5 6 7 8) 3) ;;;; (group '(1 2 3 4 5 6 7 8) 8) ;;;; (group '(1 2 3 4 5 6 7 8) 9) ;;;; (group '(0 1 2 3 4 5 6 7 8) 2) ;;;; (group '(0 1 2 3 4 5 6 7 8) 1) ;;;; (group '() 2) ; Doubly Recursive List Utilities ;; Flatten List lst with Nested Lists (defun flatten (x) "Flatten List `x' with Nested Lists" (labels ((rec (x acc) (cond ((null x) acc) ((atom x) (cons x acc)) (t (rec (car x) (rec (cdr x) acc)))))) (rec x nil))) ;;;; (flatten '(1 2 3 (4 6 (8 9 12 (32 11) 39) 7) 19)) ;;;; (flatten '(1 2 3 4 6 (8 9 12 (32 11 39) 7) 19)) ;;;; (flatten '(1 2 3 4 6 8 9 12 (32 11 39 7) 19)) ;;;; (flatten '(1 2 3 4 6 8 9 12 32 11 39 7 19)) ;; Prune List with Nested Lists using the function test (defun prune (test tree) "Prune List `tree' with Nested Lists using the function `test'" (labels ((rec (tree acc) (cond ((null tree) (nreverse acc)) ((consp (car tree)) (rec (cdr tree) (cons (rec (car tree) nil) acc))) (t (rec (cdr tree) (if (funcall test (car tree)) acc (cons (car tree) acc))))))) (rec tree nil))) ;;;; (prune #'oddp '(1 2 3 (4 6 (8 9 12 (32 11) 39) 7) 19)) ;;;; (prune #'evenp '(1 2 3 (4 6 (8 9 12 (32 11) 39) 7) 19)) ;; Another widely used class of Lisp functions are the mapping functions which ;; apply a function to a sequence of arguments. ;; both map0-n and map1-n are written using the general form mapa-b, which works ;; for any range of numbers and not only for ranges of positive integers (defun mapa-b (fn a b &optional (step 1)) "mapa-b, mapping function which ;; applies a function to a sequence of arguments and works for any range of numbers and not only for ranges of positive integers" (do ((i a (+ i step)) (result nil)) ((> i b) (nreverse result)) (push (funcall fn i) result))) ;; (mapa-b #'1+ -2 0 .5);====> (-1 -0.5 0.0 0.5 1.0) ;; (mapa-b #'(lambda (x) (sin x)) (* -1 (/ 22.0 7)) (/ 22.0 7) .5);====> (-1 -0.5 0.0 0.5 1.0) (defun map0-n (fn n) (mapa-b fn 0 n)) (defun map1-n (fn n) (mapa-b fn 1 n)) ;; (mapcar #'+ '(1 2 3) '(4 5 6)) ;; (mapcar #'+ '(1 2 3) '(4 5 6) '(7 8 9)) ;; (mapcar #'+ '(1 2 3 4) '(4 5 6 11) '(7 8 9 0)) ;; (map0-n #'1+ 5); ===> (1 2 3 4 5 6) ;; (map1-n #'1+ 5); ===> (2 3 4 5 6) ; (expt 3 2) ; (map1-n #'(lambda (x) x) 5); ===> (1 2 3 4 5) ;; (map1-n #'(lambda (x) (* x x)) 5); ===> (1 4 9 16 25) (defun map-> (fn start test-fn succ-fn) (do ((i start (funcall succ-fn i)) (result nil)) ((funcall test-fn i) (nreverse result)) (push (funcall fn i) result))) (defun mappend (fn &rest lsts) (apply #'append (apply #'mapcar fn lsts))) ;; The utility mapcars is for cases where we want to mapcar a function over ;; several lists. If we have two lists of numbers and we want to get a single ;; list of the square roots of both we could say in raw lisp (mapcar #'sqrt ;; (append list1 list2)) or using mapcars (defun mapcars (fn &rest lsts) "The utility mapcars is for cases where we want to mapcar a function over several lists. " (let ((result nil)) (dolist (lst lsts) (dolist (obj lst) (push (funcall fn obj) result))) (nreverse result))) ;; (mapcars #'sqrt '(1 2 4 6 7 9) '( 25 81 625 225)) ;; (mapcars #'log '(1 2 4 6 7 9 10) '( 25 81 625 225)) ;; Recursive mapcar a version of mapcar for trees and does what mapcar does on ;; flat lists, it does on trees (defun rmapcar (fn &rest args) "Recursive mapcar a version of mapcar for trees and does what mapcar does on flat lists, it does on trees" (if (some #'atom args) (apply fn args) (apply #'mapcar #'(lambda (&rest args) (apply #'rmapcar fn args)) args))) ;; (rmapcar #'sqrt '(1 2 4 6 7 9 ( 25 81 625 225))) ; Functions which search lists (defun find2 (fn lst) (if (null lst) nil (let ((val (funcall fn (car lst)))) (if val (values (car lst) val) (find2 fn (cdr lst)))))) (defun before (x y lst &key (test #'eql)) (and lst (let ((first (car lst))) (cond ((funcall test y first) nil) ((funcall test x first) lst) (t (before x y (cdr lst) :test test)))))) ;;; (before 'a 'b '(a)) ; ==> (A) ;;; (before 'c 'd '(a b c d)) ; ==> (C D) ;;; (before 'b 'a '(b a b a b d)); ==> (B A B A B D) (defun after (x y lst &key (test #'eql)) (let ((rest (before y x lst :test test))) (and rest (member x rest :test test)))) ;;; (after 'a 'b '(b a d)); ==> (A D) ;;; (after 'a 'b '(b a b a d)); ==> (A B A D) ;;; (after 'a 'b '(a b c)) ; ==> NIL ;; Check whether list lst contains duplicate obj using some test default ;; equality (defun duplicate (obj lst &key (test #'eql)) (member obj (cdr (member obj lst :test test)) :test test)) ;;; (duplicate 'a '(a b c a d)) ;==> (A D) ;;; (duplicate 'b '(a b c a b c a b d)) ;==> (A D) (defun split-if (fn lst) (let ((acc nil)) (do ((src lst (cdr src))) ((or (null src) (funcall fn (car src))) (values (nreverse acc) src)) (push (car src) acc)))) ;;; (split-if #'(lambda (x) (> x 4)) '(1 2 3 4 5 6 7 8 9 10)) ;;; (split-if #'(lambda (x) (> x 4)) '(1 4 5 6 7 8 9 10 2 3)) ;;; => (1 2 3 4) ;;; => (5 6 7 8 9 10) ; Search Functions which compare elements (defun most (fn lst) (if (null lst) (values nil nil) (let* ((wins (car lst)) (max (funcall fn wins))) (dolist (obj (cdr lst)) (let ((score (funcall fn obj))) (when (> score max) (setq wins obj max score)))) (values wins max)))) ; (most #'length '((a b) (a b c) (a) (e f g))) ;==> (A B C) ;===> 3 (defun best (fn lst) (if (null lst) nil (let ((wins (car lst))) (dolist (obj (cdr lst)) (if (funcall fn obj wins) (setq wins obj))) wins))) ; (best #'> '(1 2 3 4 5)) ; ==> 5 ; (best #'< '(1 2 3 4 5)) ; ==> 1 (defun mostn (fn lst) (if (null lst) (values nil nil) (let ((result (list (car lst))) (max (funcall fn (car lst)))) (dolist (obj (cdr lst)) (let ((score (funcall fn obj))) (cond ((> score max) (setq max score result (list obj))) ((= score max) (push obj result))))) (values (nreverse result) max)))) ; (mostn #'length '((ab) (a b c) (a) (e f g))) ;==>((A B C) (E F G)) ; ==> 3 ;Functions which operate on symbols and strings ; Symbols and strings are closely related.By means of priinting and reading ; functions we can go back and forth between the two representation. ;; The first,mkstr takes any number of arguments and concatenates their printed ;; representations into a string: ;;; Built upon symb (defun mkstr (&rest args) "mkstr takes any number of arguments and concatenates their printed representations into a string" (with-output-to-string (s) (dolist (a args) (princ a s)))) ; (mkstr pi " pieces of " 'pi) ;===> "3.141592653589793 pieces of PI" (defun symb (&rest args) (values (intern (apply #'mkstr args)))) ;;;; (symb pi 'mkstr) ;;;; (symb '(1 2 3 4) '2 '678) ;; Generalization of symb it takes a series of objects,prints and rereads them. ;; it can return symbols like symb,but it can also return anything else read can (defun reread (&rest args) (values (read-from-string (apply #'mkstr args)))) ;;;; (reread '(1 2 3 4) '2 '678) ;; takes a symbol and returns a list of symbols made from the characters in ;; its name (defun explode (sym) (map 'list #'(lambda (c) (intern (make-string 1 :initial-element c))) (symbol-name sym))) ; (explode 'bomb);==> (B O M B) ; (explode 'tralahtek) (defun cumsum (lst &key (smsf 0)) " Calculate the Cumulative Sum of a List `lst'. and return a new list with the incremental sums at each step. (`cumsum' '(1 3 4 6 8) :smsf 0) where `:smsf' is an optional parameter specifying where to start summing from. i.e the offset of counting." (if (null lst) '() (cons (+ smsf (car lst)) (funcall #'cumsum (cdr lst) :smsf (+ smsf (car lst)))))) ;;;; (cumsum '(1 2 3 4 5 6 7 8 9 10 11)) ;;;; (cumsum '(1 2 3 4 5 6 7 8 9 10 11) :smsf 20) ;;;; (cumsum '(1 2 3 4 5 6 7 8 9 10 11) :smsf -10) ; (cumsum '(12 34 57 33 55 77)) (defun zip (x y) "Zip 2 lists `x' and `y' into a list of pairs. Returns a list with the length of the shortest list" (cond ((and (null x) (null y)) '()) ((and (not (atom x)) (not (atom y))) (cons (list (car x) (car y)) (zip (cdr x) (cdr y)))))) ; (zip '(12 34 57) '(33 55 77)) ; (zip '(1 2 3) '(4 5 6)) ; (zip '(12 34 57 32 45) '(33 55 77)) ; (zip '(12 34 57) '(33 55 77 32 34)) ; (zip '(90 12 34 57) '(33 55 77 32 34)) ; (zip '(90 12 34 57) '(33 55 77 32 34)) (defun zipn (&rest args) (let ((acc nil)) (let ((lsts (reduce #'zip args))) ; (print lsts) (dolist (lst lsts) ; (print (flatten lst)) (push (flatten lst) acc))) ; (print acc) (nreverse acc))) ; (zipn '(1 2 3) '(4 5 6)) ; (zipn '(90 12 34 57) '(33 55 77 32 34) '(21 45 33 12)) ; (zipn '(90 12 34 57) '(33 55 77 32 34)) ; (zipn '(90 12 34 57) '(33 55 77 32 34) '(21 45 33 12) '(23 45 67 88)) (defun sumlist (lst) "Takes a list `lst' and Returns the sum of the list `lst' of numbers." (reduce #'+ lst)) ;;;; (sumlist '(1 2 3 4 5 6 7 8 9 10 11)) ;; => 66 ;;;; (sumlist '(-1 2 -3 4 -5 6 7 -8 9 10 11)) ;; => 32 (defun zipsum (&rest args) (let ((res nil)) (dolist (x (apply #'zipn args)) ; (print (apply #'zipn args)) (push (apply #'(lambda (x) (reduce #'+ x)) (list x)) res)) (nreverse res))) ;; (zipsum '(1 2 3) '(4 5 6)) ;;==> (5 7 9) ;; (zipsum '(1 -2 3) '(4 5 6)) ;;==> (5 3 9) ;; (zipsum '(1 -2 3) '(4 5 6) '(10 11 12)) ;;==> (15 14 21) (defun zipdiff (&rest args) (let ((res nil)) (dolist (x (apply #'zipn args)) ; (print (apply #'zipn args)) (push (apply #'(lambda (x) (reduce #'- x)) (list x)) res)) (nreverse res))) ;; (zipdiff '(1 2 3) '(4 5 6)) ;;==> (-3 -3 -3) ;; (zipdiff '(10 20 30) '(4 5 6)) ;;==> (6 15 24) ;; (zipdiff '(10 20 30) '(4 5 6) '(2 6 10)) ;;==> (4 9 14) (defun zipmult (&rest args) (let ((res nil)) (dolist (x (apply #'zipn args)) ; (print (apply #'zipn args)) (push (apply #'(lambda (x) (reduce #'* x)) (list x)) res)) (nreverse res))) ;; (zipmult '(1 2 3) '(4 5 6)) ;;==> (4 10 18) ;; (zipmult '(1 2 3) '(4 5 6) '(7 8 9)) ;;==> (28 80 162) (defun zipdiv (&rest args) (let ((res nil)) (dolist (x (apply #'zipn args)) ; (print (apply #'zipn args)) (push (apply #'(lambda (x) (reduce #'/ x)) (list x)) res)) (nreverse res))) ;; (zipdiv '(1 2 3) '(4 5 6)) ;;==> (1/4 2/5 1/2) ;; (zipdiv '(1.0 2.0 3.0) '(4 5 6)) ;;==> (0.25 0.4 0.5) ;; (zipdiv '(1.0 2.0 3.0) '(4 5 6) '(5 2 0.25)) ;;==> (0.05 0.2 2.0) (defun dot-product (&rest vectors) (apply #'+ (apply #'zipmult vectors))) ;; (dot-product '(1 2 3) '(4 5 6)) ;;==> (4 10 18) ;; (dot-product '(1 2 3) '(4 5 6) '(7 8 9)) ;;==> (28 80 172) (defun cross-product (xlist ylist &optional (fn #'list)) "Return a list of all (fn x y) values." (mappend #'(lambda (y) (mapcar #'(lambda (x) (funcall fn x y)) xlist)) ylist)) ;; (cross-product `(1 2 3) `(1 2 3)) ;; (cross-product `(1 2 3) `(1 2 3) #'+) ;; (cross-product `(a b c) `(1 2 3) #'list) ;; (cross-product `(a b c d) `(1 2 3) #'list)
20,391
Common Lisp
.lisp
503
35.811133
252
0.580448
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
fa8f7b259913484a1e227f44f6db0019f9f38226884de3a14f8b634ee174ef50
22,842
[ -1 ]
22,843
networks.lisp
TralahM_trtek/src/networks.lisp
(in-package :trtek) (defstruct node contents yes no) (defvar *nodes* nil) (defun defnode (&rest args) (push args *nodes*) args) (defun compile-net (root) (let ((node (assoc root *nodes*))) (if (null node) nil (let ((conts (second node)) (yes (third node)) (no (fourth node))) (if yes (let ((yes-fn (compile-net yes)) (no-fn (compile-net no))) #'(lambda () (format t "~A~%>> " conts) (funcall (if (eq (read) ’yes) yes-fn no-fn)))) #'(lambda () conts)))))) ;; Sample Network ; (defnode 'people "Is the person a man?" 'male 'female) ; (defnode 'male "Is he living?" 'liveman 'deadman) ; (defnode 'deadman "Was he Kenyan?" 'us 'them) ; (defnode 'us "Is he on a coin?" 'coin 'cidence) ; (defnode 'coin "Is the coin a shilling?" 'shilling 'coins) ; (defnode 'shilling 'kenyatta) ; (funcall (gethash 'people *nodes*)) ; (setq n (compile-net 'people))
1,094
Common Lisp
.lisp
31
26.290323
60
0.519542
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f6e013bb5ab6453c70cbc629d7d8f0ad1d1e5376b0ca15f552569212ca69a2f6
22,843
[ -1 ]
22,844
macros.lisp
TralahM_trtek/src/macros.lisp
(in-package :trtek) (defmacro nil! (var) "set var to nil" `(setq ,var nil)) (defmacro while (test &body body) `(do () ((not ,test)) ,@body)) (defmacro fn (expr) `#',(rbuild expr)) (defun rbuild (expr) (if (or (atom expr) (eq (car expr) 'lambda)) expr (if (eq (car expr) 'compose) (build-compose (cdr expr)) (build-call (car expr) (cdr expr))))) (defun build-call (op fns) (let ((g (gensym))) `(lambda (,g) (,op ,@(mapcar #'(lambda (f) `(,(rbuild f) ,g)) fns))))) (defun build-compose (fns) (let ((g (gensym))) `(lambda (,g) ,(labels ((rec (fns) (if fns `(,(rbuild (car fns)) ,(rec (cdr fns))) g))) (rec fns))))) ; (mapcar (fn (or integerp symbolp)) '(c 3 p 0.2)) => '(T T T NIL) ; (mapcar (fn (and integerp oddp)) '(c 3 p 0.2)) => '(NIL T NIL NIL) ; (mapcar (fn (list 1- identity 1+)) '(8 3 5 2)) => '((7 8 9) (2 3 4) (4 5 6) (1 2 3)) ; (mapcar (fn (list integerp oddp)) '(8 3 5 2)) => '((T NIL) (T T) (T T) (T NIL)) ;; Macros for list recursion (defun lrec (rec &optional base) "Function to define flat list recursers. The first argument to lrec must be a function of two arguments, the current car of the list,and a function which can be called to continue the recursion." (labels ((self (lst) (if (null lst) (if (functionp base) (funcall base) base) (funcall rec (car lst) #'(lambda () (self (cdr lst))))))) #'self)) ;; Using lrec we coul express our-length as: ;; (funcall (lrec #'(lambda (x f) (1+ (funcall f))) 0) '(1 2 3 4 5 6 7)) ;; Or Our-every as: ;; (funcall (lrec #'(lambda (x f) (and (oddp x) (funcall f))) t) '(1 2 3 4 5 6 7 8)) ;; (funcall (lrec #'(lambda (x f) (and (oddp x) (funcall f))) t) '(1 3 5 7 9)) (defmacro alrec (rec &optional base) "clt12 version" (let ((gfn (gensym))) `(lrec #'(lambda (it ,gfn) (symbol-macrolet ((rec (funcall ,gfn))) ,rec)) ,base))) (defmacro on-cdrs (rec base &rest lsts) `(funcall (alrec ,rec #'(lambda () ,base)) ,@lsts)) (defun tek-copy-list (lst) (on-cdrs (cons it rec) nil lst)) (defun tek-remove-duplicates (lst) (on-cdrs (adjoin it rec) nil lst)) (defun tek-find-if (fn lst) (on-cdrs (if (funcall fn it) it rec) nil lst)) (defun tek-some (fn lst) (on-cdrs (or (funcall fn it) rec) nil lst)) (defun tek-every (fn lst) (on-cdrs (or (funcall fn it) rec) t lst)) (defun unions (&rest sets) (on-cdrs (union it rec) (car sets) (cdr sets))) ; (unions '(a b c d e) '(a f d)) => '(E C B A F D) (defun intersections (&rest sets) (unless (some #'null sets) (on-cdrs (intersection it rec) (car sets) (cdr sets)))) ; (intersections '(a b c d e) '(a f d)) => '(D A) (defun differences (set &rest outs) (on-cdrs (set-difference rec it) set outs)) ; (differences '(a b c d e) '(a f) '(d)) => '(B C E) (defun maxmin (args) (when args (on-cdrs (multiple-value-bind (mx mn) rec (values (max mx it) (min mn it))) (values (car args) (car args)) (cdr args)))) ; (maxmin '(3 4 2 8 5 1 6 7)) => 8 1 (defmacro nif (expr pos zero neg) "Numerical If macro" `(case (truncate (signum ,expr)) (1 ,pos) (0 ,zero) (-1 ,neg))) (defmacro avg (&rest args) "Calculate the average of list macro." `(/ (+ ,@args) ,(length args))) ; (describe 'avg ) ; (macroexpand `(avg 1 2 3 4 5 6 7 8)) ; (macroexpand `(avg 1 2 5 4 7 6 8 86)) ; (eval (macroexpand `(avg 1 2 5 4 7 6 8.0 86))) ; (time (eval (macroexpand `(avg 1 2 5 4 7 6 8.0 86)))) ; (+ 1 2 5 4 7 6 8 86) ; (defvar x nil) ; (setq x nil) (defmacro using (var form &body body) `(let ((,var ,form)) (unwind-protect (progn ,@body) (progn (setq ,var nil) (format t "Cleaning up ~a to ~a~%" 'var ,var))))) (defun test-using (x val) (using x val (format t "Using ~a as ~a~%" 'x x) )) ; (test-using 'p 55.0)
4,132
Common Lisp
.lisp
115
30.086957
87
0.544062
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4fb0ad1bff8d4daee57c4ef1239a39c9662e0a499fc8e33c3eeeca80667077a4
22,844
[ -1 ]
22,845
packages.lisp
TralahM_trtek/src/packages.lisp
;;; packages.lisp (defpackage trtek (:use :cl) (:export abbrev ;; (short long) abbrevs ;; (&rest names) achieve-all ;; (state goals goal-stack) achieve ;; (state goal goal-stack) acos-deg ;; (x) after ;; (x y lst &key (test alrec ;; (rec &optional base) append1 ;; (lst obj) apply-op ;; (state goal op goal-stack) appropriate-p ;; (goal op) approx-equal ;; (x y &optional (*epsilon* *epsilon*)) asin-deg ;; (x) atan-deg ;; (x) avg ;; (&rest args) *banana-ops* ;; before ;; (x y lst &key (test best ;; (fn lst) break-loop ;; (fn quit &rest args) build-call ;; (op fns) build-compose ;; (fns) chars ;; (str) chars ;; (str) (loop for c across choose ;; (n r) cmplmnt ;; (fn) compile-net ;; (root) compose ;; (&rest fns) conc1 ;; (lst obj) convert-op ;; (op) cos-deg ;; (angle) cross-product ;; (xlist ylist &optional (fn #'list)) cumsum ;; (lst &key (smsf 0)) dbg ;; (id format-string &rest args) *dbg-ids* ;; nil "Identifiers used by dbg") dbg-indent ;; (id indent format-string &rest args) defnode ;; (&rest args) deg-to-rad ;; (deg) differences ;; (set &rest outs) dot-product ;; (&rest vectors) duplicate ;; (obj lst &key (test #'eql)) *epsilon* ;; 1.0e-6) executing-p ;; (x) explode ;; (sym) fact ;; (x) fif ;; (if then &optional else) filter ;; (fn lst) find2 ;; (fn lst) find-all ;; (item sequence &rest keyword-args fint ;; (fn &rest fns) flatten ;; (x) fn ;; (expr) `#',(rbuild expr)) fun ;; (fn &rest fns) gdebug ;; (&rest ids) GPS ;; (state goals &optional (*ops* *ops*)) group ;; (source n) intersections ;; (&rest sets) last1 ;; (lst) longer ;; (x y) lrec ;; (rec &optional base) map0-n ;; (fn n) map1-n ;; (fn n) mapa-b ;; (fn a b &optional (step mapcars ;; (fn &rest lsts) map-> ;; (fn start test-fn succ-fn) mappend ;; (fn &rest lsts) maxmin ;; (args) member-equal ;; (item list) memoize ;; (fn) mklist ;; (obj) mkstr ;; (&rest args) most ;; (fn lst) mostn ;; (fn lst) nif ;; (expr pos zero neg) nil! ;; (var) node ;; contents yes no) *nodes* ;; nil) on-cdrs ;; (rec base &rest lsts) op ;; (action &key preconds add-list del-list) op ;; "An operation" *ops* ;; nil "A list of available package-external-symbols ;; (package) package-internal-symbols ;; (package) prompt ;; (&rest args) propmacro ;; (propname) propmacros ;; (&rest props) prune ;; (test tree) rad-to-deg ;; (rad) rbuild ;; (expr) readlist ;; (&rest args) reread ;; (&rest args) rfind-if ;; (fn tree) rmapcar ;; (fn &rest args) *school-ops* ;; sigmoid ;; (x) sigmoid* ;; (x) sin-deg ;; (angle) single ;; (lst) split-if ;; (fn lst) starts-with ;; (list x) sumlist ;; (lst) symb ;; (&rest args) tan-deg ;; (angle) tek-copy-list ;; (lst) tek-every ;; (fn lst) tek-find-if ;; (fn lst) tek-remove-duplicates ;; (lst) tek-some ;; (fn lst) test-using ;; (x val) trec ;; (rec &optional (base #'identity)) trtek ;; ttrav ;; (rec &optional (base #'identity)) undebug ;; (&rest ids ) unions ;; (&rest sets) use ;; (oplist) using ;; (var form &body body) while ;; (test &body body) zipdiff ;; (&rest args) zipdiv ;; (&rest args) zipmult ;; (&rest args) zipn ;; (&rest args) zipsum ;; (&rest args) zip ;; (x y) ))
3,572
Common Lisp
.lisp
126
26.309524
57
0.553136
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f83782924d0cca0487ac83aa98d8a398ce7d3ded51c3fd960105838e9559b158
22,845
[ -1 ]
22,846
abbreviations.lisp
TralahM_trtek/src/abbreviations.lisp
(in-package #:trtek) (defmacro abbrev (short long) `(defmacro ,short (&rest args) `(,',long ,@args))) (defmacro abbrevs (&rest names) `(progn ,@(mapcar #'(lambda (pair) `(abbrev ,@pair)) (group names 2)))) (abbrev mvbind multiple-value-bind) (abbrev dbind destructuring-bind) (defmacro propmacro (propname) `(defmacro ,propname (obj) `(get ,obj ',',propname))) (defmacro propmacros (&rest props) `(progn ,@(mapcar #'(lambda (p) `(propmacro ,p)) props)))
537
Common Lisp
.lisp
18
24.222222
45
0.598441
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
3a3dadd82d31658f6ad760d5426edc4206be62ce12ef8cc7bc3205a7b86fdde1
22,846
[ -1 ]
22,847
gps.lisp
TralahM_trtek/src/gps/gps.lisp
(in-package :trtek) (defvar *ops* nil "A list of available operators.") (defstruct op "An operation" (action nil) (preconds nil) (add-list nil) (del-list nil)) (defvar *dbg-ids* nil "Identifiers used by dbg") (defun dbg (id format-string &rest args) "Print Debugging info if (DEBUG ID) has been specified." (when (member id *dbg-ids*) (fresh-line *debug-io*) (apply #'format *debug-io* format-string args))) (defun gdebug (&rest ids) "Start dbg output on the given ids." (setf *dbg-ids* (union ids *dbg-ids*))) (defun undebug (&rest ids ) "Stop dbg on the ids . With no ids . stop dbg altogether." (setf *dbg-ids* (if (null ids) nil (set-difference *dbg-ids* ids)))) (defun dbg-indent (id indent format-string &rest args) "Print indented debugging info if (DEBUG ID) has been specified." (when (member id *dbg-ids*) (fresh-line *debug-io*) (dotimes (i indent) (princ " " *debug-io*)) (apply #'format *debug-io* format-string args))) (defun find-all (item sequence &rest keyword-args &key (test #'eql) test-not &allow-other-keys) "Find all those elements of sequence that match item, according to the keywords. Doesn't alter sequence." (if test-not (apply #'remove item sequence :test-not (complement test-not) keyword-args) (apply #'remove item sequence :test (complement test) keyword-args))) (defun GPS (state goals &optional (*ops* *ops*)) "General Problem Solver: achieve all goals using *ops*." (remove-if #'atom (achieve-all (cons '(start) state) goals nil))) (defun achieve (state goal goal-stack) "A goal is achieved if it already holds. or if there is an appropriate op for it that is applicable." (dbg-indent :gps (length goal-stack) "Goal: ~a" goal) (cond ((member-equal goal state) state) ((member-equal goal goal-stack) nil) (t (some #'(lambda (op) (apply-op state goal op goal-stack)) (find-all goal *ops* :test #'appropriate-p))))) (defun member-equal (item list) (member item list :test #'equal)) (defun achieve-all (state goals goal-stack) "Try to achieve each goal, then make sure they still hold." (let ((current-state state)) (if (and (every #'(lambda (g) (setf current-state (achieve current-state g goal-stack))) goals) (subsetp goals current-state :test #'eql)) current-state))) (defun appropriate-p (goal op) "An op is appropriate to a goal if it is in its add list." (member-equal goal (op-add-list op))) (defun apply-op (state goal op goal-stack) "Return a new transformed state if op is applicable." (dbg-indent :gps (length goal-stack) "Consider: ~a" (op-action op)) (let ((state2 (achieve-all state (op-preconds op) (cons goal goal-stack)))) (unless (null state2) ;;Return an updated state (dbg-indent :gps (length goal-stack) "Action: ~a" (op-action op)) (append (remove-if #'(lambda (x) (member-equal x (op-del-list op))) state2) (op-add-list op))))) (defun use (oplist) "Use oplist as the default list of operators." ;;Return sth useful but not too verbose: the number of operators. (length (setf *ops* oplist))) (defun executing-p (x) "Is x of the form: (executing ...).?" (starts-with x 'executing)) (defun starts-with (list x) "Is this a list whose first element starts with x?" (and (consp list) (eql (first list) x))) (defun convert-op (op) "Make op conform to the (EXECUTING op) convention." (unless (some #'executing-p (op-add-list op)) (push (list 'executing (op-action op)) (op-add-list op))) op) (defun op (action &key preconds add-list del-list) "Make a new operator that obeys the (EXECUTING op) convention." (convert-op (make-op :action action :preconds preconds :add-list add-list :del-list del-list))) ; Some test operations for testing (defparameter *school-ops* (list (make-op :action 'drive-son-to-school :preconds '(son-at-home car-works) :add-list '(son-at-school) :del-list '(son-at-home)) (make-op :action 'shop-installs-battery :preconds '(car-needs-battery shop-knows-problem shop-has-money) :add-list '(car-works)) (make-op :action 'tell-shop-problem :preconds '(in-communication-with-shop) :add-list '(shop-knows-problem)) (make-op :action 'telephone-shop :preconds '(know-phone-number) :add-list '(in-communication-with-shop)) (make-op :action 'look-up-number :preconds '(have-phone-book) :add-list '(know-phone-number)) (make-op :action 'give-shop-money :preconds '(have-money) :add-list '(shop-has-money) :del-list '(have-money)))) (mapc #'convert-op *school-ops*) (defparameter *banana-ops* (list (op 'climb-on-chair :preconds '(chair-at-middle-room at-middle-room on-floor) :add-list '(at-bananas on-chair) :del-list '(at-middle-room on-floor)) (op 'push-chair-from-door-to-middle-room :preconds '(chair-at-door at-door) :add-list '(chair-at-middle-room at-middle-room) :del-list '(chair-at-door at-door)) (op 'walk-from-door-to-middle-room :preconds '(at-door on-floor) :add-list '(at-middle-room) :del-list '(at-door)) (op 'grasp-bananas :preconds '(at-bananas empty-handed) :add-list '(has-bananas) :del-list '(empty-handed)) (op 'drop-ball :preconds '(has-ball) :add-list '(empty-handed) :del-list '(has-ball)) (op 'eat-bananas :preconds '(has-bananas) :add-list '(empty-handed not-hungry) :del-list '(has-bananas hungry)))) ; (use *school-ops*) ;; Testing. ; (gdebug :gps) ; (gps '(son-at-home car-needs-battery have-money have-phone-book) '(son-at-school) *school-ops*) ; (gps '(son-at-home car-works) '(son-at-school) ) ; (gps '(son-at-home car-needs-battery have-money) '(son-at-school) *school-ops*) ;; Clobbered Sibling Goal Problem ; (gps '(son-at-home car-needs-battery have-money have-phone-book) '(have-money son-at-school) *school-ops*) ; (gps '(son-at-home car-needs-battery have-money have-phone-book) '(son-at-school have-money) *school-ops*) ; (undebug :gps) ; (gdebug :gps) ; (use *banana-ops*) ; (gps '(at-door on-floor has-ball hungry chair-at-door) '(not-hungry)) ; (undebug :gps)
6,576
Common Lisp
.lisp
151
37.192053
108
0.638528
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
9bcefd5036f5a133b1a455b45e85d4a6a2d9ec7711c8140ba031bf9499d35e4f
22,847
[ -1 ]
22,848
main.lisp
TralahM_trtek/tests/main.lisp
(defpackage trtek/tests/main (:use :cl :trtek :fiveam) (:export #:run! #:all-tests test-trtek)) (in-package :trtek/tests/main) (def-suite all-tests :description "The master suite of all trtek tests.") (in-suite all-tests) (defun test-trtek () (run! 'all-tests)) (test test-cumsum "(= (trtek:cumsum '(1 2 3)) '(1 3 6)) should be true" (is (equal (trtek:cumsum '(1 2 3)) '(1 3 6)))) (test test-sumlist "(= (trtek:sumlist '(1 2 3)) 6) should be true" (is (eql (trtek:sumlist '(1 2 3)) 6))) (test test-cmplmnt (is (equal (remove-if #'oddp '(1 2 3 4 5 6)) '(2 4 6))) (is (equal (remove-if (cmplmnt #'evenp) '(1 2 3 4 5 6)) '(2 4 6))) (is (equal (remove-if (cmplmnt #'oddp) '(1 2 3 4 5 6)) '(1 3 5)))) (test test-compose (is (equal (funcall (compose #'1+ #'find-if) #'oddp '(2 3 4)) 4))) (test test-last1 (is (equal (last1 '(1 2 3 4)) 4))) (test test-single (is (equal (single '(1)) t)) (is (equal (single '(1 2 3 4)) nil))) (test test-mklist (is (equal (mklist '12) '(12))) (is (equal (mklist '(1 2)) '(1 2)))) (test test-longer (is (equal (longer '(1 2 3 45) '(1 5 4 5 6 7)) NIL)) (is (equal (longer '(1 2 3 45) '(1 5)) T))) (test test-flatten (is (equal (flatten '(1 2 3 4 6 8 9 12 (32 11 39 7) 19)) '(1 2 3 4 6 8 9 12 32 11 39 7 19))) (is (equal (flatten '(1 2 3 4 6 8 9 12 32 11 39 7 19)) '(1 2 3 4 6 8 9 12 32 11 39 7 19))) (is (equal (flatten '(1 2 3 4 6 (8 9 12 (32 11 39) 7) 19)) '(1 2 3 4 6 8 9 12 32 11 39 7 19)))) (test test-mapa-b (is (equal (mapa-b #'1+ -2 0 .5) '(-1 -0.5 0.0 0.5 1.0)))) (test test-map0-n (is (equal (map0-n #'1+ 5) '(1 2 3 4 5 6)))) (test test-map1-n (is (equal (map1-n #'1+ 5) '(2 3 4 5 6)))) (test test-before (is (equal (before 'b 'a '(b a b a b d)) '(B A B A B D))) (is (equal (before 'c 'd '(a b c d)) '(C D))) (is (equal (before 'a 'b '(a)) '(A)))) (test test-after (is (equal (after 'a 'b '(b a b a d)) '(A B A D))) (is (equal (after 'a 'b '(a b c)) NIL)) (is (equal (after 'a 'b '(b a d)) '(A D)))) (test test-duplicate (is (equal (duplicate 'b '(a b c a b c a b d)) '(B C A B D))) (is (equal (duplicate 'a '(a b c a d)) '(A D)))) (test test-best (is (equal (best #'< '(1 2 3 4 5)) 1)) (is (equal (best #'> '(1 2 3 4 5)) 5))) (test test-explode (is (equal (explode 'bomb) '(B O M B)))) (test test-zip (is (equal (zip '(1 2 3) '(4 5 6)) '((1 4) (2 5) (3 6))))) (test test-zipsum (is (equal (zipsum '(1 2 3) '(4 5 6)) '(5 7 9))) (is (equal (zipsum '(1 -2 3) '(4 5 6) '(10 11 12)) '(15 14 21))) (is (equal (zipsum '(1 -2 3) '(4 5 6)) '(5 3 9)))) (test test-zipdiff (is (equal (zipdiff '(10 20 30) '(4 5 6) '(2 6 10)) '(4 9 14))) (is (equal (zipdiff '(10 20 30) '(4 5 6)) '(6 15 24))) (is (equal (zipdiff '(1 2 3) '(4 5 6)) '(-3 -3 -3)))) (test test-zipmult (is (equal (zipmult '(1 2 3) '(4 5 6) '(7 8 9)) '(28 80 162))) (is (equal (zipmult '(1 2 3) '(4 5 6)) '(4 10 18)))) (test test-zipdiv (is (equal (zipdiv '(1.0 2.0 3.0) '(4 5 6) '(5 2 0.25)) '(0.05 0.2 2.0))) (is (equal (zipdiv '(1.0 2.0 3.0) '(4 5 6)) '(0.25 0.4 0.5))) (is (equal (zipdiv '(1 2 3) '(4 5 6)) '(1/4 2/5 1/2)))) (test test-dot-product (is (equal (dot-product '(1 2 3) '(4 5 6) '(7 8 9)) 270)) (is (equal (dot-product '(1 2 3) '(4 5 6)) 32))) (test test-cross-product (is (equal (cross-product `(1 2) `(a b)) '((1 a) (2 a) (1 b) (2 b)))) (is (equal (cross-product `(1 2) `(1 2)) '((1 1) (2 1) (1 2) (2 2))))) (test factorial-test (is (equal (fact 5) 120)) (is (equal (fact 6) 720))) (test n-choose-r-test (is (equal (choose 6 2) 15)) (is (equal (choose 4 2) 6))) (test deg-to-rad-test (is (approx-equal (deg-to-rad 90) 1.5707963267948966d0)) (is (approx-equal (deg-to-rad 45) 0.7853981633974483d0)) (is (approx-equal (deg-to-rad 180) 3.141592653589793d0))) (test rad-to-deg-test (is (approx-equal (rad-to-deg (* pi 2)) 360.0d0)) (is (approx-equal (rad-to-deg (* pi .5)) 90.0d0)) (is (approx-equal (rad-to-deg pi) 180.0d0))) (test cos-deg-test (is (approx-equal (cos-deg 90) 6.1232339957d-17)) (is (approx-equal (cos-deg 30) 0.8660254)) (is (approx-equal (cos-deg 0) 1.0d0)) (is (approx-equal (cos-deg 45) 0.70710678)) (is (approx-equal (cos-deg 60) 0.5))) (test acos-deg-test (is (approx-equal (acos-deg 0) 90.0)) (is (approx-equal (acos-deg 1) 0.0d0)) (is (approx-equal (acos-deg -1) 180.0)) (is (approx-equal (acos-deg .5) 60.0))) (test sin-deg-test (is (approx-equal (sin-deg 90) 1.0d0)) (is (approx-equal (sin-deg 30) 0.5)) (is (approx-equal (sin-deg 0) 0.0d0)) (is (approx-equal (sin-deg 45) 0.70710678)) (is (approx-equal (sin-deg 60) 0.8660254))) (test asin-deg-test (is (approx-equal (asin-deg 0) 0.0d0)) (is (approx-equal (asin-deg 1) 90.0)) (is (approx-equal (asin-deg -1) -90.0)) (is (approx-equal (asin-deg .5) 30.0))) (test tan-deg-test (is (approx-equal (tan-deg 60) 1.7320508)) (is (approx-equal (tan-deg 30) 0.5773502)) (is (approx-equal (tan-deg 45) 1))) (test atan-deg-test (is (approx-equal (atan-deg 0) 0.0d0)) (is (approx-equal (atan-deg 1.0) 45.0)) (is (approx-equal (atan-deg .5) 26.56505089)))
5,583
Common Lisp
.lisp
127
38.228346
101
0.530441
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f89f82f81a2813ad58ad3b8c8abb56c2afcca930613a4eeb3a3e94d076f9628d
22,848
[ -1 ]
22,849
trtek.asd
TralahM_trtek/trtek.asd
(defsystem "trtek" :version "0.1.0" :author "Tralah M Brian <[email protected]>" :maintainer "Tralah M Brian <[email protected]>" :license "GPL" ; :homepage "https://github.com/TralahM/trtek" ; :bug-tracker "https://github.com/TralahM/trtek/issues" ; :source-control (:git "[email protected]:TralahM/trtek.git") :depends-on (:uiop :alexandria :asdf :fiveam) :components ((:module "src" :serial t :components ((:file "packages") (:file "abbreviations") (:file "main") (:file "macros") (:file "utils") (:module "gps" :serial t :components ((:file "gps")))))) :description "An Attempt at Lisp System Building." :long-description #.(uiop:read-file-string (uiop:subpathname *load-pathname* "README.md")) :in-order-to ((test-op (test-op "trtek/tests")))) (defsystem "trtek/tests" :author "Tralah M Brian <[email protected]>" :license "GPL" :defsystem-depends-on (:fiveam) :depends-on (:trtek :fiveam ) :components ((:module "tests" :serial t :components ((:file "main")))) :description "Test system for trtek" :perform (test-op (op c) (uiop:symbol-call 'trtek/tests/main :test-trtek )))
1,356
Common Lisp
.asd
30
35.933333
92
0.589434
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6dc38926c7d0e33a25096559008014e7ae74b28666b62081c9abbe435875e163
22,849
[ -1 ]
22,851
.mailmap
TralahM_trtek/.mailmap
# Prevent git from showing duplicate names with commands like "git shortlog" # See the manpage of git-shortlog for details. # The syntax is: # Name that should be used <email that should be used> Bad name <bad email> # # You can skip Bad name if it is the same as the one that should be used, and is unique. # # This file is up-to-date if the command git log --format="%aN <%aE>" | sort -u # gives no duplicates. Tralah M Brian <[email protected]> TralahM <[email protected]>
499
Common Lisp
.l
10
48.6
88
0.751029
TralahM/trtek
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
62c0f70892a2880084aa062e56054a967e3bcfeeb715066e208923f20559c3cb
22,851
[ -1 ]
22,875
package.lisp
szos_framework-client/package.lisp
;;;; package.lisp (defpackage #:matrix-framework (:use #:cl) (:export :initialize* :view-room* ))
113
Common Lisp
.lisp
6
15.5
30
0.619048
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
2f0524fade352c496700e20444b7fa22260121fa17dc95e1990514f74bff9c27
22,875
[ -1 ]
22,876
parse-timeline,etc.lisp
szos_framework-client/parse-timeline,etc.lisp
(in-package :matrix-framework) ;;; what i want is a timeline, to be then printed like so: ;;; timestamp user: message ;;; what we have now is: ;;; user says: ;;; message ;;; ------------- (for 80 characters. we assume minimum of 80 character display) (defun deal-with-newlines (formatted-event) (if (search " " formatted-event) (cat (subseq formatted-event 0 (+ 1 (search " " formatted-event))) " " (subseq formatted-event (+ 1 (search " " formatted-event)))) formatted-event)) (defun display-room-events-list (list-of-formatted-events) (let ((previous-speaker "") (current-speaker "")) (when (search "says:" (car list-of-formatted-events)) (setf previous-speaker (subseq (car list-of-formatted-events) 0 (search "says:" (car list-of-formatted-events))))) (print (car list-of-formatted-events)) (terpri) (loop for event in (rest list-of-formatted-events) do (when (search "says:" event) (setf current-speaker (subseq event 0 (search "says:" event))) (if (string= current-speaker previous-speaker) (setf event (subseq event (+ (search "says:" event) 6))) (setf previous-speaker current-speaker))) (princ event) (terpri) ;; (princ "--------------------------------------------------------------------------------") ;; (terpri) ))) (defun get-events-from-timeline (timeline) "takes a timeline and returns the 'events' portion of the timeline" (let ((events (assoc "events" (rest timeline) :test #'string=))) events)) (defun get-timeline-from-room (room) "takes a room and returns the timeline. example usage is " ;; (parse-timeline-events ;; (get-events-from-timeline ;; (get-timeline-from-room (grab-single-room name)))) (when (stringp (car room)) (setf room (cdr room))) (assoc "timeline" room :test #'string=)) (defun parse-timeline-events (list-of-events) "takes a list of events, and returns a list of strings, one for each event, that are ready to be displayed. currently only m.room.message, m.room.member, types of messages are working" (when (stringp (car list-of-events)) (setf list-of-events (rest list-of-events))) (let ((formatted-events-list (mapcar #'parse-single-event list-of-events))) formatted-events-list)) (defun parse-timeline-events* (list-of-events) "takes a list of events, and returns a list of strings, one for each event, that are ready to be displayed. currently only m.room.message, m.room.member, types of messages are working" (when (stringp (car list-of-events)) (setf list-of-events (rest list-of-events))) (let ((sender.event (mapcar #'parse-single-event list-of-events)) (last-sender "")) (mapcar #'(lambda (event) (if (string= (car event) last-sender) (values nil (cdr event)) (values (car event) (cdr event)))) sender.event))) (defun parse-timeline-evnts* (list-of-events) (when (stringp (car list-of-events)) (setf list-of-events (rest list-of-events))) (let ((last-sender "") (list-to-be-reversed nil)) (mapcar #'(lambda (event) (let ((sender (cdr (assoc "sender" event :test #'string=))))) (if (string= last-sender sender) (setf list-to-be-reversed (cons list-to-be-reversed ))))))) (defun parse-single-event* (event) ;; This needs to be reworked using clos maybe, as its getting to the point of a giant ;; dispatch table where we have to manually add things to it to get new behaviour. ;; instead we could use dynamic dispatch so people could just grab the methods and ;; everything for general events when implementing a new event type through ;; inheritance. "takes in one event, and returns that event formatted and ready for displaying. it also updates the room, based on the 'unsigned' portion of the event. this means side effects, as its calling a function that will change some data. " (let (;;(unsigned (cdr (assoc "unsigned" event :test #'string=))) (type (cdr (assoc "type" event :test #'string=))) (sender (cdr (assoc "sender" event :test #'string=)))) ;; (update-room unsigned) ;; this should check for 'replaces_state' among others and update the room to reflect any changes. (when (string= type "m.room.redaction") (princ type) (terpri)) ;; this is a giant static dispatch... BAD! rewrite to actually make use of CLOS... (values sender (cond ((string= type "m.room.message") (format-message-event event)) ((string= type "m.room.member") (format-member-event event)) ((string= type "m.room.encrypted") (format-encrypted-event event)) ((string= type "m.room.redaction") (format-redacted-event event)) ((string= type "m.room.history_visibility") (format-room-history-visible& event)) ((string= type "m.room.guest_access") (format-room-guest-access& event)) ((string= type "m.room.name") (format-room-name& event)) ((string= type "m.room.power_levels") (format-room-power-levels& event)) ((string= type "m.room.join_rules") (format-room-join-rules& event)) ((string= type "m.room.avatar") (format-room-avatar event)) ((string= (subseq type 0 7) "m.call.") (format-call-events event)) ((string= type "m.room.create") (format-room-create event)) ((preview-url-p type) (format-room-preview-url event)) (t "this message type has not been implemented"))))) (defun parse-single-event (event) ;; This needs to be reworked using clos maybe, as its getting to the point of a giant ;; dispatch table where we have to manually add things to it to get new behaviour. ;; instead we could use dynamic dispatch so people could just grab the methods and ;; everything for general events when implementing a new event type through ;; inheritance. "takes in one event, and returns that event formatted and ready for displaying. it also updates the room, based on the 'unsigned' portion of the event. this means side effects, as its calling a function that will change some data. " (let (;;(unsigned (cdr (assoc "unsigned" event :test #'string=))) (type (cdr (assoc "type" event :test #'string=))) ;;(sender (cdr (assoc "sender" event :test #'string=))) ) ;; (update-room unsigned) ;; this should check for 'replaces_state' among others and update the room to reflect any changes. (when (string= type "m.room.redaction") (princ type) (terpri)) ;; this is a giant static dispatch... BAD! rewrite to actually make use of CLOS... (cond ((string= type "m.room.message") (format-message-event event)) ((string= type "m.room.member") (format-member-event event)) ((string= type "m.room.encrypted") (format-encrypted-event event)) ((string= type "m.room.redaction") (format-redacted-event event)) ((string= type "m.room.history_visibility") (format-room-history-visible& event)) ((string= type "m.room.guest_access") (format-room-guest-access& event)) ((string= type "m.room.name") (format-room-name& event)) ((string= type "m.room.power_levels") (format-room-power-levels& event)) ((string= type "m.room.join_rules") (format-room-join-rules& event)) ((string= type "m.room.avatar") (format-room-avatar event)) ((string= (subseq type 0 7) "m.call.") (format-call-events event)) ((string= type "m.room.create") (format-room-create event)) ((preview-url-p type) (format-room-preview-url event)) (t "this message type has not been implemented")))) (defun preview-url-p (type) (let ((strstrt (search "room.preview_urls" type))) (if strstrt t nil))) (defun format-member-event (event) "takes in an event of type m.room.member and formats it, returning the formatted text" (let* ((sender (cdr (assoc "sender" event :test #'string=))) (content (cdr (assoc "content" event :test #'string=))) (member? (cdr (assoc "membership" content :test #'string=)))) (if (string= member? "leave") ;; theres only leave/join possible (format nil "~A has left the room" sender) (format nil "~A (~A) has joined the room" (cdr (assoc "displayname" content :test #'string=)) sender)))) (defun format-message-event (event) "takes in one event that is of type m.room.message and formats it, returning the formatted text. " (let ((sender (cdr (assoc "sender" event :test #'string=))) (text (let ((content (cdr (assoc "content" event :test #'string=)))) (cond ((string= "m.text" (cdr (assoc "msgtype" content :test #'string=))) (cdr (assoc "body" content :test #'string=))) ((string= "m.image" (cdr (assoc "msgtype" content :test #'string=))) (format nil "Image link: ~A" (cdr (assoc "url" content :test #'string=)))) (t "unknown msgtype"))))) (format nil "~a says:~% ~a" sender (deal-with-newlines text)))) (defun format-encrypted-event (event) "takes an event of type m.room.encrypted, and returns it formatted. if the client has the keys, it will decrypt the message. otherwise it says its cipher text / encrypted." (let ((sender (cdr (assoc "sender" event :test #'string=)))) (format nil "~A says:~% encryption is not yet implemented." sender))) (defun format-redacted-event (event) "takes a redaction message. it should replace the text of the referenced event with the word redacted, but events arent yet indexed to permit this. " (let ((sender (cdr (assoc "sender" event :test #'string=))) (event-to-redact (cdr (assoc "redacts" event :test #'string=)))) (format nil "~A redacts event ~A" sender event-to-redact))) (defun format-call-events (event) "this client cant deal with calls. " (declare (ignore event)) (format nil "this client cannot accept or place calls")) (defun format-room-name& (event) "this function and others like it should have side effects of setting our rooms metadata. in this case it should setf the room name to whatever we recieve. however room names are not yet implemented. for types m.room.name" (let ((sender (cdr (assoc "sender" event :test #'string=))) (room-name (cdr (assoc "name" (cdr (assoc "content" event :test #'string=)) :test #'string=)))) (format nil "~A set the room name to ~A" sender room-name))) (defun format-room-guest-access& (event) "takes events of type m.room.guest_access and returns a string indicating whether guests can access this room. it should also alter our data regarding the room, like format-room-name&" (let ((sender (cdr (assoc "sender" event :test #'string=))) (access? (cdr (assoc "guest_access" (cdr (assoc "content" event :test #'string=)) :test #'string=)))) (if (string= access? "can_join") (format nil "Guests can join. Set by ~A" sender) (format nil "Guests cannot join. Set by ~A" sender)))) (defun format-room-history-visible& (event) (let ((sender (cdr (assoc "sender" event :test #'string=))) (visibility-level (cdr (assoc "history_visibility" (cdr (assoc "content" event :test #'string=)) :test #'string=)))) (format nil "The history of the room was set to ~A by ~A" visibility-level sender))) (defun format-room-power-levels& (event) (let ((sender (cdr (assoc "sender" event :test #'string=)))) (format nil "~A has set the power levels. this function is not fully implemented" sender))) (defun format-room-join-rules& (event) (let ((sender (cdr (assoc "sender" event :test #'string=))) (join-rule (cdr (assoc "join_rule" (cdr (assoc "content" event :test #'string=)) :test #'string=)))) (format nil "~A set the rules regarding joining to ~A" sender join-rule))) (defun format-room-avatar (event) (let ((sender (cdr (assoc "sender" event :test #'string=)))) (format nil "~A changed their avatar" sender))) (defun format-room-create (event) (let ((creator (cdr (assoc "creator" (cdr (assoc "content" event :test #'string=)) :test #'string=))) (version (cdr (assoc "room_version" (cdr (assoc "content" event :test #'string=)) :test #'string=)))) (format nil "~A created the room. Room version is ~A." creator version))) (defun format-room-preview-url (event) (let ((disable (cdr (assoc "disable" (cdr (assoc "content" event :test #'string=)) :test #'string=)))) (format nil "URL previews are ~A for this room, but this client doesnt support them" (if (eq t disable) "enabled" "disabled"))))
12,434
Common Lisp
.lisp
266
42.522556
128
0.673459
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
910c309544afb173b82b99b3555a11a2f7cf1b50279ca528cdd767f97eeb72b5
22,876
[ -1 ]
22,877
objects.lisp
szos_framework-client/objects.lisp
(in-package :matrix-framework) ;;; all the classes and methods should go here. preferablyy rework everything to be ;;; useing methods, so that for example we just have to have our main loop running and everything ;;; else is method dispatches for updateing rooms and objects. (defclass chamber () ;; called a chamber as room is not a valid name (locks on common-lisp package) ;; this should hold on to the information needed for a specific room. ((previous-batch :initarg :previous-batch :reader previous-batch :writer (setf previous-batch) :documentation "holds the previous batch token for the earliest chunk of data in the room. ") (room-name :initarg :name :reader room-name :writer (setf room-name)) (state :initarg :state :reader state :writer (setf state) :documentation "this holds room state. this should be stored like (event-type (state-key . full event)) for example: \(\(\"m.room.member\" \(\"\@mabir:matrix.org\" . event\)\) \(\"m.room.name\" \(\"\" . event\)\)\) " ;;; in other words '(("m.room.member" ("@mabir:matrix.org" . event)) ;;; ("m.room.name" ("" . event))) ) (current-state :initarg :current-state :reader current-state :writer (setf current-state)) (notifications :initarg :notifications :reader notifications :writer (setf notifications) :documentation "notifications! yay!") (summary :initarg :summary :reader summary :writer (setf summary) :documentation "summary of room") (ephemeral :initarg :ephemeral :reader ephemeral :writer (setf ephemeral) :documentation "transient, non stored things. ") (timeline :initarg :timeline ;; this is where we should be formatting our output to the user ;; from. This holds all events that matter, and then we access ;; previous events via the /messages api :reader timeline :writer (setf timeline) :documentation "this should contain a timeline-container object. setting the timeline slot should be accompanied by a call to the formatting method for timeline-container. ") (account-data :initarg :account :reader account :writer (setf account) :documentation "houses account_data field this holds specific information on a room. "))) (defmethod update-room-from-sync ((old-room chamber) (new-room chamber)) ;;; let some variables: ;;; then do this. (make-instance 'chamber :timeline (update-timeline old-room ))) ;;; dont track ephemeral events. we can hack in support for those later. ;;; dont worry about the current-state. In fact, dont worry about anything except ;;; room-name, timeline, and account-data. with these three things we should be ;;; able to update everything as needed, and we can update from there. ;;; we sort based on event type. eg m.room* is an event specific to the room. ;;; so if we just track all these events and we can update based only on the timeline. ;;; this wont give us anything like state data, but we can parse the data looking for ;;; any and all state keys, and this makes everything easier. (defmethod update-timeline ((old-room chamber) timeline &optional (where :next)) (let ((new-timeline (if (eq where :previous) (cat-timeline (timeline old-room) timeline) (cat-timeline timeline (timeline old-room))))) ()) (cond ((eq where :next) ;; ) ((eq where :previous) ;; ) (t nil)))
3,431
Common Lisp
.lisp
81
38.54321
97
0.705988
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
85a767daf8e1ff6ef4eced778c09c716cd6411f910c3eeb04bf50c9ef7332415
22,877
[ -1 ]
22,878
parse-chambers.lisp
szos_framework-client/parse-chambers.lisp
(in-package :matrix-framework) ;; (defun display-room-events-list (list-of-formatted-events) ;; (loop for event in list-of-formatted-events ;; do ;; (princ event) ;; (terpri) ;; (princ "--------------------------------------------------------------------------------") ;; (terpri))) (defun display-all-rooms-events-list (list-of-rooms-w/-formatted-events) (loop for room in list-of-rooms-w/-formatted-events do (princ "Room ID: ") (princ (car room)) (terpri) (loop for event in (cadr room) do (princ event) (terpri) (princ "--------------------------------------------------------------------------------") (terpri)) (terpri) (terpri) (terpri))) (defun get-room-timelines-from-*chambers* (&optional (rooms *chambers*)) "takes in chambers, and converts it into a list of rooms and their timelines. " (setf rooms (cdr (cadddr rooms))) ;; rooms is now a list of rooms (let ((timeline-list (mapcar #'(lambda (room) `(,(pop room) ,(assoc "timeline" room :test #'string=))) rooms))) ;; perhaps we should replace the room id with the room name? ;; (mapcar #'(lambda (tl) ;; (list (car tl) (cadr tl))) ;; timeline-list) timeline-list )) (defun parse-all-timelines (room+timeline-list) "this takes in a list of lists, structured as so:" ;; ((\"room-id\" (timeline...)) ;; (\"room-id\" (timeline...))) ;; and returns every timeline parsed via parse-timeline-events. (mapcar #'(lambda (tl) (let ((room-id (car tl)) (line (cdadr tl))) (list room-id (parse-timeline-events (get-events-from-timeline line))))) room+timeline-list)) (defun translate-chambers (&optional (chambers *join-rooms*)) (mapcar #'translate-room chambers)) (defun translate-room (room) "takes a room WITH an ID then it.... does something? what? idk. well, its called from translate-chambers, and takes a single room. it translates this room into its formatted counterpart, and stores it in a variable. " ;; (when (stringp (car room)) ;; strip the name/id from the room. ;; (setf room (cdr room))) (let ((room-name (get-room-name-from-id (car room))) (state-variables (mapcar #'gather-state-variables (cdr (assoc "events" (cdr (assoc "state" (rest room) :test #'string=)) :test #'string=)))) (timeline-events (mapcar #'gather-timeline-events (cdr (assoc "events" (cdr (assoc "timeline" (rest room) :test #'string=)) :test #'string=))))) ;; grab the events from the timeline `(,room-name (state ,state-variables) (timeline ,timeline-events)))) (defun gather-state-variables (state-events) (let ((members nil) (join-rules nil)) )) (defun gather-timeline-events (timeline-event) (let ((type (cdr (assoc "type" event :test #'string=)))) (cond ((string= type "m.room.message") (format-message-event event)) ((string= type "m.room.member") (format-member-event event)) ((string= type "m.room.encrypted") (format-encrypted-event event)) ((string= type "m.room.redaction") (format-redacted-event event)) ((string= type "m.room.history_visibility") (format-room-history-visible& event)) ((string= type "m.room.guest_access") (format-room-guest-access& event)) ((string= type "m.room.name") (format-room-name& event)) ((string= type "m.room.power_levels") (format-room-power-levels& event)) ((string= type "m.room.join_rules") (format-room-join-rules& event)) ((string= type "m.room.avatar") (format-room-avatar event)) ((string= (subseq type 0 7) "m.call.") (format-call-events event)) (t "this message type has not been implemented"))))
3,861
Common Lisp
.lisp
106
31.424528
100
0.600589
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
be146f7f4a368ce3875c6f57eb0327cf4be38f29c50c0f39268c12f3bf09d500
22,878
[ -1 ]
22,879
auth.lisp
szos_framework-client/auth.lisp
(in-package :matrix-framework) (defun smart-login () (if *session-user-auth* (progn (princ (format nil "~a is already logged in." *user-address*)) (terpri)) (progn (princ "login") (terpri) (looped-login)))) (defun looped-login () "prompts the user for username and password, and attempts to log in using those credentials. if it fails we loop back and try again, otherwise we return :success" (loop do (let ((un nil) (pw nil) (login? nil)) (princ "username: ") (setf un (read-line)) ;;(terpri) (princ "password: ") (setf pw (read-line)) ;;(terpri) (setf login? (login un pw)) (if (eq login? :invalid-credentials) (progn (princ "Login failed, try again") (terpri)) (progn (princ (cat login? " successfully logged in.")) (terpri) (terpri) (return-from looped-login :success))))))
916
Common Lisp
.lisp
35
21.285714
82
0.613455
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6029cd878861e726f0d6eb52786437213c9592d444350a65854d1131bdb6c4e0
22,879
[ -1 ]
22,880
navigate-rooms.lisp
szos_framework-client/navigate-rooms.lisp
(in-package :matrix-framework) ;;; herin lies functions to 'visit' rooms. (defparameter *join-rooms* nil) (defun init-*join-rooms* (&optional (chambers *chambers*)) (setf *join-rooms* (rest (fourth chambers)))) (defparameter *room-id->name* '() "stores the name of the rooms, with the id as the key") (defparameter *room-name->id* '()) (defun generate-names (&optional (chambers *chambers*)) "this has been updated to use the matrix api for getting state things this is... a mess. ok so were looping through the chambers, and for every room we are grabbing the state events,cause thats where the most current room name is stored. then we loop through every event, checking to see if the content is of type name. if so we set the hash with the id as the key, and the name as the value. " (setf *room-id->name* nil) (loop for room in (rest (fourth chambers)) do (setf *room-id->name* (cons `(,(car room) . ,(cdar (sync-general (cat "_matrix/client/r0/rooms/" (car room) "/state/m.room.name/")))) *room-id->name*))) (setf *room-name->id* (mapcar #'(lambda (pair) `(,(cdr pair) . ,(car pair))) *room-id->name*))) (defun generate-names-locally (&optional (chambers *chambers*)) "this operates like generate-names, but will never call the api, and only gets names from the state events. use this if your internet connection is very slow, but know that not every room will be entered into the table of names" (loop for room in (rest (fourth chambers)) do (let ((room-id (car room)) (state-events (cdadr (assoc "state" (cdr room) :test #'string=)))) (loop for event in state-events do (princ "test") (terpri))))) (defun search-for-room.name (events-list) (when (stringp (car events-list)) (setf events-list (cdr events-list))) ()) (defun get-more-room-events (room-id previous-batch &key (limit 20) (dir "b")) "calls the message sync api, " (sync-general (cat "_matrix/client/r0/rooms/" room-id "/messages?") :additional (paginate :from previous-batch :limit limit :dir dir))) (defun grab-single-room (room-name &optional (id nil) ;; (chambers (cdr (fourth *chambers*))) ) "takes a name (which could be an id, if it is set id to t) and retrieves the proper room. " ;; (mapcar chambers #'(lambda (room) ;; ())) ;; (loop for room in chambers ;; do ;; ()) (terpri) (let ((room-id (if id id (get-room-id-from-name room-name)))) (princ room-id) (terpri) (terpri) (find-room room-id))) (defun get-room-id-from-name (name &optional (db *room-name->id*)) "looks up the room id from a name in the database 'db'" (cdr (assoc name db :test #'string=))) (defun get-room-name-from-id (id &optional (db *room-id->name*)) (cdr (assoc id db :test #'string=))) (defun find-room (room-id &optional (room-list *join-rooms*)) "takes a room id, and iterates over a list of rooms, returning the one with a matching ID. " (loop for room in room-list do (when (string= (car room) room-id) (return-from find-room room)))) ()
3,125
Common Lisp
.lisp
77
36.779221
80
0.664799
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
ef547d324dbb8856e9d9292ea1fc10c4c71ef70a874cee3cbb36a0d30639dff4
22,880
[ -1 ]
22,881
interact.lisp
szos_framework-client/interact.lisp
(in-package :matrix-framework) ;;; this file is for holding our custom repl. (defparameter *allowed-commands* '(logout initialize quit exit grab-single-room view-room inspect-room-state list-rooms exit-test-repl print-commands view-room* )) (defun print-commands (&optional (commands *allowed-commands*)) (loop for command in commands do (print command))) ;;; OK! look at clim-test.lisp in ~/, as it will have an example clim window/app thingy. ;;; we are going to use clim for our gui here. it can work! Were going to build the ;;; window similar to Riot, divided (horizontally () ;;; (1/4 client-info+rooms-list) ;;; (1/2 (vertically () ;;; (3/4 room-info) ;;; (1/4 interactor)) ;;; (1/4 room-info)) (defparameter *permitted-variables* '(*room-name->id*)) (defparameter *repl-persist?* t) (defun test-repl () (setf *repl-persist?* t) (smart-login) (loop while *repl-persist?* do (test-print (test-eval (test-read))))) (defun command? (cmd ;&optional () ) (if (member cmd *allowed-commands*) t nil)) ;;; we can say, if the room name event isnt found, we search for the members, ;;; and name the room after the first 4 members. (defun test-read () (princ "command: ") (let ((cmd (read-from-string ;; lets us input commands without parens. (let ((input (read-line))) (cat "(" input ")") ;; just for now, we let this be used to )))) (cond ((or (equal cmd '(quit)) (equal cmd '(exit))) (logout) (princ "logging out and exiting application") (terpri) '(quit)) (t cmd)))) (defun quit () (logout) (setf *repl-persist?* nil)) (defun exit-test-repl () (setf *repl-persist?* nil)) (defun test-eval (form) (cond ((member (car form) *permitted-variables*) (eval (car form))) ((and (member (car form) *allowed-commands*) (eq (car form) 'view-room) (not (stringp (second form)))) (let ((room-name "")) (loop for sym in (rest form) do (setf room-name (cat room-name " " (format nil "~A" sym)))) ;; (eval (cons (car form) (subseq room-name 1))) (eval (list (car form) (subseq room-name 1))))) ((member (car form) *allowed-commands*) (eval form)) (t "Form Not Permitted")) ;; (let* ((cmd (first form)) ;; (args (rest form)) ;; ;; we can say if the arg is in the list of allowed commands OR permitted ;; ;; variables, then unquote it and add () if its a command. then we can ;; ;; say if, once its added a (, it will search for a ) symbol in the ;; ;; following args. if it finds one, it treats it as the closing paren. ;; ;; if it doesnt find one, it adds the paren at the end. this will all ;; ;; be in the mapcar. perhaps a (let () (loop for...)) instead... ;; (eval-able-args nil)) ;; (when (stringp args) ;; (mapcar #'(lambda (arg) ;; (if (symbolp arg) ;; `',arg ;; arg)) ;; args)) ;; (cond ((member cmd *permitted-variables*) ;; (eval cmd)) ;; ((member cmd *allowed-commands*) ;; (eval (cons cmd eval-able-args))) ;; (t ;; "Form Not Permitted"))) ) (defmacro quoter (thing-to-quote) `(quote ,thing-to-quote)) (defun test-print (value) (when value (princ value)) (terpri)) (defun room-name->id (name) (cdr (assoc name *room-name->id* :test #'string=))) (defun view-room (&rest name) "displays a rooms formatted list of messages. the name can be a symbol or a string. eventually we will have to work in some sort of syntax... perhaps command arg arg arg... and move the args into their own thing and detect if they're quoted or if theyre intended to be called as arguments in their own right... for now we will stick with quoting the args to keep them as data. OR BETTER YET: we could treat it all as data and quote everything unless it is of the form (:eval (lisp s expressions)) which would get evaluated before being put into the main eval statement, or perhaps just spliced in..." ;; (unless (stringp (car name)) ;; (setf name (let ((room-name "")) ;; (mapcar #'(lambda (name-as-symbol) ;; (setf room-name (cat room-name (symbol-name name-as-symbol)))) ;; name) ;; (print room-name) ;; room-name))) (if (stringp (car name)) (display-room-events-list (parse-timeline-events (get-events-from-timeline (get-timeline-from-room (grab-single-room (car name)))))) (setf name (let ((room-name "")) (mapcar #'(lambda (name-as-symbol) (setf room-name (cat room-name (symbol-name name-as-symbol)))) name) (print room-name) room-name)))) (defun view-room* (name) "name should be a string. it returns a list of events that have been formatted. " (parse-timeline-events (get-events-from-timeline (get-timeline-from-room (grab-single-room name))))) (defun set-up-rooms () (print "Syncing rooms...") (initialize) ()) (defun send-message-to (room-name message) (send-message-to-room (room-name->id room-name) message)) (defun print-timeline (name) "this is a duplicate of view-room..." (parse-timeline-events (cdr (assoc "events" (cdr (assoc "timeline" (cdr (grab-single-room name)) :test #'string=)) :test #'string=)))) (defun inspect-room-state (name) "takes a room, and searches for the state portion, and then the events portion within the state. it then formats and prints those events. " (parse-timeline-events (cdr (assoc "events" (cdr (assoc "state" (cdr (grab-single-room name)) :test #'string=)) :test #'string=)))) (defun send-message-to-room (room-id message) "this can be implemented using dynamic scope! we define a dynamic variable *current-room*, and on the first call enter a room, we wrap it all in a let, which sets *current-room* to the room thats being visited/watched. this works because dynamic variables and lexical scope are preserved through function calls, so we can just 'let' it in the first function call, and dont have to worry about it for anything below there, as each call will have no effect. see the parameter *test-val* and the associated functions at the bottom of this file. this lets us not send the room in the function call, via a &optional \(room *current-room*\) " (let ((url (cat *homeserver* "_matrix/client/r0/rooms/" room-id "/send/m.room.message?")) (content (format nil "{\"msgtype\":\"m.text\", \"body\":~S}" message))) (send-json-macro-style url content))) ;; (defun inspect-room-state (name) ;; (display-room-events-list ;; (parse-timeline-events ;; (get-events-from-timeline ;; (cdr (assoc "state" (cdr (grab-single-room name)) :test #'string=)))))) ;;; heres a list of all the things I want to implement for top level usage. (defparameter *current-room* nil) (defun gen-spaces (number-of-spaces) (cat (loop for x from 1 to number-of-spaces collect #\SPACE))) (defun names-formatter (name-list &optional (counter 0)) "return the names, formatted in a list. it adds spaces to the names list. " (if name-list (let ((len (length (car name-list))) (result nil)) (if (> len counter) (multiple-value-bind (names length) (names-formatter (cdr name-list) len) (when (> length len) (setf len length)) (setf counter len) (setf result names)) (multiple-value-bind (names length) (names-formatter (cdr name-list) counter) (when (> length counter) (setf counter length)) (setf result names))) ;; at this point, counter is the max it will be. (values (cons (cat (car name-list) (gen-spaces (- (+ counter 4) len))) result) counter)) (values nil 0))) (defun list-rooms (&optional (rooms *room-name->id*)) (let ((names-to-print (names-formatter (mapcar #'car rooms)))) (if (> (length (car names-to-print)) 40) ;;over 40 one per line (loop for name in names-to-print do (print name)) (progn (setf names-to-print (churn-2x names-to-print)) (loop for name-s in names-to-print do (print name-s)))))) (defun churn-2x (list-of-names) (when list-of-names (cons (cat (first list-of-names) (second list-of-names)) (churn-2x (cddr list-of-names))))) (defun show-room (room-name/id)) (defun watch-room (room-name/id) "this could go like show room -> poll for update -> if found show room, otherwise poll for update again.") ;; watch-room uses show room, but continually polls for more information from ;; the server, and when it gets some, it updates. but if a poll results in ;; nothing new, no updates, no reworking, no nothing is run. save them runtime ;; resources. (defun expand-room-history (room-name/id) "this will use the rooms previous batch token to retrieve more messages. it adds them to the room store, in the appropriate place, and ") (defun create-room ()) (defun invite-user-to-room (user &optional (room *current-room*))) ;(defun ) ;; (defparameter *test-val* "test") ;; (defun test-let-vars () ;; (format t "in test-let-vars, test val is ~A~%" *test-val*) ;; (let ((*test-val* "hi")) ;; (format t "in test-let-vars after let, test val is ~A~%" *test-val*) ;; (test-letter))) ;; (defun test-letter () ;; (format t "in test-letter before let, test val is ~A~%" *test-val*) ;; (let ((*test-val* "bye")) ;; (format t "after let, test val is ~A~%" *test-val*)))
9,541
Common Lisp
.lisp
232
37.767241
88
0.647795
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
354724f10a2a5ac3499768c0643e25179107d1282083f4baf038c16b43adabec
22,881
[ -1 ]
22,882
matrix-framework.lisp
szos_framework-client/matrix-framework.lisp
;;;; matrix-framework.lisp (in-package #:matrix-framework) ;;; "matrix-framework" goes here. Hacks and glory await! (defparameter *session-user-auth* nil "users authentication token. should be set upon login") (defparameter *device-id* nil "devices id, used to differentiate between devices. currently resets on every login.") (defparameter *user-address* nil "users address, eg @username:matrix.org.") (defparameter *chambers* nil "holds an alist of room ids and chamber class instances.") (defparameter *settings* nil) (defparameter *sync-batch-token* nil "holds the batch token, which tells us how much to sync. need to implement a pagination function. ") (defparameter *homeserver* "https://matrix.org/" "holds the homeserver string. set upon login, then should be locked. ") (defmacro cat (&rest strs) `(concatenate 'string ,@strs)) (defun paginate (&key (to nil) (from nil) (limit nil) (dir nil)) "returns a string for paginating based on what was sent in. " (when (or to from limit dir) (cat (when from (format nil "&from=~A" from)) (when to (format nil "&to=~A" to)) (when limit (format nil "&limit=~A" limit)) (when dir (format nil "&dir=~A" dir))))) (defun aquire-public-rooms (&optional (paginate nil)) (recieve-json (cat *homeserver* "_matrix/client/r0/publicRooms"))) (defun post-room-to-directory ()) (defun initialize (&optional (data nil data-provided-p)) "this initializes our dataset. calling generate-names takes about 1.5x-2x longer than the general sync api. this is probably because generate names is calling the name-getting api for every room. " (multiple-value-bind (next-batch chambers) ;; account) (parse-sync (if data-provided-p data (sync-general "_matrix/client/r0/sync?"))) (setf *chambers* chambers) ;; (setf *settings* account) (setf *sync-batch-token* (cdr next-batch))) (init-*join-rooms*) (princ "Initial sync completed, obtaining room names...") (terpri) (generate-names)) (defun refresh (&optional (data nil data-provided-p)) (multiple-value-bind (next-batch chambers) ;; account) (parse-sync (if data-provided-p data (sync-general "_matrix/client/r0/sync?"))) (setf *chambers* chambers) ;; (setf *settings* account) (init-*join-rooms*) (setf *sync-batch-token* (cdr next-batch)))) (defun parse-sync (sync-data) (let ((room-list (assoc "rooms" sync-data :test #'string=)) (next-batch (assoc "next_batch" sync-data :test #'string=)) (room-holder nil)) (setf room-holder (cdr (fourth room-list))) ;; (loop for room in room-holder ;; ) (values next-batch room-list))) ;;"_matrix/client/r0/sync?" (defun sync-general (api &key (since nil) (filter nil) (full-state nil) (presence nil) (timeout nil) (additional nil)) (recieve-json (concatenate 'string *homeserver* api (when since (concatenate 'string "&since=" since)) (when filter (concatenate 'string "&filter=" filter)) (when full-state (concatenate 'string "&full_state=" full-state)) (when presence (concatenate 'string "&set_presence=" presence)) (when timeout (concatenate 'string "&timeout=" timeout)) (when additional (format nil "~A" additional))))) (defun sync-again () (multiple-value-bind (batch chambers) ;;acct) (parse-sync (sync-general "_matrix/client/r0/sync?" :since *sync-batch-token*)) (setf *sync-batch-token* (cdr batch)) ;; (setf *settings* acct ;;(update-acct acct) ;; ) chambers)) ;; (update-*chambers* (sync-again)) (defun update-*chambers* (data) "lists the rooms with their updates" (cddr data)) ;; (defun parse-sync (sync-data) ;; "takes in the results of sync-general, and parses them." ;; (let ((next-batch (assoc "next_batch" sync-data :test #'string=)) ;; (rooms (assoc "rooms" sync-data :test #'string=)) ;; (device-lists (assoc "device_lists" sync-data :test #'string=)) ;; used for encryption. ;; (presence (assoc "presence" sync-data :test #'string=)) ;; ignore for now. ;; (groups (assoc "groups" sync-data :test #'string=)) ;; ? ;; (to-device (assoc "to_device" sync-data :test #'string=)) ;; used for device management ;; (account-data (assoc "account_data" sync-data :test #'string=)) ;; used for storing settings regarding the user. things like notifications settings, or what rooms are direct rooms and not groups. ;; (device-one-time-keys-count (assoc "device_one_time_keys_count" sync-data :test #'string=))) ;; (values (cdr next-batch) ;; (generate-room-list-init rooms) ;; (cdr account-data)))) (defun parse-rooms (room-set) "takes a list of rooms and operates over them to parse the rooms contained therin." (let ((room-list (third room-set)) (join nil)) (setf join (pop room-list)) ;;(parse-single-room (second room-list)) room-list)) (defun generate-room-list-init (rooms) (mapcar #'parse-single-room (parse-rooms rooms))) (defun parse-single-room (room &optional (old-room (make-instance 'chamber))) "returns an updated room, or if an old room isnt provided, a new room with no history" (let ((room-id (first room)) (state (second room)) (notifications (third room)) (summary (fourth room)) (ephemeral (fifth room)) (timeline (sixth room)) (account-data (seventh room)) ;; (metadata (make-instance 'chamber-current-state)) ) ;; (setf metadata (generate-current-state metadata state)) (cons room-id (update-room old-room `(("room-id" . ,room-id) ("state" . ,state) ("notifications" . ,notifications) ("summary" . ,summary) ("ephemeral" . ,ephemeral) ("timeline" . ,timeline) ("account-data" . ,account-data)))))) (defun send-json (url content &rest key-plist) (if key-plist (let ((stream (drakma:http-request url :want-stream t :method :post :content-type "application/json" :content content :additional-headers `(("Authorization" . ,(concatenate 'string "Bearer " *session-user-auth*))) key-plist))) ;; (get-json-from-stream stream :utf-8 :alist) (yason:parse stream :object-as :alist)) (let ((stream (drakma:http-request url :want-stream t :method :post :content-type "application/json" :content content :additional-headers `(("Authorization" . ,(concatenate 'string "Bearer " *session-user-auth*)))))) ;; (get-json-from-stream stream :utf-8 :alist) (yason:parse stream :object-as :alist)))) (defmacro send-json-macro-style (url content &rest key-plist) (if key-plist `(let ((stream (drakma:http-request ,url :want-stream t :method :post :content-type "application/json" :content ,content :additional-headers `(("Authorization" . ,(concatenate 'string "Bearer " *session-user-auth*))) ,@key-plist))) ;; (get-json-from-stream stream :utf-8 :alist) (yason:parse stream :object-as :alist)) `(let ((stream (drakma:http-request ,url :want-stream t :method :post :content-type "application/json" :content ,content :additional-headers `(("Authorization" . ,(concatenate 'string "Bearer " *session-user-auth*)))))) ;; (get-json-from-stream stream :utf-8 :alist) (yason:parse stream :object-as :alist)))) (defun recieve-json (url) (let ((stream (drakma:http-request url :want-stream t :method :get :additional-headers `(("Authorization" . ,(concatenate 'string "Bearer " *session-user-auth*)))))) (yason:parse stream :object-as :alist))) (defun login (username password) "generates an authentication token by logging in, if no token is found. otherwise logs out and then back in. " (if (not *session-user-auth*) (let* ((data (let ((stream (drakma:http-request "https://matrix.org/_matrix/client/r0/login" :want-stream t :method :post :content-type "application/json" :content (format nil "{\"type\":\"m.login.password\", \"user\":~S, \"password\":~S, \"device_id\":\"SBCLclient\"}" username password) ))) (setf (flexi-streams:flexi-stream-external-format stream) :utf-8) (yason:parse stream :object-as :alist))) (token (cdr (assoc "access_token" data :test #'string=))) (device-id (cdr (assoc "device_id" data :test #'string=))) (user-id (cdr (assoc "user_id" data :test #'string=)))) ;; prepare for kludge (when (equal (car data) '("error" . "Invalid password")) (return-from login :invalid-credentials)) (setf *session-user-auth* token) (setf *device-id* device-id) (setf *user-address* user-id)) (progn ;; if user is logged in, logout, and then login under new user. (logout) (login username password)))) (defun logout () (recieve-json (cat *homeserver* "_matrix/client/r0/logout")) (setf *session-user-auth* nil) (setf *device-id* nil) (setf *user-address* nil) :logged-out) ;;; create a list of rooms, ;;; translate that list of rooms into a list of rooms, with their appropriate ;;; parameters stored logically! for example: ;; ((rooom-name (state ;; (general-state-variables . values)) ;; (timeline ;; (timeline-events . whatever-figure-value-later)) ;; (etc ;; (etcetc . etcetcetc))) ;; (room-name (..)))
9,470
Common Lisp
.lisp
233
35.93133
200
0.659983
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
461f06097904d9ae1fdd226e665cf769b49806025335cb54b66e636c2ea49a0e
22,882
[ -1 ]
22,883
matrix-framework.asd
szos_framework-client/matrix-framework.asd
;;;; matrix-framework.asd (asdf:defsystem #:matrix-framework :description "This heres a bad description... Tested on SBCL linux." :author "Your Name <[email protected]>" :license "GPL v3" :serial t :depends-on (#:drakma #:flexi-streams #:yason #:clim-lisp) :components ((:file "package") (:file "matrix-framework") (:file "parse-timeline,etc") (:file "parse-chambers") (:file "navigate-rooms") (:file "auth") (:file "interact")))
541
Common Lisp
.asd
17
24.529412
70
0.58046
szos/framework-client
2
0
0
GPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
07235afb5d44cdf759673d293fac63d743a5c53ec9bd6c18227ae835e30d1c22
22,883
[ -1 ]
22,907
dump.lisp
BonfaceKilz_gn-dataset-dump/dump.lisp
(defpackage :dump (:use :common-lisp :cl-json) (:import-from :alexandria :once-only :iota :plist-alist :with-gensyms) (:import-from :listopia :all :any :split-at) (:import-from :ironclad :with-octet-input-stream :with-octet-output-stream :with-digesting-stream :digest-length) (:import-from :str :concat :contains? :join :s-rest :split :starts-with? :trim-right :words) (:import-from :arrows :-> :->>) (:import-from :trivia :lambda-match :match) (:import-from :trivial-utf-8 :string-to-utf-8-bytes :write-utf-8-bytes :utf-8-bytes-to-string) (:import-from :lmdb :with-env :*env* :get-db :with-txn :put :g3t :uint64-to-octets :with-cursor :cursor-first :do-cursor :cursor-del :octets-to-uint64 :db-statistics) (:export :main)) (in-package :dump) ;; ENV SETTINGS (defvar *blob-hash-digest* :sha256) ;; Some helper functions (defun assoc-ref (alist key &key (test #'equalp)) "Given an association list ALIST, return the value associated with KEY." (match (assoc key alist :test test) ((cons _ value) value))) (defmacro with-sampledata-db ((db database-directory &key write) &body body) "Create a new LMDB database in DATABASE-DIRECTORY and execute BODY with a transaction open on DB." (with-gensyms (env) (once-only (database-directory write) `(with-env (,env ,database-directory :if-does-not-exist :create :map-size (* 100 1024 1024)) (let ((,db (get-db nil :env ,env))) (with-txn (:env ,env :write ,write) ,@body)))))) ;; Hash functions and operations on bytevectors (defun metadata-key (hash key) "Return the database key to retrieve metadata KEY associated with blob of HASH." (concatenate '(vector (unsigned-byte 8)) hash (string-to-utf-8-bytes (concat ":" key)))) (defun write-bytevector-with-length (bv stream) "Write length of BV followed by BV itself to STREAM. The length is written as a little endian 64-bit unsigned integer." (write-sequence (-> bv length uint64-to-octets) stream) ;; Accomodate strings and floats by encoding to json (write-sequence (-> bv json:encode-json-to-string string-to-utf-8-bytes) stream)) (defun hash-vector-length (hash-vector) "Return the number of hashes in HASH-VECTOR." (/ (length hash-vector) (digest-length *blob-hash-digest*))) (defun bv-hash (bv &optional metadata) "Return the hash of a bytevector BV and optionally write a HEADER to the hash stream" (with-digesting-stream (stream *blob-hash-digest*) ;; Write bytevector (write-bytevector-with-length bv stream) ;; Write metadata (mapc (lambda-match ((cons key value) (write-bytevector-with-length (string-to-utf-8-bytes key) stream) (write-bytevector-with-length (etypecase value (string (string-to-utf-8-bytes value)) ((unsigned-byte 64) (uint64-to-octets value)) ((vector (unsigned-byte 8)) value)) stream))) metadata))) (defun hash-vector-ref (hash-vector n) "Return the Nth hash in HASH-VECTOR." (let ((hash-length (digest-length *blob-hash-digest*))) (make-array hash-length :element-type '(unsigned-byte 8) :displaced-to hash-vector :displaced-index-offset (* n hash-length)))) ;; Matrix Data Structures and associated helper functions (defstruct sampledata matrix metadata) (defstruct sampledata-db-matrix db hash nrows ncols row-pointers column-pointers array transpose) (defun array-to-list (array) "Convert ARRAY into a LIST." (let* ((dimensions (array-dimensions array)) (depth (1- (length dimensions))) (indices (make-list (1+ depth) :initial-element 0))) (labels ((recurse (n) (loop for j below (nth n dimensions) do (setf (nth n indices) j) collect (if (= n depth) (apply #'aref array indices) (recurse (1+ n)))))) (recurse 0)))) (defun list-dimensions (list depth) "Return the array dimensions of a LIST given the LIST's DEPTH." (loop repeat depth collect (length list) do (setf list (car list)))) (defun list-to-array (list depth) "Convert a LIST into an ARRAY given the lists DEPTH." (make-array (list-dimensions list depth) :initial-contents list)) (defun matrix-row (matrix n) "Return the Nth row of MATRIX." (let ((ncols (array-dimension matrix 1))) (make-array ncols :element-type (array-element-type matrix) :displaced-to matrix :displaced-index-offset (* n ncols)))) (defun matrix-column (matrix n) "Return the Nth column of MATRIX." (let ((column (make-array (array-dimension matrix 0)))) (dotimes (i (length column)) (setf (aref column i) (aref matrix i n))) column)) ;; Working with sample data matrixes (defun sampledata-db-get (db key) "Get sampledata with KEY from DB. KEY may be a hash or a string. If it is a string, it is encoded into octets before querying the database." (g3t db (if (stringp key) (string-to-utf-8-bytes key) key))) (defun sampledata-db-put (db data &optional metadata) "Put DATA into DB. Associate HEADER, representing the name of the columns, with DATA. Return the hash." (let ((hash (bv-hash data metadata))) (unless (sampledata-db-get db hash) (put db hash data) (mapc (lambda-match ((cons key value) (put db (metadata-key hash key) value))) metadata)) hash)) (defun sampledata-db-metadata-get (db hash key) "Get metadata associated with KEY, HASH from sampledata DB." (sampledata-db-get db (metadata-key hash key))) (defun sampledata-db-current-matrix-hash (db) "Return the hash of the current matrix in the sampledata matrix DB." (hash-vector-ref (sampledata-db-get db "versions") 0)) (defun sampledata-db-matrix (db hash) "Return the matrix identified by HASH from sampledata matrix DB." (let ((nrows (octets-to-uint64 (sampledata-db-metadata-get db hash "nrows"))) (ncols (octets-to-uint64 (sampledata-db-metadata-get db hash "ncols"))) (hash-length (digest-length *blob-hash-digest*))) (make-sampledata-db-matrix :db db :hash hash :nrows nrows :ncols ncols :row-pointers (make-array (* nrows hash-length) :element-type '(unsigned-byte 8) :displaced-to (sampledata-db-get db hash)) :column-pointers (make-array (* ncols hash-length) :element-type '(unsigned-byte 8) :displaced-to (sampledata-db-get db hash) :displaced-index-offset (* nrows hash-length))))) (defun sampledata-db-matrix-put (db db-matrix) "Put sampledata MATRIX into DB and return the hash" (let* ((hash-length (digest-length *blob-hash-digest*)) (matrix (sampledata-matrix db-matrix)) (metadata (->> (sampledata-metadata db-matrix) json:encode-json-alist-to-string))) (match (array-dimensions matrix) ((list nrows ncols) (let* ((data (with-octet-output-stream (stream) (dotimes (i nrows) (write-sequence (sampledata-db-put db (->> i (matrix-row matrix) json:encode-json-to-string string-to-utf-8-bytes)) stream)) (dotimes (j ncols) (write-sequence (sampledata-db-put db (->> j (matrix-column matrix) json:encode-json-to-string string-to-utf-8-bytes)) stream)))) (row-pointers (make-array (* nrows hash-length) :element-type '(unsigned-byte 8) :displaced-to data)) (column-pointers (make-array (* ncols hash-length) :element-type '(unsigned-byte 8) :displaced-to data :displaced-index-offset (* nrows hash-length)))) (sampledata-db-put db data `(("nrows" . ,nrows) ("ncols" . ,ncols) ("metadata" . ,metadata) ("row-pointers" . ,row-pointers) ("column-pointers" . ,column-pointers)))))))) (defun (setf sampledata-db-current-matrix-hash) (hash db) "Set HASH as the current matrix in the sampledata matrix DB." ;; Prepend hash into versions array. (put db (string-to-utf-8-bytes "versions") (concatenate '(vector (unsigned-byte 8)) hash (sampledata-db-get db "versions"))) ;; Write a read-optimized copy of the current matrix into the database (let ((matrix (sampledata-db-matrix db hash))) (put db (string-to-utf-8-bytes "current") (sampledata-db-put db (with-octet-output-stream (stream) (dotimes (i (sampledata-db-matrix-nrows matrix)) (write-sequence (->> i (sampledata-db-matrix-row-ref matrix) json:encode-json-to-string string-to-utf-8-bytes) stream)) (dotimes (j (sampledata-db-matrix-ncols matrix)) (write-sequence (->> j (sampledata-db-matrix-column-ref matrix) json:encode-json-to-string string-to-utf-8-bytes) stream))) `(("matrix" . ,hash)))))) (defun sampledata-db-current-matrix (db) "Return the latest version of the matrix in DB." (let* ((current-matrix-hash (sampledata-db-current-matrix-hash db)) (nrows (octets-to-uint64 (sampledata-db-metadata-get db current-matrix-hash "nrows"))) (ncols (octets-to-uint64 (sampledata-db-metadata-get db current-matrix-hash "ncols")))) (make-sampledata-db-matrix :db db :nrows nrows :ncols ncols :array (make-array (list nrows ncols) :initial-contents (loop for i from 0 to (- nrows 1) collect (sampledata-db-matrix-row-ref (sampledata-db-matrix db current-matrix-hash) i))) :transpose (make-array (list ncols nrows) :initial-contents (loop for i from 0 to (- ncols 1) collect (sampledata-db-matrix-column-ref (sampledata-db-matrix db current-matrix-hash) i)))))) (defun sampledata-db-all-matrices (db) "Return a list of all matrices in DB, newest first." (let ((all-matrix-hashes (sampledata-db-get db "versions"))) (mapcar (lambda (i) (sampledata-db-matrix db (hash-vector-ref all-matrix-hashes i))) (iota (hash-vector-length all-matrix-hashes))))) (defun sampledata-db-current-matrix-ref (matrix) "Return MATRIX as a 2-D array." (let ((array (sampledata-db-matrix-array matrix))) (if array array (let* ((nrows (sampledata-db-matrix-nrows matrix)) (ncols (sampledata-db-matrix-ncols matrix)) (array (make-array (list nrows ncols) :element-type '(unsigned-byte 8)))) (dotimes (i nrows) (let ((row (sampledata-db-matrix-row-ref matrix i))) (dotimes (j ncols) (setf (aref array i j) (aref row j))))) array)))) (defun sampledata-db-matrix-row-ref (matrix i) "Return the Ith row of sampledata db MATRIX." (let ((db (sampledata-db-matrix-db matrix)) (array (sampledata-db-matrix-array matrix))) (coerce (if array (matrix-row array i) (json:decode-json-from-string (utf-8-bytes-to-string (sampledata-db-get db (hash-vector-ref (sampledata-db-matrix-row-pointers matrix) i))))) 'vector))) (defun sampledata-db-matrix-column-ref (matrix j) "Return the Jth row of sampledata db MATRIX." (let ((db (sampledata-db-matrix-db matrix)) (transpose (sampledata-db-matrix-array matrix))) (coerce (if transpose (matrix-row transpose j) (json:decode-json-from-string (utf-8-bytes-to-string (sampledata-db-get db (hash-vector-ref (sampledata-db-matrix-column-pointers matrix) j))))) 'vector))) (defun json-file->sampledata (file) "Convert FILE to SAMPLEDATA." (let* ((json-data (json:decode-json-from-source (pathname file))) (headers (assoc-ref json-data :headers)) (matrix (assoc-ref json-data :data)) (nrows (length matrix)) (ncols (length (first matrix)))) (make-sampledata :matrix (make-array (list nrows ncols) :initial-contents matrix) :metadata `(("header" . ,headers))))) (defun collect-garbage (db) "Delete all keys in DB that are not associated with a live hash." (with-cursor (cursor db) (cursor-first cursor) (do-cursor (key value cursor) (unless (live-key-p db key) (cursor-del cursor))))) (defun find-index (function n) "Return the index between 0 and n-1 (both inclusive) for which FUNCTION returns non-nil. If no such index exists, return nil. FUNCTION is invoked as (FUNCTION INDEX). The order of invocation of FUNCTION is unspecified." (unless (zerop n) (if (funcall function (1- n)) (1- n) (find-index function (1- n))))) (defun for-each-indexed (function list &optional (start 0)) "Apply FUNCTION successively on every element of LIST. FUNCTION is invoked as (FUNCTION INDEX ELEMENT) where ELEMENT is an element of LIST and INDEX is its index. START is the index to use for the first element." (match list ((list* head tail) (funcall function start head) (for-each-indexed function tail (1+ start))))) (defun hash-in-hash-vector-p (hash hash-vector) "Return non-nil if HASH is in HASH-VECTOR. Else, return nil." (find-index (lambda (i) (equalp (hash-vector-ref hash-vector i) hash)) (hash-vector-length hash-vector))) (defun live-key-p (db key) "Return non-nil if KEY is live. Else, return nil." (or (equalp key (string-to-utf-8-bytes "current")) (equalp key (string-to-utf-8-bytes "versions")) (equalp key (sampledata-db-get db "current")) (let ((versions-hash-vector (sampledata-db-get db "versions")) (key-hash-prefix (make-array (digest-length *blob-hash-digest*) :element-type '(unsigned-byte 8) :displaced-to key))) (or (hash-in-hash-vector-p key-hash-prefix versions-hash-vector) (find-index (lambda (i) (hash-in-hash-vector-p key-hash-prefix (sampledata-db-get db (hash-vector-ref versions-hash-vector i)))) (hash-vector-length versions-hash-vector)))))) (defun import-into-sampledata-db (data db-path) "Import MATRIX which is a sampledata-matrix object into DB-PATH." (with-sampledata-db (db db-path :write t) (let* ((hash (sampledata-db-matrix-put db data)) (db-matrix (sampledata-db-matrix db hash))) ;; Read written data back and verify. (unless (and (all (lambda (i) (equalp (matrix-row (sampledata-matrix data) i) (sampledata-db-matrix-row-ref db-matrix i))) (iota (sampledata-db-matrix-nrows db-matrix))) (all (lambda (i) (equalp (matrix-column (sampledata-matrix data) i) (sampledata-db-matrix-column-ref db-matrix i))) (iota (sampledata-db-matrix-ncols db-matrix)))) ;; Roll back database updates. (collect-garbage db) ;; Exit with error message. (format *error-output* "Rereading and verifying sampledata matrix written to \"~a\" failed. This is a bug. Please report it. " db-path) (uiop:quit 1)) ;; Set the current matrix. (setf (sampledata-db-current-matrix-hash db) hash)))) (defun print-sampledata-db-info (database-directory) (with-sampledata-db (db database-directory) (format t "Path: ~a~%Versions: ~a~%Keys: ~a~%~%" database-directory (length (sampledata-db-all-matrices db)) (getf (db-statistics db) :entries)) (for-each-indexed (lambda (i matrix) (format t "Version ~a Dimensions: ~a x ~a~%" (1+ i) (sampledata-db-matrix-nrows matrix) (sampledata-db-matrix-ncols matrix))) (sampledata-db-all-matrices db)))) (defun main () (match (uiop:command-line-arguments) ((list "import" json-data dump-dir) (fad:walk-directory json-data (lambda (el) (let* ((dataset-name (-> el pathname-directory last car)) (db-path (make-pathname :defaults dump-dir :directory (append (pathname-directory dump-dir) (list dataset-name (pathname-name el)))))) (format t "Dumping: ~a~%" db-path) (import-into-sampledata-db (json-file->sampledata (namestring el)) db-path))))) ((list "info" sampledata-database) (print-sampledata-db-info (fad:pathname-as-directory sampledata-database))) (_ (format t "Usage: Import JSON-DATA into DUMP-DIR: dump import JSON-DATA/ DUMP-DIR/ Print info about SAMPLEDATA-DATABASE: dump info SAMPLEDATA-DATABASE ") (uiop:quit 1))))
16,209
Common Lisp
.lisp
433
32.353349
96
0.672774
BonfaceKilz/gn-dataset-dump
2
1
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
6a6a623dbd954b7f2b2ddc61cf1edc983c1ed62a7ac650a77e050cbef5b774f2
22,907
[ -1 ]
22,908
build.lisp
BonfaceKilz_gn-dataset-dump/build.lisp
(require :asdf) ;; Load genenetwork.asd from the current directory. (asdf:load-asd (merge-pathnames "dump.asd" (directory-namestring *load-truename*))) (asdf:make :dump)
204
Common Lisp
.lisp
5
33
72
0.64467
BonfaceKilz/gn-dataset-dump
2
1
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
f952ee4cbe1e8bde186824de7f9e0e3419c8c0630c0429125b0c5ff1e3dc66f7
22,908
[ -1 ]
22,909
dump.asd
BonfaceKilz_gn-dataset-dump/dump.asd
(in-package cl-user) (asdf:defsystem #:dump :description "GeneNetwork matrix database tool" :version "0.1.0" :author "The GeneNetwork team" :licence "GNU General Public License version 3 or later" :depends-on (:alexandria :arrows :cl-conspack :cl-dbi :trivia :cl-fad :cl-json :ironclad :listopia :lmdb :str :trivial-utf-8) :components ((:file "dump")) :build-operation "program-op" :build-pathname "dump" :entry-point "dump:main")
531
Common Lisp
.asd
21
19.52381
58
0.625984
BonfaceKilz/gn-dataset-dump
2
1
0
AGPL-3.0
9/19/2024, 11:28:00 AM (Europe/Amsterdam)
4e53f220f8ac3f7b719ab00fcfe50dd64d1c50dcfe3990c849c83dab9188ae79
22,909
[ -1 ]
22,927
build.lisp
exercism_common-lisp-test-runner/build/build.lisp
(load "quicklisp/setup.lisp") (ql:quickload "test-runner") (let ((bin-dir (make-pathname :directory '(:relative "bin")))) (ensure-directories-exist bin-dir) (sb-ext:save-lisp-and-die (merge-pathnames "test-runner" bin-dir) :toplevel #'test-runner:test-runner :executable t))
332
Common Lisp
.lisp
7
38.285714
67
0.617284
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c62b61245068d26b23ad33c01f528bb00a0a980b4d42e3a4e01f403701728d9f
22,927
[ -1 ]
22,928
astonish.lisp
exercism_common-lisp-test-runner/src/test-runner/astonish.lisp
;;;; An AST Manipulation Library ;;;; This will grow and hopefully be shared by all of our tooling, even ;;;; eventually being used to test for implementation in the test-suites (defpackage astonish (:use :cl :alexandria) (:export :load-forms-from-file :select-conses :macroexpand-select)) (in-package :astonish) ;;; Public Functions ----------------------------------------------------------- (defun load-forms-from-file (file &optional package) "Read forms from a lisp file without any evaluation" (let ((current-package (or package *package*))) (uiop:with-safe-io-syntax (:package current-package) (uiop:read-file-forms (lisp-file file))))) (defun select-conses (path forms) "Given a path (a list of car's) and list of forms, return all matching conses. The second return value is the same selection, but inverted" (destructuring-bind (x &rest xs) path (let ((selected (filter-conses-by-car x forms))) (if (null xs) (values selected (cons-difference forms selected)) (select-conses xs (apply #'append selected)))))) (defun macroexpand-select (macros form) "Recursively expand all occurrences of select macros" (map-inodes (lambda (n) (if (find (car n) macros) (macroexpand n) n)) form)) ;;; Private Helper Functions --------------------------------------------------- (defun filter-conses-by-car (car forms) "Filter forms so that only ones with the specified car remain" (remove-if-not (lambda (x) (and (listp x) (string= car (car x)))) forms)) (defun map-inodes (function form) "Maps the given function over all the inner nodes of a tree" (if (proper-list-p form) (funcall function (mapcar (lambda (n) (map-inodes function n)) form)) form)) (defun cons-difference (a b) "Like set-difference, but filters for conses and preserves order" (remove-if (lambda (x) (or (find x b) (atom x))) a)) (defun lisp-file (file) "Adds a .lisp extension to pathnames without an extension" (if (pathname-type file) file (make-pathname :type "lisp" :defaults file)))
2,061
Common Lisp
.lisp
41
46.609756
80
0.672637
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9b3afda616b8faf2d098b3f71146fe611993064ad8b82525e28bacea61752d57
22,928
[ -1 ]
22,929
test-runner.lisp
exercism_common-lisp-test-runner/src/test-runner/test-runner.lisp
;;;; Exercism Common Lisp Test Runner (defpackage test-runner (:use :cl) (:export :test-runner)) (in-package :test-runner) ;;; Set some parameters (defvar *max-output-chars* 500) (defvar *results-file* "results.json") ;;; Load and run tests (defun get-test-results (slug src-path out-path) (let* ((*default-pathname-defaults* (truename src-path)) (test-slug (format nil "~A-test" slug)) (*package* (progn (load test-slug) (find-package (string-upcase test-slug)))) (test-forms (astonish:load-forms-from-file test-slug)) (test-macros (mapcar #'cadr (astonish:select-conses '(defmacro) test-forms))) (tests (mapcar (lambda (x) (astonish:macroexpand-select test-macros x)) (astonish:select-conses '(test) test-forms)))) (mapcan #'process-test tests))) (defun process-test (test) (let* ((*test-code* (with-output-to-string (*standard-output*) (loop :for sexpr :in test :unless (atom sexpr) :do (fresh-line) (write sexpr :pretty t :case :downcase)))) (5am:*test-dribble* nil) (*standard-output* (make-string-output-stream)) (results (fiveam:run (eval test))) (*test-output* (truncate-output (get-output-stream-string *standard-output*))) (*test-progress* (cons 0 (length results)))) (declare (special *test-code* *test-output* *test-progress*)) (loop :for result :in results :do (incf (car *test-progress*)) :collect (process-test-result result)))) ;;; Methods for processing different test results (defmethod process-test-result ((result 5am::test-passed)) (st-json:jso "name" (get-test-description result) "status" "pass" "message" :null "output" *test-output* "test_code" *test-code*)) (defmethod process-test-result ((result 5am::unexpected-test-failure)) (st-json:jso "name" (get-test-description result) "status" "error" "message" (princ-to-string (5am::actual-condition result)) "output" :null "test_code" *test-code*)) (defmethod process-test-result ((result 5am::test-failure)) (st-json:jso "name" (get-test-description result) "status" "fail" "message" (5am::reason result) "output" *test-output* "test_code" *test-code*)) (defmethod process-test-result ((result 5am::test-skipped))) ;;; Get information from test-results (defun get-test-description (test-result) (let* ((test-case (5am::test-case test-result)) (description (5am::description test-case)) (name (string (5am::name test-case)))) (format nil "~A (~A/~A)" (if (string= description "") name description) (car *test-progress*) (cdr *test-progress*)))) (defun truncate-output (output) (if (> (length output) *max-output-chars*) (format nil "~A...~%Output was truncated. Please limit to ~A characters." (subseq output 0 *max-output-chars*) *max-output-chars*) output)) ;;; Generate final report (defun results-status (results) (every (lambda (res) (string= "pass" (st-json:getjso "status" res))) results)) (defmethod generate-report ((err error)) (st-json:jso "version" 2 "status" "error" "message" (princ-to-string err))) (defmethod generate-report ((results list)) (st-json:jso "version" 2 "status" (if (results-status results) "pass" "fail") "tests" results)) ;;; Invoke the test-runner (defun test-runner () (destructuring-bind (slug src-path out-path) (uiop:command-line-arguments) (let ((results-file (merge-pathnames (truename out-path) *results-file*))) (with-open-file (fs results-file :direction :output :if-exists :supersede) (st-json:write-json (generate-report (handler-case (get-test-results slug src-path out-path) (error (c) c))) fs)))))
4,093
Common Lisp
.lisp
88
37.943182
87
0.611779
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b171ac9a8851e32b9cceca720943a622f47de23e7ccacfe8574755d17a86d3d9
22,929
[ -1 ]
22,930
success.lisp
exercism_common-lisp-test-runner/tests/success/success.lisp
(cl:defpackage :success (:use :common-lisp) (:export :leap-year-p)) (in-package :success) (defun divisible-by-p (n d) (= 0 (rem n d))) (defun leap-year-p (year) (and (divisible-by-p year 4) (or (not (divisible-by-p year 100)) (divisible-by-p year 400))))
275
Common Lisp
.lisp
9
27.333333
44
0.642586
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1113080cf385e30cc9207fda36e23ea3017a3ec03fc4dc4844bb7e5dc198207f
22,930
[ -1 ]
22,931
success-test.lisp
exercism_common-lisp-test-runner/tests/success/success-test.lisp
;; Ensures that success.lisp and the testing library are always loaded (eval-when (:compile-toplevel :load-toplevel :execute) (load "success") (quicklisp-client:quickload :fiveam)) ;; Defines the testing package with symbols from leap and FiveAM in scope ;; The `run-tests` function is exported for use by both the user and test-runner (defpackage :success-test (:use :cl :fiveam) (:export :run-tests)) ;; Enter the testing package (in-package :success-test) ;; Define and enter a new FiveAM test-suite (def-suite* success-suite) (test vanilla-leap-year (is (success:leap-year-p 1996))) (test any-old-year (is (not (success:leap-year-p 1997)))) (test non-leap-even-year (is (not (success:leap-year-p 1998)))) (test century (is (not (success:leap-year-p 1900)))) (test exceptional-century (is (success:leap-year-p 2400))) (defun run-tests (&optional (test-or-suite 'leap-suite)) "Provides human readable results of test run. Default to entire suite." (run! test-or-suite))
994
Common Lisp
.lisp
21
45.285714
80
0.744548
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
127cb551fc703d78d4c3b2107518b3441acb74e32a588c7dc39ded9be5d5c0a4
22,931
[ -1 ]
22,932
syntax-error-test.lisp
exercism_common-lisp-test-runner/tests/syntax-error/syntax-error-test.lisp
;; Ensures that syntax-error.lisp and the testing library are always loaded (eval-when (:compile-toplevel :load-toplevel :execute) (load "syntax-error") (quicklisp-client:quickload :fiveam)) ;; Defines the testing package with symbols from leap and FiveAM in scope ;; The `run-tests` function is exported for use by both the user and test-runner (defpackage :syntax-error-test (:use :cl :fiveam) (:export :run-tests)) ;; Enter the testing package (in-package :syntax-error-test) ;; Define and enter a new FiveAM test-suite (def-suite* syntax-error-suite) (test vanilla-leap-year (is (syntax-error:leap-year-p 1996))) (test any-old-year (is (not (syntax-error:leap-year-p 1997)))) (test non-leap-even-year (is (not (syntax-error:leap-year-p 1998)))) (test century (is (not (syntax-error:leap-year-p 1900)))) (test exceptional-century (is (syntax-error:leap-year-p 2400))) (defun run-tests (&optional (test-or-suite 'leap-suite)) "Provides human readable results of test run. Default to entire suite." (run! test-or-suite))
1,043
Common Lisp
.lisp
21
47.666667
80
0.747285
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a6b8c6ce242593acdb7e8b61281c738f332308d00f6197801c47bedaeda69e44
22,932
[ -1 ]
22,933
all-fail.lisp
exercism_common-lisp-test-runner/tests/all-fail/all-fail.lisp
(cl:defpackage :all-fail (:use :common-lisp) (:export :leap-year-p)) (in-package :all-fail) (defun divisible-by-p (n d) (= 0 (rem n d))) (defun leap-year-p (year) (not (and (divisible-by-p year 4) (or (not (divisible-by-p year 100)) (divisible-by-p year 400)))))
293
Common Lisp
.lisp
10
25.3
44
0.620939
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
090da2c3d70916e0326b390bd294789e1c2c4587977085fdfe97edea8d118a5c
22,933
[ -1 ]
22,934
all-fail-test.lisp
exercism_common-lisp-test-runner/tests/all-fail/all-fail-test.lisp
;; Ensures that all-fail.lisp and the testing library are always loaded (eval-when (:compile-toplevel :load-toplevel :execute) (load "all-fail") (quicklisp-client:quickload :fiveam)) ;; Defines the testing package with symbols from leap and FiveAM in scope ;; The `run-tests` function is exported for use by both the user and test-runner (defpackage :all-fail-test (:use :cl :fiveam) (:export :run-tests)) ;; Enter the testing package (in-package :all-fail-test) ;; Define and enter a new FiveAM test-suite (def-suite* all-fail-suite) (test vanilla-leap-year (is (all-fail:leap-year-p 1996))) (test any-old-year (is (not (all-fail:leap-year-p 1997)))) (test non-leap-even-year (is (not (all-fail:leap-year-p 1998)))) (test century (is (not (all-fail:leap-year-p 1900)))) (test exceptional-century (is (all-fail:leap-year-p 2400))) (defun run-tests (&optional (test-or-suite 'leap-suite)) "Provides human readable results of test run. Default to entire suite." (run! test-or-suite))
1,003
Common Lisp
.lisp
21
45.761905
80
0.736896
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e349c6b7290abc6549d6cb6053124aab4981758767e79c464e22f4388df95c40
22,934
[ -1 ]
22,935
empty-file-test.lisp
exercism_common-lisp-test-runner/tests/empty-file/empty-file-test.lisp
;; Ensures that empty-file.lisp and the testing library are always loaded (eval-when (:compile-toplevel :load-toplevel :execute) (load "empty-file") (quicklisp-client:quickload :fiveam)) ;; Defines the testing package with symbols from leap and FiveAM in scope ;; The `run-tests` function is exported for use by both the user and test-runner (defpackage :empty-file-test (:use :cl :fiveam) (:export :run-tests)) ;; Enter the testing package (in-package :empty-file-test) ;; Define and enter a new FiveAM test-suite (def-suite* empty-file-suite) (test vanilla-leap-year (is (empty-file:leap-year-p 1996))) (test any-old-year (is (not (empty-file:leap-year-p 1997)))) (test non-leap-even-year (is (not (empty-file:leap-year-p 1998)))) (test century (is (not (empty-file:leap-year-p 1900)))) (test exceptional-century (is (empty-file:leap-year-p 2400))) (defun run-tests (&optional (test-or-suite 'leap-suite)) "Provides human readable results of test run. Default to entire suite." (run! test-or-suite))
1,023
Common Lisp
.lisp
21
46.714286
80
0.742195
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
fc1dd0ebd3e264c3dab481de9e37ff676d780397f1ede82a0a93ceff6ec2fe87
22,935
[ -1 ]
22,936
partial-fail.lisp
exercism_common-lisp-test-runner/tests/partial-fail/partial-fail.lisp
(cl:defpackage :partial-fail (:use :common-lisp) (:export :leap-year-p)) (in-package :partial-fail) (defun divisible-by-p (n d) (= 0 (rem n d))) (defun leap-year-p (year) (and (divisible-by-p year 4) (or (not (divisible-by-p year 100)) (divisible-by-p year 404))))
285
Common Lisp
.lisp
9
28.444444
44
0.648352
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
7f1dd54f1375e16c72841558c8fe5b4f4a7072ccea3171a8de4ae1c2e4d886b1
22,936
[ -1 ]
22,937
partial-fail-test.lisp
exercism_common-lisp-test-runner/tests/partial-fail/partial-fail-test.lisp
;; Ensures that partial-fail.lisp and the testing library are always loaded (eval-when (:compile-toplevel :load-toplevel :execute) (load "partial-fail") (quicklisp-client:quickload :fiveam)) ;; Defines the testing package with symbols from leap and FiveAM in scope ;; The `run-tests` function is exported for use by both the user and test-runner (defpackage :partial-fail-test (:use :cl :fiveam) (:export :run-tests)) ;; Enter the testing package (in-package :partial-fail-test) ;; Define and enter a new FiveAM test-suite (def-suite* leap-suite) (test vanilla-leap-year (is (partial-fail:leap-year-p 1996))) (test any-old-year (is (not (partial-fail:leap-year-p 1997)))) (test non-leap-even-year (is (not (partial-fail:leap-year-p 1998)))) (test century (is (not (partial-fail:leap-year-p 1900)))) (test exceptional-century (is (partial-fail:leap-year-p 2400))) (defun run-tests (&optional (test-or-suite 'leap-suite)) "Provides human readable results of test run. Default to entire suite." (run! test-or-suite))
1,035
Common Lisp
.lisp
21
47.285714
80
0.746269
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
0dfb5b0a5e4130721cdc61006f68b118986458bc66b131147bcb169fcd9f6020
22,937
[ -1 ]
22,938
test-runner.asd
exercism_common-lisp-test-runner/src/test-runner.asd
(defsystem "test-runner" :name "test-runner" :version "0.0.0" :description "Exercism Common Lisp Test-Runner" :depends-on ("uiop" "fiveam" "st-json" "alexandria") :pathname "test-runner" :serial t :components ((:file "astonish") (:file "test-runner" :depends-on ("astonish"))))
309
Common Lisp
.asd
9
29.888889
63
0.654362
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b5628b261229fb84b64a91b8ed2eaeb697d98afa7236fbbeefc14d34ab9c297f
22,938
[ -1 ]
22,940
Dockerfile
exercism_common-lisp-test-runner/Dockerfile
FROM clfoundation/sbcl:2.1.5-alpine3.13 AS build RUN apk --no-cache add curl # Set working directory WORKDIR /opt/test-runner ENV HOME=/opt/test-runner # Pull down the latest Quicklisp RUN mkdir build && curl https://beta.quicklisp.org/quicklisp.lisp -o build/quicklisp.lisp # Install quicklisp COPY build/install-quicklisp.lisp build/ RUN sbcl --script build/install-quicklisp.lisp # Build the application COPY build/build.lisp build/ COPY src quicklisp/local-projects/test-runner RUN sbcl --script ./build/build.lisp # Build the runtime image FROM alpine:3.13 WORKDIR /opt/test-runner # Copy over the test-runner code COPY --from=build /opt/test-runner/bin/ bin/ COPY --from=build /opt/test-runner/.cache/common-lisp/ .cache/common-lisp/ COPY bin/run.sh bin/ # Set test-runner script as the ENTRYPOINT ENTRYPOINT ["bin/run.sh"]
837
Common Lisp
.l
23
35.086957
89
0.796778
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
810122bf7e37b2ccc163d42bf381548c898b151a6c5f0b420cb9f188e363e1ed
22,940
[ -1 ]
22,942
run-local.sh
exercism_common-lisp-test-runner/bin/run-local.sh
#!/bin/sh -e slug=$1 local_input=`realpath $2` local_output=`realpath $3` image=`docker build -q .` docker run \ --network none \ --read-only \ --mount type=bind,source=${local_input},target=/input \ --mount type=bind,source=${local_output},target=/output \ --rm \ -it $image $slug /input/ /output/ docker image rm $image
368
Common Lisp
.l
13
23.769231
64
0.623932
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6cd9c86a7614083eb9cca57f043e9a36d5d0b6f96b779273228aa517c9bdabbe
22,942
[ -1 ]
22,951
ci.yml
exercism_common-lisp-test-runner/.github/workflows/ci.yml
name: CI on: pull_request: branches: - main push: branches: - main jobs: build: name: Tests runs-on: ubuntu-22.04 steps: - name: Checkout code uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 - name: Set up Docker Buildx uses: docker/setup-buildx-action@4c0219f9ac95b02789c1075625400b2acbff50b1 with: install: true - name: Build Docker image and store in cache uses: docker/build-push-action@2eb1c1961a95fc15694676618e422e8ba1d63825 with: context: . push: false load: true tags: exercism/common-lisp-test-runner cache-from: type=gha cache-to: type=gha,mode=max - name: Run Tests in Docker run: bin/run-tests-in-docker.sh
821
Common Lisp
.l
30
20.2
81
0.642494
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
780b3a9dee295613e518f43793bb4906ac77609acc4376991e3d025452bb062f
22,951
[ -1 ]
22,952
expected_results.json
exercism_common-lisp-test-runner/tests/success/expected_results.json
{"version":2,"status":"pass","tests":[{"name":"VANILLA-LEAP-YEAR (1/1)","status":"pass","message":null,"output":"","test_code":"(is (success:leap-year-p 1996))"},{"name":"ANY-OLD-YEAR (1/1)","status":"pass","message":null,"output":"","test_code":"(is (not (success:leap-year-p 1997)))"},{"name":"NON-LEAP-EVEN-YEAR (1/1)","status":"pass","message":null,"output":"","test_code":"(is (not (success:leap-year-p 1998)))"},{"name":"CENTURY (1/1)","status":"pass","message":null,"output":"","test_code":"(is (not (success:leap-year-p 1900)))"},{"name":"EXCEPTIONAL-CENTURY (1/1)","status":"pass","message":null,"output":"","test_code":"(is (success:leap-year-p 2400))"}]}
665
Common Lisp
.l
1
665
665
0.619549
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f0d6b2f9d6c2b304f8d872daca3927c081530434dc7209ff4f720f45eb4018c6
22,952
[ -1 ]
22,955
expected_results.json
exercism_common-lisp-test-runner/tests/syntax-error/expected_results.json
{"version":2,"status":"error","message":"READ error during LOAD:\n\n end of file on #<SB-INT:FORM-TRACKING-STREAM for \"file /opt/test-runner/tests/syntax-error/syntax-error.lisp\" {1001A86233}>\n\n (in form starting at line: 1, column: 0, position: 0)"}
256
Common Lisp
.l
1
256
256
0.707031
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
bc4be6682e2ff33c50aaa3dabffee3446d14e88ab52659088c6e34f01d76c9d1
22,955
[ -1 ]
22,959
expected_results.json
exercism_common-lisp-test-runner/tests/all-fail/expected_results.json
{"version":2,"status":"fail","tests":[{"name":"VANILLA-LEAP-YEAR (1/1)","status":"fail","message":"\n1996\n\n evaluated to \n\n1996\n\n which does not satisfy \n\nALL-FAIL:LEAP-YEAR-P\n\n","output":"","test_code":"(is (all-fail:leap-year-p 1996))"},{"name":"ANY-OLD-YEAR (1/1)","status":"fail","message":"\n1997\n\n evaluated to \n\n1997\n\n which satisfies \n\nALL-FAIL:LEAP-YEAR-P\n\n (it should not)","output":"","test_code":"(is (not (all-fail:leap-year-p 1997)))"},{"name":"NON-LEAP-EVEN-YEAR (1/1)","status":"fail","message":"\n1998\n\n evaluated to \n\n1998\n\n which satisfies \n\nALL-FAIL:LEAP-YEAR-P\n\n (it should not)","output":"","test_code":"(is (not (all-fail:leap-year-p 1998)))"},{"name":"CENTURY (1/1)","status":"fail","message":"\n1900\n\n evaluated to \n\n1900\n\n which satisfies \n\nALL-FAIL:LEAP-YEAR-P\n\n (it should not)","output":"","test_code":"(is (not (all-fail:leap-year-p 1900)))"},{"name":"EXCEPTIONAL-CENTURY (1/1)","status":"fail","message":"\n2400\n\n evaluated to \n\n2400\n\n which does not satisfy \n\nALL-FAIL:LEAP-YEAR-P\n\n","output":"","test_code":"(is (all-fail:leap-year-p 2400))"}]}
1,127
Common Lisp
.l
1
1,127
1,127
0.652174
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
75d209794b0334daa30eea4ce3d4871e36bcc1ac2174a3dd13a40979384342c5
22,959
[ -1 ]
22,960
expected_results.json
exercism_common-lisp-test-runner/tests/empty-file/expected_results.json
{"version":2,"status":"error","message":"READ error during LOAD:\n\n Package EMPTY-FILE does not exist.\n\n Line: 18, Column: 51\n\n Stream: #<SB-INT:FORM-TRACKING-STREAM for \"file /opt/test-runner/tests/empty-file/empty-file-test.lisp\" {100095BBA3}>"}
261
Common Lisp
.l
1
261
261
0.701149
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
42e9f5f93ac214ac990ed117dd5fc3579c607b72684223c5a60142d69856861f
22,960
[ -1 ]
22,962
expected_results.json
exercism_common-lisp-test-runner/tests/partial-fail/expected_results.json
{"version":2,"status":"fail","tests":[{"name":"VANILLA-LEAP-YEAR (1/1)","status":"pass","message":null,"output":"","test_code":"(is (partial-fail:leap-year-p 1996))"},{"name":"ANY-OLD-YEAR (1/1)","status":"pass","message":null,"output":"","test_code":"(is (not (partial-fail:leap-year-p 1997)))"},{"name":"NON-LEAP-EVEN-YEAR (1/1)","status":"pass","message":null,"output":"","test_code":"(is (not (partial-fail:leap-year-p 1998)))"},{"name":"CENTURY (1/1)","status":"pass","message":null,"output":"","test_code":"(is (not (partial-fail:leap-year-p 1900)))"},{"name":"EXCEPTIONAL-CENTURY (1/1)","status":"fail","message":"\n2400\n\n evaluated to \n\n2400\n\n which does not satisfy \n\nPARTIAL-FAIL:LEAP-YEAR-P\n\n","output":"","test_code":"(is (partial-fail:leap-year-p 2400))"}]}
780
Common Lisp
.l
1
780
780
0.637179
exercism/common-lisp-test-runner
1
3
4
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1680b9ed23c55dd257ed34baca1f4c03c0c986ef5bf4ad090023b7af03209119
22,962
[ -1 ]
22,979
glol.lisp
CallmeTorre_IA/Exercises/glol.lisp
;------------------------------------------ ;| Jes√∫s Alexis Torreblanca Faces | ;| Inteligencia Artificial | ;| Resuelve el problema Granjero, Lobo, | ;| Oveja y Legumbres | ;------------------------------------------ (defparameter *open* '()) (defparameter *memory* '()) (defparameter *id* 0) (defparameter *ops* '((:GranjeroSolo (1 0 0 0)) (:Granjero-Lobo (1 1 0 0)) (:Granjero-Oveja (1 0 1 0)) (:Granjero-Legumbres (1 0 0 1)))) (defparameter *current-ancestor* nil) (defparameter *solucion* nil) (defparameter *contadorNodos* 0) (defparameter *contadorExpandir* 0) (defparameter *contadorFronteraBusqueda* 0) (defparameter *tiempoInicial* 0) (defparameter *tiempoFinal* 0) (defun create-node (estado operador) (incf *id*) (incf *contadorNodos*) (list (1- *id*) estado *current-ancestor* (first operador))) (defun barge-shore (estado) (if (= 1 (fifth (first estado))) 0 1)) (defun insert-to-open (estado operador metodo) (let ((nodo (create-node estado operador))) (cond ((equal metodo :depth-first) (push nodo *open*)) ((equal metodo :breath-first) (setq *open* (append *open* (list nodo)))) (T Nil)))) (defun get-from-open () (pop *open*)) (defun valid-operator (operador estado) (let* ((orilla (barge-shore estado)) (granjero (first (nth orilla estado))) (lobo (second (nth orilla estado))) (oveja (third (nth orilla estado))) (legumbres (fourth (nth orilla estado)))) (or (= granjero (first (second operador))) (= lobo (second (second operador))) (= oveja (third (second operador))) (= legumbres (fourth (second operador)))))) (defun valid-state (estado) (let ((orilla1 (first estado)) (orilla2 (second estado))) (and (not (equal orilla1 '(0 1 1 0 0))) (not (equal orilla2 '(0 1 1 0 0))) (not (equal orilla1 '(0 0 1 1 0))) (not (equal orilla2 '(0 0 1 1 0)))))) (defun flip (bit) (boole BOOLE-XOR bit 1)) (defun apply-operator (operador estado) (let* ((orilla1 (first estado)) (orilla2 (second estado)) (g0 (first orilla1)) (l0 (second orilla1)) (ov0 (third orilla1)) (leg0 (fourth orilla1)) (b0 (fifth orilla1)) (g1 (first orilla2)) (l1 (second orilla2)) (ov1 (third orilla2)) (leg1 (fourth orilla2)) (b1 (fifth orilla2)) (orilla-barco (barge-shore estado)) (op (first operador))) (case op (:GranjeroSolo (if (= orilla-barco 0) (list (list 0 l0 ov0 leg0 0) (list 1 l1 ov1 leg1 1)) (list (list 1 l0 ov0 leg0 1) (list 0 l1 ov1 leg1 0)))) (:Granjero-Lobo (if (= orilla-barco 0) (list (list 0 0 ov0 leg0 0) (list 1 1 ov1 leg1 1)) (list (list 1 1 ov0 leg0 1) (list 0 0 ov1 leg1 0)))) (:Granjero-Oveja (if (= orilla-barco 0) (list (list 0 l0 0 leg0 0) (list 1 l1 1 leg1 1)) (list (list 1 l0 1 leg0 1) (list 0 l1 0 leg1 0)))) (:Granjero-Legumbres (if (= orilla-barco 0) (list (list 0 l0 ov0 0 0) (list 1 l0 ov0 1 1)) (list (list 1 l0 ov0 1 1) (list 0 l0 ov0 0 0)))) (T "Error")))) (defun expand (estado) (incf *contadorExpandir*) (let ((descendientes nil) (nuevo-estado nil)) (dolist (op *ops* descendientes) (setq nuevo-estado (apply-operator op estado)) (when (and (valid-operator op estado) (valid-state nuevo-estado)) (setq descendientes (cons (list nuevo-estado op) descendientes)))))) (defun remember-state (estado memoria) (cond ((null memoria) nil) ((equal estado (second (first memoria))) T) (T (remember-state estado (rest memoria))))) (defun filter-memories (lista-estados-y-ops) (cond ((null lista-estados-y-ops) Nil) ((remember-state (first (first lista-estados-y-ops)) *memory*) (filter-memories (rest lista-estados-y-ops))) (T (cons (first lista-estados-y-ops) (filter-memories (rest lista-estados-y-ops))))) ) (defun extract-solution (nodo) (labels ((locate-node (id lista) (cond ((null lista) Nil) ((equal id (first (first lista))) (first lista)) (T (locate-node id (rest lista)))))) (let ((current (locate-node (first nodo) *memory*))) (loop while (not (null current)) do (push current *solucion*) (setq current (locate-node (third current) *memory*)))) *solucion*)) (defun display-solution (lista-nodos) (setq *tiempoFinal* (get-internal-real-time)) (format t "Nodos creados ~A ~%" *contadorNodos*) (format t "Nodos expandidos ~A ~%" *contadorExpandir*) (format t "Longitud maxima de frontera de busqueda ~A ~%" *contadorFronteraBusqueda*) (format t "Tiempo para encontrar la solucion: ~A~%" (/ (- *tiempoFinal* *tiempoInicial*) internal-time-units-per-second)) (format t "Solucion con ~A pasos~%" (1- (length lista-nodos))) (let ((nodo nil)) (dotimes (i (length lista-nodos)) (setq nodo (nth i lista-nodos)) (if (= i 0) (format t "Inicio en: ~A~%" (second nodo)) (format t "\(~A\) aplicando ~A se llega a ~A~%" i (fourth nodo) (second nodo)))))) (defun reset-all () (setq *open* nil) (setq *memory* nil) (setq *id* 0) (setq *contadorNodos* 0) (setq *contadorExpandir* 0) (setq *contadorFronteraBusqueda* 0) (setq *tiempoInicial* 0) (setq *tiempoFinal* 0) (setq *current-ancestor* nil) (setq *solucion* nil)) (defun blind-search (inicial final metodo) (reset-all) (setq *tiempoInicial* (get-internal-real-time)) (let ((nodo nil) (estado nil) (sucesores '()) (operador nil) (meta-encontrada nil)) (insert-to-open inicial nil metodo) (loop until (or meta-encontrada (null *open*)) do (setq nodo (get-from-open) estado (second nodo) operador (third nodo)) (push nodo *memory*) (incf *contadorFronteraBusqueda*) (cond ((equal final estado) (format t "Exito. Meta encontrada en ~A intentos~%" (first nodo)) (display-solution (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo)) (setq sucesores (expand estado)) (setq sucesores (filter-memories sucesores)) (loop for element in sucesores do (insert-to-open (first element) (second element) metodo))))))) (blind-search '((1 1 1 1 1)(0 0 0 0 0)) '((0 0 0 0 0)(1 1 1 1 1)) :depth-first) (blind-search '((1 1 1 1 1)(0 0 0 0 0)) '((0 0 0 0 0)(1 1 1 1 1)) :breath-first)
6,303
Common Lisp
.lisp
158
36.075949
151
0.63626
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4b78228298317591d936789e91b3ae3220bb063bb31036ceffd619e6e0dca2a3
22,979
[ -1 ]
22,980
Misioneros-Canibales.lisp
CallmeTorre_IA/Exercises/Misioneros-Canibales.lisp
;;;======================================================================= ;;; Misioneros-Canibales.lisp ;;; Resuelve el problema de misioneros y canibales con búsqueda ciega, a lo profundo y a lo ancho. ;;; ;;; Ejemplo explicado en clase. Presentaciones #3 y #4 ;;; ;;; Dr. Salvador Godoy C. ;;; enero, 2013 ;;;======================================================================= (defparameter *open* '()) ;; Frontera de busqueda... (defparameter *memory* '()) ;; Memoria de intentos previos (defparameter *ops* '( (:Dos-Misioneros (2 0)) ;; Operadores para el problema de misioneros y canibales (:Un-Misionero (1 0)) (:Misionero-y-Caníbal (1 1)) (:Un-Caníbal (0 1)) (:Dos-Caníbales (0 2)) ) ) (defparameter *id* 0) ;; Identificador del ultimo nodo creado, cada vez que se cree un nodo se debe incrementar (defparameter *current-ancestor* nil) ;;Id del ancestro común a todos los descendientes que se generen (defparameter *solucion* nil) ;;lista donde se almacenará la solución recuperada de la memoria ;;======================================================================= ;; CREATE-NODE [estado op] ;; estado - Un estado del problema a resolver (sistema)... ;; op - El operador cuya aplicación generó el [estado]... ;;======================================================================= (defun create-node (estado op) "Construye y regresa un nuevo nodo de búsqueda que contiene al estado y operador recibidos como parámetro " (incf *id*) ;;incrementamos primero para que lo último en procesarse sea la respuesta (list (1- *id*) estado *current-ancestor* (first op)) ) ;;los nodos generados son descendientes de *current-ancestor* ;;======================================================================= ;; INSERT-TO-OPEN y GET-FROM-OPEN ;; ;; Insert-to-open recibe una lista y una llave que identifica el metodo a usar para insertar: ;; :depth-first Inserta los elementos de la lista en orden inverso y por el inicio de la lista ;; :breath-first Inserta los elementos de la lista en orden normal y por el final de la lista ;; Get-from-open siempre retira el primer elemento de la lista *open* ;;======================================================================= (defun insert-to-open (estado op metodo) "Permite insertar nodos de la frontera de busqueda *open* de forma apta para buscar a lo profundo y a lo ancho" (let ((nodo (create-node estado op))) (cond ((eql metodo :depth-first) (push nodo *open*)) ((eql metodo :breath-first) (setq *open* (append *open* (list nodo)))) (T Nil))) ) (defun get-from-open () "Recupera el siguiente elemento a revisar de frontera de busqueda *open*" (pop *Open*)) ;;======================================================================= ;; BARGE-SHORE [estado] ;; Regresa la orilla del rio en la que se encuentra la barca en [estado] ;; 0 - Orilla origen (primer sublista del estado) ;; 1 - Orilla destino (segunda sublista del estado) ;;======================================================================= (defun barge-shore (estado) "Regresa la orilla del río en la que se encuentra la barca en el estado recibido como parámetro: 0 - origen 1 - destino" (if (= 1 (third (first estado))) 0 1)) ;;======================================================================= ;; VALID-OPERATOR [op, estado] ;; Predicado. Indica si es posible aplicar el operador [op] a [estado] segun los recursos en la orilla donde esta la barca ;;======================================================================= (defun valid-operator (op estado) "Predicado. Valida la aplicación de un operador a un estado... el estado tiene estructura: [(<m0><c0><b0>) (<m1><c1><b1>)], el operador tiene estructura : [<etiqueta-humana> <lista operador con (<num misioneros><num caníbales>)>]" (let* ((orilla (barge-shore estado)) (misioneros (first (nth orilla estado))) (canibales (second (nth orilla estado)))) (and (>= misioneros (first (second op))) ;;el número de misioneros a mover, primer elemento de la lista-operador (>= canibales (second (second op))))) ) ;;el número de caníbales a mover, segundo elemento de la lista-operador ;;======================================================================= ;; VALID-STATE [estado] ;; Predicado. Indica si [estado] es valido segun las restricciones del problema ;; Es decir, si en c/orilla hay igual o mayor numero de misioneros que de canibales ;;======================================================================= (defun valid-state (estado) "Predicado. Valida un estado según las restricciones generales del problema... el estado tiene estructura: [(<m0><c0><b0>) (<m1><c1><b1>)]" (let ((m0 (first (first estado))) ;;el estado tiene estructura ((<m0><c0><b0>) (<m1><c1><b1>)) ... (c0 (second (first estado))) (m1 (first (second estado))) (c1 (second (second estado)))) (and (or (>= m0 c0) (zerop m0)) ;; mayor o igual número de misioneros que caníbales, excepto si hay 0 misioneros (or (>= m1 c1) (zerop m1)))) ) ;;======================================================================= ;; APPLY-OPERATOR [op, estado] ;; Solución simbólica del problema ;;======================================================================= (defun flip (bit) (boole BOOLE-XOR bit 1)) (defun apply-operator (op estado) "Obtiene el descendiente de [estado] al aplicarle [op] SIN VALIDACIONES" (let* ((orilla1 (first estado)) (orilla2 (second estado)) (m0 (first orilla1)) (c0 (second orilla1)) (b0 (third orilla1)) (m1 (first orilla2)) (c1 (second orilla2)) (b1 (third orilla2)) (orilla-barca (barge-shore estado)) (operador (first op))) ;; este operador es la etiqueta humana del operador... (case operador (:Dos-Misioneros (if (= orilla-barca 0) ;;siempre restar elementos de la orilla con la barca y sumarlos en la otra orilla... (list (list (- m0 2) c0 (flip b0)) (list (+ m1 2) c1 (flip b1))) (list (list (+ m0 2) c0 (flip b0)) (list (- m1 2) c1 (flip b1))))) (:Un-Misionero (if (= orilla-barca 0) (list (list (- m0 1) c0 (flip b0)) (list (+ m1 1) c1 (flip b1))) (list (list (+ m0 1) c0 (flip b0)) (list (- m1 1) c1 (flip b1))))) (:Misionero-y-Caníbal (if (= orilla-barca 0) (list (list (- m0 1) (- c0 1) (flip b0)) (list (+ m1 1) (+ c1 1) (flip b1))) (list (list (+ m0 1) (+ c0 1) (flip b0)) (list (- m1 1) (- c1 1) (flip b1))))) (:Un-Caníbal (if (= orilla-barca 0) (list (list m0 (- c0 1) (flip b0)) (list m1 (+ c1 1) (flip b1))) (list (list m0 (+ c0 1) (flip b0)) (list m1 (- c1 1) (flip b1))))) (:Dos-Caníbales (if (= orilla-barca 0) (list (list m0 (- c0 2) (flip b0)) (list m1 (+ c1 2) (flip b1))) (list (list m0 (+ c0 2) (flip b0)) (list m1 (- c1 2) (flip b1))))) (T "error")))) ;;======================================================================= ;; EXPAND [ estado] ;; Construye y regresa una lista con todos los descendientes validos de [estado] ;;======================================================================= (defun expand (estado) "Obtiene todos los descendientes válidos de un estado, aplicando todos los operadores en *ops* en ese mismo órden" (let ((descendientes nil) (nuevo-estado nil)) (dolist (op *Ops* descendientes) (setq nuevo-estado (apply-operator op estado)) (when (and (valid-operator op estado) (valid-state nuevo-estado)) (setq descendientes (cons (list nuevo-estado op) descendientes))))) ) ;;======================================================================= ;; REMEMBER-STATE? y FILTER-MEMORIES ;; Permiten administrar la memoria de intentos previos ;;======================================================================= (defun remember-state? (estado lista-memoria) "Busca un estado en una lista de nodos que sirve como memoria de intentos previos el estado tiene estructura: [(<m0><c0><b0>) (<m1><c1><b1>)], el nodo tiene estructura : [<Id> <estado> <id-ancestro> <operador> ]" (cond ((null lista-memoria) Nil) ((equal estado (second (first lista-memoria))) T) ;;el estado es igual al que se encuentra en el nodo? (T (remember-state? estado (rest lista-memoria)))) ) (defun filter-memories (lista-estados-y-ops) "Filtra una lista de estados-y-operadores quitando aquellos elementos cuyo estado está en la memoria *memory* la lista de estados y operadores tiene estructura: [(<estado> <op>) (<estado> <op>) ... ]" (cond ((null lista-estados-y-ops) Nil) ((remember-state? (first (first lista-estados-y-ops)) *memory*) ;; si se recuerda el primer elemento de la lista, filtrarlo... (filter-memories (rest lista-estados-y-ops))) (T (cons (first lista-estados-y-ops) (filter-memories (rest lista-estados-y-ops))))) ) ;; de lo contrario, incluirlo en la respuesta ;;======================================================================= ;; EXTRACT-SOLUTION y DISPLAY-SOLUTION ;; Recuperan y despliegan la secuencia de solucion del problema... ;; extract-solution recibe un nodo (el que contiene al estado meta) que ya se encuentra en la memoria y ;; rastrea todos sus ancestros hasta llegar al nodo que contiene al estado inicial... ;; display-solution despliega en pantalla la lista global *solucion* donde ya se encuentra, en orden correcto, ;; el proceso de solución del problema... ;;======================================================================= (defun extract-solution (nodo) "Rastrea en *memory* todos los descendientes de [nodo] hasta llegar al estado inicial" (labels ((locate-node (id lista) ;; función local que busca un nodo por Id y si lo encuentra regresa el nodo completo (cond ((null lista) Nil) ((eql id (first (first lista))) (first lista)) (T (locate-node id (rest lista)))))) (let ((current (locate-node (first nodo) *memory*))) (loop while (not (null current)) do (push current *solucion*) ;; agregar a la solución el nodo actual (setq current (locate-node (third current) *memory*)))) ;; y luego cambiar a su antecesor... *solucion*)) (defun display-solution (lista-nodos) "Despliega la solución en forma conveniente y numerando los pasos" (format t "Solución con ~A pasos~%" (1- (length lista-nodos))) (let ((nodo nil)) (dotimes (i (length lista-nodos)) (setq nodo (nth i lista-nodos)) (if (= i 0) (format t "Inicio en: ~A~%" (second nodo)) ;; a partir de este estado inicial ;;else (format t "\(~A\) aplicando ~A se llega a ~A~%" i (fourth nodo) (second nodo))))) ) ;; imprimir el número de paso, operador y estado... ;;======================================================================= ;; RESET-ALL y BLIND-SEARCH ;; ;; Recuperan y despliegan la secuencia de solucion del problema... ;; extract-solution recibe un nodo (el que contiene al estado meta) que ya se encuentra en la memoria y ;; rastrea todos sus ancestros hasta llegar al nodo que contiene al estado inicial... ;; display-solution despliega en pantalla la lista global *solucion* donde ya se encuentra, en orden correcto, ;; el proceso de solucion del problema... ;;======================================================================= (defun reset-all () "Reinicia todas las variables globales para iniciar una nueva búsqueda..." (setq *open* nil) (setq *memory* nil) (setq *id* 0) (setq *current-ancestor* nil) (setq *solucion* nil)) (defun blind-search (edo-inicial edo-meta metodo) "Realiza una búsqueda ciega, por el método especificado y desde un estado inicial hasta un estado meta los métodos posibles son: :depth-first - búsqueda en profundidad :breath-first - búsqueda en anchura" (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (operador nil) (meta-encontrada nil)) (insert-to-open edo-inicial nil metodo) (loop until (or meta-encontrada (null *open*)) do (setq nodo (get-from-open) estado (second nodo) operador (third nodo)) (push nodo *memory*) (cond ((equal edo-meta estado) (format t "Éxito. Meta encontrada en ~A intentos~%" (first nodo)) (display-solution (extract-solution nodo)) (setq meta-encontrada T)) (t (setq *current-ancestor* (first nodo)) (setq sucesores (expand estado)) (setq sucesores (filter-memories sucesores)) (loop for element in sucesores do (insert-to-open (first element) (second element) metodo)))))) ) ;;======================================================================= ;;=======================================================================
13,970
Common Lisp
.lisp
222
56.774775
150
0.532582
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
02a6eec151fdd8332cadd6756d56e33ddce0c09691afc64ae431e9a395628cc9
22,980
[ 24355 ]
22,981
Mancala.lisp
CallmeTorre_IA/Exercises/Mancala.lisp
;------------------------------------------ ;| Jesús Alexis Torreblanca Faces | ;| Inteligencia Artificial | ;| Agente Jugador de Mancala | ;------------------------------------------ (defparameter *board* '((1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)()(1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)())) (defparameter *shoot-again* T) (defparameter *slots-shooted* nil) (defparameter *alfa* most-positive-fixnum) (defparameter *ops* '((:primera-casilla 7) (:segunda-casilla 8) (:tercera-casilla 9) (:cuarta-casilla 10) (:quinta-casilla 11) (:sexta-casilla 12))) (defparameter *end-game* nil) (defparameter *winner-player* nil) (defparameter *IA-points* 0) (defparameter *human-points* 0) (defun print-board () "Funcion que imprime el tablero del mancala, en cada casilla imprime el valor de la suma de las canicas que se encuentran en esa casilla" (format t "~&~% | ~A | | ~:A | | ~:A | | ~:A | | ~:A | | ~:A | | ~:A | ~%" (apply #'+ (nth 13 *board*))(apply #'+ (nth 12 *board*)) (apply #'+ (nth 11 *board*)) (apply #'+ (nth 10 *board*)) (apply #'+ (nth 9 *board*)) (apply #'+ (nth 8 *board*)) (apply #'+ (nth 7 *board*))) (format t "~& | ~:A | | ~:A | | ~:A | | ~:A | | ~:A | | ~:A | | ~:A | ~%~%" (apply #'+ (nth 0 *board*)) (apply #'+ (nth 1 *board*)) (apply #'+ (nth 2 *board*)) (apply #'+ (nth 3 *board*)) (apply #'+ (nth 4 *board*)) (apply #'+ (nth 5 *board*)) (apply #'+ (nth 6 *board*)))) (defun reset-game () "Funcion que reinicia el tablero a su estado original" (setq *board* '((1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)()(1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)(1 5 10)()))) (defun game-ended? () "Predicado el cual valida si el juego ya termino checando si alguna hilera esta completamente vacia" (return-from game-ended? (or (and (null (nth 0 *board*)) (null (nth 1 *board*)) (null (nth 2 *board*)) (null (nth 3 *board*)) (null (nth 4 *board*)) (null (nth 5 *board*))) (and (null (nth 7 *board*)) (null (nth 8 *board*)) (null (nth 9 *board*)) (null (nth 10 *board*)) (null (nth 11 *board*)) (null (nth 12 *board*)))))) (defun get-balls (casilla) "Funcion que obtiene las canicas en una casilla" (nth casilla *board*)) ;(defun same-slot? (casilla-actual) ; "Predicado que valida que no se tire en la misma casilla" ; (member casilla-actual *slots-shooted*)) (defun insert-ball (lista casilla) "Funcion que inserta las canicas de la forma (canica canica canica ...) en las casillas aledañas" (let ((casilla-siguiente (1+ casilla))) (loop for x in lista do (push x (nth casilla-siguiente *board*)) (push casilla-siguiente *slots-shooted*) (setq casilla-siguiente (1+ casilla-siguiente)) (if (> casilla-siguiente 13) (setq casilla-siguiente 0) )))) (defun move-ball (casilla-actual) "Funcion que mueve las canicas de la casilla seleccionada" (let ((canicas (get-balls casilla-actual)) (movimiento nil)) (format t "~& Canicas en casilla: ~A ~%" canicas) (format t "~& Indique la casilla a la cual ira cada canica de la forma (canica canica canica ...)~%") (setq movimiento(read)) (insert-ball movimiento casilla-actual) (loop for canica in canicas do (pop (nth casilla-actual *board*))) (print-board))) (defun valid-human-slot? (casilla-actual) "Predicado que checa las casillas validas que el jugador humano puede escoger" (cond ((member casilla-actual '(6 7 8 9 10 11 12 13)) nil) ((null (get-balls casilla-actual)) nil) (T T))) (defun human-turn() "Funcion en la cual se ejecuta el turno humano" (let* ((casilla-actual nil) (mValido nil)) (print-board) (loop until (null *shoot-again*) do (loop until mValido do (print "~& Escoge una casilla ~%") (print "~& #ProTip: Solo puedes escoger las casillas de la parte de abajo del tablero (0,1,2,3,4,5)") (if (valid-human-slot? (setq casilla-actual(read))) (setq mValido T) (print "Tu movimiento no es valido"))) (move-ball casilla-actual) (if (= (first *slots-shooted*) 6) (setq *shoot-again* T) (setq *shoot-again* nil)) (setq casilla-actual nil *slots-shooted* nil mValido nil) (if (game-ended?) (progn (setq *end-game* (game-ended?) *winner-player* 0 *shoot-again* nil)))))) (defun valid-operator? (operador estado) "Predicado que valida si es el operador seleccionado es valido" (let ((operador (second operador))) (cond ((= operador 7) (if (null (nth 7 estado)) nil T)) ((= operador 8) (if (null (nth 8 estado)) nil T)) ((= operador 9) (if (null (nth 9 estado)) nil T)) ((= operador 10) (if (null (nth 10 estado)) nil T)) ((= operador 11) (if (null (nth 11 estado)) nil T)) ((= operador 12) (if (null (nth 12 estado)) nil T)) (T nil)))) (defun apply-operator (operador estado) "Funcion que aplica un operador de *ops* a un estado determinado" (let* ((ops (first operador)) (casilla-actual (second operador)) (canicas-casilla (get-balls casilla-actual)) (estado-resultado nil)) (case ops (:primera-casilla (setq estado-resultado (move-machine-balls estado casilla-actual canicas-casilla))) (:segunda-casilla (setq estado-resultado (move-machine-balls estado casilla-actual canicas-casilla))) (:tercera-casilla (setq estado-resultado (move-machine-balls estado casilla-actual canicas-casilla))) (:cuarta-casilla (setq estado-resultado (move-machine-balls estado casilla-actual canicas-casilla))) (:quinta-casilla (setq estado-resultado (move-machine-balls estado casilla-actual canicas-casilla))) (:sexta-casilla (setq estado-resultado (move-machine-balls estado casilla-actual canicas-casilla))) (T "Error")) estado-resultado)) (defun copy-board (tablero) "Funcion que crea una copia del tablero (por motivos de seguridad)" (let ((estado-copia nil)) (loop for elemento in tablero do (setq estado-copia (cons elemento estado-copia))) (setq estado-copia (reverse estado-copia)))) (defun move-machine-balls (tablero casilla-actual canicas-casilla) "Funcion que mueve las canicas de la IA" (let* ((canica-a-meter nil) (cont 0) (estado nil) (canicas nil) (longitud-canicas 0) (estado-copia nil) (best-canca 0) (shoot-again nil) (casilla-target (1+ casilla-actual))) (setq estado-copia (copy-board tablero)) (loop for can in canicas-casilla do (setq canicas (cons can canicas))) (setq canicas(sort canicas #'>)) (setq longitud-canicas (length canicas)) (if ( >= (length canicas) (- 13 casilla-actual)) (progn (setq best-canca (first canicas)) (push best-canca (nth 13 estado-copia)) )) ;Si la longitud de tus canicas es igual a la canica en la que te encuentras, la IA vuelve a tirar (if (= 0 (- (length canicas) (- 13 casilla-actual))) (setq shoot-again T) (setq shoot-again nil)) (loop for canica in canicas do (setq canica-a-meter (pop (nth casilla-actual estado-copia))) (if (and ( = cont 0 ) ( = best-canca canica-a-meter)) (progn (setq cont (1+ cont))) (progn (if (> casilla-target 12) (setq casilla-target 0)) (push canica-a-meter (nth casilla-target estado-copia)) (setq casilla-target (1+ casilla-target)))) finally (return (list estado-copia shoot-again casilla-actual))))) (defun heuristic-function (estado) "Funcion de evaluación del estado la (BaseIA - BaseH)+(CanicasIA - CanicasH)" (let ((movimiento 0) (tablero (first estado))) (setq movimiento (+ (- (apply #'+ (nth 13 tablero)) (apply #'+ (nth 6 tablero))) (- (+ (apply #'+ (nth 7 tablero))(apply #'+ (nth 8 tablero))(apply #'+ (nth 9 tablero)) (apply #'+ (nth 10 tablero))(apply #'+ (nth 11 tablero))(apply #'+ (nth 12 tablero))) (+ (apply #'+ (nth 0 tablero))(apply #'+ (nth 1 tablero))(apply #'+ (nth 2 tablero)) (apply #'+ (nth 3 tablero))(apply #'+ (nth 4 tablero))(apply #'+ (nth 5 tablero)))))) movimiento)) (defun change-player (jugador) "Funcion la cual cambia de jugador, si es 0 --> 1 (le toca a la IA) y si es 1 --> 0 (le toca al humano)" (case jugador (0 1) (1 0))) (defun expand (estado) "Funcion que aplica todos los operadores de *ops* a un estado determinado y los regresa en una lista" (let* ((sucesores nil) (nuevo-estado nil) (estado-copia (copy-list estado))) (loop for operador in *ops* do (if (valid-operator? operador estado-copia) (progn (setq nuevo-estado (apply-operator operador estado-copia)) (push nuevo-estado sucesores))) finally (return sucesores)))) (defun minimax (tablero profundidad max-profundidad jugador alpha beta) "Funcion Minimax con Poda Alfa y Beta" (if (= profundidad max-profundidad) (heuristic-function tablero) (let ((sucesores (expand tablero))) (if (null sucesores) (heuristic-function tablero) (do ((nuevo-valor nil) (mejor-mov (first sucesores))) ((null sucesores) (if (= profundidad 0) mejor-mov beta)) (setf nuevo-valor (- (minimax (first sucesores) (1+ profundidad) max-profundidad (change-player jugador) (- beta) (- alpha)))) (when (> nuevo-valor beta) (setf beta nuevo-valor) (setf mejor-mov (first sucesores))) (if (>= beta alpha) (setf sucesores nil) (setf sucesores (cdr sucesores)))))))) (defun machine-turn () "Funcion en la cual se ejecuta el turno de la IA" (let ((movimiento nil) (movimiento-final nil) (shoot-again T)) (loop until (null shoot-again) do (setq movimiento (minimax *board* 0 1 1 *alfa* (- *alfa*))) (setq movimiento-final (first movimiento)) (setq shoot-again (second movimiento)) (format t "~& La casilla que escogio la IA fue ~A ~%" (third movimiento)) (setq *board* movimiento-final)) (if (game-ended?) (progn (setq *end-game* (game-ended?)) (setq *winner-player* 0) (setq *shoot-again* nil))))) (defun play () "Funcion main" (reset-game) (loop until (not (null *end-game*)) do (game-ended?) (human-turn) (setq *shoot-again* T) (if (null *end-game*) (machine-turn))) (if (= *winner-player* 1) (setq *IA-points* (+ (apply #'+ (nth 0 *board*)) (apply #'+ (nth 1 *board*)) (apply #'+ (nth 2 *board*)) (apply #'+ (nth 3 *board*)) (apply #'+ (nth 4 *board*)) (apply #'+ (nth 5 *board*)) (apply #'+ (nth 13 *board*)))) (setq *IA-points* (apply #'+ (nth 13 *board*)))) (if (= *winner-player* 0) (setq *human-points* (+ (apply #'+ (nth 7 *board*)) (apply #'+ (nth 8 *board*)) (apply #'+ (nth 9 *board*)) (apply #'+ (nth 10 *board*)) (apply #'+ (nth 11 *board*)) (apply #'+ (nth 12 *board*)) (apply #'+ (nth 6 *board*)))) (setq *human-points* (apply #'+ (nth 6 *board*)))) (format t "~& Tu puntuación: ~A Puntuacion de la IA: ~A ~%" *human-points* *IA-points*)) (play)
12,669
Common Lisp
.lisp
274
36.007299
210
0.546624
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
679cd341f3a34d20a1306f768342e748e1fb0c06a51b5fa06b31b72bf30935e7
22,981
[ -1 ]
22,982
8puzzle.lisp
CallmeTorre_IA/Exercises/8puzzle.lisp
;------------------------------------------ ;| Jes√∫s Alexis Torreblanca Faces | ;| Inteligencia Artificial | ;| Resuelve el problema 8-puzzle | ;------------------------------------------ (defparameter *open* '()) (defparameter *memory* '()) (defparameter *id* 0) (defparameter *ops* '((:arriba "^") (:abajo "v") (:izquierda "<") (:derecha ">"))) (defparameter *current-ancestor* nil) (defparameter *solucion* nil) (defparameter *contadorNodos* 0) (defparameter *contadorExpandir* 0) (defparameter *maximaFronteraBusqueda* 0) (defparameter *tiempoInicial* 0) (defparameter *tiempoFinal* 0) (defparameter *meta* nil) (defun where-is-x (estado) "Funcion que nos permite saber donde esta x" (let ((filax 0) (casillax 0)) (dolist (fila estado) (if (or (equal (first fila) 'x) (equal (second fila) 'x) (equal (third fila) 'x)) (cond ((equal (first fila) 'x) (return (list filax casillax))) ((equal (second fila) 'x) (return (list filax (setq casillax (1+ casillax))))) (T (return (list filax (setq casillax (+ 2 casillax)))))) (setq filax (1+ filax)))))) (defun up (estado) "Funcion que mueve x hacia arriba en el tablero" (let* ((filax (first (where-is-x estado))) (casillax (second (where-is-x estado))) (filatarget (nth (1- filax) estado)) (elemtarget (nth casillax filatarget)) (filaconx (nth filax estado))) (if (= filax 1) (list (substitute 'x elemtarget filatarget) (substitute elemtarget 'x filaconx) (third estado)) (list (first estado) (substitute 'x elemtarget filatarget) (substitute elemtarget 'x filaconx))))) (defun down (estado) "Funcion que mueve x hacia abajo en el tablero" (let* ((filax (first (where-is-x estado))) (casillax (second (where-is-x estado))) (filatarget (nth (1+ filax) estado)) (elemtarget (nth casillax filatarget)) (filaconx (nth filax estado))) (if (= filax 0) (list (substitute elemtarget 'x filaconx) (substitute 'x elemtarget filatarget) (third estado)) (list (first estado) (substitute elemtarget 'x filaconx) (substitute 'x elemtarget filatarget))))) (defun left (estado) "Funcion que mueve x hacia la izquierda en el tablero" (let* ((filax (first (where-is-x estado))) (casillax (second (where-is-x estado))) (filaconx (nth filax estado)) (elemtarget (nth (1- casillax) filaconx))) (cond ((= filax 0) (list (substitute 'x elemtarget (substitute elemtarget 'x filaconx) :count 1) (second estado) (third estado))) ((= filax 1) (list (first estado) (substitute 'x elemtarget (substitute elemtarget 'x filaconx) :count 1) (third estado))) (T (list (first estado) (second estado) (substitute 'x elemtarget (substitute elemtarget 'x filaconx) :count 1)))))) (defun right (estado) "Funcion que mueve x hacia la derecha en el tablero" (let* ((filax (first (where-is-x estado))) (casillax (second (where-is-x estado))) (filaconx (nth filax estado)) (elemtarget (nth (1+ casillax) filaconx))) (cond ((= filax 0) (list (substitute elemtarget 'x (substitute 'x elemtarget filaconx) :count 1) (second estado) (third estado))) ((= filax 1) (list (first estado) (substitute elemtarget 'x (substitute 'x elemtarget filaconx) :count 1) (third estado))) (T (list (first estado) (second estado) (substitute elemtarget 'x (substitute 'x elemtarget filaconx) :count 1)))))) (defun valid-operator? (operador estado) "Predicado que regresa si el operador es valido o no" (let ((filax (first (where-is-x estado))) (casillax (second (where-is-x estado))) (ops (first operador))) (cond ((equal ops :arriba) (if (= filax 0) nil T)) ((equal ops :abajo) (if (= filax 2) nil T)) ((equal ops :izquierda) (if (= casillax 0) nil T)) ((equal ops :derecha) (if (= casillax 2) nil T)) (T "Error")))) (defun apply-operator (operador estado) "Funcion que aplica el operador especificado al estado" (let ((ops (first operador))) (case ops (:arriba (up estado)) (:abajo (down estado)) (:izquierda (left estado)) (:derecha (right estado)) (T "Error")))) (defun smooth (lista) "Funcion auxiliar que nos permite 'aplanar' una lista" (cond ((null lista) nil) ((atom (first lista)) (cons (first lista) (smooth (rest lista)))) (T (append (smooth (first lista)) (smooth (rest lista)))))) (defun aux-count-wrong-pieces (estado meta cont) "Funcion auxiliar que nos permite contar el numero de piezas desacomodadas en el estado actual" (cond ((null estado) cont) ((equal (first estado) 'x) (aux-count-wrong-pieces (rest estado) (rest meta) cont)) ((equal (first estado) (first meta)) (aux-count-wrong-pieces (rest estado) (rest meta) cont)) (T (+ (aux-count-wrong-pieces (rest estado) (rest meta) (1+ cont)))))) (defun count-wrong-pieces (estado meta) "Funcion la cual nos devuelve el numero de piezas desacomodadas" (aux-count-wrong-pieces (smooth estado) (smooth meta) 0)) (defun expand (estado) "Funcion que expande el estado" (incf *contadorExpandir*) (let ((descendientes nil) (nuevo-estado nil)) (dolist (op *ops* descendientes) (if (valid-operator? op estado) (progn (setq nuevo-estado (apply-operator op estado)) (setq descendientes (cons (list nuevo-estado op) descendientes))))))) (defun create-node (estado operador fichas) "Funcion que crea los nodos del arbol" (incf *id*) (incf *contadorNodos*) (list (1- *id*) estado *current-ancestor* (first operador) fichas)) (defun order-open () "Funcion que permite reordenar la frontera de busqueda" (setq *open* (stable-sort *open* #'< :key #'(lambda (x) (fifth x))))) (defun insert-to-open (estado operador metodo) "Funcion que inserta el nodo en la frontera de busqueda dependiendo del metodo que se le haya indicado" (let ((nodo '())) (cond ((equal metodo :wrong-pieces) (setq nodo (create-node estado operador (count-wrong-pieces estado *meta*))) (push nodo *open*) (order-open)) ((equal metodo :moves-left) (setq nodo (create-node estado operador (count-moves estado *meta*))) (push nodo *open*) (order-open)) ((equal metodo :random-value) (setq nodo (create-node estado operador (random 5))) (push nodo *open*) (order-open)) ((equal metodo :custom-value) (setq nodo (create-node estado operador (/ (+(count-moves estado *meta*) (count-wrong-pieces estado *meta*)) 2))) (push nodo *open*) (order-open)) (T Nil)))) (defun get-from-open () "Funcion que permite obtener un elemento de la frontera de busqueda" (pop *open*)) (defun get-max-in-open () (if (> (length *open*) *maximaFronteraBusqueda*) (setq *maximaFronteraBusqueda* (length *open*)))) (defun insert-to-memory (nodo) "Funcion que permite insertar un elemento a la memoria" (push nodo *memory*)) (defun remember-state-memory? (estado memoria) "Predicado que permite saber si un estado esta en la memoria" (cond ((null memoria) Nil) ((equal estado (second (first memoria))) T) (T (remember-state-memory? estado (rest memoria))))) (defun remember-state-open? (estado open) "Predicado que permite saber si un estado esta en la frontera de busqueda" (cond ((null open) Nil) ((equal estado (second (first open))) T) (T (remember-state-open? estado (rest open))))) (defun filter-memories (lista-estados-y-ops) "Funcion que permite filtrar los estados que aun no estan en la memoria" (cond ((null lista-estados-y-ops) Nil) ((remember-state-memory? (first (first lista-estados-y-ops)) *memory*) (filter-memories (rest lista-estados-y-ops))) (T (cons (first lista-estados-y-ops) (filter-memories (rest lista-estados-y-ops)))))) (defun filter-open (lista-estados-y-ops) "Funcion que permite filtrar los estados que aun no estan en la memoria" (cond ((null lista-estados-y-ops) Nil) ((remember-state-open? (first (first lista-estados-y-ops)) *open*) (filter-open (rest lista-estados-y-ops))) (T (cons (first lista-estados-y-ops) (filter-open (rest lista-estados-y-ops)))))) (defun extract-solution (nodo) "Funcion que extrae la solucion" (labels ((locate-node (id lista) (cond ((null lista) Nil) ((equal id (first (first lista))) (first lista)) (T (locate-node id (rest lista)))))) (let ((current (locate-node (first nodo) *memory*))) (loop while (not (null current)) do (push current *solucion*) (setq current (locate-node (third current) *memory*)))) *solucion*)) (defun aux-manhattan-distance (meta elemento casilla) "Funcion que calcula la distancia de cada elemento basandose en la casilla (columna)" (let ((contador 0)) (cond ((= casilla 2) (cond ((equal elemento (third meta)) contador) ((equal elemento (second meta)) (1+ contador)) (T (+ 2 contador)))) ((= casilla 1) (cond ((equal elemento (third meta)) (1+ contador)) ((equal elemento (second meta)) contador) (T (1+ contador)))) (T (cond ((equal elemento (third meta)) (+ 2 contador)) ((equal elemento (second meta)) (1+ contador)) (T contador)))))) (defun manhattan-distance (elemento meta fila casilla) "Funcion que calcula la distancia de cada elemento en las filas" (cond ((= fila 0) (cond ((member elemento (first meta)) (+ 0 (aux-manhattan-distance (first meta) elemento casilla))) ((member elemento (second meta)) (1+ (aux-manhattan-distance (second meta) elemento casilla))) (T (+ 2 (aux-manhattan-distance (third meta) elemento casilla))))) ((= fila 1) (cond ((member elemento (first meta)) (1+ (aux-manhattan-distance (first meta) elemento casilla))) ((member elemento (second meta)) (+ 0 (aux-manhattan-distance (first meta) elemento casilla))) (T (1+ (aux-manhattan-distance (third meta) elemento casilla))))) (T (cond ((member elemento (first meta)) (+ 2 (aux-manhattan-distance (first meta) elemento casilla))) ((member elemento (second meta)) (1+ (aux-manhattan-distance (second meta) elemento casilla))) (T (+ 0 (aux-manhattan-distance (third meta) elemento casilla))))))) (defun count-moves (estado meta) "Funcion que nos permite calcular la distancia Manhattan del estado actual" (let ((mov-cada-ficha 0) (columna 0) (fila 0) (casilla 0) (elementos (smooth estado))) (loop for elem in elementos do (if (= columna 3) (progn (setq casilla 0) (setq fila (1+ fila)) (setq columna 0))) (setq mov-cada-ficha (+ mov-cada-ficha (manhattan-distance elem meta fila casilla))) (setq casilla (1+ casilla)) (setq columna (1+ columna))) mov-cada-ficha)) (defun display-solution (lista-nodos) "Funcion la cual despliega la solucion" (setq *tiempoFinal* (get-internal-real-time)) (format t "Nodos creados ~A ~%" *contadorNodos*) (format t "Nodos expandidos ~A ~%" *contadorExpandir*) (format t "Longitud maxima de frontera de busqueda ~A ~%" *maximaFronteraBusqueda*) (format t "Tiempo para encontrar la solucion: ~A~%" (/ (- *tiempoFinal* *tiempoInicial*) internal-time-units-per-second)) (format t "Solucion con ~A pasos~%" (1- (length lista-nodos))) (let ((nodo nil)) (dotimes (i (length lista-nodos)) (setq nodo (nth i lista-nodos)) (if (= i 0) (format t "Inicio en: ~A~%" (second nodo)) (format t "\(~A\) aplicando ~A se llega a ~A~%" i (fourth nodo) (second nodo)))))) (defun reset-all () "Funcion de limpiado" (setq *open* nil) (setq *memory* nil) (setq *id* 0) (setq *contadorNodos* 0) (setq *contadorExpandir* 0) (setq *maximaFronteraBusqueda* 0) (setq *tiempoInicial* 0) (setq *tiempoFinal* 0) (setq *current-ancestor* nil) (setq *solucion* nil)) (defun informed-search (inicio meta metodo) "Funcion main" (reset-all) (setq *tiempoInicial* (get-internal-real-time)) (let ((nodo nil) (estado nil) (sucesores '()) (meta-encontrada nil)) (setq *meta* meta) (insert-to-open inicio nil metodo) (loop until (or meta-encontrada (null *open*)) do (setq nodo (get-from-open) estado (second nodo)) (get-max-in-open) (insert-to-memory nodo) (cond ((equal meta estado) (display-solution (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo)) (setq sucesores (expand estado)) (setq sucesores (filter-open sucesores)) (setq sucesores (filter-memories sucesores)) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) ;(informed-search '((2 8 3)(1 4 5)(7 x 6)) '((1 2 3)(8 x 4)(7 6 5)) :wrong-pieces) ;(informed-search '((2 8 3)(1 4 5)(7 x 6)) '((1 2 3)(8 x 4)(7 6 5)) :moves-left) ;(informed-search '((2 8 3)(1 4 5)(7 x 6)) '((1 2 3)(8 x 4)(7 6 5)) :random-value) ;(informed-search '((2 8 3)(1 4 5)(7 x 6)) '((1 2 3)(8 x 4)(7 6 5)) :custom-value)
12,937
Common Lisp
.lisp
311
37.784566
124
0.665185
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
77c6099d985f04c3486a03eb0f07198b7e2a97e1bb22b6715cc11a09dcda99a6
22,982
[ -1 ]
22,983
SearchEngine.lisp
CallmeTorre_IA/Exercises/SearchEngine/SearchEngine.lisp
;------------------------------------------ ;| Jesús Alexis Torreblanca Faces | ;| Inteligencia Artificial | ;| Motor de consulta | ;------------------------------------------ (defparameter *knowledge-vector* (make-array 100 :adjustable T :element-type 'list)) (defparameter *answer* nil) (defparameter *final-answer* nil) (defparameter *opertor* nil) (defparameter *value* nil) (defun reset-all () "Funcion que reinicia las variables globale spara las nuevas consultas" (setq *answer* nil *final-answer* nil)) (defun read-knowledge (filename) "Funcion que permite obtener la información de la base de conocimientos" (with-open-file (stream filename) (let ((numrows (read stream))) (adjust-array *knowledge-vector* numrows) (read-line stream nil nil) (dotimes (row numrows *knowledge-vector*) (setf (aref *knowledge-vector* row) (read stream nil nil)))))) (defun notEqual (valor1 valor2) "Funcion que imita el comportamiento de hacer un Not Equal" (not (equal valor1 valor2))) (defun conditional (expresion) "Funcion que permite saber si se esta usando reducción de terminos con los operadores lógicos básicos" (let* ((exp (write-to-string expresion)) (len-exp (length exp)) (exp-igual nil) (condicion-extra nil) (exp-sin-igual nil)) (if (equal (subseq exp 0 1) "[") (setq exp-igual (subseq exp 0 3) exp-sin-igual (subseq exp 0 2))) (cond ((string-equal exp-igual '[>=) (progn (setq *opertor* #'>= *value* (parse-integer (subseq exp 3 (1- len-exp)))))) ((string-equal exp-igual '[!=) (setq *opertor* #'notEqual) (setq condicion-extra (read-from-string (subseq exp 3 (1- len-exp)))) (if (numberp condicion-extra) (progn (setq *opertor* #'/=) (setq *value* (parse-integer (subseq exp 3 (1- len-exp))))) (setq *value* (intern (subseq exp 3 (1- len-exp)))))) ((string-equal exp-igual '[<=) (progn (setq *opertor* #'<= *value* (parse-integer (subseq exp 3 (1- len-exp)))))) ((string-equal exp-sin-igual '[>) (progn (setq *opertor* #'> *value* (parse-integer (subseq exp 2 (1- len-exp)))))) ((string-equal exp-sin-igual '[<) (progn (setq *opertor* #'< *value* (parse-integer (subseq exp 2 (1- len-exp)))))) (T (setq *opertor* nil *value* nil))))) (defun get-info-existencial (attr base-conocimiento) "Funcion que realiza las consultas para el cuantificador existencial" (loop for x from 0 to 128 do (loop for i from 0 to (1- (length (aref base-conocimiento x))) do (let ((clave (first (nth i (aref base-conocimiento x)))) (valor (rest (nth i (aref base-conocimiento x))))) (loop for atributo in attr do (conditional (rest atributo)) (if (equal (first atributo) clave) (if (null *opertor*) (if (equal (rest atributo) valor) (push 1 *answer*)) (progn (if (funcall *opertor* valor *value*) (push 1 *answer*)))))))) (if (= (apply #'+ *answer*)(length attr)) (push (aref base-conocimiento x) *final-answer*)) (setq *answer* nil *opertor* nil *value* nil))) (defun get-info-universal (attr base-conocimiento) "Funcion que realiza las consultas para el cuantificador universal" (loop for x from 0 to 128 do (loop for i from 0 to (1- (length (aref base-conocimiento x))) do (let ((clave (first (nth i (aref base-conocimiento x)))) (valor (rest (nth i (aref base-conocimiento x))))) (loop for atributo in attr do (conditional (rest atributo)) (if (equal (first atributo) clave) (if (null *opertor*) (if (not (equal (rest atributo) valor)) (setq *answer* t)) (progn (if (not (funcall *opertor* valor *value*)) (setq *answer* t) (setq *answer* nil)))))))) (if (not (null *answer*)) (push (aref base-conocimiento x) *final-answer*)) (setq *answer* nil *opertor* nil *value* nil))) (defun search-engine (consulta) "Funcion que recibe la consulta y determina que tipo de consulta esta realizando el usuario" (let* ((operador (first consulta)) (busqueda (rest consulta))) (cond ((equal operador '+) (get-info-existencial busqueda *knowledge-vector*) (if (null *final-answer*) (print "False") (progn (print "True") (print *final-answer*)))) ((equal operador '-) (get-info-existencial busqueda *knowledge-vector*) (if (null *final-answer*) (print "True") (progn (print "False") (print *final-answer*)))) ((equal operador '*) (get-info-universal busqueda *knowledge-vector*) (if (null *final-answer*) (print "True") (progn (print "False") (print *final-answer*)))) ((equal operador '/) (get-info-universal busqueda *knowledge-vector*) (if (null *final-answer*) (print "False") (progn (print "True") (print *final-answer*)))) (T "Operador Erroneo")))) (defun main () "Función Principal" (let ((consulta nil)) (read-knowledge "BaseDeConocimiento.txt") (loop (reset-all) (print "Escriba la consulta") (setq consulta (read)) (if (equal consulta 'exit) (Return)) (search-engine consulta)))) (main)
6,808
Common Lisp
.lisp
149
30.644295
102
0.481476
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
245b80d7d0dcb8e0fe434670509143f2c4ddfdccf62f27f223a7c52f6323fa96
22,983
[ -1 ]
22,984
3DMazes.lisp
CallmeTorre_IA/Exercises/Mazes/3DMazes.lisp
;------------------------------------------ ;| Jesús Alexis Torreblanca Faces | ;| Inteligencia Artificial | ;| Resuelve laberintos 3D | ;------------------------------------------ ;| Probar en: http://idic.likufanele.com/~fundamentosia/Maze3D/ (load "maze_lib.lisp") (add-algorithm 'depth-first) (add-algorithm 'breath-first) (add-algorithm 'best-first) (add-algorithm 'A*) (defparameter *open* '()) (defparameter *memory* '()) (defparameter *id* 0) (defparameter *current-ancestor* nil) (defparameter *solution* nil) (defparameter *filas* nil) (defparameter *columnas* nil) (defparameter *sol* nil) (defparameter *puente* 0) (defparameter *operadores* '((:Mover-Arriba 0) (:Mover-Arriba-Derecha 1) (:Mover-Derecha 2) (:Mover-Abajo-Derecha 3) (:Mover-Abajo 4) (:Mover-Abajo-Izquierda 5) (:Mover-Izquierda 6) (:Mover-Arriba-Izquierda 7))) (defun reset-all () "Función que limpia todas las variables globales" (setq *open* nil) (setq *memory* nil) (setq *id* 0) (setq *sol* nil) (setq *puente* 0) (setq *current-ancestor* nil) (setq *solution* nil)) (defun create-node (estado operador importancia) "Función la cual crea un nodo con la estructura (<id> <estado> <id-ancestro> <operador> <función-heuristica>)" (incf *id*) (list (1- *id*) importancia estado *current-ancestor* (second operador))) (defun get-distance (estado) "Función basada en la ecuación para obtener la distancia entre dos puntos (((x2-x1)^2 +(y2-y1)^2)^1/2) pero ligeramente modificada (x2-x1) + (y2-y1)" (max (- (max (aref estado 0) (aref *goal* 0)) (min (aref estado 0) (aref *goal* 0))) (- (max (aref estado 1) (aref *goal* 1)) (min (aref estado 1) (aref *goal* 1))))) (defun insert-to-open (estado operador metodoBusqueda) "Función la cual dependiendo del metodo que se le pase inserta a la frontera de busqueda el nodo" (let* ((nodo '())) (cond ((eql metodoBusqueda :depth-first ) (setq nodo (create-node estado operador nil)) (push nodo *open* )) ((eql metodoBusqueda :breath-first ) (setq nodo (create-node estado operador nil)) (setq *open* (append *open* (list nodo)))) ((eql metodoBusqueda :best-first) (setq nodo (create-node estado operador (get-distance estado))) (push nodo *open* ) (order-open)) ((eql metodoBusqueda :Astar) (setq nodo (create-node estado operador (get-distance estado))) (setf (second nodo) (+ (second nodo) (get-cost nodo 0))) (if (remember-state-open? (third nodo) *open* ) (compare-node nodo *open* ) (push nodo *open* )) (order-open) )))) (defun get-cost (nodo num) "Función la cual obtiene el nivel de profundidad (costo) de un nodo determinado" (labels ((locate-node (id lista) (cond ((null lista) nil) ((eql id (first (first lista))) (first lista)) (T (locate-node id (rest lista)))))) (let ((current (locate-node (fourth nodo) *memory*))) (loop while (not (null current)) do (setq num (incf num)) (setq current (locate-node (fourth current) *memory*)))) num)) (defun get-from-open () "Función que obtiene el primer nodo de la frontera de busqueda" (pop *open* )) (defun order-open () "Funcion que permite reordenar la frontera de busqueda" (setq *open* (stable-sort *open* #'< :key #'(lambda (x) (fifth x))))) (defun valid-operator? (op estado) "Predicado que valida si un operador es aplicable a un estado determinado" (let* ((fila (aref estado 0)) (columna (aref estado 1)) (casillaActual (get-cell-walls fila columna)) (operador (second op)) (casillaArriba nil) (casillaAbajo nil) (casilla-Arriba-Derecha -1) (casilla-Abajo-Derecha -1) (casilla-Arriba-Izquierda -1) (casilla-Abajo-Izquierda -1) (casillaIzquierda nil) (casillaDerecha nil) (operadorPasado -1) (diagonal? nil)) (if (not (= fila 0)) (setq casillaArriba (get-cell-walls (1- fila) columna))) (if (not (= columna 0)) (setq casillaIzquierda (get-cell-walls fila (1- columna)))) (if (not (= columna (1- *columnas*))) (setq casillaDerecha (get-cell-walls fila (1+ columna)))) (if (not (= fila (1- *filas* ))) (setq casillaAbajo (get-cell-walls (1+ fila) columna))) (if (not (or (null casillaArriba)(null casillaDerecha))) (setq casilla-Arriba-Derecha (get-cell-walls (1- fila) (1+ columna)))) (if (not (or (null casillaDerecha) (null casillaAbajo))) (setq casilla-Abajo-Derecha (get-cell-walls (1+ fila) (1+ columna)))) (if (not (or (null casillaIzquierda) (null casillaAbajo))) (setq casilla-Abajo-Izquierda (get-cell-walls (1+ fila) (1- columna)))) (if (not (or (null casillaIzquierda) (null casillaArriba))) (setq casilla-Arriba-Izquierda (get-cell-walls (1- fila) (1- columna)))) (if (not (or (null casillaArriba) (null casillaAbajo ) (null casillaIzquierda ) (null casillaDerecha ))) (progn (if (and (not (or (= casillaArriba 16 ) (= casillaAbajo 16 ) (= casillaIzquierda 16 ) (= casillaDerecha 16 ) (= casillaActual 16 ))) (not (or (= casillaArriba 17 ) (= casillaAbajo 17 ) (= casillaIzquierda 17 ) (= casillaDerecha 17 ) (= casillaActual 17 )))) (setq diagonal? T)))) (if (not ( null (fifth (first *memory*)))) (setq operadorPasado (fifth(first *memory*)))) (if (or (= casillaActual 16)(= casillaActual 17)) (setq *puente* 1)(setq *puente* 0)) (cond ((= operador 0) (cond ((null casillaArriba) nil) ((or (= casillaActual 16)(= casillaActual 17)) (if (= operadorPasado 0) T nil)) ((= (boole boole-and casillaActual 1) 0) T) (T nil))) ((= operador 1) (cond ((or (= casilla-Arriba-Derecha 16)(= casilla-Arriba-Derecha 17)) nil) ((null diagonal?) nil) ((or (null casillaArriba) (null casillaDerecha)) nil) ((and (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaDerecha 1) 0)) (or (= (boole boole-and casillaArriba 2) 0) (= (boole boole-and casillaDerecha 1) 0)) (or (= (boole boole-and casillaArriba 2) 0) (= (boole boole-and casillaActual 2) 0)) (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaActual 2) 0))) T) (T nil))) ((= operador 2) (cond ((null casillaDerecha) nil) ((or (= casillaActual 16)(= casillaActual 17)) (if (= operadorPasado 2) T nil)) ((= (boole boole-and casillaActual 2) 0) T) (T nil))) ((= operador 3) (cond ((or (= casilla-Abajo-Derecha 16)(= casilla-Abajo-Derecha 17)) nil) ((null diagonal?) nil) ((or (null casillaDerecha) (null casillaAbajo)) nil) ((and (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaDerecha 4) 0)) (or (= (boole boole-and casillaAbajo 2) 0) (= (boole boole-and casillaDerecha 4) 0)) (or (= (boole boole-and casillaAbajo 2) 0) (= (boole boole-and casillaActual 2) 0)) (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaActual 2) 0))) T) (T nil))) ((= operador 4) (cond ((or (= casillaActual 16)(= casillaActual 17)) (if (= operadorPasado 4) T nil)) ((null casillaAbajo) nil) ((= (boole boole-and casillaActual 4) 0) T) (T nil))) ((= operador 5) (cond ((or (= casilla-Abajo-Izquierda 16)(= casilla-Abajo-Izquierda 17)) nil) ((null diagonal?) nil) ((or (null casillaAbajo) (null casillaIzquierda)) nil) ((and (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaIzquierda 4) 0)) (or (= (boole boole-and casillaAbajo 8) 0) (= (boole boole-and casillaIzquierda 4) 0)) (or (= (boole boole-and casillaAbajo 8) 0) (= (boole boole-and casillaActual 8) 0)) (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaActual 8) 0))) T) (T nil))) ((= operador 6) (cond ((null casillaIzquierda) nil) ((or (= casillaActual 16)(= casillaActual 17)) (if (= operadorPasado 6) T nil)) ((= (boole boole-and casillaActual 8) 0) T) (T nil))) ((= operador 7) (cond ((or (= casilla-Arriba-Izquierda 16)(= casilla-Arriba-Izquierda 17)) nil) ((null diagonal?) nil) ((or (null casillaArriba) (null casillaIzquierda)) nil) ((and (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaIzquierda 1) 0)) (or (= (boole boole-and casillaArriba 8) 0) (= (boole boole-and casillaIzquierda 1) 0)) (or (= (boole boole-and casillaArriba 8) 0) (= (boole boole-and casillaActual 8) 0)) (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaActual 8) 0))) T) (T nil))) (T nil)))) (defun apply-operator (operador estado) "Función que aplica un operador a un estado" (let* ((fila (aref estado 0)) (columna (aref estado 1)) (casillaActual (get-cell-walls fila columna)) (operador (first operador)) (estadoFinal nil)) (if (or (= casillaActual 16)(= casillaActual 17)) (setq *puente* 1) (setq *puente* 0)) (case operador (:Mover-Arriba (setq estadoFinal (make-array 3 :initial-contents (list (1- fila) columna *puente*)))) (:Mover-Arriba-Derecha (setq estadoFinal (make-array 3 :initial-contents (list (1- fila) (1+ columna) *puente*)))) (:Mover-Derecha (setq estadoFinal (make-array 3 :initial-contents (list fila (1+ columna) *puente*)))) (:Mover-Abajo-Derecha (setq estadoFinal (make-array 3 :initial-contents (list (1+ fila) (1+ columna) *puente* )))) (:Mover-Abajo (setq estadoFinal (make-array 3 :initial-contents (list (1+ fila) columna *puente*)))) (:Mover-Abajo-Izquierda (setq estadoFinal (make-array 3 :initial-contents (list (1+ fila) (1- columna) *puente*)))) (:Mover-Izquierda (setq estadoFinal (make-array 3 :initial-contents (list fila (1- columna) *puente*)))) (:Mover-Arriba-Izquierda (setq estadoFinal (make-array 3 :initial-contents (list (1- fila) (1- columna) *puente*)))) (T "error")) estadoFinal)) (defun compare-node (nodo listaMemoria) "Funcion la cual busca si el nodo a insertar está ya en la frontera y si es asi compara el valor de su función heuristica" (let ((nodoAux nil)) (cond ((null listaMemoria) (push nodo *open* )) ((and (equal (aref (third nodo) 0) (aref (third (first listaMemoria)) 0)) (equal (aref (third nodo) 1) (aref (third (first listaMemoria)) 1))) (setq nodoAux (first listaMemoria)) (if (< (second nodo) (second nodoAux)) (progn (delete nodoAux listaMemoria) (push nodo *open* )))) (T (compare-node nodo (rest listaMemoria)))))) (defun expand (estado) "Función que expande el estado a todos sus posibles descendientes" (let ((descendientes nil) (nuevoEstado nil)) (dolist (operador *operadores* descendientes) (if (valid-operator? operador estado) (progn (setq nuevoEstado (apply-operator operador estado)) (setq descendientes (cons (list nuevoEstado operador) descendientes))))))) (defun filter-memories (listaDeEstados lista) "Funcion que filtra los estados que se encuentran en la memoria" (cond ((null listaDeEstados) nil) ((remember-state-memory? (first (first listaDeEstados)) lista) (filter-memories (rest listaDeEstados) lista)) (T (cons (first listaDeEstados) (filter-memories (rest listaDeEstados) lista))))) (defun remember-state-memory? (estado memoria) "Predicado que nos dice si un estado se encuentra en la memoria" (let* ((fila (aref estado 0)) (columna (aref estado 1)) (casilla (get-cell-walls fila columna))) (cond ((null memoria) nil) ((and (equal (aref estado 0) (aref (third (first memoria)) 0)) (equal (aref estado 1) (aref (third (first memoria)) 1)) (not (or (= casilla 16) (= casilla 17)))) T) (T (remember-state-memory? estado (rest memoria)))))) (defun filter-open (lista-estados-y-ops) "Funcion que filtra los estados que se encuentran en la frontera de busqueda" (cond ((null lista-estados-y-ops) Nil) ((remember-state-open? (first (first lista-estados-y-ops)) *open*) (filter-open (rest lista-estados-y-ops))) (T (cons (first lista-estados-y-ops) (filter-open (rest lista-estados-y-ops)))))) (defun remember-state-open? (estado open) "Predicado que nos dice si un estado se encuentra en la frontera de busqueda" (cond ((null open) Nil) ((and (equal (aref estado 0) (aref (second (first open)) 0)) (equal (aref estado 1) (aref (second (first open)) 1))) T) (T (remember-state-memory? estado (rest open))))) (defun extract-solution (nodo) "Función que extrae la solución del laberinto" (labels ((locate-node (id lista) (cond ((null lista) nil) ((eql id (first (first lista))) (first lista)) (T (locate-node id (rest lista)))))) (let ((current (locate-node (first nodo) *memory*))) (loop while (not (null current)) do (if (not (null (fifth current))) (push (fifth current) *sol*)) (setq current (locate-node (fourth current) *memory*)))) *sol*)) (defun depth-first () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (inicialColumna nil) (inicialFila nil) (meta-encontrada nil) (metodo :depth-first)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (setq inicialColumna (aref *start* 0)) (setq inicialFila (aref *start* 1)) (insert-to-open (make-array 3 :initial-contents (list inicialColumna inicialFila 0 )) nil metodo) (loop until (or meta-encontrada (null *open* )) do (setq nodo (get-from-open) estado (third nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (expand estado) *memory*)) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) (defun breath-first () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (meta-encontrada nil) (inicialColumna nil) (inicialFila nil) (metodo :breath-first)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (setq inicialColumna (aref *start* 0)) (setq inicialFila (aref *start* 1)) (insert-to-open (make-array 3 :initial-contents (list inicialColumna inicialFila 0 )) nil metodo) (loop until (or meta-encontrada (null *open* )) do (setq nodo (get-from-open) estado (third nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (expand estado) *memory*)) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) (defun best-first () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (inicialColumna nil) (inicialFila nil) (meta-encontrada nil) (metodo :best-first)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (setq inicialColumna (aref *start* 0)) (setq inicialFila (aref *start* 1)) (insert-to-open (make-array 3 :initial-contents (list inicialColumna inicialFila 0 )) nil metodo) (loop until (or meta-encontrada (null *open* )) do (setq nodo (get-from-open) estado (third nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (filter-memories (expand estado) *open* ) *memory*)) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) (defun A* () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (inicialColumna nil) (inicialFila nil) (meta-encontrada nil) (metodo :Astar)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (setq inicialColumna (aref *start* 0)) (setq inicialFila (aref *start* 1)) (insert-to-open (make-array 3 :initial-contents (list inicialColumna inicialFila 0 )) nil metodo) (loop until (or meta-encontrada (null *open* )) do (setq nodo (get-from-open) estado (third nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (expand estado) *memory*)) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) ;[Inicio] Iniciamos nuestro laberinto (start-maze)
19,384
Common Lisp
.lisp
389
38.951157
151
0.567622
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1ec54491c0e058bc60033ae266142ed7d108d515a5af67db5357cdf3308159f3
22,984
[ -1 ]
22,985
maze_lib.lisp
CallmeTorre_IA/Exercises/Mazes/maze_lib.lisp
;Biblioteca maze-lib.lisp - Versión para descargar. ;Variables propias de esta biblioteca. Favor de no usarse o modificarse dentro de su código. (defvar *algorithms-list* nil) (defvar *goal*) (defvar *start*) (defvar *solution* nil) (defvar *exec_time* 100000) (defvar *num_algorithm* 0) (defvar *num_laberinto* 0) (defvar *maze*) (defclass maze nil ((data :initarg :data :initform (make-array '(1 1))) (start_position :initarg :start_position :initform #(0 0)) (goal_position :initarg :goal_position :initform #(1 1)) (dimensions :initarg :dimensions :initform '(5 5)))) (setq *maze* (make-instance 'maze :data #2A((13 1 3 12 3) (9 6 12 3 10) (12 5 3 10 10) (3 9 6 10 10) (12 6 13 4 6)) :start_position #(0 3) :goal_position #(3 0))) (setq *start* (slot-value *maze* 'start_position)) (setq *goal* (slot-value *maze* 'goal_position)) (defmacro add-algorithm (algoritmo) ;Añade un algoritmo a ejecutar. `(setq *algorithms-list* (append *algorithms-list* (list ,algoritmo)))) (defun get-maze-data () ;Obtiene los datos del laberinto (slot-value *maze* 'data)) (defun get-cell-walls (x y) ;Regresa las paredes de una celda del laberinto. (let ((maze_size (array-dimensions (get-maze-data)))) (cond ((and (>= x 0) (< x (nth 0 maze_size)) (>= y 0) (< y (nth 1 maze_size))) (aref (get-maze-data) x y)) (t (error "Coordenadas fuera de las dimensiones del laberinto."))))) (defun draw-cell-walls (x y) ;Dibuja las paredes del laberinto, solo como referencia. (let ((paredes (get-cell-walls x y))) (case paredes (0 (format t "~%~%~%")) (1 (format t "────~%~%")) (2 (format t " │~% │~%")) (3 (format t "───┐~% │~%")) (4 (format t "~%~%────")) (5 (format t "────~%~%────")) (6 (format t " │~% │~%───┘")) (7 (format t "───┐~% │~%───┘")) (8 (format t "│~%│~%")) (9 (format t "┌───~%│~%")) (10 (format t "│ │~%│ │~%")) (11 (format t "┌──┐~%│ │~%")) (12 (format t "│~%│~%└───")) (13 (format t "┌───~%│~%└───")) (14 (format t "│ │~%│ │~%└──┘")) (15 (format t "┌──┐~%│ │~%└──┘"))))) (defun get-maze-rows () ;Regresa las filas del laberinto. (first (slot-value *maze* 'dimensions))) (defun get-maze-cols () ;Regresa las columnas del laberinto (second (slot-value *maze* 'dimensions))) (defun start-maze () ;Función para procesar la línea de comandos. (loop for k from 1 below (length *posix-argv*) do (eval (read-from-string (nth k *posix-argv*)))))
2,806
Common Lisp
.lisp
73
31.205479
98
0.566535
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c2e7f239626ce06543fe2b2982aff3b82b696c2e71b20da1b242071f8b493ada
22,985
[ -1 ]
22,986
2DMazes.lisp
CallmeTorre_IA/Exercises/Mazes/2DMazes.lisp
;------------------------------------------ ;| Jesús Alexis Torreblanca Faces | ;| Inteligencia Artificial | ;| Resuelve laberintos 2D | ;------------------------------------------ ;| Probar en: http://idic.likufanele.com/~fundamentosia/Maze2D/ ;Librería que genera los laberintos (load "maze_lib.lisp") ;Metodos de Busqueda para la solución del algoritmo (add-algorithm 'depth-first) (add-algorithm 'breath-first) (add-algorithm 'best-first) (add-algorithm 'A*) (defparameter *open* '()) ;Frontera de Busqueda (defparameter *memory* '()) ;Memoria de Intentos Previos (defparameter *id* 0) (defparameter *current-ancestor* nil) (defparameter *solution* nil) (defparameter *filas* 0) (defparameter *columnas* 0) (defparameter *sol* nil) (defparameter *ops* '((:Arriba 0) (:Arriba-derecha 1) (:Derecha 2) (:Abajo-derecha 3) (:Abajo 4) (:Abajo-izquierda 5) (:Izquierda 6) (:Arriba-izquierda 7))) (defun create-node (estado operador funcion) "Función la cual crea un nodo con la estructura (<id> <estado> <id-ancestro> <operador> <función-heuristica>)" (incf *id*) (list (1- *id*) estado *current-ancestor* (second operador) funcion)) (defun insert-to-open (estado operador metodo) "Función la cual dependiendo del metodo que se le pase inserta a la frontera de busqueda el nodo" (let ((nodo '())) (cond ((equal metodo :depth-first) (setq nodo (create-node estado operador nil)) (push nodo *open*)) ((equal metodo :breath-first) (setq nodo (create-node estado operador nil)) (setq *open* (append *open* (list nodo)))) ((equal metodo :best-first) (setq nodo (create-node estado operador (get-distance estado))) (push nodo *open*) (order-open)) ((equal metodo :A*) (setq nodo (create-node estado operador nil)) (setf (fifth nodo) (A-star nodo)) (if (remember-state-open? (second nodo) *open*) (compare-node nodo *open*) (push nodo *open*)) (order-open)) (T Nil)))) (defun get-from-open () "Función que obtiene el primer nodo de la frontera de busqueda" (pop *open*)) (defun order-open () "Funcion que permite reordenar la frontera de busqueda" (setq *open* (stable-sort *open* #'< :key #'(lambda (x) (fifth x))))) (defun get-distance (estado) "Función basada en la ecuación para obtener la distancia entre dos puntos (((x2-x1)^2 +(y2-y1)^2)^1/2) pero ligeramente modificada (x2-x1) + (y2-y1)" (+ (- (max (aref estado 0) (aref *goal* 0)) (min (aref estado 0) (aref *goal* 0))) (- (max (aref estado 1) (aref *goal* 1)) (min (aref estado 1) (aref *goal* 1))))) (defun compare-node (nodo open) "Funcion la cual busca si el nodo a insertar está ya en la frontera y si es asi compara el valor de su función heuristica" (let ((nodo-copia-de-open nil)) (cond ((null open) (push nodo *open*)) ((and (equal (aref (second nodo) 0) (aref (second (first open)) 0)) (equal (aref (second nodo) 1) (aref (second (first open)) 1))) (setq nodo-copia-de-open (first open)) (if (< (fifth nodo) (fifth nodo-copia-de-open)) (progn (delete nodo-copia-de-open open) (push nodo *open*)))) (T (compare-node nodo (rest open)))))) (defun get-cost (nodo cont) "Función la cual obtiene el nivel de profundidad (costo) de un nodo determinado" (labels ((locate-node (id lista) (cond ((null lista) Nil) ((equal id (first (first lista))) (first lista)) (T (locate-node id (rest lista)))))) (let ((current (locate-node (third nodo) *memory*))) (loop while (not (null current)) do (setq cont (incf cont)) (setq current (locate-node (third current) *memory*)))) cont)) (defun A-star (nodo) "Función que obtiene el valor de la función de evaluación del algoritmo A* f(x) = g(x) + h(x)" (+ (get-distance (second nodo)) (get-cost nodo 0))) (defun valid-operator? (op estado) "Predicado que valida si un operador es aplicable a un estado determinado" (let* ((fila (aref estado 0)) (columna (aref estado 1)) (casillaActual (get-cell-walls fila columna)) (operador (second op)) (casillaArriba 0) (casillaAbajo 0) (casillaIzquierda 0) (casillaDerecha 0)) (if (not (= fila 0)) (setq casillaArriba (get-cell-walls (1- fila) columna))) (if (not (= columna 0)) (setq casillaIzquierda (get-cell-walls fila (1- columna)))) (if (not (= columna (1- *columnas*))) (setq casillaDerecha (get-cell-walls fila (1+ columna)))) (if (not (= fila (1- *filas*))) (setq casillaAbajo (get-cell-walls (1+ fila) columna))) (cond ((= operador 0) (and (not (= fila 0)) (= (boole boole-and casillaActual 1) 0))) ((= operador 1) (and (not (= fila 0)) (not (= columna (1- *columnas*))) (and (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaDerecha 1) 0)) (or (= (boole boole-and casillaArriba 2) 0) (= (boole boole-and casillaDerecha 1) 0)) (or (= (boole boole-and casillaArriba 2) 0) (= (boole boole-and casillaActual 2) 0)) (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaActual 2) 0))))) ((= operador 2) (and (not (= columna (1- *columnas*))) (= (boole boole-and casillaActual 2) 0))) ((= operador 3) (and (not (= fila (1- *filas*))) (not (= columna (1- *columnas*))) (and (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaDerecha 4) 0)) (or (= (boole boole-and casillaAbajo 2) 0) (= (boole boole-and casillaDerecha 4) 0)) (or (= (boole boole-and casillaAbajo 2) 0) (= (boole boole-and casillaActual 2) 0)) (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaActual 2) 0))))) ((= operador 4) (and (not (= fila (1- *filas*))) (= (boole boole-and casillaActual 4) 0))) ((= operador 5) (and (not (= fila (1- *filas*))) (not (= columna 0)) (and (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaIzquierda 4) 0)) (or (= (boole boole-and casillaAbajo 8) 0) (= (boole boole-and casillaIzquierda 4) 0)) (or (= (boole boole-and casillaAbajo 8) 0) (= (boole boole-and casillaActual 8) 0)) (or (= (boole boole-and casillaActual 4) 0) (= (boole boole-and casillaActual 8) 0))))) ((= operador 6) (and (not (= columna 0)) (= (boole boole-and casillaActual 8) 0))) ((= operador 7) (and (not (= fila 0)) (not (= columna 0)) (and (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaIzquierda 1) 0)) (or (= (boole boole-and casillaArriba 8) 0) (= (boole boole-and casillaIzquierda 1) 0)) (or (= (boole boole-and casillaArriba 8) 0) (= (boole boole-and casillaActual 8) 0)) (or (= (boole boole-and casillaActual 1) 0) (= (boole boole-and casillaActual 8) 0))))) (T nil)))) (defun apply-operator (operador estado) "Función que aplica un operador a un estado" (let* ((fila (aref estado 0)) (columna (aref estado 1)) (op (first operador)) (estado nil)) (case op (:Arriba (setq estado (make-array 2 :initial-contents (list (1- fila) columna)))) (:Arriba-derecha (setq estado (make-array 2 :initial-contents (list (1- fila) (1+ columna))))) (:Derecha (setq estado (make-array 2 :initial-contents (list fila (1+ columna))))) (:Abajo-derecha (setq estado (make-array 2 :initial-contents (list (1+ fila) (1+ columna))))) (:Abajo (setq estado (make-array 2 :initial-contents (list (1+ fila) columna)))) (:Abajo-izquierda (setq estado (make-array 2 :initial-contents (list (1+ fila) (1- columna))))) (:Izquierda (setq estado (make-array 2 :initial-contents (list fila (1- columna))))) (:Arriba-izquierda (setq estado (make-array 2 :initial-contents (list (1- fila) (1- columna))))) (T "Error")) estado)) (defun expand (estado) "Función que expande el estado a todos sus posibles descendientes" (let ((descendientes nil) (nuevo-estado nil)) (dolist (op *ops* descendientes) (if (valid-operator? op estado) (progn (setq nuevo-estado (apply-operator op estado)) (if (not (null nuevo-estado)) (setq descendientes (cons (list nuevo-estado op) descendientes)))))))) (defun filter-memories (lista-estados-y-ops) "Funcion que filtra los estados que se encuentran en la memoria" (cond ((null lista-estados-y-ops) Nil) ((remember-state-memory? (first (first lista-estados-y-ops)) *memory*) (filter-memories (rest lista-estados-y-ops))) (T (cons (first lista-estados-y-ops) (filter-memories (rest lista-estados-y-ops)))))) (defun remember-state-memory? (estado memoria) "Predicado que nos dice si un estado se encuentra en la memoria" (cond ((null memoria) Nil) ((and (equal (aref estado 0) (aref (second (first memoria)) 0)) (equal (aref estado 1) (aref (second (first memoria)) 1))) T) (T (remember-state-memory? estado (rest memoria))))) (defun filter-open (lista-estados-y-ops) "Funcion que filtra los estados que se encuentran en la frontera de busqueda" (cond ((null lista-estados-y-ops) Nil) ((remember-state-open? (first (first lista-estados-y-ops)) *open*) (filter-open (rest lista-estados-y-ops))) (T (cons (first lista-estados-y-ops) (filter-open (rest lista-estados-y-ops)))))) (defun remember-state-open? (estado open) "Predicado que nos dice si un estado se encuentra en la frontera de busqueda" (cond ((null open) Nil) ((and (equal (aref estado 0) (aref (second (first open)) 0)) (equal (aref estado 1) (aref (second (first open)) 1))) T) (T (remember-state-memory? estado (rest open))))) (defun extract-solution (nodo) "Función que extrae la solución del laberinto" (labels ((locate-node (id lista) (cond ((null lista) Nil) ((equal id (first (first lista))) (first lista)) (T (locate-node id (rest lista)))))) (let ((current (locate-node (first nodo) *memory*))) (loop while (not (null current)) do (if (not (null (fourth current))) (push (fourth current) *sol*)) (setq current (locate-node (third current) *memory*)))) *sol*)) (defun reset-all () "Función que limpia todas las variables globales" (setq *open* nil) (setq *memory* nil) (setq *id* 0) (setq *sol* nil) (setq *current-ancestor* nil) (setq *solution* nil)) (defun depth-first () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (meta-encontrada nil) (metodo :depth-first)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (insert-to-open *start* nil metodo) (loop until (or meta-encontrada (null *open*)) do (setq nodo (get-from-open) estado (second nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (expand estado))) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) (defun breath-first () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (meta-encontrada nil) (metodo :breath-first)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (insert-to-open *start* nil metodo) (loop until (or meta-encontrada (null *open*)) do (setq nodo (get-from-open) estado (second nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (expand estado))) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) (defun best-first () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (meta-encontrada nil) (metodo :best-first)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (insert-to-open *start* nil metodo) (loop until (or meta-encontrada (null *open*)) do (setq nodo (get-from-open) estado (second nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (filter-open (expand estado)))) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) (defun A* () (reset-all) (let ((nodo nil) (estado nil) (sucesores '()) (meta-encontrada nil) (metodo :A*)) (setq *filas* (get-maze-rows)) (setq *columnas* (get-maze-cols)) (insert-to-open *start* nil metodo) (loop until (or meta-encontrada (null *open*)) do (setq nodo (get-from-open) estado (second nodo)) (push nodo *memory*) (cond ((and (equal (aref *goal* 0) (aref estado 0)) (equal (aref *goal* 1) (aref estado 1))) (setq *solution* (extract-solution nodo)) (setq meta-encontrada T)) (T (setq *current-ancestor* (first nodo) sucesores (filter-memories (expand estado))) (loop for elem in sucesores do (insert-to-open (first elem) (second elem) metodo))))))) (start-maze)
15,826
Common Lisp
.lisp
324
37.12037
151
0.54329
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3eb1384278a3f568e6ffdb75203a60cf3682a427c3af2084c3dbf4d9bce34775
22,986
[ -1 ]
22,987
Código_de_ejemplo.lisp
CallmeTorre_IA/Exercises/Mazes/Código_de_ejemplo.lisp
;;;Código de ejemplo. ;;;Este código muestra como deben usarse las funciones de la biblioteca ;;;maze-lib.lsp para que pueda ser usado en la página de internet. Este código ;;;sólo funciona para el laberinto Chico, ya que la solución ya está escrita ;;;dentro del código. Si se usa en los demás laberintos surgirán mensajes de ;;;error. ;Primero debe cargarse la biblioteca de la siguiente forma. (load "maze_lib.lisp") ;Para añadir un algoritmo al menú de la página es necesario usar la función ;add-algorithm, como se muestra a continuación. No importa en que lugar ;del archivo se use, pero de preferencia que sea al inicio del código. ;Si están haciendo pruebas en su computadora entonces no hay problema si se ;omiten. (add-algorithm 'breadth-first) (add-algorithm 'depth-first) (add-algorithm 'error-example) ;Función de muestra. Regresa el resultado de un algoritmo de búsqueda a lo ;ancho. Esta función no debe llevar argumentos. (defun breadth-first () ;La posición inicial y la posición meta del laberinto están almacenadas en las ;variables *start* y *goal*. Estas son arreglos de dos elementos, el ;primero es la fila y la segunda la columna. La posición #(0 0) está ubicada en ;la celda superior izquierda. La primer coordenada es el número de fila (y) y ;la segunda es el número de columna (x). (format t "Posición inicial: ~S~%" *start*) (format t "Posición meta: ~S~%" *goal*) ;Para saber cuantas filas y cuantas columnas tiene el laberinto en total, es ;necesario usar las funciones get-maze-rows y get-maze-cols (format t "Número total de filas: ~S~%" (get-maze-rows)) (format t "Número total de columnas ~S~%" (get-maze-cols)) ;Para pedir las paredes de una celda determinada es necesario usar la función ;get-cell-walls. Recibe dos argumentos: el número de la fila y el número de la ;columna. (format t "Paredes de la celda #(0 3): ~S~%" (get-cell-walls 0 3)) ;Si sienten la necesidad de ver dibujadas las paredes de una celda, pueden ;usar la función draw-cell-walls. (format t "Dibujo de las paredes de la celda #(0 3):~%") (draw-cell-walls 0 3) ;Si desean obtener la información de todas las paredes del laberinto pueden ;usar la función get-maze-data (format t "Datos del laberinto: ~%~S~%" (get-maze-data)) ;La solución debe almacenarse en la variable global *solution*, la cual ya ;está declarada dentro de la biblioteca maze_lib. (setq *solution* '(3 4 4 4 7 0 7 7 5 3 3 5 7))) ;La solución debe ser expresada como una lista conteniendo las direcciones de ;los desplazamientos. Cada dirección está representada por un número, empezando ;desde arriba con el 0 y después en sentido horario. De esta forma, los 8 ;movimientos posibles son: ;Arriba (N): 0 ;Arriba-derecha (NE): 1 ;Derecha (E): 2 ;Abajo-derecha (SE): 3 ;Abajo (S): 4 ;Abajo-izquierda (SW): 5 ;Izquierda (W): 6 ;Arriba-izquierda (NW): 7 ;Función de muestra. Regresa el resultado de un algoritmo de búsqueda a lo ;profundo. Esta función no debe llevar argumentos. (defun depth-first () (setq *solution* '(3 4 4 5 0 0 7 7 5 3 3 6 5 0))) ;Función defectuosa. Esta función genera un error al trater de obtener las ;paredes de una celda fuera de las fronteras del laberinto. Esto es para que ;puedan ver como se despliegan los errores de ejecución dentro de la página. (defun error-example () (get-cell-walls 1000 1000)) ;La última línea ejecutable del código debe ser la siguiente. Es la que se ;encarga de enviar la solución a la página de internet para que pueda ser ;dibujada. Si están haciendo pruebas en su computadora entonces pueden omitirla ;o comentarla. (start-maze)
3,698
Common Lisp
.lisp
68
51.367647
85
0.752944
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e6a13402868cfc9b486d62ca076a7e8bfaab4480462e080133cfc43b57eda266
22,987
[ -1 ]
22,988
ExercisePackage4.lisp
CallmeTorre_IA/LISP/ExercisePackage4.lisp
;Jesús Alexis Torreblanca Faces ;1) (defun Collect (fun l) (cond ((null lista) nil) (t (Collect (funcall fun (car lista) (cadr lista)))))) (Collect #'+ '(1 2 3 4)) ; 10 ;2) (defun palindromo (lista) (if (equal nil lista) T (if (equal (first lista) (first (last lista))) (palindromo (rest (butlast lista))) nil))) (palindromo '(a b a)) ; T ;3) (defun 2palindrome (cadena &optional (inicio 0)) (if (= (length cadena) 0) T (if (char= (char cadena inicio) (char (reverse cadena) inicio)) (2palindrome (subseq cadena (+ inicio 1) (- (length cadena) 1)) inicio) nil))) (2palindrome "abba") ; T ;4) (defun iterativepalindrome (lista) (loop for i from 0 for a in lista for b in (reverse lista) always (equal a b) until (> i(/(length lista)2)))) (iterativepalindrome '(a b a)) ; T ;5) (defun listRotate (l &key (right nil) (left nil)) (if right (rotate l right) (rotate l (* -1 left)))) (defun rotate (list count) (if (minusp count) (rotate list (+ (length list) count)) (nconc (subseq list count) (subseq list 0 count)))) (listRotate '(a b c d e f g h) :right 3) ; (D E F G H A B C) ;6) (defun Max&Pos (a) (let* ((dim (array-dimensions a)) (f (first dim)) (c (second dim)) (elem 0) (pos 0)) (loop for i from 0 to (- c 1) collect(dotimes(j f (cons elem pos)) (if (< elem (aref a j i)) (setq pos j)) (setq elem (max elem (aref a j i))))))) (setq mat (make-array '(3 3) :initial-contents '((1 2 3) (4 5 6) (7 8 9)))) (Max&Pos mat) ; ((7 . 2) (8 . 2) (9 . 2)) ;7) (defun Combine (fun lista) (cond ((null lista) 0) (T (funcall fun (first lista) (second lista) (Combine fun (cddr lista)))))) ;8) (defun levelAux (cadena lista cont) (cond ((null lista) cont) ((listp (first lista)) (levelAux cadena (first lista) (1+ cont))) ((equal cadena (string(first lista))) (return-from levelAux cont)) (T (levelAux cadena (rest lista) cont)))) (levelAux "hola" ((hola a ) b c) 0) ;9) (defun encode (list) (labels ((encode-run (element count list) (cond ((null list) (list (list count element))) ((eql element (first list)) (encode-run element (1+ count) (rest list))) (t (cons (list count element) (encode-run (first list) 1 (rest list))))))) (if (null list) '() (encode-run (first list) 1 (rest list))))) (encode '(a a a a b c c a a d e e e e)) ; ((4 A) (1 B) (2 C) (2 A) (1 D) (4 E)) ;10) (defun StrCypherAux (cadena code ct) (cond ((equal (length cadena) ct) (return-from StrCypherAux cadena)) (t (StrCypherAux (substitute (char code ct) (char cadena ct) cadena) code (+ ct 1))))) (defun StrCypher (c cc) (StrCypherAux c cc 0)) (StrCypher "Clor" "abcd") ; "abcd" ;11) (defun mmul (A B) (if (not (equal (car (array-dimensions A)) (car (array-dimensions B)))) (return-from mmul nil)) (let* ((m (car (array-dimensions A))) (n (cadr (array-dimensions A))) (l (cadr (array-dimensions B))) (C (make-array `(,m ,l) :initial-element 0))) (loop for i from 0 to (- m 1) do (loop for k from 0 to (- l 1) do (setf (aref C i k) (loop for j from 0 to (- n 1) sum (* (aref A i j) (aref B j k)))))) C)) (mmul #2a((1 2) (3 4)) #2a((5 6 7) (8 9 10))) ; #2A((21 24 27) (47 54 61)) (length #2a((1 2) (3 4))) (equal (array-dimensions #2a((1 2) (3 4))) (array-dimensions #2a((1 2) (1 2)))) (car (array-dimensions #2a((1 2) (3 4)))) (car (array-dimensions #2a((-3 -8 3) (-2 1 4)))) ;13) (defun recorta (l n) (cond ((equal 0 n) nil) (t (cons (car l) (recorta (cdr l) (- n 1)))))) (defun all-permutations (list) (cond ((null list) nil) ((null (cdr list)) (list list)) (t (loop for element in list append (mapcar (lambda (l) (cons element l)) (all-permutations (remove element list))))))) (defun filtersubset (lista posicion) (all-permutations ( recorta lista posicion))) (filtersubset '(a b c d) 2) ; ((A B) (B A)) ;14) (defun combinations (count list) (cond ((zerop count) '(())) ((endp list) '()) (t (nconc (mapcar (let ((item (first list))) (lambda (combi) (cons item combi))) (combinations (1- count) (rest list))) (combinations count (rest list)))))) (combinations 5 '(a b c d e f)); ((A B C D E) (A B C D F) (A B C E F) (A B D E F) (A C D E F) (B C D E F)) ;15) (defmacro If-positive (number) (let ((c (gensym "cond-"))) `(let* ((,c ,number)) (if (plusp ,c) (print "NumeroPositivo") (print "NumeroNegativo"))))) (If-positive 10) ; Numero Positivo
4,943
Common Lisp
.lisp
130
31.361538
106
0.548724
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3bb5c56e79dc67c490e8b2437b2b72e004043cf488794ccecc74f3868e7f3418
22,988
[ -1 ]
22,989
ExercisePackage1.lisp
CallmeTorre_IA/LISP/ExercisePackage1.lisp
;Jesús Alexis Torreblanca Faces ;1.a) El quinto elemento de la lista (((1 2) 3) 4 (5 (6)) A (B C) D (E (F G))) sin usar la función FIFTH (first (rest (rest (rest (rest '(((1 2) 3) 4 (5 (6)) A (B C) D (E (F G)))))))) ;(B C) ;1.b) El numero de segundos que tiene el año bisiesto 2004 (* 366 24 3600) ;31622400 ;1.c) Si el valor numerico asociado a la variable x es diferente de cero y además menor o igual que el valor asociado a la variable y. (setq x 10) ;x=10 (setq y 20) ;y=20 ;1.d) Una lista con las dos soluciones reales de la ecuación 2x^2+7x+5=0 (list (/(+ 7(sqrt (-(expt 7 2)(* 4 2 5))))(* 2 2)) (/(- 7(sqrt (-(expt 7 2)(* 4 2 5))))(* 2 2)));(2.5 1.0) ;2.a) (+ (* 2 4)(- 6 8)) ;6 ;2.b) (/ (+ 5(+ -3 4))(+ 6 .4)) ;.9375 ;2.c) (sqrt (/ (+ (-(- -4 3/8)) 1.4502)(expt -1 (expt -2 1/3)))) ;#C(7.355944 -11.196843) ;2.d) (expt (/ (expt (/ 65.402 (sqrt -1)) 1/5) .17) 1/7) ;#C(1.4500145 -0.065120235) ;3.a) (cdar '((one two) three four))) (TWO) ;3.b) (append (cons '(eva lisa) '(karl sven)) '(eva lisa) '(karl sven)) ((EVA LISA) KARL SVEN EVA LISA KARL SVEN) ;3.c) (subst 'gitan 'birgitta '(eva birgitta lisa birgitta karin)) (EVA GITAN LISA GITAN KARIN) ;3.d) (remove 'sven '(eva sven lisa sven anna)) (EVA LISA ANNA) ;3.e) (butlast '(karl adam nilsson gregg alisson vilma) 3) (KARL ADAM NILSSON) ;3.f) (nth 2 '(a b c d e)) C ;3.g) (nthcdr 2 '(a b c d e)) (C D E) ;3.h) (intersection '(a b c) '(x b z c)) (C B) ;3.i) (cdadar '(((((1 2 3) z) y)(x 4)) 7 8 (a b c (5 (6 7 8))))) (4) ;4) (defun Recombina (lista) (let ((A (first (first lista))) (X (rest (first lista))) (B (first(first (rest lista)))) (Y (rest(second lista))) (C (first (third lista))) (Z (rest (third lista)))) (list (cons (list X Y) A) (cons (list Y Z) C) (cons (list Z Y X) B)))) (RECOMBINA '((A . x)(B . Y)(C . Z))) ;(((X Y) . A) ((Y Z) . C) ((Z Y X) . B)) ;5) (defun NoCero? (n) (if (or (plusp n)(minusp n)) "No es Cero" "Es cero")) (NoCero? 10) ;No es Cero (NoCero? -10) ;No es Cero (NoCero? 0) ;Es cero ;6) (defun Analiza (x) (list (if (atom x) "Es un atomo" "No es un atomo") (if (numberpx) "Es un numero" "No es un numero") (if (listp x) "Es una lista" "No es una lista") (if (consp x) "Es una celda de construcción" "No es una celda de construcción") (if (null x) "Es nulo" "No es nulo"))) (ANALIZA 1) ;("Es un atomo" "Es un numero" "No es una lista" "No es una celda de construcción" "No es nulo")
2,506
Common Lisp
.lisp
60
38.55
134
0.572908
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c7ceafc5df4436927913cf68a84c2f002312de9946858894e63ace276afcd227
22,989
[ -1 ]
22,990
ExercisePackage2.lisp
CallmeTorre_IA/LISP/ExercisePackage2.lisp
;Jesús Alexis Torreblanca Faces ;1) (defun ElemInPos (elem lista pos) (if (equal elem (nth pos lista)) T NIL)) (ELEMINPOS 'a '(a) 0) ; T (ELEMINPOS 'b '(a j c) 4) ; NIL ;2) (defun Inicio-en (lista elem) (cons (position elem lista) lista)) (inicio-en '(a b c) 'a) ; (0 A B C) ;3) (defun Termina-en (lista elem) (let* ((lista_invertida (reverse lista)) ;Invertimos la Lista (contador (position elem lista_invertida)) ;Obtenemos la ultima incidencia de elem en la lista (tamaño (- (length lista)1)) ;Obtenemos el tamaño -1 de la lista (final (- tamaño contador)) ;Obtenemos hasta donde tenemos que ciclar (aux 0)) (loop for i in lista do(setq aux(+ aux 1)) collect(list i) until(equal aux final)))) (TERMINA-EN '(a b c a c a) 'a) ;((A) (B) (C) (A) (C)) ;4) (defun Primer-impar (lista) (let ((contador -1)) (loop for i in lista do(setq contador(+ contador 1)) if (oddp i) return (list i contador)))) (Primer-impar '(2 3 4 5)) ; (3 1) ;5) (defun Ultimo-impar (lista) (let* ((incidencias 0) (ultimo 0) (contador 0)) (dolist (i (reverse lista)) (if (>= i 0) (setq contador(+ contador 1))) (if (and (>= i 0) (equal contador 1)) (setq ultimo i))) (dolist (x lista) (if (equal x ultimo) (setq incidencias(+ incidencias 1)))) (list ultimo incidencias))) (ultimo-impar '(1 2 3 8 8 8 -3)) ; (8 3) ;6) (defun Conteo (lista) (let* ((elem_num 0) (sublistas 0)) (dolist (i lista) (if (numberp i) (setq elem_num(+ elem_num 1))) (if (listp i) (setq sublistas(+ sublistas 1)))) (list elem_num sublistas))) (Conteo '(2 a b c (a d) 1 (a b c 2) 3)) ; (3 2) ;7) (defun Aplana (l) (cond ((null l) nil) ((atom (car l)) (cons (car l) (Aplana (cdr l)))) (t (append (Aplana (car l)) (Aplana (cdr l)))))) (Aplana '((a b) c d ((e f g)) h)) ; (A B C D E F G H) ;8) (defun Diagonal (lista) (loop for i from 0 for elem in lista collect(nth i elem))) (diagonal '((a b c) (a b c) (a b c))) ;(A B C) ;9) (defun Analiza (lista) (let ((lista_nueva '())) (dolist (i lista (reverse lista_nueva)) (cond ((null i) (setq lista_nueva(cons 'N lista_nueva))) ((listp i) (setq lista_nueva(cons 'L lista_nueva))) (T (setq lista_nueva(cons 'A lista_nueva))))))) (Analiza '(a () 2 3 (a b c))) ; (A N A A L) ;10) (defun Suma-numerica (lista) (loop for i in lista if(numberp i) sum i)) (SUMA-numerica '(1 2 3 a b 2 c 3)) ; 11 ;11) (defun FiltraVocales (l) (cond ((null l) nil) ((atom (car l)) (if (or (equal 'a (car l)) (equal 'e (car l)) (equal 'i (car l)) (equal 'o (car l)) (equal 'u (car l))) (FiltraVocales (cdr l)) (cons (car l) (Filtravocales (cdr l))))) (t (append (FiltraVocales (car l)) (FiltraVocales (cdr l)))))) (FiltraVocales '((A E I) 1 2 a u u)) ;(1 2) ;12) (defun Filtra-múltiplos (lista elem) (loop for i in lista if(not(equal 0 (mod i elem))) collect i)) (filtra-múltiplos '(1 2 3 4 5 6) 2) ; (1 3 5) ;13) (defun CeldasAux (l n) (cond ((null l) n) ((atom (car l)) (Celdas(cdr l) (+ n 1))) (t (+ (Celdas (car l) (+ n 0)) (Celdas (cdr l) (+ n 1)))))) (defun Celdas (lista) (Celdas lista 0)) (Celdas '(((1)) 2 3 4 5 )) ; 7 ;14) (defun Implica (&rest argumentos) (every #'identity argumentos)) (Implica T T) ;=> T ;15) (defun Multiplicar (a-matrix b-matrix) (let ((result (make-array (list (nth 0 (array-dimensions a-matrix)) (nth 1 (array-dimensions b-matrix))))) (m (nth 0 (array-dimensions a-matrix))) (n (nth 1 (array-dimensions b-matrix))) (common (nth 0 (array-dimensions b-matrix)))) (dotimes (i m result) (dotimes (j n) (setf (aref result i j) 0.0) (dotimes (k common) (incf (aref result i j) (* (aref a-matrix i k) (aref b-matrix k j)))))))) (defun Mult (&key fm sm) (if (not (eq (length (first fm)) (length sm))) (return-from mm nil)) (let* (( a (make-array (list (length fm) (length (first fm))) :initial-contents fm)) ( b (make-array (list (length sm) (length (first sm))) :initial-contents sm))) (Multiplicar a b))) (Mult :fm '((1 2 3)(1 2 3)(1 2 3)) :sm '((1 2)(1 2)(1 2))) ; #2A((6.0 12.0) (6.0 12.0) (6.0 12.0))
4,587
Common Lisp
.lisp
134
28.044776
98
0.545866
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
09671ab5c1add7eaa9d8ccc97bc839b92c7731227eccb9a7e6d8d3c382785529
22,990
[ -1 ]
22,991
ExercisePackage3.lisp
CallmeTorre_IA/LISP/ExercisePackage3.lisp
;Jesús Alexis Torreblanca Faces ;1) (defun ElemInPos (elem lista pos cont) (cond ((null lista) nil) ((and (equal pos cont)(equal (first lista) elem)) T) (T (ElemInPos elem (rest lista) pos (+ cont 1))))) (ElemInPos 'a '(a b c d) 2 0) ; NIL (ElemInPos 'a '(a b c d) 0 0) ; T ;2) (defun Inicio-en(lista elem) (cond ((null lista) NIL) ((equal (first lista) elem) lista) (T (Inicio-en (rest lista) elem)))) (Inicio-en '(1 2 3) '2) ; (2 3) ;3) (defun Termina-en(lista elem) (cond ((null lista) NIL) ((equal (first lista) elem) (cons elem nil)) (T (cons (first lista) (Termina-en (rest lista) elem))))) (TERMINA-EN '(1 2 3) '2) ; (1 2) ;4) (defun Primer-impar(lista cont) (cond ((null lista) nil) ((oddp (first lista)) (cons (first lista) cont)) (T (Primer-impar (rest lista) (+ cont 1))))) (Primer-impar '(2 3 4 5) 0) ; (3 . 1) ;5) (defun ImparAux (lista) (cond ((null lista) nil) ((>= (first lista) 0) (first lista)) (T (ImparAux (rest lista))))) (defun Contar (elem lista &optional cont) (cond ((null lista) (list elem cont)) ((equal elem (first lista)) (Contar elem (rest lista) (+ cont 1))) (T (Contar elem (rest lista) cont)))) (defun Ultimo-impar (lista) (Contar (ImparAux (reverse lista)) lista 0)) (ultimo-impar '(1 2 1)) ; (1 2) ;6) (defun Conteo (lista num sublis) (cond ((null lista) (list num sublis)) ((listp (first lista)) (Conteo (rest lista) (+ sublis 1) sublis)) ((numberp (first lista)) (Conteo (rest lista) num (+ num 1))) (T (Conteo (rest lista) num sublis)))) (Conteo '(1 2 3 (1)) 0 0) ; (1 3) ;7) (defun Aplana (lista) (cond ((null lista) nil) ((atom (first lista)) (cons (first lista) (Aplana (rest lista)))) (T (append (Aplana (first lista)) (Aplana (rest lista)))))) (Aplana '(a (b c) ((a)) x)) ; (A B C A X) ;8) (defun Diagonal (lista cont) (cond ((null lista) nil) (T (cons (nth cont (first lista)) (Diagonal (rest lista) (+ cont 1)))))) (diagonal '((a b c) (a b c) (a b c)) 0) ; (A B C) ;9) (defun Analiza (lista) (cond ((null lista) nil) ((null (first lista)) (cons 'N (Analiza (rest lista)))) ((listp (first lista)) (cons 'L (Analiza (rest lista)))) (T (cons 'A (Analiza (rest lista)))))) (Analiza '(a () 2 3 (a b c))) ; (A N A A L) ;10) (defun Suma-numerica (lista resultado) (cond ((null lista) resultado) ((numberp (first lista)) (Suma-numerica (rest lista) (+ resultado (first lista)))) (T (Suma-numerica (rest lista) resultado)))) (SUMA-numerica '(1 2 3 a b 2 c 3) 0) ; 11 ;11) (defun FiltraVocales (l) (cond ((null l) nil) ((atom (car l)) (if (or (equal 'a (car l)) (equal 'e (car l)) (equal 'i (car l)) (equal 'o (car l)) (equal 'u (car l))) (FiltraVocales (cdr l)) (cons (car l) (Filtravocales (cdr l))))) (t (append (FiltraVocales (car l)) (FiltraVocales (cdr l)))))) ;12) (defun Filtra-multiplos (lista elem) (cond ((null lista) nil) ((not (equal 0 (mod (first lista) elem))) (cons (first lista) (Filtra-multiplos (rest lista) elem))) (T (Filtra-multiplos (rest lista) elem)))) (filtra-multiplos '(1 2 3 4 5 6) 2) ; (1 3 5) ;13) (defun Celdas (lista cont) (cond ((null lista) cont) ((atom (first lista)) (Celdas (rest lista) (+ cont 1))) (T (+ (Celdas (first lista) cont) (Celdas (rest lista) (+ cont 1)))))) (Celdas '(((1)) 2 3 4 5) 0) ; 7 ;14) (defun Implica (&rest a) (cond ((null a) t) (t (AND (car a) (Implica (cdr a)))))) (Implica T T nil t) ; Nil ;15) (defun matrix-multiply (m1 m2) (mapcar (lambda (row) (apply #'mapcar (lambda (&rest column) (apply #'+ (mapcar #'* row column))) m2)) m1)) (matrix-multiply '((1 2) (3 4)) '((-3 -8 3) (-2 1 4))) ; ((-7 -6 11) (-17 -20 25)) ;16) (defun Encuentra(lista elem) (cond ((null lista) NIL) ((equal (first lista) elem) lista) (T (Encuentra (rest lista) elem)))) (Encuentra '(b c d a c b) 'a) ; (A C B) ;17) (defun Cambia(lista elem1 elem2) (cond ((null lista) NIL) ((equal (first lista) elem1) (cons elem2 (Cambia(rest lista) elem1 elem2))) (T (cons (first lista) (Cambia (rest lista) elem1 elem2))))) (Cambia '(a b c a b c) 'a '1) ; (1 B C 1 B C) ;18) (defun fib (n) "Tail-recursive computation of the nth element of the Fibonacci sequence" (check-type n (integer 0 *)) (labels ((fib-aux (n f1 f2) (if (zerop n) f1 (fib-aux (1- n) f2 (+ f1 f2))))) (fib-aux n 0 1))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000005 seconds of total run time (0.000005 user, 0.000000 system) ;100.00% CPU ;8,616 processor cycles ;0 bytes consed (defun fib (n) "loop-based iterative computation of the nth element of the Fibonacci sequence" (check-type n (integer 0 *)) (loop for f1 = 0 then f2 and f2 = 1 then (+ f1 f2) repeat n finally (return f1))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000005 seconds of total run time (0.000005 user, 0.000000 system) ;100.00% CPU ;7,012 processor cycles ;0 bytes consed (defun fib (n) "do-based iterative computation of the nth element of the Fibonacci sequence" (check-type n (integer 0 *)) (do ((i n (1- i)) (f1 0 f2) (f2 1 (+ f1 f2))) ((= i 0) f1))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000004 seconds of total run time (0.000003 user, 0.000001 system) ;100.00% CPU ;5,504 processor cycles ;0 bytes consed (defun fib (n) "CPS computation of the nth element of the Fibonacci sequence" (check-type n (integer 0 *)) (labels ((fib-aux (n k) (if (zerop n) (funcall k 0 1) (fib-aux (1- n) (lambda (x y) (funcall k y (+ x y))))))) (fib-aux n #'(lambda (a b) a)))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000006 seconds of total run time (0.000006 user, 0.000000 system) ;100.00% CPU ;7,788 processor cycles ;4,088 bytes consed (defun fib (n) (labels ((fib2 (n) (cond ((= n 0) (values 1 0)) (t (multiple-value-bind (val prev-val) (fib2 (- n 1)) (values (+ val prev-val) val)))))) (nth-value 0 (fib2 n)))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000004 seconds of total run time (0.000004 user, 0.000000 system) ;100.00% CPU ;6,634 processor cycles ;0 bytes consed (defun fib (n) "Successive squaring method from SICP" (check-type n (integer 0 *)) (labels ((fib-aux (a b p q count) (cond ((= count 0) b) ((evenp count) (fib-aux a b (+ (* p p) (* q q)) (+ (* q q) (* 2 p q)) (/ count 2))) (t (fib-aux (+ (* b q) (* a q) (* a p)) (+ (* b p) (* a q)) p q (- count 1)))))) (fib-aux 1 0 0 1 n))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000005 seconds of total run time (0.000005 user, 0.000000 system) ;100.00% CPU ;7,900 processor cycles ;0 bytes consed (defun fib (n) (if (< n 2) n (if (oddp n) (let ((k (/ (1+ n) 2))) (+ (expt (fib k) 2) (expt (fib (1- k)) 2))) (let* ((k (/ n 2)) (fk (fib k))) (* (+ (* 2 (fib (1- k))) fk) fk))))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000010 seconds of total run time (0.000009 user, 0.000001 system) ;100.00% CPU ;18,438 processor cycles ;0 bytes consed ;; Taken from Winston's Lisp, 3rd edition, this is a tail-recursive version, w/o an auxiliary function (defun fib (n &optional (i 1) (previous-month 0) (this-month 1)) (if (<= n i) this-month (fib n (+ 1 i) this-month (+ this-month previous-month)))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000004 seconds of total run time (0.000004 user, 0.000000 system) ;100.00% CPU ;6,628 processor cycles ;0 bytes conse ;; Fibonacci - Binet's Formula (defun fib (n) (* (/ 1 (sqrt 5)) (- (expt (/ (+ 1 (sqrt 5)) 2) n) (expt (/ (- 1 (sqrt 5)) 2) n)))) (time (fib 50)) ;Evaluation took: ;0.048 seconds of real time ;0.000985 seconds of total run time (0.000048 user, 0.000937 system) ;2.08% CPU ;119,580,276 processor cycles ;14 page faults ;0 bytes consed (defun fib (n) (/ (- (expt (/ (+ 1 (sqrt 5)) 2) n) (expt (/ (- 1 (sqrt 5)) 2) n)) (sqrt 5))) (time (fib 50)) ;Evaluation took: ;0.000 seconds of real time ;0.000010 seconds of total run time (0.000009 user, 0.000001 system) ;100.00% CPU ;16,166 processor cycles ;4,096 bytes consed ;19) (defun Mapea(funcion lista1 lista2) (if lista1 (cons (funcall funcion (first lista1) (first lista2)) (Mapea funcion (rest lista1) (rest lista2))) NIL)) (mapea #'- '(1 2 3 4) '(1 1 1 1)) ; (0 1 2 3) ;20) (defun Aplana(lista) (cond ((null lista) NIL) ((listp (first lista)) (append (Aplana (first lista)) (Aplana (rest lista)))) (T (cons (first lista) (Aplana (rest lista)))))) (Aplana '(((b) a) a (c))) ; (B A A C) ;21) (defun Elimina(lista n) (cond ((null lista) NIL) ((not (numberp (first lista))) (Elimina (rest lista) n)) ((<=(first lista) n)(Elimina (rest lista) n)) (T (cons (first lista) (Elimina (rest lista) n))))) (elimina '(1 a 2 b 3) 1) ; (2 3) ;22) (defun PegayCambia (lista1 lista2 elem1 elem2) (Cambia(Pega lista1 lista2) elem1 elem2)) (defun Cambia(lista elem1 elem2) (cond ((null lista) NIL) ((equal (first lista) elem1) (cons elem2 (Cambia(rest lista) elem1 elem2))) (T (cons (first lista) (Cambia (rest lista) elem1 elem2))))) (defun Pega (lista1 lista2) (cond ((null lista1) lista2) (T (cons (first lista1) (Pega (rest lista1) lista2))))) (PegaYCambia '(d b c d) '(d b d b) 'b 'w) ; (D W C D D W D W) ;23) (defun qsort (l) (cond ((null l) nil) (t (append (qsort (listMenor (car l) (cdr l))) (cons (car l) nil) (qsort (listMayor (car l) (cdr l))))))) (defun listMenor (a b) (cond (( or (null a) (null b)) nil) (( < a (car b)) (listMenor a (cdr b))) (t (cons (car b) (listMenor a (cdr b)))))) (defun listMayor (a b) (cond (( or ( null a)(null b)) nil) (( >= a (car b)) (listMayor a (cdr b))) (t (cons (car b) (listMayor a (cdr b)))))) (qsort '(6 5 4 3 1)) ; (1 3 4 5 6)
11,133
Common Lisp
.lisp
310
29.36129
127
0.551609
CallmeTorre/IA
1
3
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4d8ee9ed61e0a53331fd34da5604f22e080a156c6671cbd1533474fdda5d770d
22,991
[ -1 ]
23,020
classifier.lisp
codingisacopingstrategy_k-Nearest-Neighbor-Classifier/classifier.lisp
(in-package :classifier.knn) (declaim (optimize (speed 3) (safety 0))) ;(proclaim '(inline data weights)) (defparameter *item-matrix* nil "The main matrix holding the data.") (defun partition-data (data-set &key (start 0) end) "Help function to divide dataset into test and training part." (loop for idx from start below (or end (length data-set)) collect (elt data-set idx))) (defun divide-into-train-and-test (data-set testing-fraction) "Divide a dataset into a test and training set using a defined testing fraction" (let* ((shuffled (shuffle-list (cdr data-set))) (size (length (cdr data-set))) (train-on (floor (* size (- 1 testing-fraction))))) (setf *training-set* (setup-data (partition-data shuffled :start 0 :end train-on))) (setf *test-set* (setup-data (partition-data shuffled :start train-on))))) (defun train-and-test (data-set start end k &optional (test-set nil)) "Reserve items from START to END for test set; train on remainder." (when (null test-set) (setf *test-set* (setup-data (partition-data data-set :start start :end end)))) (setf *training-set* (setup-data (nconc (partition-data data-set :end start) (partition-data data-set :start end)))) (classify-testset *test-set* k)) (defun cross-validation (data-set &key (folds 10) (k 1)) "Do k-fold cross-validation test and return their mean. That is, keep out 1/k of the examples for testing on each of k runs. shuffle the examples first." (declare (fixnum folds k)) (let* ((size (length data-set)) (shuffled (shuffle-list data-set)) (results (make-array folds)) (accuracy 0.0)) (declare (type (simple-array *) results) (single-float accuracy) (fixnum size)) (dotimes (i folds) (setf (svref results i) (train-and-test shuffled (floor (* i (/ size folds))) (floor (* (+ i 1) (/ size folds))) k)) (incf accuracy (the single-float (car (accuracy (svref results i) (length (svref results i))))))) (dolist (category (categories *test-set*)) (let ((category-result (make-array folds)) (validation-result nil)) (declare (type simple-array category-result)) (dotimes (result folds) (setf (svref category-result result) (score (car category) (svref results result)))) (setf validation-result (return-validation-results category-result category folds)) (pprint-results validation-result))) (format t "Overall accuracy:~20t~,7f~%" (/ accuracy folds)))) (defun leave-one-out (data-set &key (k 1) (print-exemplars nil)) "Leave one out cross-validation over the dataset." (let* ((shuffled (shuffle-list data-set)) (results (list))) (setf *training-set* (setup-data shuffled)) (let ((temp-set (make-array (data-counts *training-set*) :initial-contents (data *training-set*)))) (declare (type (simple-array hash-table) temp-set)) (dotimes (i (length temp-set)) (setf (data *training-set*) (concatenate 'vector (partition-data temp-set :end i) (partition-data temp-set :start (1+ i)))) (push (classify (svref temp-set i) k) results)) (collect-score-and-accuracy results *training-set* :info t :print-exemplars print-exemplars)))) (defun learning-curve (data-set &key (trials 10) (sizes nil) (k 1)) "Return the learning curve of the classifier over the dataset." (declare (fixnum trials k)) (let ((size-result (list))) (when (null sizes) (setf sizes (loop for i from 2 to (- (length data-set) 12) by 2 collect i))) (dolist (size sizes) (declare (fixnum size)) (format t "Test / Train: ~d / ~d~%" size (- (length data-set) size)) (push (list size (- (length data-set) size) (mean (loop for trail from 1 to trials collect (car (accuracy (train-and-test (shuffle-list data-set) 0 size k) size))))) size-result)) (print-learning-curve size-result))) (defun accumulative-learning (file test-indexes &key (k 1) (periods 3) (print-exemplars nil)) "Accumulative learning function. Given a data-set and defined test items within this data-set, the algorithm classifies each test item on the basis of all previously seen items in the data-set." (let ((data-set (open-file file)) (classification-results nil) (time-frames (split-periods test-indexes periods))) (do ((i 0 (1+ i))) ((= i (length test-indexes))) (let ((test-item (make-array (length (elt data-set 0)) :initial-contents (elt data-set (elt test-indexes i))))) (setf *training-set* (setup-data (partition-data data-set :end (elt test-indexes i)))) (push (classify test-item k) classification-results))) (progn (scores-within-timeframe time-frames classification-results) (collect-score-and-accuracy classification-results *training-set* :counts (length test-indexes) :print-exemplars print-exemplars)))) (defun split-periods (indexes periods) (let* ((start-ends (list 0)) (highest-index (car (last indexes))) (steps (floor (/ highest-index periods)))) (do ((i 0 (+ i steps)) (j steps (+ j steps))) ((> j highest-index)) (loop for k from 0 below (length indexes) do (when (> (elt indexes k) j) (return (push k start-ends))))) (reverse start-ends))) (defun scores-within-timeframe (time-frames results) (do ((i 0 (1+ i)) (j 1 (1+ j))) ((= j (length time-frames))) (let ((frame-results (subseq results (elt time-frames i) (elt time-frames j)))) (collect-score-and-accuracy frame-results *training-set* :counts (length frame-results))))) (defun print-learning-curve (results) "Pretty-print the learning-curve results in tabular format." (dolist (result results) (format t "~&~d~3@T~d~3@T~,7f" (elt result 0) (elt result 1) (elt result 2)))) (defun classify-dataset (file test-fn) "Open a single file from which a testing and a training set will be derived." (setf *training-set* nil) (setf *test-set* nil) (let ((data-set (open-file file))) (funcall test-fn data-set))) (defmacro run-classification ((&key (test-fn 'with-test-set) (data-set nil) (test-file nil) (voting 'majority-voting)) &rest function-arguments) (setf *voting-function* voting) (if (eql test-fn 'with-test-set) (if (null test-file) (error "No test-file given") `(progn (load-training-file ,data-set) (load-test-file ,test-file) (classify-test-on-trainingfile *test-set* ,@function-arguments))) `(,test-fn (open-file ,data-set) ,@function-arguments))) (defun load-training-file (file) "Load the training file." (let ((training-file (open-file file))) (setf *training-set* (setup-data training-file)))) (defun load-test-file (file) "Load the test file." (let ((test-file (open-file file))) (setf *test-set* (setup-data test-file)))) (defun classify (test-item &optional (k 1)) "Classify a test-item on the basis of a training set. Calculate the distances between the test item and the training items, define the set of nearest neighbors and finally predict the outcome of the test item." (let* ((results (distances test-item k)) ; define the set of nearest neighbors (nearest-neighbors (neighbor-set results *k-distance*)) ; predict the outcome of the test-item (prediction (predict-outcome nearest-neighbors test-item k))) ; make instance of exemplar containing the test-item, ; the nearest neighbors and the predicted outcome. (if (null prediction) (classify test-item (+ k 1)) (make-instance 'exemplar-features :exemplar test-item :nearest-neighbors nearest-neighbors :prediction prediction :k-level k)))) (defun classify-testset (test-items &optional (k 1)) "Classify a test-set on the basis of a training set." (let ((results (loop for test-item across (data test-items) for result = (classify test-item k) unless (null result) collect result))) results)) (defun classify-test-on-trainingfile (test-set &key (k 1) (print-exemplars nil)) "Classify a separate test-file on the basis of a training-file." (collect-score-and-accuracy (classify-testset test-set k) test-set :info t :print-exemplars print-exemplars)) ;; classifier.lisp ends here
8,290
Common Lisp
.lisp
187
39.705882
80
0.680654
codingisacopingstrategy/k-Nearest-Neighbor-Classifier
1
1
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
77fe9840a22843dde69437409c5cecc5ff9aad57025426ad01a7cea3ef729d91
23,020
[ -1 ]
23,021
classifier-utilities.lisp
codingisacopingstrategy_k-Nearest-Neighbor-Classifier/classifier-utilities.lisp
(in-package :classifier.knn) (declaim (optimize (speed 3) (safety 0))) (defun transpose (lst) "Zip function." (apply #'mapcar #'list lst)) (defun assoc-cdr (item alist) "Return last element of association list." (cdr (assoc item alist))) (defun sort-hash-table (ht sort-fn &optional &key (by :values)) "Sort a hash table on its keys or values" (let ((sorted-entries nil)) (maphash #'(lambda (k v) (push (cons k v) sorted-entries)) ht) (let ((sort-key #'car)) (when (equal by :values) (setf sort-key #'cdr)) (sort sorted-entries sort-fn :key sort-key)))) (defun nshuffle-list (lst) "Shuffle a vector in place." (loop for idx downfrom (1- (length lst)) to 1 for other = (random (1+ idx)) do (unless (= idx other) (rotatef (elt lst idx) (elt lst other)))) lst) (defun shuffle-list (lst) "Return a shuffled copy of lst" (nshuffle-list (copy-seq lst))) (defun pprint-hash-table (hash-table) "Print the values of a hash-table." (loop for value being the hash-value in hash-table collect value)) (defmacro matrix-element (i j matrix) "Return element of matrix at position (i,j)" `(nth (1- ,j) (nth (1- ,i) ,matrix))) (defun matrix-rows (matrix) "Return number of rows in the matrix" (length matrix)) (defun matrix-row (n matrix) "Return a specific row in the matrix" (if (or (> n (matrix-rows matrix)) (< n 1)) (error "Invalid row.")) (list (copy-list (nth (1- n) matrix)))) (defun matrix-columns (matrix) "Return number of columns in the matrix" (length (first matrix))) (defun matrix-column (n matrix) "Return the nth column of a matrix (i.e. list of lists)" (if (or (> n (matrix-columns matrix)) (< n 1)) (error "Invalid column.")) (mapcar #'(lambda (r) (list (nth (1- n) r))) matrix)) (defun matrix-minor (row column matrix) "Return a matrix without a particular row or column." (let ((result (copy-tree matrix))) (if (eql row 1) (pop result) (setf (cdr (nthcdr (- row 2) result)) (nthcdr row result))) (dotimes (current-row-index (length result)) (let ((current-row (nth current-row-index result))) (if (eql column 1) (pop (nth current-row-index result)) (setf (cdr (nthcdr (- column 2) current-row)) (nthcdr column current-row))))) result)) (defun extract-values (exemplar &optional (sep #\COMMA)) "Split sequence on the basis of preset separator" (string->integers (split-sequence:SPLIT-SEQUENCE sep exemplar))) (defun open-file (file) (with-open-file (in file :external-format :iso-8859-1) (loop for line = (read-line in nil) while line collect (extract-values line)))) (defun print-exemplars-and-NN (exemplars stream) "Write the results from the classification to a file." (if (symbolp stream) (dolist (exemplar exemplars) (print-object exemplar stream)) (with-open-file (out stream :direction :output :if-exists :supersede :if-does-not-exist :create :external-format :iso-8859-1) (dolist (exemplar exemplars) (print-object exemplar out))))) (defun get-attributes (data) "The list of attribute names in the data set." (car (matrix-row 1 data))) (defun category-label (exemplar) "The category label of an exemplar" (last exemplar)) (defun exemplar-values (exemplar) "The values of an exemplar" (butlast exemplar)) (defun number-of-categories (data-set) "How many categories are there in the data set?" (length (delete-duplicates (matrix-column (matrix-columns data-set) data-set) :test #'equal))) (defun get-categories (data-set) "What are the target categories?" (delete-duplicates (matrix-column (matrix-columns data-set) data-set) :test #'equal)) ; from Peter Norvig's PAIP (defun memo (fn name key test) "Return a memo-function of fn." (let ((table (make-hash-table :test test))) (setf (get name 'memo) table) #'(lambda (&rest args) (let ((k (funcall key args))) (multiple-value-bind (val found-p) (gethash k table) (if found-p val (setf (gethash k table) (apply fn args)))))))) (defun memoize (fn-name &key (key #'first) (test #'eql)) "Replace fn-name's global definition with a memoized version." (setf (symbol-function fn-name) (memo (symbol-function fn-name) fn-name key test))) (defun clear-memoize (fn-name) "Clear the hash table from a memo function." (let ((table (get fn-name 'memo))) (when table (clrhash table)))) (defmacro defun-memo (fn args &body body) "Define a memoized function." `(memoize (defun ,fn ,args . ,body))) ;; functions for association lists quering (defun make-comparisons-expr (field value) `(equal (getf item ,field) ,value)) (defun make-comparisons-list (fields) (loop while fields collecting (make-comparisons-expr (pop fields) (pop fields)))) (defmacro where (&rest clauses) `#'(lambda (item) (and ,@(make-comparisons-list clauses)))) (defun select (selector-fn database) (remove-if-not selector-fn database)) (defun k-record (k neighbor distance) "Add a nearest neighbor to the database with its k value, the item itself and its distance to the test item" (list :k k :neighbor neighbor :distance distance)) (defun sum (numbers &optional (key #'identity)) "Add up all the numbers; if KEY is given, apply it to each number first." (if (null numbers) 0 (+ (funcall key (first numbers)) (sum (rest numbers) key)))) (defun mean (numbers) "Numerical average (mean) of a list of numbers." (/ (sum numbers) (length numbers))) (defun hash-print (h &optional (stream t)) "Prints a hash table line by line." (maphash #'(lambda (key val) (format stream "~&~A:~10T ~A" key val)) h) h) (defparameter *integer->char* (make-array 0 :adjustable t :fill-pointer 0)) (defun char->integer (char) "Convert a character into an integer and save the character on the index equal to the integer in the array." (when (equal (position char *integer->char* :test #'equal) nil) (vector-push-extend char *integer->char*)) (position char *integer->char* :test #'equal)) (defun string->integers (string) "Convert a list of strings into a list of integers" (let ((result-string (copy-list string))) (dotimes (element (length string)) (setf (elt result-string element) (char->integer (elt string element)))) result-string)) (defun integers->string (integer-list) (let ((result-string (make-array (length integer-list) :adjustable t :fill-pointer 0))) (loop for item across integer-list do (vector-push-extend (aref *integer->char* item) result-string)) result-string)) (defun print-line (length) "print line of certain length" (dotimes (i length) (format t "-")))
6,707
Common Lisp
.lisp
172
35.453488
78
0.689666
codingisacopingstrategy/k-Nearest-Neighbor-Classifier
1
1
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
dd86173dd0ae953cdaaaf40ef960d4d571ba714b3d33b273c9a34e975842edf2
23,021
[ -1 ]
23,022
prediction.lisp
codingisacopingstrategy_k-Nearest-Neighbor-Classifier/prediction.lisp
(in-package :classifier.knn) (declaim (optimize (speed 3) (safety 0))) (defparameter *voting-function* nil) (defclass exemplar-features () ((exemplar :initarg :exemplar :accessor exemplar :initform (error "Must supply exemplar!") :documentation "A particular exemplar") (nearest-neighbors :initarg :nearest-neighbors :accessor nearest-neighbors :initform (error "Supply nearest neighbors") :documentation "The set of nearest neighbors of an exemplar") (prediction :initarg :prediction :accessor prediction :initform (error "Couldn't resolve prediction...") :documentation "The prediction of the exemplar") (k-level :initarg :k-level :accessor k-level :initform 1 :documentation "The levels of k used for the prediction of the exemplar"))) (defmethod print-object ((object exemplar-features) stream) (with-slots (exemplar nearest-neighbors prediction k-level) object (format stream "~&~@(~a~):~7t" 'exemplar) (loop for attr across exemplar do (format stream "~a," (aref *integer->char* attr))) (format stream "~&~@(~a~):~7t~a~%" 'prediction (aref *integer->char* prediction)) (print-neighbors nearest-neighbors k-level stream))) (defun print-neighbors (neighbors k stream) "Function to pretty-print the neighbors of an exemplar. The neighbors are printed at distinct k values." (loop for i from 1 to k for k-items = (select (where :k i) neighbors) do (format stream "\# k=~d, ~d Neighbor(s) at distance:~1@T~,8f~%" i (length k-items) (getf (car k-items) :distance)) (dolist (neighbor k-items) (loop for attr across (getf neighbor :neighbor) do (format stream "~a," (aref *integer->char* attr))) (format stream "~%"))) (format stream "~%")) (defparameter *k-distance* nil) ;; moet dit een globale variable blijven? (defun set-distance (distance k) "Put the found distances in an array and sort in increasing order." (declare (single-float distance) (fixnum k) (type (vector single-float *) *k-distance*)) ; only add a new item when its not already in the list. (when (<= distance (the single-float (aref *k-distance* (1- (length *k-distance*))))) (when (not (find distance *k-distance*)) (if (= (length *k-distance*) k) (progn (vector-pop *k-distance*) (vector-push distance *k-distance*)) (vector-push distance *k-distance*)) (sort *k-distance* #'<)))) (defun calculate-distance (test-item training-item k weight-order) "Return distance between test and training item using Manhattan distance and Gain Ratio weighting." (declare (type (vector single-float *) *k-distance*) (type simple-array test-item training-item weight-order) (type fixnum k)) (let ((distance 0.0) (compare-distance (aref *k-distance* (1- (length *k-distance*))))) (declare (single-float distance compare-distance)) ; loop over the attributes (columns) in decreasing gain ratio order (loop for attr across weight-order never (> distance compare-distance) ; when the distance between test and training item is larger than ; allowed under a level of k, stop the loop. Otherwise calculate the ; distance between two attributes of the test and training item. :unless (eql (aref (the (simple-array fixnum *) test-item) attr) (aref (the (simple-array fixnum *) training-item) attr)) :do (incf distance (the single-float (* 1.0 (the single-float (gethash attr (weights *training-set*)))))) ; we place the new distance in the *k-distance* list and return the ; distance plus the training-item. :finally (set-distance distance k) (return (list distance training-item))))) (defun predict-outcome (nearest-neighbors test-item k) "Predict the outcome category of a record in the dataset." (let ((prediction-table (make-hash-table :test #'eql)) (outcome (target-attr *training-set*))) ; loop over all nearest neighbors and add frequencies to prediction table. (dolist (neighbor-record nearest-neighbors) (let* ((neighbor (getf neighbor-record :neighbor)) (prediction (svref neighbor outcome))) (if (gethash prediction prediction-table) (incf (gethash prediction prediction-table) (funcall *voting-function* (getf neighbor-record :k))) (setf (gethash prediction prediction-table) (funcall *voting-function* (getf neighbor-record :k)))))) ; push all predictions with their frequencies in list of conses (let* ((predictions (sort-hash-table prediction-table #'>)) ; take the best guess (first in sorted list) (first-guess (nth 0 predictions))) ; if there is not only one best guess (if (> (count (cdr first-guess) (loop for (prediction . count) in predictions collect count) :test #'eql) 1) nil ; return no prediction (car first-guess))))) ; else return best guess (defun majority-voting (k) 1) (defun inverse-linear-weighting (k) "Inverse linear weighting of neihgbors at different levels of k." (let ((d-k (aref *k-distance* (1- (length *k-distance*)))) (d-j (aref *k-distance* (- k 1))) (d-1 (aref *k-distance* 0))) (if (= d-j d-1) ; if d-j equals k=1 1 (/ (- d-k d-j) (- d-k d-1))))) (defun inverse-distance-weight (k) "Inverse distance weighting of neighbor at different levels of k." (/ 1 (+ (aref *k-distance* (- k 1)) ; the distance at level k 0.0001))) ; to ensure divisionability (defun neighbor-set (neighbors k-distance) "Calculate the set of nearest neighbors for a particular test item." (declare (type (vector single-float *) k-distance) (type (vector list *) neighbors)) (let ((compare-distance (aref k-distance (1- (length k-distance)))) (neighbor-database nil)) (declare (single-float compare-distance)) (loop for neighbor across neighbors while (<= (the single-float (car neighbor)) compare-distance) do (push (k-record (+ (position (car neighbor) k-distance) 1) (car (last neighbor)) (car neighbor)) neighbor-database)) neighbor-database)) (defun distances (test-item &optional (k 1)) "Return sorted distances between test item and training items" (declare (fixnum k)) (setf *k-distance* (make-array k :fill-pointer 0 :element-type 'single-float)) (vector-push 1000.0 *k-distance*) (let* ((weight-order (attribute-weight-order *training-set*)) (distances (make-array k :adjustable t :fill-pointer 0))) (declare (type (vector list *) distances) (type simple-array weight-order)) (dotimes (i (length (data *training-set*))) (let ((result (calculate-distance test-item (svref (the simple-array (data *training-set*)) i) k weight-order))) (unless (null result) (vector-push-extend result distances)))) (sort distances #'< :key #'car))) ;; distance calculation and prediction ends here
6,904
Common Lisp
.lisp
149
41.644295
80
0.689143
codingisacopingstrategy/k-Nearest-Neighbor-Classifier
1
1
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
eb6f234cdba4e5cb7e7ce60cc737291285bf5c56df6ef10e0c8d1bd0f0554d0f
23,022
[ -1 ]
23,023
knn.asd
codingisacopingstrategy_k-Nearest-Neighbor-Classifier/knn.asd
(defpackage :classifier.knn-system (:use :asdf :cl)) (in-package :classifier.knn-system) (defsystem knn :name "kNN" :author "Folgert Karsdorp <[email protected]>" :version "0.3" :maintainer "Folgert Karsdorp <[email protected]>" :licence "GNU General Public Licence" :description "k-Nearest Neighbor classifier" :long-description "" :components ((:file "packages") (:file "classifier-utilities" :depends-on ("packages")) (:file "data-set" :depends-on ("classifier-utilities")) (:file "scores" :depends-on ("data-set")) (:file "prediction" :depends-on ("data-set" "classifier-utilities")) (:file "classifier" :depends-on ("classifier-utilities" "scores" "prediction"))) :depends-on (:split-sequence))
741
Common Lisp
.asd
18
38.222222
83
0.710927
codingisacopingstrategy/k-Nearest-Neighbor-Classifier
1
1
0
GPL-2.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
29c37ef2607a68a3da9d3bfff90b68ab3b6c8a4939882762b0e854dae7434087
23,023
[ -1 ]
23,042
cdrack.dcl
dentonyoder_LISP/cdrack.dcl
cdrack : dialog { label = "This is a sample drafting tool"; width = 40; :text { label = "Program to draw a CD/DVD/VHS Rack"; } :edit_box{label = "Length = "; key = x;} :edit_box{label = "No of CD Rows = "; key = cd;} :edit_box{label = "No of DVD Rows = "; key = dvd;} :edit_box{label = "No of VHS Shelves = "; key = vhs;} ok_cancel; }
363
Common Lisp
.cl
10
32.5
56
0.578797
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2031c0554ab60fd9b7ccb6ae19119e9c2ef999da1691562687b9b8fb6cd2fde9
23,042
[ -1 ]
23,044
bi.lsp
dentonyoder_LISP/bi.lsp
(defun c:bi(/ ans myset p1 p2 oldcmdecho) ;;; build isometric macro by Denton Yoder (c) 2006 (setq oldcmdecho (getvar "cmdecho")) (setvar "cmdecho" 0) (command "undo" "group") (princ"\nProgram by Denton Yoder to build an isometric view from existing geometry.") (setq ans (getstring "\nBuild from existing (Top, Front, or Side) T,F, or S:")) (princ "\nSelect objects to copy:") (setq MySet (ssget)) (setq p1 (getpoint "\nFrom or Reference point:")) (setq p2 (getpoint p1 "\nTo or Destination point:")) (setq ans (strcase ans)) (setq ans (substr ans 1 1)) (if (= ans "T") (progn (command "copy" myset "" p1 p1) (command "move" myset "" p1 p2) (command "rotate" myset "" p2 "-45") (command "rotate3d" myset "" "x" p2 -60) )) (if (= ans "F") (progn (command "copy" myset "" p1 p1) (command "move" myset "" p1 p2) (command "rotate3d" myset "" "y" p2 -45) (command "rotate3d" myset "" "x" p2 30) )) (if (= ans "S") (progn (command "copy" myset "" p1 p1) (command "move" myset "" p1 p2) (command "rotate3d" myset "" "y" p2 45) (command "rotate3d" myset "" "x" p2 30) )) (command "undo" "end") (setvar "cmdecho" oldcmdecho) (princ) )
1,238
Common Lisp
.l
35
31.2
88
0.613903
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
22db4d817dc832e75dda3bca8a3ded3cdacd34d73e39347d0895a340e59456e2
23,044
[ -1 ]
23,045
bacres.lsp
dentonyoder_LISP/bacres.lsp
(defun c:bacres(/ o1 a1 ostyle p1) (setvar "cmdecho" 0) (setq olayer (getvar "clayer")) (setq ostyle (getvar "textstyle")) (command "undo" "group") ;;; ;;; ;;; program to draw a boundary and label its acres....;;; ;;; ;;; (princ "\nProgram to label Acreage by picking inside the boundary: ") (setq p1 (getpoint "Pick inside boundary at label location:")) (command "-layer" "m" "boundary" "Plot" "no" "boundary" "color" "2" "boundary" "") (command "style" "dyplain" "romans" "" "" "" "" "" "") (command "-boundary" p1 "") (command "area" "ob" "last") (setq a1 (getvar "area")) (setq a1 (cvunit a1 "sq ft" "acres")) (princ (strcat "\n Acres = " (rtos a1 2 3))) (command "text" "j" "m" p1 (* 0.25 (getvar "dimscale")) 0 (strcat "Acres = " (rtos a1 2 3))) (command "undo" "end") (setvar "textstyle" ostyle) (setvar "clayer" olayer) (setvar "cmdecho" 1) (princ) )
1,050
Common Lisp
.l
24
39.041667
94
0.54095
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d160b0235f13afd495d23d03f7fa09dec76858644a25f739aee0062f83b80f38
23,045
[ -1 ]
23,046
clevis.lsp
dentonyoder_LISP/clevis.lsp
(defun c:clevis(/ oldosnap p1 p2 p3 p4) ; clevis program to draw pole with clevis attachment at each end. ; options are side view or top view. (setq p1 (getpoint "\nStarting point for clevis rod:")) (setq o1 (getstring "\nPlace by Top or <Side>:")) (setq p2 (getpoint "\nEnding point:" p1)) (setq o2 (getstring "\nPlace by Top or <Side>:")) (setq oldosnap (getvar "osmode")) (setvar "osmode" 0) (if (= (strcase o1) "T") (command "-insert" "clevis-top" p1 1 1 (/ (* (angle p1 p2) 180.0) pi)) (command "-insert" "clevis-side" p1 1 1 (/ (* (angle p1 p2) 180.0) pi)) ) (if (= (strcase o2) "T") (command "-insert" "clevis-top" p2 1 1 (/ (* (angle p2 p1) 180.0) pi)) (command "-insert" "clevis-side" p2 1 1 (/ (* (angle p2 p1) 180.0) pi)) ) ;calc points 12" from p1 and p2, for shaft start and end locations. (setq p3 (polar p1 (angle p1 p2) 12.0)) (setq p4 (polar p2 (angle p2 p1) 12.0)) ;pline for the 2" shaft, will be turned into wipeout (command "pline" (polar p3 (- (angle p3 p4) (/ pi 2.0)) 1.0) (polar p4 (- (angle p3 p4) (/ pi 2.0)) 1.0) (polar p4 (+ (angle p3 p4) (/ pi 2.0)) 1.0) (polar p3 (+ (angle p3 p4) (/ pi 2.0)) 1.0) "c") ;turn the pline you just drew into a wipeout (command "wipeout" "p" "l" "y") ;draw pline again incase the wipeout frames are turned off. (command "pline" (polar p3 (- (angle p3 p4) (/ pi 2.0)) 1.0) (polar p4 (- (angle p3 p4) (/ pi 2.0)) 1.0) (polar p4 (+ (angle p3 p4) (/ pi 2.0)) 1.0) (polar p3 (+ (angle p3 p4) (/ pi 2.0)) 1.0) "c") (setvar "osmode" oldosnap) (princ) )
1,769
Common Lisp
.l
35
42.028571
80
0.552336
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6b5b8a1379fbbbaff532666d5df3e8999eee1b096fa901d855dfc9c2667f624b
23,046
[ -1 ]
23,047
acaddoc.lsp
dentonyoder_LISP/acaddoc.lsp
(defun s::startup() (setvar "cmdecho" 0) (command "navvcube" "off" "navbar" "off") (setvar "mbuttonpan" 1) (setvar "filedia" 1) (setvar "cmdecho" 1) (defun c:za() (command "zoom" "e" "zoom" "0.9x")) )
231
Common Lisp
.l
8
24.125
54
0.577982
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
131e122b830c3cf42efad4a4a2536bccadabf4ef129d15c949fe2322684d18bf
23,047
[ -1 ]
23,049
cdrack.lsp
dentonyoder_LISP/cdrack.lsp
(defun updateall() (set_tile "x" (rtos x-var)) (set_tile "cd" (itoa cd-var)) (set_tile "dvd" (itoa dvd-var)) (set_tile "vhs" (itoa vhs-var)) ) (defun c:cdrack () ;;; store defaults to variables (setq cd-var 2) (setq dvd-var 3) (setq vhs-var 0) (setq x-var 36) (setq dcl_id (load_dialog "cdrack.dcl")) (if (not (new_dialog "cdrack" dcl_id)) (exit)) ;;; upload defaults to dialog (set_tile "x" (rtos x-var)) (set_tile "cd" (itoa cd-var)) (set_tile "dvd" (itoa dvd-var)) (set_tile "vhs" (itoa vhs-var)) ;;; read dialog actions (action_tile "x" "(setq x-var (distof $value 4)) (updateall)") (action_tile "cd" "(setq cd-var (atoi $value)) (updateall)") (action_tile "dvd" "(setq dvd-var (atoi $value)) (updateall)") (action_tile "vhs" "(setq vhs-var (atoi $value)) (updateall)") (action_tile "accept" "(done_dialog 1)") (action_tile "cancel" "(done_dialog 0)") (setq done_dlg_val (start_dialog)) (if (= 1 done_dlg_val) (progn (prompt "\nUser pressed OK") ;;; do the job, it's OK (setq p1 (getpoint "\nSelect a lower left point :")) (setq x x-var) (setvar "osmode" 0) (setq y (+ (* 6.25 vhs-var) (* 7.5 cd-var) (* 9.5 dvd-var))) (setq y (+ y 3)) (command "line" p1 (polar p1 (/ pi 2.0) y) (polar (polar p1 (/ pi 2.0) y) 0 x) (polar p1 0 x) "c") (command "line" (polar p1 0 (- x 0.75)) (polar (polar p1 (/ pi 2.0) y) 0 (- x 0.75)) "") (command "line" (polar p1 0 0.75) (polar (polar p1 (/ pi 2.0) y) 0 0.75) "") (command "line" (polar (polar p1 0 0.75) (/ pi 2.0) 0.75) (polar (polar p1 0 (- x 0.75)) (/ pi 2.0) 0.75) "") (command "line" (polar (polar p1 0 0.75) (/ pi 2.0) (- y 0.75)) (polar (polar p1 0 (- x 0.75)) (/ pi 2.0) (- y 0.75)) "") (setq temp-p1 (polar (polar p1 0 0.75) (/ pi 2.0) 0.75)) (setq temp-x (- x 1.5)) (setq n 0) (while (< n vhs-var) ;;; loop on vhs shelves front view (command "line" (polar temp-p1 (/ pi 2.0) 0.5) (polar (polar temp-p1 (/ pi 2.0) 0.5) 0 temp-x) "") (command "line" (polar temp-p1 (/ pi 2.0) 5.5) (polar (polar temp-p1 (/ pi 2.0) 5.5) 0 temp-x) "") (command "line" (polar temp-p1 (/ pi 2.0) 6.25) (polar (polar temp-p1 (/ pi 2.0) 6.25) 0 temp-x) "") (setq temp-p1 (polar temp-p1 (/ pi 2.0) 6.25)) (setq n (+ n 1)) ) (setq temp-p1 (polar p1 pi 24)) ;;; side view (command "line" temp-p1 (polar temp-p1 (/ pi 2.0) y) (polar (polar temp-p1 (/ pi 2.0) y) 0 8.5) (polar temp-p1 0 8.5) "c") (command "line" (polar (polar temp-p1 (/ pi 2.0) y) 0 8.25) (polar temp-p1 0 8.25) "") (command "line" (polar temp-p1 (/ pi 2.0) 0.75) (polar (polar temp-p1 (/ pi 2.0) 0.75) 0 8.25) "") (command "line" (polar temp-p1 (/ pi 2.0) (- y 0.75)) (polar (polar temp-p1 (/ pi 2.0) (- y 0.75)) 0 8.25) "") (setq n 0) (setq temp-p1 (polar temp-p1 (/ pi 2.0) 0.75)) (while (< n vhs-var) ;;; loop on vhs shelves front view (command "line" (polar temp-p1 (/ pi 2.0) 0.5) (polar (polar temp-p1 (/ pi 2.0) 0.5) 0 0.5) (polar temp-p1 0 0.5) "") (command "line" (polar temp-p1 (/ pi 2.0) 5.5) (polar (polar temp-p1 (/ pi 2.0) 5.5) 0 8.25) "") (command "line" (polar temp-p1 (/ pi 2.0) 6.25) (polar (polar temp-p1 (/ pi 2.0) 6.25) 0 8.25) "") (setq temp-p1 (polar temp-p1 (/ pi 2.0) 6.25)) (setq n (+ n 1)) ) (setq n 0) (while (< n cd-var) ;;; loop on cdrack (command "line" (polar (polar temp-p1 (/ pi 2.0) 2.5743) 0 0.5710) (polar (polar temp-p1 (/ pi 2.0) 0.2131) 0 5.8138) (polar (polar temp-p1 (/ pi 2.0) 4.7721) 0 7.867) (polar (polar temp-p1 (/ pi 2.0) 7.1333) 0 2.6242) "c") (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.82) 0 1.6371) 0.25) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 0.5749) 0 4.4018) 0.25) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.1849) 0 6.5257) 0.25) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 3.3968) 0 7.5218) 0.25) (setq temp-p1 (polar temp-p1 (/ pi 2.0) 7.5)) (setq n (+ n 1)) ) (setq n 0) (while (< n dvd-var) ;;; loop on dvd rack (command "line" (polar (polar temp-p1 (/ pi 2.0) 1.8688) 0 0.2686) (polar (polar temp-p1 (/ pi 2.0) 0.3374) 0 5.8109) (polar (polar temp-p1 (/ pi 2.0) 8.0484) 0 7.9416) (polar (polar temp-p1 (/ pi 2.0) 9.5799) 0 2.3993) "c") (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.2865) 0 1.4375) 0.25) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 0.4789) 0 4.3602) 0.25) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.4066) 0 6.3658) 0.25) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 3.7449) 0 7.0118) 0.25) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 6.0831) 0 7.6578) 0.25) (setq temp-p1 (polar temp-p1 (/ pi 2.0) 9.5)) (setq n (+ n 1)) ) ;;;; 3d view (setq temp-p1 (polar p1 0 (+ x 48))) (command "pline" temp-p1 (polar temp-p1 (/ pi 2.0) y) (polar (polar temp-p1 (/ pi 2.0) y) 0 8.25) (polar temp-p1 0 8.25) "c") (command "zoom" "e" "zoom" "0.8x") (command "extrude" "l" "" -0.75 0) (setq e1 (entlast)) (command "copy" "l" "" "0,0,0" (list 0 0 (- x 0.75))) (command "pline" (polar temp-p1 0 8.25) (polar (polar temp-p1 (/ pi 2.0) y) 0 8.25) (polar (polar temp-p1 (/ pi 2.0) y) 0 8.5) (polar temp-p1 0 8.5) "c") (command "extrude" "l" "" x 0) (command "move" "l" "" "0,0,-0.75" "") (command "pline" (polar temp-p1 (/ pi 2.0) y) (polar (polar temp-p1 (/ pi 2.0) y) 0 8.25) (polar (polar temp-p1 (/ pi 2.0) (- y 0.75)) 0 8.25) (polar temp-p1 (/ pi 2.0) (- y 0.75)) "c") (command "extrude" "l" "" (- x 1.5) 0) (command "copy" "l" "" (list 0 (- y 0.75) 0) "0,0,0") (setq n 0) (setq temp-p1 (polar temp-p1 (/ pi 2.0) 0.75)) (while (< n vhs-var) ;;; loop on vhs shelves front view (command "pline" temp-p1 (polar temp-p1 (/ pi 2.0) 0.5) (polar (polar temp-p1 (/ pi 2.0) 0.5) 0 0.5) (polar temp-p1 0 0.5) "c") (command "extrude" "l" "" (- x 1.5) 0) (command "pline" (polar temp-p1 (/ pi 2.0) 5.5) (polar (polar temp-p1 (/ pi 2.0) 5.5) 0 8.25) (polar (polar temp-p1 (/ pi 2.0) 6.25) 0 8.25) (polar temp-p1 (/ pi 2.0) 6.25) "c") (command "extrude" "l" "" (- x 1.5) 0) (command "pline" (polar temp-p1 0 0.5) ;;; tape cartridge (polar (polar temp-p1 (/ pi 2.0) 4.125) 0 0.5) (polar (polar temp-p1 (/ pi 2.0) 4.125) 0 8) (polar temp-p1 0 8) "c") (command "extrude" "l" "" 1 0) (setq temp-p1 (polar temp-p1 (/ pi 2.0) 6.25)) (setq n (+ n 1)) ) (setq n 0) (while (< n cd-var) ;;; loop on cdrack (command "pline" (polar (polar temp-p1 (/ pi 2.0) 2.5743) 0 0.5710) (polar (polar temp-p1 (/ pi 2.0) 0.2131) 0 5.8138) (polar (polar temp-p1 (/ pi 2.0) 4.7721) 0 7.867) (polar (polar temp-p1 (/ pi 2.0) 7.1333) 0 2.6242) "c") (command "extrude" "l" "" 0.42 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.82) 0 1.6371) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 0.5749) 0 4.4018) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.1849) 0 6.5257) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 3.3968) 0 7.5218) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (setq temp-p1 (polar temp-p1 (/ pi 2.0) 7.5)) (setq n (+ n 1)) ) (setq n 0) (while (< n dvd-var) ;;; loop on dvd rack (command "pline" (polar (polar temp-p1 (/ pi 2.0) 1.8688) 0 0.2686) (polar (polar temp-p1 (/ pi 2.0) 0.3374) 0 5.8109) (polar (polar temp-p1 (/ pi 2.0) 8.0484) 0 7.9416) (polar (polar temp-p1 (/ pi 2.0) 9.5799) 0 2.3993) "c") (command "extrude" "l" "" 0.45 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.2865) 0 1.4375) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 0.4789) 0 4.3602) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 1.4066) 0 6.3658) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 3.7449) 0 7.0118) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (command "circle" (polar (polar temp-p1 (/ pi 2.0) 6.0831) 0 7.6578) 0.25) (command "extrude" "l" "" (- x 1.5) 0) (setq temp-p1 (polar temp-p1 (/ pi 2.0) 9.5)) (setq n (+ n 1)) ) (setq p1 (polar p1 0 (+ x 48))) (setq edsifirst e1) (setq edsiss nil) (setq edsiss (ssadd edsifirst)) (setq edsifirst (entnext edsifirst)) (while (/= edsifirst nil) (ssadd edsifirst edsiss) (setq edsifirst (entnext edsifirst)) ) (command "move" edsiss "" "0,0,0" "0,0,0") (command "ucs" "o" p1) (command "ucs" "x" "-90") (command "Rotate" "p" "" (list 0 0 0) "45") (command "ucs" "p") (command "ucs" "y" "90") (command "rotate" "p" "" (list 0 0 0) "30") (command "ucs" "w") (command "redraw") ) (prompt "\nUSER PRESSED CANCEL") ) (unload_dialog dcl_id) (prin1) )
9,343
Common Lisp
.l
214
38.242991
92
0.543906
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
88f41d09f849d4e039c59e1191ef540699254c7b2f3e81a3bbba8ee8fbca50b2
23,049
[ -1 ]
23,050
arrow.lsp
dentonyoder_LISP/arrow.lsp
(defun c:arrow(/ p1 p2 arrowlength oldsnap) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Command to draw an arrow by Denton Yoder (c) 2016 ;;; ;;; Uses dimension arrow size variable and current dimscale ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (setq p1 (getpoint "\nPick arrow point location:")) (setq p2 (getpoint "\nnext point:" p1)) (setq oldsnap (getvar "osmode")) (setvar "osmode" 0) (setq arrowlength (* (getvar "dimscale") (getvar "dimasz"))) (command "pline" p1 "w" "0" (/ arrowlength 3.0) (polar p1 (angle p1 p2) arrowlength) "w" 0 0) (while (/= p2 nil) (command p2) (setq p2 (getpoint "\nnext point:" p2)) ) (command "") (setvar "osmode" oldsnap) (princ) ) (defun c:farrow(/ p1 p2 arrowlength oldsnap) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Command to draw an arrow by Denton Yoder (c) 2016 ;;; ;;; Uses dimension arrow size variable and current dimscale ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (setq p1 (getpoint "\nPick arrow point location:")) (setq p2 (getpoint "\nnext point:" p1)) (setq oldsnap (getvar "osmode")) (setvar "osmode" 0) (setq arrowlength (* (getvar "dimscale") (getvar "dimasz"))) (command "pline" p1 "w" "0" arrowlength (polar p1 (angle p1 p2) arrowlength) "w" 0 0) (while (/= p2 nil) (command p2) (setq p2 (getpoint "\nnext point:" p2)) ) (command "") (setvar "osmode" oldsnap) (princ) ) (defun c:sarrow(/ p1 p2 ptemp arrowlength oldsnap) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Command to draw an arrow by Denton Yoder (c) 2016 ;;; ;;; Uses dimension arrow size variable and current dimscale ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (setq p1 (getpoint "\nPick arrow point location:")) (setq p2 (getpoint "\nnext point:" p1)) (setq oldsnap (getvar "osmode")) (setvar "osmode" 0) (setq arrowlength (* (getvar "dimscale") (getvar "dimasz"))) (setq ptemp (polar p1 (angle p1 p2) arrowlength)) (command "pline" p1 "w" "0" (/ arrowlength 3.0) ptemp "w" 0 0 "") (command "spline" p1 ptemp) (while (/= p2 nil) (command p2) (setq p2 (getpoint "\nnext point:" p2)) ) (command "" "" "") (setvar "osmode" oldsnap) (princ) )
2,483
Common Lisp
.l
59
36.711864
96
0.517154
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6e784a39eb7021b5705418812eec7240ad00445c27ab7543f312f622c26abe2f
23,050
[ -1 ]
23,051
tlabel.lsp
dentonyoder_LISP/tlabel.lsp
(defun c:tlabel(/ p1 dx dy noff x i ip) (setvar "cmdecho" 0) (setq Myscale (getvar "dimscale")) (setq oldsnap (getvar "osmode")) (setvar "osmode" 0) (command "-layer" "m" (strcat "Text-" (rtos myscale 2 2)) "") (command "-style" (strcat "Text-" (rtos myscale 2 2)) "romans" (* myscale 0.125) "" "" "" "" "") (setq p1 (getpoint "\nStarting point for text placement:")) (setq dx (getreal "\nX offset :")) (setq dy (getreal "\nY offset :")) (setq n1 (getreal "\nStarting number :")) (setq noff (getreal "\nNumber increment value :")) (setq x (getint "\nNumber of items :")) (setq ip (getstring "\nInclude a + ? Y/N :")) (setq i 0) (while (< i x) (progn (if (or (= "y" ip) (= "Y" ip)) (progn (setq numb (strcat (itoa (fix (/ n1 100.0))) "+" (substr (rtos n1 2 0) (- (strlen (rtos n1 2 0)) 1)))) (command "-text" "j" "m" p1 "0" numb) )(progn (command "-text" "j" "m" p1 "0" (rtos n1 2 0)) )) (setq n1 (+ n1 noff)) (setq p1 (list (+ (car p1) dx) (+ (cadr p1) dy))) (setq i (+ i 1)) )) (setvar "cmdecho" 1) (setvar "osmode" oldsnap) (princ) )
1,257
Common Lisp
.l
30
33.566667
115
0.511316
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
86acac06d57c44ca86dc69302696c241bbba118b5293c221a8e77add519845c9
23,051
[ -1 ]
23,052
graph.lsp
dentonyoder_LISP/graph.lsp
(defun pos(mychar myline / x flag) (setq x 1) (setq flag 0) (while (< x (strlen myline)) (if (and (= flag 0) (= mychar (substr myline x 1))) (setq flag x) ) (setq x (+ x 1)) ) (setq flag flag) ) (defun parse(Mydelimiter MyItemNo MyString / x) (setq x 1) (while (< x MyItemNo) (setq Mystring (substr Mystring (+ (pos mydelimiter mystring) 1))) (setq x (+ x 1)) ) (If (> (pos mydelimiter mystring) 0) (setq Mystring (substr Mystring 1 (- (pos mydelimiter mystring) 1))) (setq mystring mystring) ) ) (defun c:graph() (princ "\nSuper graph program for AutoCAD by Denton, requires comma delimited file of values:") (princ "\nUses the line number for the X-value:") (setq p1 (getpoint "\nPick bottom left fcorner of graph:")) (setq xl (getdist p1 "\nEnter graph max length:")) (setq yl (getdist p1 "\nEnter graph max height:")) (setq gx (getdist p1 "\nEnter grid X interval:")) (setq gy (getdist p1 "\nEnter grid Y interval:")) (setq yscale (getreal "\nEnter data scaling factor:")) (setq fname (getfiled "File to Graph" "" "*" 0)) (setq oldmode (getvar "osmode")) (setvar "osmode" 0) (setq passes (getint "\nNumber of columns of data? ")) (command "-layer" "m" "Graph" "") (command "pline" p1 (strcat "@" (rtos xl) "<0") (strcat "@" (rtos (* yl yscale)) "<90") (strcat "@" (rtos xl) "<180") "c") (command "-layer" "m" "Graph-grid" "c" "8" "" "") ;;; produce x-grid (setq x gx) (while (< x xl) (command "line" (polar p1 0 x) (strcat "@" (rtos (* yl yscale)) "<90") "") ;; add text label here... (setq x (+ x gx)) ) ;;; produce y-grid (setq y gy) (while (< y yl) (command "line" (polar p1 (/ pi 2.0) (* y yscale)) (strcat "@" (rtos xl) "<0") "") ;; add text label here... (setq y (+ y gy)) ) ;;; loop for data (setq item 1) (while (<= item passes) (command "-layer" "m" (strcat "GraphData-" (itoa item)) "c" (itoa item) "" "") (setq ifile (open fname "r")) (command "pline") (setq x 0) (while (setq myline (read-line ifile)) (setq x (+ x 1)) (princ "\n") (princ myline) (setq y (atof (parse "," item myline))) (command (polar (polar p1 0 x) (/ pi 2.0) (* y yscale))) ) (command "") (close ifile) (setq item (+ item 1)) ) (setvar "osmode" oldmode) (princ) )
2,366
Common Lisp
.l
74
28.054054
97
0.594139
dentonyoder/LISP
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
48ebb55e49230a272e9097787c4d9f9a0b121759a02a2f67f7b8a1e08726eb1f
23,052
[ -1 ]
23,075
p3.lisp
jquaid0001_LispInsSort/p3.lisp
; p3.lisp ; course: Organization of Programming Langauges, Spring 2022 ; assignment: Programming Assignment 3 ; author: Josh Quaid ; due: March 5, 11:59pm ; submitted: March 3, 10am ; directions: - To use the clisp REPL: ; - Enter clisp by typing clisp at a prompt ; - Type (load "p3.lisp") ; - Type (lins '(list of nums here)) ; - ie (lins '(6 5 4 7 8)) ; The insertion sort function definition "lins" (defun lins (list) ; Define lins to accept one parameter "list" and accept only real number lists (declare (type real list)) (if (null list) ; Base case, if list is empty do nothing it is either an empty list or is sorted (return-from lins list)) ; so return the list. (insert (car list) (lins (cdr list)))) ; if list is not empty call insert with the head ; of the list as "item" and the tail of the list ; as "list". ; The insert helper function (defun insert (item list) ; Define insert to accept 2 parameters item to insert and list to insert into (cond ((null list) (list item)) ; Base case, if item is null, list is sorted so return to lins ((funcall #'< item (car list)) ; else make a function call with < literal to insert item if item is less than the head of list (cons item list)) ; and if true, cons the item to the front of the list and return to lins ((cons (car list) (insert item (cdr list)))))) ; else if false check the next item in the list by consing the head of the list with ; the result of inserting the item into the tail of the list continuing until ; the item is inserted into the proper position in the list
2,075
Common Lisp
.lisp
27
65.333333
156
0.54901
jquaid0001/LispInsSort
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
dad477b2887322184352ec564b990f43620d67bfc52cef38f1447830806a0105
23,075
[ -1 ]
23,092
imagen.lisp
josrr_lisp2js/imagen.lisp
;;;; -*- coding: utf-8-unix; -*- ;;;; Copyright (C) 2016 Jos√© Ronquillo Rivera <[email protected]> ;;;; This file is part of lisp2js. ;;;; ;;;; lisp2js is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; lisp2js 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with lisp2js. If not, see <http://www.gnu.org/licenses/>. (in-package #:common-lisp-user) (ql:quickload "lisp2js") (in-package :lisp2js) (uiop/image:register-image-restore-hook (lambda () (compile-from-command-line-arguments (command-line-arguments))) nil) (uiop/image:dump-image "lisp2js" :executable t)
1,046
Common Lisp
.lisp
24
42.333333
73
0.726738
josrr/lisp2js
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1ee7256cac1f615408be45574377b8e8000266c4254dc6af072f50309f53da3d
23,092
[ -1 ]
23,093
lisp2js.lisp
josrr_lisp2js/lisp2js.lisp
;;;; -*- coding: utf-8-unix; -*- ;;;; Copyright (C) 2016 Jos√© Ronquillo Rivera <[email protected]> ;;;; This file is part of lisp2js. ;;;; ;;;; lisp2js is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; lisp2js 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with lisp2js. If not, see <http://www.gnu.org/licenses/>. (in-package #:common-lisp-user) (defpackage #:lisp2js (:use :cl :parenscript) (:export #:defsource-js #:list-sources-js #:compile-file-to-js #:compile-sources-to-js #:compile-from-command-line-arguments) (:import-from #:getopt #:getopt) (:import-from #:uiop/image #:command-line-arguments) (:import-from #:uiop/filesystem #:delete-file-if-exists) (:import-from #:uiop/pathname #:split-unix-namestring-directory-components #:split-name-type)) (in-package #:lisp2js) (defparameter *js-type* "js") (defparameter *sources* (make-hash-table :test #'equal :size 20)) (defparameter *getopt-options* '(("input" :required) ("output-path" :optional) ("minify" :none))) (defun compile-from-command-line-arguments (args) (let* ((arguments (multiple-value-list (getopt args *getopt-options*))) (getopts (cadr arguments))) (when getopts (let ((input (assoc "input" getopts :test #'equal)) (output-path (assoc "output-path" getopts :test #'equal)) (minify (assoc "minify" getopts :test #'equal))) (when (consp input) ;;(log:debug minify) (defsource-js (cdr input) :output-dir (if (consp output-path) (cdr output-path) #P"./") :minify (not (null minify))) (compile-sources-to-js)))))) (defun list-sources-js (&optional (sources *sources*)) (when sources (let ((list)) (maphash (lambda (input output) (setf list (append list (list (list input output))))) sources) list))) (defun defsource-js (input &key (output-dir #P"./") minify) (when (and (probe-file input) (probe-file output-dir)) (let ((input-parts (multiple-value-list (split-unix-namestring-directory-components (namestring input))))) (multiple-value-bind (name type) (split-name-type (caddr input-parts)) (declare (ignore type)) (setf (gethash (namestring input) *sources*) (list (merge-pathnames (pathname (concatenate 'string name "." *js-type*)) output-dir) minify)))))) (defun compile-file-to-js (input output) (when (probe-file input) (with-open-file (*parenscript-stream* output :direction :output :if-exists :supersede) (ps-compile-file input :external-format :utf-8)))) (defun compile-sources-to-js (&optional (sources *sources*)) (when sources (maphash (lambda (input output) (delete-file-if-exists (car output)) (let ((*ps-print-pretty* (not (cadr output)))) (compile-file-to-js input (car output))) (when (null (probe-file (car output))) (error "Compiling ~S" input))) sources) t))
3,366
Common Lisp
.lisp
84
36.27381
90
0.67807
josrr/lisp2js
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1d46dc0dc6bebef3d3a7cc2826abc34e58ba14f47fab20f2cfff5a8ca12c50e9
23,093
[ -1 ]
23,094
inicia.lisp
josrr_lisp2js/inicia.lisp
;;;; -*- coding: utf-8-unix; -*- ;;;; Copyright (C) 2016 Jos√© Ronquillo Rivera <[email protected]> ;;;; This file is part of lisp2js. ;;;; ;;;; lisp2js is free software: you can redistribute it and/or modify ;;;; it under the terms of the GNU General Public License as published by ;;;; the Free Software Foundation, either version 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; lisp2js 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 General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with lisp2js. If not, see <http://www.gnu.org/licenses/>. (in-package #:common-lisp-user) (ql:quickload "lisp2js") (ql:quickload "swank") (ql:quickload "log4cl") (swank:create-server :port 4005 :dont-close t) (log:config :sane2) (log:config :debug)
986
Common Lisp
.lisp
23
41.782609
73
0.721124
josrr/lisp2js
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f9387e2538373ef4cc7d4dddafe20ba05dfb4d4bcdb91fc6a495fd05153f13f8
23,094
[ -1 ]
23,095
funcion-02.lisp
josrr_lisp2js/pruebas/funcion-02.lisp
(defun foo (x) (1+ x)) (lambda (x) (case x (1 (loop repeat 3 do (alert "foo"))) (:bar (alert "bar")) (otherwise 4))) (dotimes (x 3) (+ x x))
159
Common Lisp
.lisp
8
16.625
40
0.516779
josrr/lisp2js
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9c09f9196f23128b0c0005a5350d4a36f213de2d361f7afa2b454e0fe43d2ca9
23,095
[ -1 ]