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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
39,717 | helper.lisp | hwa_lisp-helpers/cl-json-helper/helper.lisp | (in-package #:cl-json-helper)
;;
;;;; cl-json reversible encoder and decoder.
;;
;; The default encoder doesn't distinguish {}, [], null, false.
;; So we shall use WITH-CODER-SIMPLE-CLOS-SEMANTICS to decode {} as empty Object;
;; set *JSON-ARRAY-TYPE* to 'VECTOR to decode [] as #();
;; set *BOOLEAN-HANDLER* to decode true as '(:TRUE), false as '(:FALSE),
;; null as '(:NULL) so as for EXPLICIT-ENCODER to encode them correctly back.
;;The explicit decoder: If S is a list, the first symbol defines the encoding:
;; If (car S) is :TRUE return a JSON true value. If (car S) is :FALSE return a
;; JSON false value. If (car S) is :NULL return a JSON null value. If (car S) is
;; :JSON princ the strings in (cdr s) to stream If (car S) is :LIST or :ARRAY
;; encode (cdr S) as a a :JSON Array. If (car S) is :OBJECT encode (cdr S) as
;; A JSON Object, interpreting (cdr S) either as an A-LIST or a P-LIST.
;; (test explicit-encoder
;; (is (string= "true" (with-explicit-encoder
;; (encode-json-to-string '(:true))))
;; "True")
;; (is (string= "false"
;; (with-explicit-encoder
;; (encode-json-to-string '(:false))))
;; "False")
;; (is (string= "null"
;; (with-explicit-encoder
;; (encode-json-to-string '(:null))))
;; "False")
;; (is (string= "[1,\"a\"]"
;; (with-explicit-encoder
;; (encode-json-to-string '(:list 1 "a"))))
;; "List")
;; (is (string= "[1,\"a\"]"
;; (with-explicit-encoder
;; (encode-json-to-string '(:array 1 "a"))))
;; "Array")
;; (is (string= "{\"a\":1,\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:object "a" 1 "b" 2))))
;; "Plist")
;; (is (string= "{\"a\":1,\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:object ("a" . 1) ( "b" . 2)))))
;; "Alist")
;; (is (string= "{\"a\":1,\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:alist ("a" . 1) ( "b" . 2)))))
;; "Explicit Alist")
;; (is (string= "{\"a\":1,\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:plist "a" 1 "b" 2))))
;; "Explicit Plist")
;; (is (string= "{\"a\":{\"c\":1,\"d\",2},\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:object
;; "a" (:json "{\"c\":1,\"d\",2}")
;; "b" 2))))
;; "Embedded json")
;; (is (string= "{\"a\":{\"c\":1,\"d\":2},\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:object
;; "a" (:object "c" 1 "d" 2)
;; "b" 2))))
;; "Object in object")
;; (is (string= "{\"a\":{\"c\":1,\"d\":2},\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:object
;; "a" (:object ( "c" . 1) ( "d" . 2))
;; "b" 2))))
;; "Mixed alist and plist")
;; (is (string= "{\"a\":1,\"b\":2}"
;; (with-explicit-encoder
;; (encode-json-to-string '(:object ("a" . 1) nil ( "b" . 2)))))
;; "Alist with a nil value"))
(defmacro with-reversible-json-decoder (&body body)
`(cl-json:with-decoder-simple-clos-semantics
(let ((cl-json:*json-array-type* 'vector)
(cl-json:*boolean-handler* #'(lambda (str)
(let ((mapping '(("true" . (:true))
("false" . (:false))
("null" . (:null)))))
(cdr (assoc str mapping :test #'string=))))))
,@body)))
(defmacro with-reversible-json-encoder (&body body)
`(cl-json:with-explicit-encoder ,@body))
;;;;
| 4,113 | Common Lisp | .lisp | 85 | 44.552941 | 89 | 0.447984 | hwa/lisp-helpers | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 819b5a2d38edeaf27c524f1d9c52f8c2817ac9b5e57eb9e2c34992ad034916b2 | 39,717 | [
-1
] |
39,718 | hunchentoot-helper.asd | hwa_lisp-helpers/hunchentoot-helper/hunchentoot-helper.asd | (in-package #:cl-user)
(defpackage #:hunchentoot-helper-system
(:use #:cl #:asdf))
(in-package #:hunchentoot-helper-system)
(defsystem hunchentoot-helper
:author "hwa<[email protected]>"
:license "GPL 3.0"
:description "My own helpers for using Hunchentoot."
:depends-on (:hunchentoot)
:components ((:file "package")
(:file "helper")))
| 371 | Common Lisp | .asd | 11 | 30 | 54 | 0.697479 | hwa/lisp-helpers | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 6e7a12433a05f7e8516f785a8185cd7ab71354a97b9c33222ef757a06daed271 | 39,718 | [
-1
] |
39,719 | cl-yaml-helper.asd | hwa_lisp-helpers/cl-yaml-helper/cl-yaml-helper.asd | (in-package #:cl-user)
(defpackage #:cl-yaml-helper-system
(:use #:cl #:asdf))
(in-package #:cl-yaml-helper-system)
(defsystem cl-yaml-helper
:author "hwa<[email protected]>"
:license "GPL 3.0"
:description "My own helpers for cl-yaml"
:depends-on (:cl-yaml)
:components ((:file "package")
(:file "helper")))
| 344 | Common Lisp | .asd | 11 | 27.545455 | 43 | 0.663636 | hwa/lisp-helpers | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 944c5d9f6681ca86bd0063364fb4a4ae3931272f45730dcf750cc3891cb8241d | 39,719 | [
-1
] |
39,720 | cl-json-helper.asd | hwa_lisp-helpers/cl-json-helper/cl-json-helper.asd | (in-package #:cl-user)
(defpackage #:cl-json-helper-system
(:use #:cl #:asdf))
(in-package #:cl-json-helper-system)
(defsystem cl-json-helper
:author "hwa<[email protected]>"
:license "GPL 3.0"
:description "My own helpers for cl-json"
:depends-on (:cl-json)
:components ((:file "package")
(:file "helper")))
| 344 | Common Lisp | .asd | 11 | 27.545455 | 43 | 0.663636 | hwa/lisp-helpers | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 0e7ca319d45fbdb79353580ac37b4e8ca5c8dbafebd4762b161e68fc9eb4174d | 39,720 | [
-1
] |
39,742 | build.lisp | REve-Workshop_xyz_revecloud_re_cl/build.lisp | (push #P"/home/roland/codes/revews/cl/tools/" asdf:*central-registry*)
(push #P"/home/roland/codes/revews/cl/logging/" asdf:*central-registry*)
(push #P"/home/roland/codes/revews/cl/is/" asdf:*central-registry*)
(asdf:oos 'asdf:load-op 'xyz.revecloud.re)
| 255 | Common Lisp | .lisp | 4 | 62.75 | 72 | 0.741036 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | a630d99fec8e2cf57baa333fba4542024e366281d0391640d2671311fd8dcc5d | 39,742 | [
-1
] |
39,743 | builder.lisp | REve-Workshop_xyz_revecloud_re_cl/logging/builder.lisp | (defpackage xyz.revecloud.re.logging.builder
(:use :cl)
(:export #:init-logging #:set-operation #:make-log-record)
(:import-from :xyz.revecloud.re.tools.tools "escape-double-quote"))
(in-package :xyz.revecloud.re.logging.builder)
(defparameter *application* nil
"The application calling the logger.")
(defparameter *operation* nil
"The operation, function, macro, calling the logger.")
(defun init-logging (application)
"Init the logging system and set the application context."
(setf *application* application))
(defun set-operation (operation)
"Set the operation context."
(setf *operation* operation))
(defun make-compta-error-message (subject what? context)
"Return a string formatted as an error message for the compta package."
(escape-double-quote (format nil "~a: ~a. ~a." subject what? context)))
(defun make-log-record (log-level error-type message &rest args)
"Renvoie un list des information concernant en enregistrement dans le journal."
`(log
(context
(application ,*application*)
(operation ,*operation*))
(log-level ,log-level)
(type ,error-type)
(record-date ,(get-universal-time))
(message ,message)
,@args))
(defun make-log-record-unknown-account-type (compte faux-type)
"Retourne une structure décrivant le type d'erreur type de compte inconnu."
(let ((message-to-join (make-compta-error-message faux-type
"type de compte inconnu"
(format nil "Erreur lors de l'ajout du compte ~a" compte))))
(make-log-record 'error
'unknown-account-type-error
message-to-join
(list 'account-type-received faux-type)
(list 'account (escape-double-quote compte)))))
(defun make-log-record-unknown-transaction-type (compte-destination faux-type transaction-date)
"Retourne une structure décrivant le type d'erreur type de compte inconnu."
(let ((message-to-join (make-compta-error-message faux-type
"type de transaction inconnu"
(format nil "Erreur lors de l'ajout d'une transaction. Destination: ~a - Date: ~a" compte-destination transaction-date))))
(make-log-record 'error
'unknown-transaction-type-error
message-to-join
(list 'transaction-type-received faux-type)
(list 'destination-account (escape-double-quote compte-destination))
(list 'transaction-date (escape-double-quote transaction-date)))))
(defun make-log-record-database-not-set (operation)
"Retourne une structure décrivant le type d'erreur type de compte inconnu."
(make-log-record 'error
'database-not-set-error
(escape-double-quote "Aucune base de donnée ouverte.")
(list 'requested-operation operation)))
| 3,024 | Common Lisp | .lisp | 56 | 43.214286 | 174 | 0.644211 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | fd5b873f9d145d554d8bbbf5e196080aea67442b43db37d802280879398a9653 | 39,743 | [
-1
] |
39,744 | main.lisp | REve-Workshop_xyz_revecloud_re_cl/logging/tests/main.lisp | (defpackage revesh/tests/main
(:use :cl
:revesh
:rove))
(in-package :revesh/tests/main)
;; NOTE: To run this test file, execute `(asdf:test-system :revesh)' in your Lisp.
(deftest test-target-1
(testing "should (= 1 1) to be true"
(ok (= 1 1))))
| 272 | Common Lisp | .lisp | 9 | 26.333333 | 82 | 0.639847 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 1bb4d5d5c4a3efa9c4f5327d0192feea61598e87794c8cab6a0328bfa969bf42 | 39,744 | [
-1
] |
39,745 | cabs.lisp | REve-Workshop_xyz_revecloud_re_cl/tools/cabs.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: cabs.lisp
;;;;LANGUAGE: common-lisp
;;;;SYSTEM: common-lisp
;;;;USER-INTERFACE: common-lisp
;;;;DESCRIPTION
;;;;
;;;; File originally generated with Emacs package
;;;; 'file-create.re'. This package can be found at
;;;; 'https://github.com/montaropdf/reve-workshop'.
;;;;
;;;; The header comment template is inspired by the one in
;;;; common-lisp source files at
;;;; https://github.com/informatimago/lisp
;;;;
;;;; See defpackage documentation string.
;;;;
;;;;AUTHORS
;;;; <RE> Roland Everaert <[email protected]>
;;;;MODIFICATIONS
;;;; YYYY-MM-DD <RE> Some comment describing a modification.
;;;;BUGS
;;;;
;;;;LEGAL
;;;;
;;;; Insert your legalese here.
;;;;****************************************************************************
(defpackage xyz.revecloud.re.tools.cabs
(:use :cl)
;;; Export functions
;;
;; (:export "awesome-function-of-doom" "terrifying-macro-of-courtesy")
;;
;;; Import functions
;;
;; (:import-from "that.great.package.extra" "another-awesome-function" "that-great-function-i-like-to-use-in-every-file")
(:documentation
"This package provides tools to help compile common-lisp systems."))
(in-package :xyz.revecloud.re.tools.cabs)
;;; Begin to write your code here
(defun collect-asd-directories (path)
"Collect all directories containing an asd file."
(let ((asd-directories (directory path/**/*.asd))
(directory-with-asd-file '()))
(dolist (asd-file asd-directories directory-with-asd-file)
(push (directory-namestring asd-file) directory-with-asd-file))))
| 1,688 | Common Lisp | .lisp | 47 | 34.382979 | 121 | 0.62149 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 5e443e437df08a4f7017b6e9712f09c0aac35d60d7a8e77f4033b467ed126a9c | 39,745 | [
-1
] |
39,746 | misc.lisp | REve-Workshop_xyz_revecloud_re_cl/tools/misc.lisp | (defpackage xyz.revecloud.re.tools.misc
(:use :cl)
(:export "pp-hash-table"
"merge-pathnames-to-string"
"escape-double-quote"))
(in-package :xyz.revecloud.re.tools.misc)
(defmacro merge-pathnames-to-string (root sub)
"Return a merge ROOT and SUB to form a pathname as a string."
`(namestring (merge-pathnames ,sub ,root)))
(defun pp-hash-table (table)
"Print the content of the hash table TABLE."
(maphash (lambda (k v) (print (format nil "~a : ~a" k v))) table))
(defun escape-double-quote (text)
"Returns TEXT surrounded by \"."
(format nil "\"~a\"" text))
| 601 | Common Lisp | .lisp | 15 | 36.266667 | 68 | 0.680412 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | d2369da0e75e6294f9dc780196a236391668bb60ab85b19fbdafd835fcb44d38 | 39,746 | [
-1
] |
39,747 | main.lisp | REve-Workshop_xyz_revecloud_re_cl/tools/tests/main.lisp | (defpackage xyz.revecloud.re.tools/tests/main
(:use :cl
:xyz.revecloud.re.tools
:rove))
(in-package :xyz.revecloud.re.tools/tests/main)
;; NOTE: To run this test file, execute `(asdf:test-system :xyz.revecloud.re.tools)' in your Lisp.
(deftest test-target-1
(testing "should (= 1 1) to be true"
(ok (= 1 1))))
| 347 | Common Lisp | .lisp | 9 | 33.444444 | 98 | 0.651786 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 9374ecf9d0f30e2c4cb2ece1998a59e89c1c247cede44057425ee4a961eef2c2 | 39,747 | [
-1
] |
39,748 | tree.lisp | REve-Workshop_xyz_revecloud_re_cl/is/tree.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: tree.lisp
;;;;LANGUAGE: common-lisp
;;;;SYSTEM: common-lisp
;;;;USER-INTERFACE: common-lisp
;;;;DESCRIPTION
;;;;
;;;; See defpackage documentation string.
;;;;
;;;; File originally generated with Emacs template found at
;;;; 'https://github.com/montaropdf/reve-workshop/elisp/'.
;;;;
;;;;AUTHORS
;;;; <RE> Roland Everaert <[email protected]>
;;;;MODIFICATIONS
;;;; YYYY-MM-DD <RE> Some comment describing a modification.
;;;;BUGS
;;;;
;;;;LEGAL
;;;;
;;;; GNU AGPL
;;;;
;;;; Copyright (C) 2020 by Roland Everaert
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;;;****************************************************************************
(defpackage xyz.revecloud.is.tree
(:use :cl)
(:export "walk" "node-sane-p" "path-exists-p")
;;; Import functions
;;
;; (:import-from "that.great.package.extra" "another-awesome-function" "that-great-function-i-like-to-use-in-every-file")
(:documentation
"Tree manipulation."))
(in-package :xyz.revecloud.is.tree)
;;; Begin to write your code here.
;; * Tree design
;; A node, is composed of a CAR and a CDR
;; - The CAR must be a symbol
;; - The CDR can be
;; - a spliced list of atoms
;; - a spliced list of nodes
;;
;; - Example 1: One node made of a symbol and an atom
;; (a 1)
;; - Example 2: One node made of a symbol and several atoms
;; (a 1 2 3 567 "things")
;; - Example 3: A node containing another node
;; (a (b fur so da))
;; - Example 4: A node made of a symbol and several nodes
;; (a (b fus ro da) (c 3) (bar "foo") (e (grad 4) (more e-nough)))
;; How to grow the tree:
;; * Graft design
;; A graft, can be
;; - A node, the rule of a tree node applies
;; - a list of atoms. They will be spliced
;; * Use cases:
;; 1. Add a graft to a branch
;; - The graft must be a node
;; 2. Replace a branch with a graft
;; * Work flow
;; 1. Ensure the path exists (use the walk function)
;; 2. Ensure the graft, is valid
;; 3. Which case to perform?
;; a. Add a graft to a branch
;; - If the path lead to a leaf:
;; - Raise an error
;; - Else, Push the tree in the branch
;; b. Replace a branch with a graft
;; - Remove the branch at path
;; - Add the graft to the parent branch
;; * The grow function
;; ** Input
;; - the path to the affected node
;; - the tree affected
;; - the graft
;; - the type of operation
;; ** Output
;; - t, the operation succeed
;; - nil, the operation failed
;; - error condition, invalid parameters
(defun walk (path tree &key (operation :walk) (new-nodes-or-atoms nil))
"Walk in the TREE following PATH and sweat the element found or nil.
This function does not use any loop construct to walk through the nodes
at the same level. It calls itself with the CDR of TREE."
(let ((breath (car tree))
(node-head nil))
(cond ((eq operation :walk)
;; Is the exhaled node a cons or a symbol?
(unless (setf node-head (if (consp breath) (car breath)
(when (symbolp breath) breath)))
(error "Bad node type: ~a / ~a" (type-of breath) breath)))
((find operation '(:replace :graft))
(unless (or (node-sane-p new-nodes-or-atoms)
(every #'(lambda (x) (typep x 'atom)) new-nodes-or-atoms))
(error "Bad graft: ~a~%" new-nodes-or-atoms)))
((eq operation :cut)
(unless (path-exists-p path tree)
(error "Invalid path: ~a~%" path))
(setf new-nodes-or-atoms nil))
(t
(error "Unknown operation: ~a~%" operation)))
(setf node-head (when (consp breath) (car breath)))
;; Is inhaling keep us on track?
(if (eq (car path) node-head)
;; Yes, check if we finish walking
(if (cdr path)
;; Yes, continue on this path
(walk (cdr path)
(cdr breath)
:operation operation
:new-nodes-or-atoms new-nodes-or-atoms)
;; No, time to sweat off
(cond ((eq operation :replace)
(rplacd (car tree) new-nodes-or-atoms)
t)
((eq operation :cut)
(rplaca tree nil)
t)
((eq operation :graft)
(push new-nodes-or-atoms (cdar tree))
t)
((eq operation :walk)
(cdr breath))
(t
(error "Bad operation: ~a~%" operation))))
;; No, time to exhale and keep walking
;; If not at the end of the run...
(when (cdr tree)
;; continue with a side track
(walk path
(cdr tree)
:operation operation
:new-nodes-or-atoms new-nodes-or-atoms)))))
(defun path-exists-p (path node)
(let ((breath (car node))
(node-head nil))
;; Is the exhaled node a cons or a symbol?
(setf node-head (when (consp breath) (car breath)))
;; Is inhaling keep us on track?
(if (eq (car path) node-head)
;; Yes, check if we finish walking
;; Do we need to continue?
(if (cdr path)
;; Yes, continue on this path
(when (path-exists-p (cdr path) (cdr breath)) t)
;; No, time to sweat off
t)
;; No, time to exhale and keep walking
(when (and (cdr node) (path-exists-p path (cdr node))) t))))
(defun node-sane-p (node)
"Return t if the NODE and its children are sane.
A sane node is a cons made of a car with a symbol and a cdr with one
or more nodes or one or more atoms."
(let ((node-head nil))
(setf node-head (when (consp node) (car node)))
(when (and node-head (symbolp node-head))
(let ((node-body (cdr node)))
(if (every #'(lambda (x) (typep x 'atom)) node-body)
t
(every #'node-sane-p node-body))))))
;; (defun graft (path node new-node-or-atoms operation)
;; "Add nodes or atoms at path or replace the content of a node at path."
;; (let ((breath (car node))
;; (node-head nil))
;; (unless (or (node-sane-p new-node-or-atoms)
;; (every #'(lambda (x) (typep x 'atom)) new-node-or-atoms))
;; (error "Bad graft: ~a~%" new-node-or-atoms))
;; (unless (find operation '(:replace :add))
;; (error "Bad operation: ~a~%" operation))
;; ;; Is the exhaled node a cons or a symbol?
;; (setf node-head (when (consp breath) (car breath)))
;; ;; Is inhaling keep us on track?
;; (if (eq (car path) node-head)
;; ;; Yes, check if we are done walking
;; (if (cdr path)
;; ;; Yes, continue on this path
;; (graft (cdr path) (cdr breath) new-node-or-atoms operation)
;; ;; No, time to sweat off
;; (cond ((eq operation :replace)
;; (rplacd (car node) new-node-or-atoms))
;; ((eq operation :add)
;; (push new-node-or-atoms (cdar node)))
;; (t
;; (error "Bad operation: ~a~%" operation))))
;; ;; No, time to exhale and keep walking
;; ;; If not at the end of the run...
;; (when (and (cdr node)
;; (graft path
;; (cdr node)
;; new-node-or-atoms
;; operation))
;; t))))
;;; Code ends here.
| 8,292 | Common Lisp | .lisp | 206 | 35.121359 | 123 | 0.558831 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 010a908faa82c55851f6f3cb324e1db120e5528064d3c7fc56668eb37362a4cd | 39,748 | [
-1
] |
39,749 | define.lisp | REve-Workshop_xyz_revecloud_re_cl/is/define.lisp | (defpackage pim.re.error
(:use #:cl #:xyz.revecloud.re.logging.builder)
(:export #:init
#:make-log-record-unknown-account-type
#:make-log-record-unknown-transaction-type
#:make-log-record-database-not-set)
(:import-from #:xyz.revecloud.re.logging.builder "make-log-record"))
(in-package pim.re.error)
(defun make-compta-error-message (subject what? context)
"Return a string formatted as an error message for the compta package."
(escape-double-quote (format nil "~a: ~a. ~a." subject what? context)))
(defun make-log-record-unknown-account-type (compte faux-type)
"Retourne une structure décrivant le type d'erreur, type de compte inconnu."
(let ((message-to-join (make-compta-error-message faux-type
"type de compte inconnu"
(format nil "Erreur lors de l'ajout du compte ~a" compte))))
(make-log-record 'error
'unknown-account-type-error
message-to-join
(list 'account-type-received faux-type)
(list 'account (escape-double-quote compte)))))
(defun make-log-record-unknown-transaction-type (compte-destination faux-type transaction-date)
"Retourne une structure décrivant le type d'erreur, type de transaction inconnue."
(let ((message-to-join (make-compta-error-message faux-type
"type de transaction inconnu"
(format nil "Erreur lors de l'ajout d'une transaction. Destination: ~a - Date: ~a" compte-destination transaction-date))))
(make-log-record 'error
'unknown-transaction-type-error
message-to-join
(list 'transaction-type-received faux-type)
(list 'destination-account (escape-double-quote compte-destination))
(list 'transaction-date (escape-double-quote transaction-date)))))
(defun make-log-record-database-not-set (operation)
"Retourne une structure décrivant le type d'erreur, base de donnée non définie."
(make-log-record 'error
'database-not-set-error
(escape-double-quote "Aucune base de donnée ouverte.")
(list 'requested-operation operation)))
| 2,392 | Common Lisp | .lisp | 38 | 48.052632 | 174 | 0.612463 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 4f2ae80271b37daf893d84cb6f20f7817e28259facc66dc858f3e7be406a6d32 | 39,749 | [
-1
] |
39,750 | main.lisp | REve-Workshop_xyz_revecloud_re_cl/is/tests/main.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: main.lisp
;;;;LANGUAGE: common-lisp
;;;;SYSTEM: common-lisp
;;;;USER-INTERFACE: common-lisp
;;;;DESCRIPTION
;;;;
;;;; See defpackage documentation string.
;;;;
;;;; File originally generated with Emacs template found at
;;;; 'https://github.com/montaropdf/reve-workshop/elisp/'.
;;;;
;;;;AUTHORS
;;;; <RE> Roland Everaert <[email protected]>
;;;;MODIFICATIONS
;;;; YYYY-MM-DD <RE> Some comment describing a modification.
;;;;BUGS
;;;;
;;;;LEGAL
;;;;
;;;; GNU AGPL
;;;;
;;;; Copyright (C) 2020 by Roland Everaert
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero General Public License as published by
;;;; the Free Software Foundation, either version 3 of the License, or
;;;; (at your option) any later version.
;;;;
;;;; 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;;;;****************************************************************************
(defpackage xyz.revecloud.is/test
(:use :cl :rove :xyz.revecloud.is.tree)
;;; Export functions
;;
;; (:export "awesome-function-of-doom" "terrifying-macro-of-courtesy")
;;
;;; Import functions
;;
(:import-from "xyz.revecloud.is/test" "walk" "node-sane-p")
(:documentation
"Testing of the information system package."))
(in-package :xyz.revecloud.is/test)
;;; Begin to write your code here.
;; NOTE: To run this test file, execute `(asdf:test-system :revesh)' in your Lisp.
(defparameter *a-tree* '(prime (a (a-prime 1) (a-second r)) (b (4r (var #\%)))))
(deftest walk-this-way
(testing "(walk '(b 4r var) *a-tree*) to return #\%."
(ok (outputs (walk '(b 4r var) *a-tree*) #\%))))
(defparameter *a-malformed-tree* '(sec (a ("meh" 1) (a r)) (b (4r (var #\%)))))
(deftest walk-are-you-talking-to-me
(testing "(walk '(b 4r var) *a-malformed-tree*) to signal an error."
(ok (signals (walk '(b 4r var) *a-tree*)
'error)
"Invalid path: (b 4r var)")))
(defparameter *another-malformed-tree* '(ter ((truc 1) (a r)) (b (4r (var #\%)))))
(deftest walk-are-you-talking-to-me-too
(testing "(walk '(b 4r var) *another-malformed-tree*) to signal an error."
(ok (signals (walk '(b 4r var) *a-tree*)
'error)
"Invalid path: (b 4r var)")))
(defparameter *a-thriving-tree* '(prime
(a (a-prime 1 5 9 "bidule")
(a-second r)
(a-ter (w a)
(l 47)
(f #P"/home/roland/.sbclrc")))
(b (4r
(var #\%)))))
(defparameter *yet-another-malformed-tree* '(prime
(a (a-prime 1 5 9 "bidule")
(a-second r)
(a-ter w a
(l 47)
(f #P"/home/roland/.sbclrc ")))
(b (4r
(var #\%)))))
(defparameter *a-path* '(b 4r var))
(defparameter *une-hache* (make-hash-table))
(defparameter *wrong-path* '(a var))
(defstruct test-type
(bla 2)
(bli "ret"))
(defparameter *une-structure* (make-test-type))
(defclass truc ()
(one
(two
:reader two)
three))
(defparameter *une-classe* (make-instance 'truc))
;;; Code ends here.
| 4,105 | Common Lisp | .lisp | 98 | 32.969388 | 82 | 0.518984 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 246054c1181622ac767e30cd89a257617a6d34466fdc7d626f61018aa8100a08 | 39,750 | [
-1
] |
39,751 | git.lisp | REve-Workshop_xyz_revecloud_re_cl/someday/git.lisp | (defpackage xyz.revecloud.re.someday.git
(:use :cl :inferior-shell :str :xyz.revecloud.re.tools)
(:export #:commits-stat
#:repo-stat
#:repository-statistics))
(in-package :xyz.revecloud.re.someday.git)
(defstruct commits-stat
(ahead 0 :type number)
(behind 0 :type number))
(defstruct repo-stat
(is-repo nil)
(remotes 0 :type number)
(branches 0 :type number)
(branch "master" :type string)
(untracked 0 :type number)
(modified 0 :type number)
(unmerged 0 :type number)
(commits (make-commits-stat) :type commits-stat))
(defun is-repo-p (dir)
"Check if DIR is a git repository."
(probe-file (reve-workshop.tools:merge-pathnames-to-string ".git" dir)))
(defun has-remote-p (repo-dir)
"Return non-nil if the repo in REPO-DIR has a remote configured."
(not (inferior-shell:run/nil `(progn
(cd ,repo-dir)
(git remote)))))
(defun get-repo-list (rootdir)
"Return the list of git repositories available in a given directory"
(if (is-repo-p rootdir)
(list (file-namestring rootdir))
(let (repo-list)
(dolist (dir (inferior-shell:run/lines `(ls ,rootdir)) repo-list)
(when (is-repo-p (merge-pathnames-to-string rootdir dir))
(setf repo-list (append repo-list (list dir))))))))
(defun set-remote (local-repo remote-repo &optional remote branch)
"Bind the local repo, REPO, to the remote REMOTE-REPO."
(let ((remote-target (or remote "origin")))
(progn
(inferior-shell:run/nil `(progn
(cd ,local-repo)
(git remote add ,remote-target ,remote-repo)))
(when branch
(inferior-shell:run/nil `(progn
(cd ,local-repo)
(git fetch ,remote)
(git branch ,branch)
(git checkout ,branch)
(git push ,remote ,branch)))))))
(defun make-remote-hash (repo-list repo-url-list &optional (operation #\o))
"Build a hash map with one entry for each element of REPO-LIST."
(when (member operation '(#\b #\o))
(let ((repos-hash (make-hash-table :test 'EQUAL)))
(dotimes (repo-i (length repo-list) repos-hash)
(setf (gethash (nth repo-i repo-list) repos-hash)
(list (nth repo-i repo-url-list) operation))))))
(defun make-git-repo (repo-dir url)
"Initialize REPO-DIR as a git repository, following URL."
(inferior-shell:run/nil `(progn
(cd ,repo-dir)
(git init)
(echo "*~" >> .gitignore)
(git remote add origin ,url))))
(defun remotes-count (repo)
"Counts the number of remotes in the REPO."
(length (inferior-shell:run/lines `(progn
(cd ,repo)
(git remote))
:on-error nil)))
(defun branches-count (repo)
"Counts the number of remotes in the REPO."
(length (inferior-shell:run/lines `(progn
(cd ,repo)
(git branch))
:on-error nil)))
(defun get-status-detail (repo)
"Get all the information related to the status of REPO.
This use the command:
#begin_example
git status -b --porcelain=v2
#end_example"
(let ((repo-status (inferior-shell:run/lines `(progn
(cd ,repo)
(git status -b --porcelain=v2))))
(state :INIT))
(do ((stat (str:split " " (first repo-status)))
(repo-statistics (make-hash-table)))
((or (eq state :ERROR) (eq state :END) (null stat)) repo-statistics)
(cond
((eq state :INIT)
(progn
(setf (gethash :untracked repo-statistics) 0)
(setf (gethash :modified repo-statistics) 0)
(setf (gethash :unmerged repo-statistics) 0)
(setf state :ADD)))
((eq state :READ)
(progn
(setf repo-status (cdr repo-status))
(if (null repo-status)
(setf state :END)
(progn
(setf stat (str:split " " (first repo-status)))
(setf state :ADD)))))
((eq state :ADD)
(progn
(cond
((string= (first stat) "#")
(cond ((string= (second stat) "branch.ab")
(setf (gethash :commits repo-statistics (make-commits-stat))
(make-commits-stat :ahead (parse-integer (third stat))
:behind (parse-integer (fourth stat)))))
((string= (second stat) "branch.head")
(setf (gethash :branch repo-statistics "") (third stat)))))
((string= (first stat) "1")
(incf (gethash :modified repo-statistics)))
((string= (first stat) "2")
(incf (gethash :modified repo-statistics)))
((string= (first stat) "u")
(incf (gethash :unmerged repo-statistics)))
((string= (first stat) "?")
(incf (gethash :untracked repo-statistics))))
(setf state :READ)))))))
(defun normalize-git-repos (rootdir remotes-hash)
"Ensure that all repos in ROOTDIR are configured the same way.
REMOTE-HASH is a hash table specifying what to do for each repositories and there information."
(dolist (dir (inferior-shell:run/lines `(ls ,rootdir)))
(let ((fullpath (reve-workshop.tools:merge-pathnames-to-string rootdir dir)))
(if (is-repo-p fullpath)
(unless (has-remote-p fullpath)
(let ((remote-data (gethash dir remotes-hash)))
(when remote-data
(cond ((equal (second remote-data) #\o)
(progn
(set-remote fullpath (first remote-data))
(inferior-shell:run/nil `(progn
(cd ,fullpath)
(git push -u origin --all)))))
((equal (second remote-data) #\b)
(set-remote fullpath (first remote-data) "neo" "neo"))
))))
(progn
(let ((remote-data (gethash dir remotes-hash)))
(when remote-data
(cond ((equal (second remote-data) #\o)
(progn
(make-git-repo fullpath (first remote-data))
;; (set-remote fullpath (first remote-data))
(inferior-shell:run/nil `(progn
(cd ,fullpath)
(git push -u origin --all)))))
((equal (second remote-data) #\b)
(progn
(make-git-repo fullpath (first remote-data))
(set-remote fullpath (first remote-data) "neo" "neo")))))))))))
(defun repository-statistics (repo-dir)
"Return a REPO-STAT object containing statistics about REPO-DIR.
If =REPO-DIR= is not a git repository, then =REPO-STAT::IS-REPO= will be
/nil/ and all other fields set to there default values. Else
=REPO-STAT::IS-REPO= will be /T/ and each field of the object will be
filled with the statistics computed from the information gather with
the available git commands."
(let ((stat (make-repo-stat))
(repo-status-detail))
(progn
(if (not (is-repo-p repo-dir))
(setf (repo-stat-is-repo stat) nil)
(progn
(setf repo-status-detail (get-status-detail repo-dir))
(setf (repo-stat-is-repo stat) t)
(setf (repo-stat-remotes stat) (remotes-count repo-dir))
(setf (repo-stat-branches stat) (branches-count repo-dir))
(setf (repo-stat-branch stat) (gethash :branch repo-status-detail ""))
(setf (repo-stat-untracked stat) (gethash :untracked repo-status-detail 0))
(setf (repo-stat-unmerged stat) (gethash :unmerged repo-status-detail 0))
(setf (repo-stat-modified stat) (gethash :modified repo-status-detail 0))
(setf (repo-stat-commits stat) (gethash :commits repo-status-detail (make-commits-stat)))))
stat)))
;; (with-childs-dir-of "/home/roland/codes/reve/conf.private.d/" (git status))
;; (inferior-shell:run/lines '(progn
;; (for repo in {repo1,repo2,repo3,repo4})
;; (do)
;; (cd $ROOTDIR/repo1)
;; (git status)
;; (done)
;; ))
;; (defmacro with-childs-dir-of (root &body body)
;; (let ((child-dir (gensym))
;; (cmd-list (gensym)))
;; (progn
;; (setf cmd-list (apply #'append (lambda (repo) ()))))
;; ;; `(dolist (,child-dir (inferior-shell:run/lines '(ls ,root)))
;; ;; ,@body)
;; ))
| 9,212 | Common Lisp | .lisp | 192 | 35.083333 | 103 | 0.529909 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 3d7f45909bb878e5d33e5700bfda7d6b381e09564073f3d1144cdbe08d87a1ba | 39,751 | [
-1
] |
39,754 | xyz.revecloud.re.asd | REve-Workshop_xyz_revecloud_re_cl/xyz.revecloud.re.asd | (asdf:defsystem "xyz.revecloud.re"
:version "0.1.0"
:author "Roland Everaert"
:license ""
:depends-on (:xyz.revecloud.re.tools
:xyz.revecloud.re.logging
:xyz.revecloud.re.is)
;; :components ((:module "src"
;; :components
;; ((:file "git")
;; (:file "tools"))))
:description "REVE Workshop environment."
:in-order-to ((test-op (test-op "xyz.revecloud.re/tests"))))
(asdf:defsystem "xyz.revecloud.re/tests"
:author "Roland Everaert"
:license ""
:depends-on ("xyz.revecloud.re"
"rove")
:components ((:module "tests"
:components
((:file "main"))))
:description "Test system for reve-workshop"
:perform (test-op (op c) (symbol-call :rove :run c)))
| 854 | Common Lisp | .asd | 23 | 29.869565 | 62 | 0.533735 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 2d18f54db6d89c95f2c4d603deedf7d5bd4fd824c6e75afbf3c6e46709db58be | 39,754 | [
-1
] |
39,755 | xyz.revecloud.re.logging.test.asd | REve-Workshop_xyz_revecloud_re_cl/logging/xyz.revecloud.re.logging.test.asd | (asdf:defsystem "xyz.revecloud.re.logging/tests"
:author "Roland Everaert"
:license ""
:depends-on ("xyz.revecloud.re.logging"
"rove")
:components ((:module "tests"
:components
((:file "main"))))
:description "Test system for reve-workshop lisp logging system."
:perform (test-op (op c) (symbol-call :rove :run c)))
| 409 | Common Lisp | .asd | 10 | 30.6 | 69 | 0.566416 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 9a17e4267864beb95b515b012295f5ec19899f71d23f5a00a735fd3bf85e9906 | 39,755 | [
-1
] |
39,756 | xyz.revecloud.re.logging.asd | REve-Workshop_xyz_revecloud_re_cl/logging/xyz.revecloud.re.logging.asd | (asdf:defsystem "xyz.revecloud.re.logging"
:version "0.1.0"
:author "Roland Everaert"
:license ""
;; :depends-on (:str)
:components ((:file "builder"))
:description "REVE Workshop lisp logging system."
:in-order-to ((test-op (test-op "xyz.revecloud.re.logging/tests"))))
| 299 | Common Lisp | .asd | 8 | 32.875 | 72 | 0.656357 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 751667a35d8e35ace2ed10884be0b0de2bdc77de870ed725ff19e1f121d28baa | 39,756 | [
-1
] |
39,757 | xyz.revecloud.re.tools.test.asd | REve-Workshop_xyz_revecloud_re_cl/tools/xyz.revecloud.re.tools.test.asd | (asdf:defsystem "xyz.revecloud.re.tools/tests"
:author "Roland Everaert"
:license ""
:depends-on ("xyz.revecloud.re.tools"
"rove")
:components ((:module "tests"
:components
((:file "main"))))
:description "Test system for reve-workshop tools."
:perform (test-op (op c) (symbol-call :rove :run c)))
| 391 | Common Lisp | .asd | 10 | 28.8 | 57 | 0.551181 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 17068096f72fe271a2df48633271f8346a58ccd50c1b6c770fad419aa154791b | 39,757 | [
-1
] |
39,758 | xyz.revecloud.re.tools.asd | REve-Workshop_xyz_revecloud_re_cl/tools/xyz.revecloud.re.tools.asd | (asdf:defsystem "xyz.revecloud.re.tools"
:version "0.1.0"
:author "Roland Everaert"
:license ""
;; :depends-on (:xyz.revecloud.re.tools.tools)
:components ((:file "misc")
(:file "cabs"))
:description "REVE Workshop tools."
:in-order-to ((test-op (test-op "xyz.revecloud.re.tools/tests"))))
| 335 | Common Lisp | .asd | 9 | 31.222222 | 70 | 0.616564 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 9351d273c9fa5248216a2f1260de417fda01f369b5a19da4a5334402cabb35cf | 39,758 | [
-1
] |
39,759 | xyz.revecloud.re.is.asd | REve-Workshop_xyz_revecloud_re_cl/is/xyz.revecloud.re.is.asd | (asdf:defsystem "xyz.revecloud.re.is"
:version "0.1.0"
:author "Roland Everaert"
:license ""
;; :depends-on (:fact-base :str)
:components (;; (:file "define")
(:file "tree"))
:description "REVE Workshop information system."
:in-order-to ((test-op (test-op "xyz.revecloud.re.is/tests"))))
| 333 | Common Lisp | .asd | 9 | 31 | 67 | 0.604938 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 2339a7cd7066d722a68c3f122e95b7240eea6749e3f29792f76d78bf4ddcac14 | 39,759 | [
-1
] |
39,760 | xyz.revecloud.re.is.test.asd | REve-Workshop_xyz_revecloud_re_cl/is/xyz.revecloud.re.is.test.asd | (asdf:defsystem "xyz.revecloud.re.is/tests"
:author "Roland Everaert"
:license ""
:depends-on ("xyz.revecloud.re.is"
"rove")
:components ((:module "tests"
:components
((:file "main"))))
:description "Test system for reve-workshop information system."
:perform (test-op (op c) (symbol-call :rove :run c)))
| 398 | Common Lisp | .asd | 10 | 29.5 | 68 | 0.556701 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | e7e93980599e65cc7ad1873c508e84d67682bd3d68512fd41172141c7238e9b8 | 39,760 | [
-1
] |
39,769 | .dir-locals.el | REve-Workshop_xyz_revecloud_re_cl/.dir-locals.el | ((nil . ((reve:license-abbreviation . "GNU AGPL")
(reve:project-version . "0.0.1")
(reve:author-initial . "RE")
(user-mail-address . "[email protected]")
(reve:short-license . "This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>."))))
| 861 | Common Lisp | .l | 14 | 57.785714 | 100 | 0.747929 | REve-Workshop/xyz.revecloud.re.cl | 0 | 0 | 3 | AGPL-3.0 | 9/19/2024, 11:46:54 AM (Europe/Amsterdam) | 893bfb629910faf30d9e64c30ccef2329ea6482f90785eb825681c3198c691ca | 39,769 | [
-1
] |
39,803 | eulersmethod.lisp | l4e21_LispExercises/eulersmethod.lisp |
;; Just a simple program designed to make euler's method recursive rather than by utilising loops
(defun acceleration (x)
;; Non-constant acceleration dependent on x
(+ (* -1 (expt x 3)) (* 2 (expt x 2)) (* 5 x) 3))
(defun eulermethod (x u accel tmax &optional (tacc 0) (tstep 1))
(cond ((= tmax tacc)
nil)
(t
(cons x (eulermethod (+ x (* u tstep)) (+ u (* (funcall accel x) tstep)) accel tmax (+ tacc tstep) tstep)))))
| 442 | Common Lisp | .lisp | 9 | 45.666667 | 111 | 0.654028 | l4e21/LispExercises | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 337ce5178da6160f8d880d8fb74ad05221a4c2670f7847344b40d23317303678 | 39,803 | [
-1
] |
39,820 | package.lisp | gabriel-barrett_Formality-CL/package.lisp | (defpackage #:formality
(:documentation "Formality implementation in Common Lisp.")
(:use #:cl)
(:nicknames #:fm)
(:export
#:cl->term-macro ; MACRO
#:term-type ; TYPE
#:term-type-p ; FUNCTION (PREDICATE)
#:cl->term ; FUNCTION
#:norm ; FUNCTION
#:whnf ; FUNCTION
#:equal-term ; FUNCTION
#:stringify ; FUNCTION
))
| 550 | Common Lisp | .lisp | 14 | 35.785714 | 62 | 0.401119 | gabriel-barrett/Formality-CL | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 7c04c2fa95d44d7bbe905981388ca45dc7de086900bb445974cc3bb755608179 | 39,820 | [
-1
] |
39,821 | pretty-print.lisp | gabriel-barrett_Formality-CL/pretty-print.lisp | (in-package #:formality)
(defun stringify (term)
(adt:match term-type term
((ver indx) (format nil "#~A" indx))
((ref name) (write-to-string name))
(typ "*")
((all eras self name bind body)
(format nil "~A~A(~A: ~A) ~A"
(if eras "∀" "Π")
(if (equal self "_") "" self)
name
(stringify bind)
(stringify (funcall body (ref (read-from-string self)) (ref (read-from-string name))))))
((lam eras name body)
(format nil "~A~A ~A"
(if eras "Λ" "λ")
name
(stringify (funcall body (ref (read-from-string name))))))
((app eras func argm)
(if eras
(format nil "<~A ~A>"
(stringify func)
(stringify argm))
(format nil "(~A ~A)"
(stringify func)
(stringify argm))))
((lat name expr body)
(format nil "$ ~A = ~A; ~A"
name
(stringify expr)
(stringify (funcall body (ref (read-from-string name))))))
((ann done expr type)
(format nil ":~A ~A"
(stringify type)
(stringify expr)))))
| 1,472 | Common Lisp | .lisp | 35 | 23.685714 | 110 | 0.387142 | gabriel-barrett/Formality-CL | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 038c76025849c5efb7553baa65e57b7ad3470b81122357dbea32d092315ed932 | 39,821 | [
-1
] |
39,822 | cl-to-fm.lisp | gabriel-barrett_Formality-CL/cl-to-fm.lisp | (in-package #:formality)
(adt:defdata erasure
(erase t))
(defun single-erase-reader (stream char)
(declare (ignore char))
(list (quote erase) (read stream t nil t)))
(set-macro-character #\! #'single-erase-reader)
(defun extract-eras (x) (adt:match erasure x ((erase x) x)))
;; (lam* eras (A B ...) body) expands to (lam eras "A" (lambda (A) (lam eras "B" (lambda (B) ...body...))))
(defmacro lam* (vars body)
(dolist (var (reverse vars))
(setf body
(let ((eras (typep var 'erasure)))
(when eras (setf var (extract-eras var)))
`(lam ,eras ,(write-to-string var) (lambda (,var) ,body)))))
body)
;; (app* func a b ...) expands to ...(app eras (app eras func a) b)...
(defmacro app* (func arg &rest args)
(dolist (arg (cons arg args))
(setf func
(let ((eras (typep arg 'erasure)))
(when eras (setf arg (extract-eras arg)))
`(app ,eras ,func ,arg))))
func)
(defmacro lat* (((name expr) &rest binds) body)
(dolist (bind (reverse (cons (list name expr) binds)))
(trivia:match bind
((list name expr)
(setf body
`(lat ,(write-to-string name) ,expr (lambda (,name) ,body))))
(_ (error "Malformed let binding."))))
body)
(defmacro all* (self name bind body)
(let ((eras (typep bind 'erasure)))
(when eras (setf bind (extract-eras bind)))
`(all
,eras
,(write-to-string self)
,(write-to-string name)
,bind
(lambda (,self ,name) ,body))))
;; Function that transforms simple CL lambda terms to FormalityCore terms
(defun cl->term (qcode &optional (names (make-hash-table)))
(setf names (alexandria:copy-hash-table names)) ;; to avoid side-effects
(trivia:match qcode
((list 'lambda args body)
(let ((traverse (lambda (arg)
(trivia:match arg
((list 'erase arg)
(unless (symbolp arg)
(error "Lambda arguments must be either symbols or erased symbols."))
(setf (gethash arg names) t) (erase arg))
((type symbol) (setf (gethash arg names) t) arg)
(_ (error "Lambda arguments must be either symbols or erased symbols."))))))
(macroexpand `(lam* ,(mapcar traverse args) ,(cl->term body names)))))
((cons 'lambda _) (error "Improper lambda expression."))
((list 'let binds body)
(macroexpand
`(lat* ,(mapcar
(lambda (bind)
(trivia:match bind
((list name expr)
;; Since let is not recursive, setf should come afterwards
(let ((res (list name (cl->term expr names))))
(setf (gethash name names) t)
res))
(_ (error "Malformed let binding."))))
binds)
,(cl->term body names))))
((cons 'let _) (error "Improper let expression."))
((list 'erase x) (erase (cl->term x names)))
((list 'all self (list name bind) body)
(macroexpand
(let* ((bind (cl->term bind names))
(ename (trivia:match name
((list 'erase ename)
(unless (symbolp ename)
(error "All arguments must be either symbols or erased symbols."))
(setf name ename)
(erase ename))
((type symbol) name)
(_ (error "All arguments must be either symbols or erased symbols."))))
(body (progn
(setf (gethash self names) t (gethash name names) t)
(cl->term body names))))
`(all* ,self ,name ,bind ,body))))
((cons 'all _) (error "Improper all expression."))
((list x '@ y) `(ann nil ,(cl->term x names) ,(cl->term y names)))
((cons x _)
(macroexpand `(app* ,@(mapcar (lambda (qcode) (cl->term qcode names)) qcode))))
((type integer) `(ver ,qcode))
('* 'typ)
((or 'lambda 'let 'all 'erase '@) (error (format nil "~A is a keyword." qcode)))
((type symbol)
(if (gethash qcode names) qcode `(ref (quote ,qcode))))
(_ (error "Cannot be translated to FormalityCore term."))))
;; Macro version of last function (runs at compile time)
(defmacro cl->term-macro (code) (cl->term code))
| 4,378 | Common Lisp | .lisp | 98 | 34.683673 | 107 | 0.548349 | gabriel-barrett/Formality-CL | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | cd009eac24d9b47a7a61932ae4267bd7d5801323ffdd9f94acd0029d5adb86b7 | 39,822 | [
-1
] |
39,823 | core.lisp | gabriel-barrett_Formality-CL/core.lisp | (in-package #:formality)
(adt:defdata term-type
"Data type for FormalityCore terms."
;; var indx
;; ref name
;; all eras self name bind body
;; lam eras name body
;; app eras func argm
;; let name expr body
;; ann done expr type
;; loc from upto expr
(ver integer)
(ref symbol)
typ
(all boolean string string term-type function)
(lam boolean string function)
(app boolean term-type term-type)
(lat string term-type function)
(ann boolean term-type term-type))
;; (defun term-type-p
(defun whnf (term defs &optional erased)
(adt:match term-type term
((ref name)
(if (gethash name defs)
(whnf (gethash name defs) defs erased)
(error (format nil "~A is undefined." name))))
((lam eras name body)
(if (and erased eras)
(whnf (funcall body (lam nil "" (lambda (x) x))) defs erased)
(lam eras name body)))
((app eras func argm)
(if (and erased eras)
(whnf func defs erased)
(let ((func (whnf func defs erased)))
(adt:match term-type func
((lam _ _ body)
(whnf (funcall body argm) defs erased))
(_
(app eras func argm))))))
((lat _ expr body) (whnf (funcall body expr) defs erased))
((ann _ expr _) (whnf expr defs erased))
(_ term)))
(defun hash (term &optional (dep 0))
(adt:match term-type term
((ver indx)
(if (< indx 0)
(format nil "^~d" (+ dep indx))
(format nil "#~d" indx)))
((ref name)
(format nil "$~A" name))
(typ
"type")
((all _ self _ bind body)
(let ((bind (hash bind dep))
(body (hash (funcall body (ver (- -1 dep)) (ver (- -2 dep))) (+ 2 dep))))
(concatenate 'string "π" self bind body)))
((lam _ _ body)
(let ((body (hash (funcall body (ver (- -1 dep))) (+ 1 dep))))
(concatenate 'string "λ" body)))
((app _ func argm)
(let ((func (hash func dep))
(argm (hash argm dep)))
(concatenate 'string "@" func argm)))
((lat _ expr body)
(let ((expr (hash expr dep))
(body (hash (funcall body (ver (- -1 dep))) (+ 1 dep))))
(concatenate 'string "$" expr body)))
((ann _ expr _)
(hash expr dep))))
(defun norm (term defs &optional erased (seen (make-hash-table)))
(let* ((head (whnf term defs erased))
(term_hash (hash term))
(head_hash (hash head)))
(if (or (gethash term_hash seen) (gethash head_hash seen)) term
(progn
(setf (gethash term_hash seen) t (gethash head_hash seen) t)
(adt:match term-type head
((all eras self name bind body)
(let ((bind (norm bind defs erased seen))
(body (lambda (s x) (norm (funcall body s x) defs erased seen))))
(all eras self name bind body)))
((lam eras name body)
(let ((body (lambda (x) (norm (funcall body x) defs erased seen))))
(lam eras name body)))
((app eras func argm)
(let ((func (norm func defs erased seen))
(argm (norm argm defs erased seen)))
(app eras func argm)))
(_ head))))))
;; Are two terms equal?
(defun equal-term (a b defs &optional (dep 0) (seen (make-hash-table :test 'equal)))
(let* ((a1 (whnf a defs t))
(b1 (whnf b defs t))
(ah (hash a1))
(bh (hash b1))
(id (format nil "~A==~A" ah bh)))
(when (or (equal ah bh) (gethash id seen)) (return-from equal-term t))
(setf (gethash id seen) t)
(adt:match term-type a1
((all a1-eras a1-self a1-name a1-bind a1-body)
(adt:match term-type b1
((all b1-eras b1-self b1-name b1-bind b1-body)
(setf a1-body (funcall a1-body (ver dep) (ver (+ dep 1))))
(setf b1-body (funcall b1-body (ver dep) (ver (+ dep 1))))
(and
(equal a1-eras b1-eras)
(equal a1-self b1-self)
(equal-term a1-bind b1-bind defs dep seen)
(equal-term a1-body b1-body defs (+ 2 dep) seen)))
(_ nil)))
((lam a1-eras a1-name a1-body)
(adt:match term-type b1
((lam b1-eras b1-name b1-body)
(setf a1-body (funcall a1-body (ver dep)))
(setf b1-body (funcall b1-body (ver dep)))
(and
(equal a1-eras b1-eras)
(equal-term a1-body b1-body defs (+ 1 dep) seen)))
(_ nil)))
((app a1-eras a1-func a1-argm)
(adt:match term-type b1
((app b1-eras b1-func b1-argm)
(and
(equal a1-eras b1-eras)
(equal-term a1-func b1-func defs dep seen)
(equal-term a1-argm b1-argm defs dep seen)))
(_ nil)))
((lat a1-name a1-expr a1-body)
(adt:match term-type b1
((lat b1-name b1-expr b1-body)
(setf a1-body (funcall a1-body (ver dep)))
(setf b1-body (funcall b1-body (ver dep)))
(and
(equal-term a1-expr b1-expr defs dep seen)
(equal-term a1-body b1-body defs (+ 1 dep) seen)))
(_ nil)))
(_ nil))))
| 5,115 | Common Lisp | .lisp | 137 | 29.19708 | 84 | 0.548692 | gabriel-barrett/Formality-CL | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 1e03c109e100a8d6fb34ff5df934cf4844b447a7a2432fabec76d52b883af2f4 | 39,823 | [
-1
] |
39,824 | formality.asd | gabriel-barrett_Formality-CL/formality.asd | (asdf:defsystem #:formality
:description "Formality implementation in Common Lisp."
:version "0.0.6"
:author "Gabriel Barreto <[email protected]>"
:license "GPLv3"
:depends-on (#:alexandria #:cl-algebraic-data-type #:trivia)
:serial t
:components ((:static-file "LICENSE.txt")
(:file "package")
(:file "core")
(:file "cl-to-fm")
(:file "pretty-print")))
| 443 | Common Lisp | .asd | 12 | 29.75 | 62 | 0.610209 | gabriel-barrett/Formality-CL | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 5ddedb2179c1f75710bdf13bbda722101f8fd6273a7b3ea496841201bd4c67a5 | 39,824 | [
-1
] |
39,845 | solver.lisp | O-Jun-S_CL_caesar/solver.lisp | ; String to ascii list.
(defun str-code (str)
(mapcar #'char-code
(coerce str 'list)))
; Ascii list to string.
(defun dec-code (asc)
(coerce (mapcar #'code-char
asc)
'string))
; String shift function.
(defun ascii-shift (lst val)
(mapcar
(lambda (chr)
(setq plused-ascii (+ chr val))
(cond ((<= 65 chr 90)
(cond ((< plused-ascii 65) (incf plused-ascii 26)
plused-ascii)
((> plused-ascii 90) (decf plused-ascii 26)
plused-ascii)
(t plused-ascii)))
((<= 97 chr 122)
(cond ((< plused-ascii 97) (incf plused-ascii 26)
plused-ascii)
((> plused-ascii 122) (decf plused-ascii 26)
plused-ascii)
(t plused-ascii)))
(t chr)))
lst))
; Shift str for val.
(defun solve (str val)
(princ (dec-code (ascii-shift (str-code str) val))))
; Shift str from 1 to 26.
(defun solve-all (str)
(let ((ascii (str-code str)))
(loop for i
from 1
below 26
do(progn;
(princ i)
(princ ">> ")
(princ (dec-code (ascii-shift ascii i)))
(fresh-line)))))
| 1,345 | Common Lisp | .lisp | 42 | 20.857143 | 63 | 0.469954 | O-Jun-S/CL_caesar | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 95b47ccc5179cf21afb8a31187495f34fcde8068f1d18a659c98b02bd222fe82 | 39,845 | [
-1
] |
39,862 | server.lisp | cmatzenbach_cl-webserver-api-skeleton/server.lisp | (in-package :server)
;; create variable to store acceptor
(defvar *acceptor* nil)
;; start server
(defun start-server ()
(stop-server)
(hunchentoot:start (setf *acceptor*
(make-instance 'easy-routes:easy-routes-acceptor
:port 5000))))
;; function to stop server
(defun stop-server ()
(when *acceptor*
(when (hunchentoot:started-p *acceptor*)
(hunchentoot:stop *acceptor*))))
;; try to set global server settings here
;; (setf (hunchentoot:header-out "Access-Control-Allow-Origin") "*")
;; (setf (hunchentoot:header-out "Access-Control-Allow-Methods") "POST,GET,OPTIONS,DELETE,PUT")
;; (setf (hunchentoot:header-out "Access-Control-Max-Age") 1000)
;; (setf (hunchentoot:header-out "Access-Control-Allow-Headers") "x-requested-with, Content-Encoding, Content-Type, origin, authorization, accept, client-security-token")
;; (setf (hunchentoot:header-out "Content-Type") "application/json")
;; global vars
(defvar *page-views* 0)
;; simple route for testing front-end axios calls
(easy-routes:defroute project ("/matzy" :method :get) (home)
(setf (hunchentoot:content-type*) "text/plain")
(format nil "~a" home))
;; route to use jonathan to send JSON data back to FE
(easy-routes:defroute testjson ("/testjson" :method :get
:decorators (@json @allow-origin)) ()
(jonathan.encode:to-json '(:name "Common Lisp" :born 1984 :impls (SBCL KCL))))
;; of course this works but the loop example from the README doesn't
(easy-routes:defroute testgetdata ("/testgetdata" :method :get) ()
(dbi:with-connection (conn :mysql :database-name "fantasy_football" :host "conway-ff1.cctpeqxowyn7.us-east-2.rds.amazonaws.com" :port 3306 :username "matzy" :password "Paintitred1")
(let* ((query (dbi:prepare conn "SELECT * FROM Users"))
(query (dbi:execute query)))
(format nil "~a" (dbi:fetch query)))))
;; (loop for row = (dbi:fetch query)
;; while row
;; do (format nil "~A~%" row))
;; FINALLY got it to work - does not look like it's opening extra connections either
(easy-routes:defroute myusername ("/myusername" :method :get) ()
(let* ((query (dbi:prepare db:*connection* "SELECT * FROM Users WHERE username = ?"))
(results (dbi:execute query "cmatzenbach")))
(format nil "~a" (dbi:fetch results))))
;; (loop for row = (dbi:fetch query)
;; while row
;; do (format nil "~a~%" row))
;; second hack at it, from SO
;; https://stackoverflow.com/questions/31745456/cl-dbi-query-mysql-from-sbcl-with-error-illegal-utf-8-character-starting-at-p
(easy-routes:defroute myuser2 ("/testusertwo") ()
(setf query (dbi:prepare db:*connection*
"SELECT * FROM Users"))
(setf result (dbi:execute query))
(loop for row = (dbi:fetch result)
while row
do (format t "~A~%" row)))
;; probably ideal query response, but persistent connection required, so prob need funcs above
;; also hangs for awhile - all in one go query relying on persistent connection
(easy-routes:defroute createuser ("/createuser" :method :post) (&post user pass team)
;; (type-of user)
(trace dbi:do-sql)
(dbi:do-sql db:*connection*
"INSERT INTO Users (username, password, team_name) VALUES (?, ?, ?)"
(list user pass team))
;; (dbi:do-sql db:*connection*
;; "INSERT INTO Users (username, password, team_name) VALUES (?, ?, ?)"
;; (list 0))
(untrace dbi:do-sql)
(format nil " user: ~a | pass: ~a | team-two: ~a" user pass team))
;; format nil doesn't go to stdout, but rather prints to page (output stream?)
(easy-routes:defroute printpath ("/print") (x y)
(format nil "~a ~a" x y))
(easy-routes:defroute name ("/foo/:x") (y &get z)
(format nil "x: ~a y: ~a z: ~a" x y z))
;; first ever route!
(easy-routes:defroute yo ("/yo") (name)
(setf (hunchentoot:content-type*) "text/plain")
(format nil "Hey~@[ ~A~]!" name))
;; test getting data from GET vars in url
(easy-routes:defroute getvars ("/getvars") (x &get y z)
(format nil "x: ~a y: ~a z: ~a" x y z))
(easy-routes:defroute printconn ("/printconn") ()
(format nil "x: ~a" db:*connection*))
;; route to store page views
(easy-routes:defroute views ("/store_page_views") ()
(setf (hunchentoot:content-type*) "text/plain")
;; for now, print out that page is viewed, later store in database
(incf *page-views*)
;; TODO doesn't print to page for some reason
(format nil "~d" *page-views*))
;; decorators
(defun @json (next)
(setf (hunchentoot:content-type*) "application/json")
(funcall next))
;; custom decorator to set Access-Control-Allow-Origin
(defun @allow-origin (next)
(setf (hunchentoot:header-out :Access-Control-Allow-Origin hunchentoot:*reply*) "*")
(funcall next))
;; TODO Figure out how to build this decorator with cl-di - example is for postmodern
;; (defun @db (next)
;; (db:*connection*
;; (funcall next)))
(defun @html (next)
(setf (hunchentoot:content-type*) "text/html")
(funcall next))
| 5,004 | Common Lisp | .lisp | 105 | 44.009524 | 183 | 0.67562 | cmatzenbach/cl-webserver-api-skeleton | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 240b1c60826fc2de631900f01bcac72688f17c1e43146d18fa008e756b971c64 | 39,862 | [
-1
] |
39,863 | packages.lisp | cmatzenbach_cl-webserver-api-skeleton/packages.lisp | (defpackage :server
(:use cl)
(:export
:start-server
:stop-server))
(defpackage :db
(:export
:connect-db
:disconnect-db
:create-users-table))
| 159 | Common Lisp | .lisp | 10 | 13.2 | 23 | 0.70068 | cmatzenbach/cl-webserver-api-skeleton | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 23d2c13ad61a59e1f2ca66339d011dd64950d1b1900b390d99a5b2373406124d | 39,863 | [
-1
] |
39,864 | conway-ff-api.asd | cmatzenbach_cl-webserver-api-skeleton/conway-ff-api.asd | (asdf:defsystem "conway-ff-api"
:description "Simple app for conway's class"
:version "0.0.1"
:depends-on ("hunchentoot" "easy-routes" "jonathan" "mito")
:components ((:file "packages")
(:file "db" :depends-on ("packages"))
(:file "server" :depends-on ("packages"))
(:file "main" :depends-on ("server"))))
| 334 | Common Lisp | .asd | 8 | 37.25 | 60 | 0.631902 | cmatzenbach/cl-webserver-api-skeleton | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | de723a0431faf87845dc092ae818cff14e1293d200695abb85d9eb3d8256aade | 39,864 | [
-1
] |
39,867 | Makefile | cmatzenbach_cl-webserver-api-skeleton/Makefile | app_dir := $(dir $(CURDIR))
all: container
container:
sudo docker build -t conway-ff-api .
run: container
sudo docker run -a stdin -a stdout -a stderr -i -t conway-ff-api
clean:
sudo docker rm $(docker ps -a -q)
sudo docker rmi $(docker images -q)
| 257 | Common Lisp | .l | 9 | 26.555556 | 65 | 0.713115 | cmatzenbach/cl-webserver-api-skeleton | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 27dec17b2a6e2f094346fe9e92f51de7fa16fb9ecd38dbeda1626d375f736ba0 | 39,867 | [
-1
] |
39,868 | Dockerfile | cmatzenbach_cl-webserver-api-skeleton/Dockerfile | # Chose this ubuntu base image because its small and optimized for Docker(ness)
FROM phusion/baseimage:latest-amd64
# Installing what I need from ubuntu to do the job.
# - wget to download stuff from the web
# -- curl gave me a 301 trying to download build app so I swiched to wget
# - sbcl and build-essentials - To build the version of sbcl downloaded
# -- the sbcl in ubuntu is usually a bit dated that why we download what we want
# - libev-dev - is used by the woo http server that we are using for our example
#
RUN apt update &&\
apt-get install -y sbcl wget build-essential time libev-dev rlwrap
# Downloading, compiling and installing our prefered version of SBCL
RUN cd /tmp && \
wget https://ufpr.dl.sourceforge.net/project/sbcl/sbcl/2.0.5/sbcl-2.0.5-source.tar.bz2 && \
tar jxvf sbcl-2.0.5-source.tar.bz2 && \
cd /tmp/sbcl-2.0.5 && \
sh ./make.sh && \
sh ./install.sh && \
rm -rf /tmp/sbcl*
# Install quicklisp
RUN curl -k -o /tmp/quicklisp.lisp 'https://beta.quicklisp.org/quicklisp.lisp' && \
sbcl --noinform --non-interactive --load /tmp/quicklisp.lisp --eval \
'(quicklisp-quickstart:install :path "~/quicklisp/")' && \
sbcl --noinform --non-interactive --load ~/quicklisp/setup.lisp --eval \
'(ql-util:without-prompting (ql:add-to-init-file))' && \
echo '#+quicklisp(push "/src" ql:*local-project-directories*)' >> ~/.sbclrc && \
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
RUN sbcl --noinform --non-interactive --eval '(ql:quickload :swank)'
# Make a dir for my source on the docker image
RUN mkdir /src/
# Copy project directory to new directory on docker container
COPY . /src/
#ADD ./conway-ff-api.asd /src/
# Create symlink to ~/quicklisp/local-projects for .asd file
RUN ln -s /src/conway-ff-api/conway-ff-api.asd ~/quicklisp/local-projects/conway-ff-api.asd
# Let quicklisp do its thing
RUN sbcl --noinform --non-interactive --eval '(ql:quickload :conway-ff-api)'
# Expose the port that hunchentoot is listening on
EXPOSE 5000
# Expose the port that swank is listening on
EXPOSE 4005
# When then docker is run this is called to load our toy app.
CMD sleep 0.05; rlwrap sbcl --eval '(ql:quickload :swank)' \
--eval "(require :swank)" \
--eval "(setq swank::*loopback-interface* \"0.0.0.0\")" \
--eval "(swank:create-server :port 4005 :style :spawn :dont-close t)" \
--eval "(ql:quickload :conway-ff-api)"
| 2,415 | Common Lisp | .l | 47 | 48.787234 | 95 | 0.704237 | cmatzenbach/cl-webserver-api-skeleton | 0 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:47:02 AM (Europe/Amsterdam) | 5d91239b587fd56294199bad4992a976c28a9378aa24e85d3600bb539d164e66 | 39,868 | [
-1
] |
39,884 | donut.lisp | theRealZauberwuerfel_donut-math/donut.lisp | (deftype fuzzy-float () '(float 0.0 1.0))
(defconstant +theta-spacing+ (the fuzzy-float 0.07))
(defconstant +phi-spacing+ (the fuzzy-float 0.02))
(defconstant +R1+ (the fuzzy-float 1.0))
(defconstant +R2+ (the float 2.0))
(defconstant +K2+ (the float 5.0))
(defconstant +K1+ (the float (/ (* *screen-width* +K2+ 3)
(* 8 (+ +R1+ +R2+)))))
(defun render-frame (A B)
(declare (type float A B))
(let ((cos[A] (cos A)) (sin[A] (sin A))
(cos[B] (cos B)) (sin[B] (sin B)))
(let ((output (make-array '(#.*screen-width* #.*screen-height*)
:element-type 'character
:initial-element #\Space))
(zbuffer (make-array '(#.*screen-width* #.*screen-height*)
:element-type 'fixnum
:initial-element 0))
;; literally 2*PI
(tau (the float 6.283185)))
(loop
:named outer
:for theta :from 0.0 :by +theta-spacing+
:while (< theta tau)
:do (let ((cos[theta] (cos theta))
(sin[theta] (sin theta)))
(loop
:named inner
:for phi :from 0.0 :by +phi-spacing+
:while (< phi tau)
:do (let ((cos[phi] (cos phi))
(sin[phi] (sin phi)))
(let ((circle-x (+ +R2+ (* +R1+ cos[theta])))
(circle-y (* +R1+ sin[theta])))
(let* ((x (- (* circle-x (+ (* cos[B] cos[phi])
(* sin[A] sin[B] sin[phi])))
(* circle-y cos[A] sin[B])))
(y (+ (* circle-x (- (* sin[B] cos[phi])
(* sin[A] cos[B] sin[phi])))
(* circle-y cos[A] cos[B])))
(z (+ +K2+ (* cos[A] circle-x sin[phi]) (* circle-y sin[A])))
(1/z (/ z)))
(let ((x-proj (+ (/ *screen-width* 2)
(* +K1+ 1/z x)))
(y-proj (- (/ *screen-height* 2)
(* +K1+ 1/z y))))
(let ((L (+ (* cos[phi] cos[theta] sin[B])
(- (* cos[A] cos[theta] sin[phi]))
(- (* sin[A] sin[theta]))
(* cos[B] (- (* cos[A] sin[theta])
(* cos[theta] sin[A] sin[phi]))))))
(when (> L 0)
(when (> 1/z (aref zbuffer x-proj y-proj))
(setf (aref zbuffer x-proj y-proj) 1/z)
(let ((luminance-index (* L 8)))
(setf (aref output x-proj y-proj)
(svref ".,-~:;=!*#$@" luminance-index)))))))))))))
(format t "\x1b[H")
(loop
:for j :from 0 :by 1
:while (< j *screen-height*)
:do (loop
:for i :from 0 :by 1
:while (< i *screen-width*)
:do (format t "~c" (aref output i j)))
(format t "~%")))))
| 3,402 | Common Lisp | .lisp | 66 | 30.060606 | 92 | 0.352041 | theRealZauberwuerfel/donut-math | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:11 AM (Europe/Amsterdam) | 36359bcbe53c5545f67f07f706c393bdb97bf8c679ca27ddb074d237f73aaf54 | 39,884 | [
-1
] |
39,901 | eql.lisp | sam-falvo_equilibrium-cl/eql.lisp | ;;;; Equilibrium/CL
;;;;
;;;; A port of a video game I once wrote in 2010 in Forth, for the SDL
;;;; 1.2 library. I wonder how easy it will be to port the software
;;;; to the Common Lisp environment?
;;;;
;;;; NOTE NOTE NOTE: You cannot run this software from the SLIME IDE.
;;;; SLIME keeps the SBCL (or whatever) instance running indefinitely;
;;;; SDL2 **expects** the process to die after SDL_Quit() is called,
;;;; because it fails to clean up all the resources that are acquired
;;;; by SDL_Init() and/or other SDL2 functions. This can be observed
;;;; by noting the first time you run the program, things seems to
;;;; work well; but the second time around, you get SDL_RC_ERROR
;;;; errors when attempting to initialize the library.
(ql:quickload :sdl2)
;;; Game Configuration
(defparameter *n-opponents* 4
"Number of on-screen opponents.")
(defparameter *acceleration* 1/2
"Acceration of a player when WASD is pressed.")
;;; State of the game's universe. You have a playfield, a player,
;;; a handful of opponents, and so forth.
(defparameter *playfield* nil)
(defparameter *player* nil)
(defparameter *opponents* nil)
(defparameter *sparks* nil)
;;; Visible objects are those things which the game player
;;; can see on the screen.
;;;
;;; Note that because something is visible does not mean it
;;; has a *location* on the screen. The playfield and
;;; score, for example, are fixed on the display. They do not
;;; move; ergo, they have no need for an origin coordinate.
;;;
;;; Visible objects, however, *do* have a width and height.
(defclass visible ()
((w :initarg :w :reader w :initform (error ":w required"))
(h :initarg :h :reader h :initform (error ":h required"))
(color :initarg :color :accessor color :initform '(255 255 255 255))))
(defgeneric init-visible (p))
(defgeneric paint-with-renderer (v r))
(defmethod initialize-instance :after ((v visible) &key)
; This hook is required so that constructors of VISIBLE
; objects don't conflict. Consider the OPPONENT class, which
; is a subclass of PLAYER, and that is a subclass of VISIBLE.
; The order of after-methods is OPPONENT, PLAYER, and then
; VISIBLE. So, any initialization needed by OPPONENT will be
; undone by PLAYER's initialization code, etc.
(init-visible v))
;;; Particle objects can be repositioned on the screen and have
;;; a velocity. They optionally can collide with things.
(defclass particle ()
((dx :accessor dx :initform 0)
(dy :accessor dy :initform 0)
(left :initarg :left :accessor left)
(top :initarg :top :accessor top)))
(defgeneric move-object (p))
(defgeneric move-to (p x y))
(defgeneric border-collision-consequence (p x y pf))
(defgeneric handle-bumps (p1 p2))
(defmethod handle-bumps (p1 p2)
; unless otherwise specified, it is an error to 'bump'
; one object against another unless they're both players
; or opponents.
(error "should never be called."))
(defmethod move-to ((p particle) x y)
(let ((x (floor x))
(y (floor y)))
(setf (left p) x)
(setf (top p) y))
(values))
(defmethod move-object ((p particle))
(let ((new-x (+ (left p) (dx p)))
(new-y (+ (top p) (dy p))))
(move-to p new-x new-y))
(values))
;;; A controllable object can be directed somehow by an
;;; intelligence, natural or artificial. Controllable
;;; entities implies that they are particle-like somehow.
(defclass controllable ()
((force :accessor force :initform nil)
(ax :accessor ax :initform 0.0)
(ay :accessor ay :initform 0.0)))
(defun accelerate (c direction)
(setf (force c) (adjoin direction (force c))))
(defun decelerate (c direction)
(setf (force c) (remove direction (force c))))
(defgeneric jerk (c))
(defmethod jerk ((c controllable))
"Apply a change in acceleration."
(mapcar #'(lambda (dir)
(cond
((eq dir :up) (decf (ay c) *acceleration*))
((eq dir :down) (incf (ay c) *acceleration*))
((eq dir :left) (decf (ax c) *acceleration*))
((eq dir :right) (incf (ax c) *acceleration*))))
(force c))
(values))
;;; The playfield represents the most distantly visible object
;;; on the screen. It is literally the field on which the
;;; other actors in the game reside upon.
(defclass playfield (visible)
())
; nothing to initialize.
(defmethod init-visible ((p playfield)))
(defmethod paint-with-renderer ((p playfield) r)
(sdl2:set-render-draw-color r 0 0 0 255)
(sdl2:render-clear r)
(apply #'sdl2:set-render-draw-color (append (list r) (color p)))
(sdl2:render-draw-rect r (sdl2:make-rect 0 0 (w p) (h p)))
(values))
;;; Player objects represent the human player or one or more
;;; computer-driven opponents. The human player is always
;;; white; opponents' colors are chosen randomly, such that
;;; they should always be visible and always be distinct from
;;; the human player.
(defun random-color (&key (range 128) (offset 64))
(let ((r (+ (random range *random-state*) offset))
(g (+ (random range *random-state*) offset))
(b (+ (random range *random-state*) offset)))
(list r g b 255)))
(defun random-xy (dimension length)
(let* ((xy (random dimension *random-state*))
(constrained-xy (max 0 (- xy length))))
constrained-xy))
(defun center-xy (dimension length)
(/ (- dimension length) 2))
(defun right (p)
(+ (left p) (w p)))
(defun bottom (p)
(+ (top p) (h p)))
(defun h-rebound (p)
(setf (dx p) (- (dx p))))
(defun v-rebound (p)
(setf (dy p) (- (dy p))))
(defun avg (a b)
(floor (/ (+ a b) 2)))
(defclass player (controllable particle visible)
((w :initform 16 :reader w) ; override visible
(h :initform 16 :reader h) ; override visible
(pf :initarg :on-playfield :initform nil :reader playfield-of)))
(defclass opponent (player)
())
(defmethod init-visible ((p player))
(let ((pf (playfield-of p)))
(move-to p (center-xy (w pf) (w p))
(center-xy (h pf) (h p)))))
(defmethod init-visible ((o opponent))
(setf (color o) (random-color))
(setf (dx o) (- (random 7 *random-state*) 3))
(setf (dy o) (- (random 7 *random-state*) 3))
(move-to o (random-xy (w (playfield-of o)) (w o))
(random-xy (h (playfield-of o)) (h o))))
(defmethod paint-with-renderer ((p player) r)
(let ((left (left p))
(top (top p))
(right (right p))
(bottom (bottom p))
(color (color p)))
(apply #'sdl2:set-render-draw-color (append (list r) color))
(sdl2:render-draw-line r left top right top)
(sdl2:render-draw-line r right top right bottom)
(sdl2:render-draw-line r right bottom left bottom)
(sdl2:render-draw-line r left bottom left top)
(values)))
(defmethod border-collision-consequence ((p player) x y pf)
(declare (ignore p))
(make-sparks x y pf))
(defun preserve-momentum (p1 p2)
(rotatef (dx p1) (dx p2))
(rotatef (dy p1) (dy p2)))
(defun overlap (p1 p2)
"Answers the common rectangle between two players. If no overlap,
the coordinates of the rectangle returned will be (partially) backwards."
(let ((left (max (left p1) (left p2)))
(top (max (top p1) (top p2)))
(right (min (right p1) (right p2)))
(bottom (min (bottom p1) (bottom p2))))
(list left top right bottom)))
(defun valid-p (left top right bottom)
(and (<= left right) (<= top bottom)))
(defmethod handle-bumps ((p1 player) (p2 player))
(unless (eq p1 p2)
(destructuring-bind (left top right bottom)
(overlap p1 p2)
(when (valid-p left top right bottom)
(preserve-momentum p1 p2)
(make-sparks (avg left right) (avg top bottom) (playfield-of p1))
(move-object p1)
(move-object p2)
)))
(values))
(defmethod jerk :after ((p player))
"Apply a change in acceleration."
(when (> (ax p) 0.9)
(incf (dx p))
(setf (ax p) 0))
(when (< (ax p) -0.9)
(decf (dx p))
(setf (ax p) 0))
(when (> (ay p) 0.9)
(incf (dy p))
(setf (ay p) 0))
(when (< (ay p) -0.9)
(decf (dy p))
(setf (ay p) 0))
(values))
;;; Sparks are single-pixel, brightly-colored objects which
;;; are generated whenever there's a collision between two
;;; things. Like players, they have a velocity; however,
;;; they also have a time-to-live aspect. Sparks fizzle out
;;; after a certain number of game loop iterations.
(defclass spark (particle visible)
((w :reader w :initform 1) ; override visible
(h :reader h :initform 1) ; override visible
(ttl :accessor ttl)))
(defmethod init-visible ((s spark))
(setf (color s) (random-color :range 256 :offset 0))
(setf (dx s) (- (random 15 *random-state*) 7))
(setf (dy s) (- (random 15 *random-state*) 7))
(setf (ttl s) (random 60 *random-state*)))
(defmethod paint-with-renderer ((s spark) r)
(apply #'sdl2:set-render-draw-color (append (list r) (color s)))
(sdl2:render-draw-point r (left s) (top s))
(values))
(defun make-sparks (x y pf)
(dotimes (i (random 50 *random-state*))
(declare (ignore i))
(push (make-instance 'spark
:left (floor x)
:top (floor y))
*sparks*)))
(defmethod border-collision-consequence ((s spark) x y pf)
; Sparks do not generate their own sparks upon
; collision with a wall or other player.
(declare (ignore s x y pf)))
;;; General Game Logic that doesn't really fit in anywhere else.
(defun repaint-playfield (renderer)
"Use painter's algorithm to redraw the game board."
(loop for object in (append (list *playfield* *player*)
*opponents*
*sparks*)
do (paint-with-renderer object renderer))
(values))
(defun apply-jerks ()
"Apply changes in acceleration ('jerk') to all controllable objects."
(loop for object in (append (list *player*) *opponents*)
do (jerk object))
(values))
(defun move-objects ()
"Update the position of all objects with a non-zero
velocity vector."
(loop for object in (append (list *player*) *opponents* *sparks*)
do (move-object object))
(values))
(defun border-collisions (p pf)
(let ((player-left (left p))
(player-top (top p))
(player-right (right p))
(player-bottom (bottom p))
(field-left 0)
(field-top 0)
(field-right (w pf))
(field-bottom (h pf)))
(cond ((>= player-right field-right)
; We've exceeded the right edge by N pixels. Moving back
; by N pixels puts us right on the edge, which isn't realistic.
; Move by another N pixels to properly emulate the reflection
; off the wall.
(decf (left p) (* 2 (- player-right field-right)))
(border-collision-consequence
p player-right (avg player-top player-bottom) pf)
(h-rebound p))
((< player-left field-left)
(incf (left p) (* 2 (- field-left player-left)))
(border-collision-consequence
p player-left (avg player-top player-bottom) pf)
(h-rebound p))
((>= player-bottom field-bottom)
(decf (top p) (* 2 (- player-bottom field-bottom)))
(border-collision-consequence
p (avg player-left player-right) player-bottom pf)
(v-rebound p))
((< player-top field-top)
(incf (top p) (* 2 (- field-top player-top)))
(border-collision-consequence
p (avg player-left player-right) player-top pf)
(v-rebound p))))
(values))
(defun handle-all-collisions ()
(let* ((vehicles (append (list *player*) *opponents*))
(everything (append vehicles *sparks*)))
(loop for object in everything
do (border-collisions object *playfield*))
(loop for x in vehicles
do (loop for y in *opponents*
do (handle-bumps x y))))
(values))
(defun reap-sparks ()
;; For some reason, this procedure doesn't seem to delete every spark.
;; I do not know why this should be the case; is this a bug in SBCL's
;; implementation or libraries? But, when MAKE-SPARKS is called at a
;; later time, it allows older sparks to be reaped as expected.
;; At least it isn't a fatal bug; more cute than anything.
(delete-if #'(lambda (s)
(decf (ttl s))
(<= (ttl s) 0))
*sparks*))
(defun game-loop-iteration (renderer)
(repaint-playfield renderer)
(apply-jerks)
(move-objects)
(handle-all-collisions)
(reap-sparks)
(values))
(defun initialize-game (window)
(multiple-value-bind (w h) (sdl2:get-window-size window)
(setf *playfield* (make-instance 'playfield :w w :h h)))
(setf *player* (make-instance 'player :on-playfield *playfield*))
(dotimes (unused *n-opponents*)
(push (make-instance 'opponent :on-playfield *playfield*) *opponents*))
(values))
(defmacro push-direction (ks key dir)
`(when (sdl2:scancode= (sdl2:scancode-value ,ks)
(intern (format nil "SCANCODE-~A" (string ,key))
"KEYWORD"))
(accelerate *player* ,dir)))
(defmacro stop-direction (ks key dir)
`(when (sdl2:scancode= (sdl2:scancode-value ,ks)
(intern (format nil "SCANCODE-~A" (string ,key))
"KEYWORD"))
(decelerate *player* ,dir)))
(defun game ()
(sdl2:with-init (:video)
(sdl2:with-window (window :title "Equilibrium/CL" :flags '(:shown))
(sdl2:with-renderer (renderer window)
(initialize-game window)
(sdl2:with-event-loop ()
(:keydown (:keysym ks)
(push-direction ks 'w :up)
(push-direction ks 's :down)
(push-direction ks 'a :left)
(push-direction ks 'd :right))
(:keyup (:keysym ks)
(stop-direction ks 'w :up)
(stop-direction ks 's :down)
(stop-direction ks 'a :left)
(stop-direction ks 'd :right)
(when (sdl2:scancode= (sdl2:scancode-value ks)
:scancode-escape)
(sdl2:push-event :quit)))
(:idle ()
(game-loop-iteration renderer)
(sdl2:render-present renderer)
(sdl2:delay 33))
(:quit () t)))))
(values))
#+sbcl (sdl2:make-this-thread-main #'game)
#-sbcl (game)
| 14,500 | Common Lisp | .lisp | 359 | 34.526462 | 75 | 0.631163 | sam-falvo/equilibrium-cl | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:11 AM (Europe/Amsterdam) | ad14fbd2405f5d2e2251d5b0119f2b54702a6d0e66aee4d7550f9fe261976ccd | 39,901 | [
-1
] |
39,918 | lmc.lisp | make-drop_LMC/lmc.lisp | ;;; Marco Caspani
;;; Marco Gatti
;;; LMC SIMULATOR functions (first part)
;; Returns the instruction fetched from the ram memory
(defun fetch (state)
(let ((pc (get-pc state)))
(cons state (mem-load state pc))))
;; Returns a list cell with the state, instruction to execute and the xx value
(defun decode (cell) ; Input: cons cell of state and instruction to execute
(let ((state (car cell))
(opcode (floor (/ (cdr cell) 100)))
(xx-value (mod (cdr cell) 100)))
(cond
((equal opcode 1) (list state 'ins-addition xx-value))
((equal opcode 2) (list state 'ins-subtraction xx-value))
((equal opcode 3) (list state 'ins-instruction-store xx-value))
((equal opcode 5) (list state 'ins-load xx-value))
((equal opcode 6) (list state 'ins-branch xx-value))
((equal opcode 7) (list state 'ins-branch-if-zero xx-value))
((equal opcode 8) (list state 'ins-branch-if-positive xx-value))
((equal opcode 0) (list state 'ins-halt xx-value))
((equal (cdr cell) 901) (list state 'ins-input NIL))
((equal (cdr cell) 902) (list state 'ins-output NIL))
(T (list state 'ins-illegal-opcode NIL)))))
;; Decoded instruction = (state instruction-function xx)
;; Calls the instruction function and returns the value
(defun execute-instruction (decoded-instruction)
(let ((state (first decoded-instruction))
(ins-function (second decoded-instruction))
(ins-xx-value (third decoded-instruction)))
(funcall ins-function state ins-xx-value)))
;; INSTRUCTIONS FUNCTIONS
;; The addition function (ADD)
;; Performs the addition acc = acc + xx
(defun ins-addition (state xx-value)
(let ((sum (+ (get-acc state) (mem-load state xx-value))))
(if (> sum 999)
(list 'state :ACC (mod sum 1000)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG 'flag)
(list 'state :ACC (mod sum 1000)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG 'noflag))))
;; The subtraction function (SUB)
;; Performs the subtraction acc = acc - xx
(defun ins-subtraction (state xx-value)
(let ((sub (- (get-acc state) (mem-load state xx-value))))
(if (< sub 0)
(list 'state :ACC (mod sub 1000)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG 'flag)
(list 'state :ACC (mod sub 1000)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG 'noflag))))
;; The store function (STA)
;; Returns the state with the mem with the value stored
(defun ins-instruction-store (state xx-value)
(let ((mem (copy-list (get-mem state)))) ; not to produce side effects
(setf (nth xx-value mem) (get-acc state))
(list 'state :ACC (get-acc state)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM mem
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG (get-flag state))))
;; Illegal opcode : 4 -> fail the computation
(defun ins-illegal-opcode (state xx-value) NIL)
;; The load instruction (LDA)
(defun ins-load (state xx-value)
(list 'state :ACC (mem-load state xx-value)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG (get-flag state)))
;; The branch function (BRA)
;; Returns state but with the PC changed to xx
(defun ins-branch (state xx-value)
(list 'state :ACC (get-acc state)
:PC xx-value
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG (get-flag state)))
;; The branch if zero instruction (BRZ)
;; changes the PC if ACC = 0 and flag = noflag
(defun ins-branch-if-zero (state xx-value)
(if (and (equal (get-acc state) 0) (equal (get-flag state) 'noflag))
(ins-branch state xx-value)
(list 'state :ACC (get-acc state)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG (get-flag state))))
;; The branch if positive instruction (BRP)
;; changes the PC if flag = noflag
(defun ins-branch-if-positive (state xx-value)
(if (equal (get-flag state) 'noflag)
(ins-branch state xx-value)
(list 'state :ACC (get-acc state)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG (get-flag state))))
;; Returns an halted state with the PC value that hasn't been incremented
(defun ins-halt (state xx-value)
(list 'halted-state :ACC (get-acc state)
:PC (get-pc state)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (get-output-queue state)
:FLAG (get-flag state)))
;; Input function returns a state with acc = car of input-queue
;; and removes the first element of input-queue
(defun ins-input (state xx-value)
(if (null (get-input-queue state))
NIL
(list 'state :ACC (car (get-input-queue state))
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (cdr (get-input-queue state))
:OUT (get-output-queue state)
:FLAG (get-flag state))))
;; Output function adds acc to output-queue
;; and returns the state with that queue
(defun ins-output (state xx-value)
(list 'state :ACC (get-acc state)
:PC (mod (+ 1 (get-pc state)) 100)
:MEM (get-mem state)
:IN (get-input-queue state)
:OUT (append (get-output-queue state) (list (get-acc state)))
:FLAG (get-flag state)))
;; Returns execute(decode(fetch-instruction(state)))
(defun one-instruction (state)
(cond
((null state) NIL)
((not (equal (length (get-mem state)) 100)) NIL)
((is-halted state) NIL)
(T (let ((whole-instruction (compose 'execute-instruction 'decode 'fetch)))
(funcall whole-instruction state)))))
;; Calls one-instruction till the computation stops with an halted state
(defun execution-loop (state)
(let ((new-state (one-instruction state)))
(if (is-halted state)
(get-output-queue state)
(if (is-halted new-state)
(get-output-queue new-state)
(execution-loop new-state)))))
;; UTILITY FUNCTIONS
;; Functions to return components of the state
(defun get-acc (state)
(getf (cdr state) :acc))
(defun get-pc (state)
(getf (cdr state) :pc))
(defun get-mem (state)
(getf (cdr state) :mem))
(defun get-input-queue (state)
(getf (cdr state) :in))
(defun get-output-queue (state)
(getf (cdr state) :out))
(defun get-flag (state)
(getf (cdr state) :flag))
;; returns the value that is contained at memcell in state
(defun mem-load (state memcell)
(let ((mem (get-mem state)))
(nth memcell mem)))
;; Returns T if the state of the lmc is an halted-state
(defun is-halted (state)
(if (equal (car state) 'state) NIL T))
;; T if the string is empty
(defun is-empty (string)
(equal string ""))
;; Alias of write-to-string
(defun to-string (number)
(write-to-string number))
;; Compose composes a list of functions (f1 f2 ... fn)
;; Returns the function f1(f2(...(fn(x))..)
(defun compose (func1 &rest funcs)
(if (null (car (flatten funcs)))
(lambda (x) (funcall func1 x))
(let ((func2 (compose (car (flatten funcs)) (cdr (flatten funcs)))))
(lambda (y) (funcall func1 (funcall func2 y))))))
;; Flattens a list at the first level
(defun flatten (l)
(cond ((null l) NIL)
((atom (car l)) (cons (car l) (flatten (cdr l))))
(T (append (flatten (car l)) (flatten (cdr l))))))
;; Split a string where there are space characters and turns it into a list
(defun split-string (string)
(reverse (split-string-iter string NIL)))
(defun split-string-iter (string acc)
(let ((space-position (position #\Space string)))
(if (null space-position)
(append (list string) acc)
(let (
(new-string (subseq string (+ space-position 1) (length string)))
(new-acc (append (list (subseq string 0 space-position)) acc))
)
(split-string-iter new-string new-acc)))))
;; Compresses any consecutive spaces
(defun compress-spaces-list (parts)
(if (null parts)
""
(let ((first-part
(concatenate 'string (string-trim
'(#\Space #\Tab #\Newline) (car parts)) " "))
(second-part
(compress-spaces-list (cdr parts))))
(string-trim
'(#\Space #\Tab #\Newline) (concatenate
'string first-part second-part)))))
;; Needed to remove multiple occurrences of spaces in strings
;; Like " string1 string2 string3"
(defun compress-spaces (string)
(let ((parts (split-string string)))
(compress-spaces-list parts)))
;; ASSEMBLER functions (second part)
;; Read all the lines from a file-stream
(defun read-lines (file-stream lines)
(let ((line (read-line file-stream NIL)))
(if (and (null line) (close file-stream))
(values lines)
(read-lines file-stream (append lines (list line))))))
;; Read all the file at the path filename
(defun read-file (filename)
(let ((file-stream (open filename :if-does-not-exist :error)))
(read-lines file-stream NIL)))
;; Get the position of a comment in an instruction string
(defun get-comment-position (string offset)
(if (>= (length string) 2)
(if (equal (subseq string 0 2) "//")
(values offset)
(progn
(let ((new-string-to-check (subseq string 1 (length string))))
(get-comment-position new-string-to-check (+ offset 1)))))
(values NIL)))
;; Removes the comment from one instruction
(defun remove-comment (string)
(let ((comment-position (get-comment-position string 0)))
(if (null comment-position)
string
(subseq string 0 comment-position))))
;; Removes comments from every line of the code
(defun remove-comments (code)
(mapcar 'remove-comment code))
;; Removes useless spaces
(defun trim-code (code)
(let ((no-spaces (mapcar (lambda (e)
(funcall
#'string-trim '(#\Space #\Tab #\Newline) e))
code)))
(mapcar #'compress-spaces no-spaces)))
;; removes empty lines of codes
(defun remove-empty-lines (code) ; cell = (code . labels)
(remove-if 'is-empty code))
;; Returns the label if it exists in line
(defun get-label (line)
(let ((string-parts (split-string line)))
(cond
((equal (length string-parts) 0) (values NIL))
((equal (length string-parts) 1) (values NIL))
((equal (length string-parts) 2)
(if (or (equalp (cadr string-parts) "INP")
(equalp (cadr string-parts) "OUT")
(equalp (cadr string-parts) "HLT")
(equalp (cadr string-parts) "DAT"))
(car string-parts)
NIL))
((equal (length string-parts) 3) (values (car string-parts))))))
;; Returns a list of the labels associated to the line number
(defun get-labels (code &optional (offset 0))
(if (null code)
NIL
(let ((label (list (cons (get-label (car code)) offset))))
(if (null (car (car label)))
(get-labels (cdr code) (+ offset 1))
(append label (get-labels (cdr code) (+ offset 1)))))))
;; Returns a cons cell with code and the labels-list (code . labels-list)
(defun get-code-and-labels (code)
(cons code (get-labels code)))
;; Removes a label from the source-code
(defun remove-label (source-code label)
(let ((code (copy-list source-code))
(label-position (cdr label)) ; get the position of the label to remove
(line (nth (cdr label) source-code))) ; get the line where the label is
(let ((new-line (subseq line (+ 1 (position #\Space line)) (length line))))
(progn
(setf (nth label-position code) new-line)
(values code)))))
;; Cleans the code by removing the labels
(defun remove-labels (code labels-list)
(if (null labels-list)
code
(let ((new-code (remove-label code (car labels-list))))
(remove-labels new-code (cdr labels-list)))))
;; Removes labels from the code and returns (code . labels-list)
(defun get-code-without-labels (cell) ; cell = (code . labels)
(let ((code (car cell)) (labels-list (cdr cell)))
(cons (remove-labels code labels-list) labels-list)))
;; Given the name of the label and the labels-list
;; This function returns the position inside the code where the label is
(defun get-label-position (label labels-list)
(if (null labels-list)
NIL
(if (equalp label (car (car labels-list)))
(cdr (car labels-list))
(get-label-position label (cdr labels-list)))))
;; Returns the prefix of the instruction code the lmc can run
(defun get-instruction-code (ins)
(cond
((equalp ins "DAT") 0)
((equalp ins "ADD") 1)
((equalp ins "SUB") 2)
((equalp ins "STA") 3)
((equalp ins "LDA") 5)
((equalp ins "BRA") 6)
((equalp ins "BRZ") 7)
((equalp ins "BRP") 8)))
;; Returns the prefix of the instruction code the lmc can run
;; If ins does not take arguments
(defun get-instruction-code-len1 (ins)
(cond
((equalp ins "DAT") 0)
((equalp ins "HLT") 0)
((equalp ins "INP") 901)
((equalp ins "OUT") 902)))
;; returns the 3 digits number code of the instruction translated from
;; the instruction name string and the xx value argument
(defun concatenate-inscode-xx (ins xx)
(if (equal xx "NIL")
NIL ; The label hasn't been found in the labels list
(if (< (parse-integer xx) 10)
(parse-integer
(concatenate 'string
(write-to-string (get-instruction-code ins))
"0"
(write-to-string (parse-integer xx))) :junk-allowed T)
(parse-integer
(concatenate 'string
(write-to-string (get-instruction-code ins))
(write-to-string (parse-integer xx))) :junk-allowed T))))
;; Translate a string instruction into its instruction code (3 digits)
(defun translate-instruction (line labels-list)
(let ((parts (split-string line)))
(cond
((equal (length parts) 1) (get-instruction-code-len1 (car parts)))
((equal (length parts) 2)
(if (null (parse-integer (cadr parts) :junk-allowed T))
; If there is a label
(if (not (equalp (car parts) "dat")) ; Exclude the case "dat label"
(concatenate-inscode-xx
(car parts)
(to-string (get-label-position (cadr parts) labels-list)))
NIL)
; If there is no label in the instruction
(concatenate-inscode-xx (car parts) (cadr parts)))))))
;; Translates the whole code into machine-code
(defun translate-to-machine-code (code-labels)
(let ((code (car code-labels)) (labels-list (cdr code-labels)))
(mapcar (lambda (e) (funcall 'translate-instruction e labels-list)) code)))
;; If some errors occurred ignores the generated code and returns NIL
(defun final-code-check (code)
(if (null (position NIL code))
code ; there are no "NIL" instruction in the code (successfull translation)
NIL))
;; Fill the memory with zeros if the code is less than 100 lines long
(defun fill-mem-with-zeros (code)
(if (null code)
NIL
(if (> (length code) 99)
code
(fill-mem-with-zeros (append code '(0))))))
;; Assembler of the lmc
(defun lmc-load (filename)
(let ((whole-function (compose 'fill-mem-with-zeros
'final-code-check
'translate-to-machine-code
'get-code-without-labels
'get-code-and-labels
'remove-empty-lines
'trim-code
'remove-comments
'read-file)))
(funcall whole-function filename)))
;; Loads a program written in lmc assembly and runs it with
;; a specific input-queue taken as an argument
(defun lmc-run (filename input-queue)
(let ((machine-code (lmc-load filename)))
(if (null machine-code)
NIL
(execution-loop
(list 'state :acc 0
:pc 0
:mem machine-code
:in input-queue
:out ()
:flag 'noflag)))))
| 17,116 | Common Lisp | .lisp | 411 | 34.209246 | 79 | 0.609947 | make-drop/LMC | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:19 AM (Europe/Amsterdam) | 5cd33a3f0c6d5b8d50627d66d359369a3da4087c0274150a8f74535b599e7f38 | 39,918 | [
-1
] |
39,921 | lmc.pl | make-drop_LMC/lmc.pl | %Marco Gatti
%Marco Caspani
:- dynamic
label/2.
%LMC_RUN
lmc_run(Filename, Input, Output) :-
lmc_load(Filename, Istruction),
make_memory(Istruction, Memory),
execution_loop(state(0, 0, Memory, Input, [], noflag), Output),
!.
%LMC_LOAD
lmc_load(Filename, Mem) :-
open_file(Filename, List1),
delete(List1, [], List2),
assembly(List2, Mem, 0),
retractall(label(_, _)),
!.
%ONE ISTRUCTION
one_instruction(State, NewState) :-
State = state(Acc, Pc, Mem, In, Out, Flag),
is_acc(Acc),
queue(In),
fetch(Acc, Pc, Mem, In, Out, Flag, NewState),
NewState =.. L,
nth0(5, L, NewOut, _),
queue(NewOut),
!.
%EXECUTION LOOP
execution_loop(State, Out) :-
one_instruction(State, NewState),
execution_loop(NewState, Out),
!.
execution_loop(State, Out) :-
State = halted_state(_, _, _, _, Out, _),
!.
%INSTRUCTIONS
%loop fetch-execute
%FETCH
fetch(Acc, Pc, Mem, In, Out, Flag, NewState) :-
State = [Acc, Pc, Mem, In, Out, Flag],
next_program_counter(Pc, Next_Pc),
nth0(Pc, Mem, Value, _),
is_value(Value),
number_codes(Value, Cod_Value),
!,
decode(Cod_Value, State, Next_Pc, NewState).
%DECODE
decode([Cod_istr | Value], State, Next_pc, NewState) :-
execute(Cod_istr, Value, State, Next_pc, NewState).
decode(Cod_istr, State, Next_pc, NewState) :-
number_codes(Number_istr, Cod_istr),
between(0, 99, Number_istr),
execute(48, _, State, Next_pc, NewState).
%EXECUTE
%ADDITION
execute(49, COD_Cell_Number, State, Next_Pc, NewState) :-
State = [Acc, _, Mem, In, Out, _],
COD_Cell_Number = [_, _],
number_codes(Cell_Number, COD_Cell_Number),
nth0(Cell_Number, Mem, Valore_Cella, _),
New_Acc is Acc + Valore_Cella,
flag(New_Acc, New_Flag),
Acc_Mod is New_Acc mod 1000,
NewState = state(Acc_Mod, Next_Pc, Mem, In, Out, New_Flag),
!.
%SUBTRACTION
execute(50, COD_Cell_Number, State, Next_Pc, NewState) :-
State = [Acc, _, Mem, In, Out, _],
COD_Cell_Number = [_, _],
number_codes(Cell_Number, COD_Cell_Number),
nth0(Cell_Number, Mem, Valore_Cella, _),
New_Acc is Acc - Valore_Cella,
flag(New_Acc, New_Flag),
Acc_Mod is New_Acc mod 1000,
NewState = state(Acc_Mod, Next_Pc, Mem, In, Out, New_Flag),
!.
%STORE
execute(51, COD_Cell_Number, State, Next_Pc, NewState) :-
State = [Acc, _, Mem, In, Out, Flag],
COD_Cell_Number = [_, _],
number_codes(Cell_Number, COD_Cell_Number),
replace(Acc, Cell_Number, Mem, NewMem),
NewState = state(Acc, Next_Pc, NewMem, In, Out, Flag),
!.
%LOAD
execute(53, COD_Cell_Number, State, Next_Pc, NewState) :-
State = [_, _, Mem, In, Out, Flag],
COD_Cell_Number = [_, _],
number_codes(Cell_Number, COD_Cell_Number),
nth0(Cell_Number, Mem, NewAcc, _),
NewState = state(NewAcc, Next_Pc, Mem, In, Out, Flag),
!.
%BRANCH
execute(54, COD_Value, State, _, NewState) :-
State = [Acc, _, Mem, In, Out, Flag],
COD_Value = [_, _],
number_codes(Value, COD_Value),
NewState = state(Acc, Value, Mem, In, Out, Flag),
!.
%BRANCH IF ZERO
execute(55, COD_Value, State, _, NewState) :-
State = [0, _, Mem, In, Out, noflag],
COD_Value = [_, _],
number_codes(Value, COD_Value),
NewState = state(0, Value, Mem, In, Out, noflag),
!.
execute(55, _, State, Next_Pc, NewState) :-
State = [Acc, _, Mem, In, Out, Flag],
NewState = state(Acc, Next_Pc, Mem, In, Out, Flag).
%BRANCH IF POSITIVE
execute(56, COD_Value, State, _, NewState) :-
State = [Acc, _, Mem, In, Out, noflag],
COD_Value = [_, _],
number_codes(Value, COD_Value),
NewState = state(Acc, Value, Mem, In, Out, noflag),
!.
execute(56, _, State, Next_Pc, NewState) :-
State = [Acc, _, Mem, In, Out, Flag],
NewState = state(Acc, Next_Pc, Mem, In, Out, Flag).
%INPUT
execute(57, COD_Value, State, Next_Pc, NewState) :-
State = [_, _, Mem, In, Out, Flag],
number_codes(1, COD_Value),
In = [X | Y],
NewState = state(X, Next_Pc, Mem, Y, Out, Flag),
!.
%OUTPUT
execute(57, COD_Value, State, Next_Pc, NewState) :-
State = [Acc, _, Mem, In, Out, Flag],
number_codes(2, COD_Value),
append(Out, [Acc], NewOut),
NewState = state(Acc, Next_Pc, Mem, In, NewOut, Flag),
!.
%HALT
%Halt not produce PC increment, as request
execute(48, _, State, _, NewState) :-
State = [Acc, Pc, Mem, In, Out, Flag],
NewState = halted_state(Acc, Pc, Mem, In, Out, Flag).
%non-existent instruction
execute(_, _, _, _, _) :-
false.
%flag
flag(Value, noflag) :-
between(0, 999, Value),
!.
flag(_, flag).
%value in memory
is_value(Value) :-
integer(Value),
between(0, 999, Value),
!.
is_value(_) :-
false.
%PC
next_program_counter(99, 0) :-
!.
next_program_counter(X, Y) :-
Y is X + 1.
%set label, use of dynamic memory
set_label([X, Y, Z], Cell_Number, [Y, Z]) :-
not(atom_number(X, _)),
list_istructions(List),
not(member(X, List)),
asserta(label(X, Cell_Number)),
!.
set_label([X, Y], Cell_Number, [Y]) :-
not(atom_number(X, _)),
list_istructions(List),
not(member(X, List)),
asserta(label(X, Cell_Number)),
!.
set_label([X, Y], _, [X, Y]) :-
!.
set_label([X], _, [X]).
%is_label
is_label([Value], Val) :-
label(Value, Val),
!.
is_label([Value], Value_Num) :-
atom_number(Value, Value_Num).
%list of instructions
list_istructions(List) :-
List1 = ["ADD", "SUB", "STA", "LDA", "BRA", "BRZ"],
List2 = ["BRP", "INP", "OUT", "HLT", "DAT"],
append(List1, List2, List),
!.
%translation in assembly language
%end of file
set_instruction(["END_OF_FILE"], 0) :-
!.
%ADD
set_instruction(["ADD" | Value], Cod) :-
is_label(Value, Val),
Val < 10,
atomic_concat(0, Val, Val1),
atomic_concat(1, Val1, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
set_instruction(["ADD" | Value], Cod) :-
is_label(Value, Val),
atomic_concat(1, Val, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
%SUB
set_instruction(["SUB" | Value], Cod) :-
is_label(Value, Val),
Val < 10,
atomic_concat(0, Val, Val1),
atomic_concat(2, Val1, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
set_instruction(["SUB" | Value], Cod) :-
is_label(Value, Val),
atomic_concat(2, Val, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
%STA
set_instruction(["STA" | Value], Cod) :-
is_label(Value, Val),
Val < 10,
atomic_concat(0, Val, Val1),
atomic_concat(3, Val1, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
set_instruction(["STA" | Value], Cod) :-
is_label(Value, Val),
atomic_concat(3, Val, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
%LDA
set_instruction(["LDA" | Value], Cod) :-
is_label(Value, Val),
Val < 10,
atomic_concat(0, Val, Val1),
atomic_concat(5, Val1, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
set_instruction(["LDA" | Value], Cod) :-
is_label(Value, Val),
atomic_concat(5, Val, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
%BRA
set_instruction(["BRA" | Value], Cod) :-
is_label(Value, Val),
Val < 10,
atomic_concat(0, Val, Val1),
atomic_concat(6, Val1, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
set_instruction(["BRA" | Value], Cod) :-
is_label(Value, Val),
atomic_concat(6, Val, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
%BRZ
set_instruction(["BRZ" | Value], Cod) :-
is_label(Value, Val),
Val < 10,
atomic_concat(0, Val, Val1),
atomic_concat(7, Val1, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
set_instruction(["BRZ" | Value], Cod) :-
is_label(Value, Val),
atomic_concat(7, Val, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
%BRP
set_instruction(["BRP" | Value], Cod) :-
is_label(Value, Val),
Val < 10,
atomic_concat(0, Val, Val1),
atomic_concat(8, Val1, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
set_instruction(["BRP" | Value], Cod) :-
is_label(Value, Val),
atomic_concat(8, Val, Value_COD),
atom_number(Value_COD, Cod),
integer(Cod),
!.
%DAT
set_instruction(["DAT" | Value], ValN) :-
Value = [Val],
atom_number(Val, ValN),
is_value(ValN),
!.
set_instruction(["DAT"], 0) :-
!.
%IN
set_instruction(["INP"], 901) :-
!.
%OUT
set_instruction(["OUT"], 902) :-
!.
%HLT
set_instruction(["HLT"], 0) :-
!.
%unrecognized instruction
set_instruction(_, _) :-
false.
%replaces nth element of the list
replace(Value, 0, [_ | Rest], [Value | Rest]) :-
!.
replace(Value, N, [A | B], [A | NewList]) :-
N > 0,
N1 is N -1,
replace(Value, N1, B, NewList).
%make memory
make_memory(Istruction, Memory) :-
make_memory(Istruction, 0, [], Memory),
!.
make_memory([], 99, Mem, Memory) :-
!,
append(Mem, [0], Memory).
make_memory(Istruction, 99, Mem, Memory) :-
!,
Istruction = [Value],
is_value(Value),
append(Mem, Istruction, Memory).
make_memory([], Counter, Mem, Memory) :-
append(Mem, [0], Mem1),
Counter1 is Counter + 1,
make_memory([], Counter1, Mem1, Memory).
make_memory([X | Y], Counter, Mem, Memory) :-
is_value(X),
append(Mem, [X], Mem1),
Counter1 is Counter + 1,
make_memory(Y, Counter1, Mem1, Memory).
%read file
open_file(Filename, List) :-
open(Filename, read, In),
!,
read_string(In, _, String),
upcase_atom(String, String1),
split_string(String1, "\n", "", String2),
splitt(String2, List1),
delete(List1, [], List),
close(In),
!.
open_file(_, _) :-
write("File error"),
false.
%assembly
assembly([], [], _) :-
!.
assembly([X], Mem, 99) :-
!,
set_label(X, 99, Rest_value),
set_instruction(Rest_value, Machine_code),
append([Machine_code], [], Mem).
assembly([X | Y], Mem, Counter) :-
Counter < 99,
!,
set_label(X, Counter, Rest_value),
Counter1 is Counter + 1,
assembly(Y, Mem_Y, Counter1),
set_instruction(Rest_value, Machine_code),
append([Machine_code], Mem_Y, Mem).
assembly(_, _, _) :-
write("Too many instructions"),
false.
%Split string
whitespace(X) :-
findall(X, char_type(X, space), Spaces),
member(X, Spaces),
!.
first_word([], [], []) :-
!.
first_word([C | Cs], [], Cs) :-
whitespace(C),
!.
first_word([C | Cs], [C | Xs], Rest) :-
first_word(Cs, Xs, Rest).
split_string_into_words([], []) :-
!.
split_string_into_words([C | Cs], Ws) :-
whitespace(C),
!,
split_string_into_words(Cs, Ws).
split_string_into_words(CharCodes, [W | Ws]) :-
first_word(CharCodes, WCodes, Rest),
string_codes(W, WCodes),
split_string_into_words(Rest, Ws).
split(String, Res) :-
split_string(String, "//", "", [String2 | _]),
string_codes(String2, CharCodes),
split_string_into_words(CharCodes, Res),
!.
splitt([], []) :-
!.
splitt([A | B], [C | D]) :-
split(A, C),
splitt(B, D).
%control of values queue
queue([]) :-
!.
queue([X | C]) :-
is_value(X),
queue(C).
%is_acc
is_acc(Acc) :-
between(0, 999, Acc).
| 11,865 | Common Lisp | .l | 417 | 23.275779 | 68 | 0.576862 | make-drop/LMC | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:19 AM (Europe/Amsterdam) | d5199eda42c4bc0694037a43313f1a61f20ee879905830788b9796debaf65a0b | 39,921 | [
-1
] |
39,937 | zone.lsp | gattosilversto_autocadLISP/zone.lsp | ; Length/Area of Polyline by Layer
; David Bethel May 2004 from an original idea by David Watson
; This command will give a total area or length for all polylines on a specified layer.
;
(defun c:zone ( / ss la rv i tv op en)
(while (not ss)
(princ "\nPick any object on the required layer")
(setq ss (ssget)))
(initget "Length Area")
(setq rv (getkword "\nWould you like to measure Length/<Area> : "))
(and (not rv)
(setq rv "Area"))
(setq la (cdr (assoc 8 (entget (ssname ss 0))))
ss (ssget "X" (list (cons 0 "*POLYLINE")
(cons 8 la)))
i (sslength ss)
tv 0
op 0)
(while (not (minusp (setq i (1- i))))
(setq en (ssname ss i))
(command "_.AREA" "_E" en)
(cond ((= rv "Length")
(setq tv (+ tv (getvar "PERIMETER"))))
(T
(setq tv (+ tv (getvar "AREA")))
(if (/= (logand (cdr (assoc 70 (entget en))) 1) 1)
(setq op (1+ op))))))
(princ (strcat "\nTotal " rv
" for layer " la
" = " (rtos tv 2 2)
" in " (itoa (sslength ss)) " polylines\n"
(if (/= rv "Length")
(strcat (itoa op) " with open polylines") "")))
(prin1)) | 1,417 | Common Lisp | .l | 34 | 28.941176 | 90 | 0.460756 | gattosilversto/autocadLISP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | a9e7fee372feb55918b103fb3d604b0fae1606d3f07f27c88bdfae59842e1bef | 39,937 | [
-1
] |
39,938 | zp.lsp | gattosilversto_autocadLISP/zp.lsp | :sets all lines to zero elevation
(DEFUN C:ZP2 ()
(graphscr)
(setq FNM (getstring "Enter name of TEXT file to create: "))
(setq FNM (strcat FNM ".txt"))
(setq FD (open FNM "w"))
(setq HEAD "POINT \t\tX \t\tY \t\tELEV")
(write-line "Exported coordinates:-" FD)
(princ "\n" FD)
(write-line HEAD FD)
(princ "\n" FD)
(if (Null PN)(setq PN 1))
(prompt "\nEnter first point reference number <")
(princ PN)
(setq PNN (getint ">: "))
(if (Null PNN)(setq PN PN)(setq PN PNN))
(setq A1 (getpoint "\nSelect bottom left corner of area to be selected: "))
(initget 32)
(setq A2 (getcorner A1 "\nSelect top right corner of area to be selected: "))
(setq S1 (ssget "c" A1 A2 (LIST (CONS 0 "insert"))))
(setq SSL (sslength S1))
(setq COUNT 0)
(repeat SSL
(setq SSN (ssname S1 COUNT))
(setq ENA (entget SSN))
(setq ASS2 (assoc 10 ENA))
(setq P1 (cdr ASS2))
(setq SSM (entnext SSN))
(setq ENB (entget SSM))
(if (= "ATTRIB" (DXF 0 ENB))(progn
(setq ASS1 (assoc 1 ENB))
(setq PZ1 (cdr ASS1))
(setq PZ1 (atof PZ1))
(if (/= PZ1 NIL)(progn
(setq PX1 (car P1))
(setq PY1 (cadr P1))
(setq POINT1 (list PX1 PY1 PZ1))
(setq ENB (subst (cons 10 (list (car (dxf 10 ENB))(cadr (dxf 10 ENB)) PZ1))(cons 10 (dxf 10 ENB)) ENB))
(setq ENB (entmod ENB))
))
(setq ENA (subst (cons 10 (list (car (dxf 10 ENA))(cadr (dxf 10 ENA)) PZ1))(cons 10 (dxf 10 ENA)) ENA))
(setq ENA (entmod ENA))
(setq SSN (ENTUPD SSN))
))
(setq PX1 (car P1))
(setq PX1 (rtos PX1 2 3))
(setq PY1 (cadr P1))
(setq PY1 (rtos PY1 2 3))
(princ PN FD)(princ "\t\t" FD)(princ PX1 FD)(princ "\t" FD)(princ PY1 FD)(princ "\t" FD)(princ PZ1 FD)
(princ "\n" FD)
(setq PN (1+ PN))
(setq COUNT (1+ COUNT))
)
(close FD)
(SETQ PN NIL)
(princ)
) | 1,798 | Common Lisp | .l | 57 | 28.263158 | 107 | 0.615075 | gattosilversto/autocadLISP | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 8e27d01769c5000b4b5f457e50f1f0005d62c55fd02ae98de5f6b1f9cf45660b | 39,938 | [
-1
] |
39,955 | jmc.lisp | TralahM_lisp_programs/jmc.lisp | ; The Lisp defined in McCarthy's 1960 paper, translated into CL.
; Assumes only quote, atom, eq, cons, car, cdr, cond.
; Bug reports to [email protected].
(defun null. (x)
(eq x '()))
(defun and. (x y)
(cond (x (cond (y 't) ('t '())))
('t '())))
(defun not. (x)
(cond (x '())
('t 't)))
(defun append. (x y)
(cond ((null. x) y)
('t (cons (car x) (append. (cdr x) y)))))
(defun list. (x y)
(cons x (cons y '())))
(defun pair. (x y)
(cond ((and. (null. x) (null. y)) '())
((and. (not. (atom x)) (not. (atom y)))
(cons (list. (car x) (car y))
(pair. (cdr x) (cdr y))))))
(defun assoc. (x y)
(cond ((eq (caar y) x) (cadar y))
('t (assoc. x (cdr y)))))
(defun eval. (e a)
(cond
((atom e) (assoc. e a))
((atom (car e))
(cond
((eq (car e) 'quote) (cadr e))
((eq (car e) 'atom) (atom (eval. (cadr e) a)))
((eq (car e) 'eq) (eq (eval. (cadr e) a)
(eval. (caddr e) a)))
((eq (car e) 'car) (car (eval. (cadr e) a)))
((eq (car e) 'cdr) (cdr (eval. (cadr e) a)))
((eq (car e) 'cons) (cons (eval. (cadr e) a)
(eval. (caddr e) a)))
((eq (car e) 'cond) (evcon. (cdr e) a))
('t (eval. (cons (assoc. (car e) a)
(cdr e))
a))))
((eq (caar e) 'label)
(eval. (cons (caddar e) (cdr e))
(cons (list. (cadar e) (car e)) a)))
((eq (caar e) 'lambda)
(eval. (caddar e)
(append. (pair. (cadar e) (evlis. (cdr e) a))
a)))))
(defun evcon. (c a)
(cond ((eval. (caar c) a)
(eval. (cadar c) a))
('t (evcon. (cdr c) a))))
(defun evlis. (m a)
(cond ((null. m) '())
('t (cons (eval. (car m) a)
(evlis. (cdr m) a)))))
| 1,894 | Common Lisp | .lisp | 56 | 25.964286 | 64 | 0.425835 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 083bf4254f2d8d17b11246dc35e1f998a154df6250bdc41dd4e8b1885a651ee5 | 39,955 | [
-1
] |
39,956 | functions.lisp | TralahM_lisp_programs/functions.lisp | ; Named Functions:defun
; creating named functions is done with the defun keyword. It follows this mode
; (defun <name> (list of arguments)
; "docstring"
; (function body))
;; example
(defun greet ()
"greet function"
(print "Greetings!"))
;;; (greet)
;; Arguments
(defun greeta (name)
"Greet a `name."
(format t "hello ~a ! ~&"))
;; where ~a is the most used format directive to print a variable aesthetically
;; and ~& prints a new line
;;; (greeta "Himself")
;; Optional arguments: &optional
(defun hello (name &optional age gender)
(format "Hello ~a ! ~&" name ))
;; Named Parameters: &key
(defun helloa (name &key happy)
"If `happy` is `t', print a smiley"
(format t "hello ~a " name)
(when happy
(format t ":)~&")))
;;; (hello "me")
;;; (hello "me" :happy t)
;;; Several key parameters: (defun hellob (name &key happy lisper
;;; cookbook-contributor-p) ...)
;; Default values
(defun helloc (name &key (happy t))
(format t "Hello ~a :)~&" name))
;; Variable number of arguments: &rest
;;; sometime you want a function to accept a variable number of arguments. Use
;;; &rest <variable>, where variable will be a list.
(defun mean (x &rest numbers)
(/ (apply #'+ x numbers)
(1+ (length numbers))))
;;; (mean 1)
;;; (mean 1 2)
;;; (mean 1 3 4 5 6 7 8)
; &allow-other-keys ===> Equivalent to python's **kwargs
(defun hellokwargs (name &key happy &allow-other-keys)
(format t "hello ~a~&" name))
;;example
(defun open-supersede (f &rest other-keys &key &allow-other-keys)
(apply #'open f :if-exists :supersede other-keys))
;; multiple return values: values, multiple-value-bind and nth-value
(defun foo (a b c)
(values a b c))
;;; We destructure multiple values with multiple-value-bind and we can get one
;;; given its position with nth-value
(multiple-value-bind (res1 res2 res3)
(foo :a :b :c)
(format t "res1 is ~a, res2 is ~a, res3 is ~a~&" res1 res2 res3))
(nth-value 2 (values :a :b :c)) ;; => :C
;;; multiple-value-list turns multiple values to a list the reverse is
(multiple-value-list (values 1 2 3))
;;; values-list which turns a list into multiple values
(values-list '(1 2 3))
; Anonymous Functions: lambda, funcall, apply
((lambda (x) (print x)) "hello")
(funcall #'+ 1 2 )
(apply #'+ '(1 2))
; Higher order functions:functions that return functions
(defun adder (n)
(lambda (x) (+ x n)))
;; (adder 5) => CLOSURE (LAMBDA (X) IN ADDER)
(funcall (adder 5) 3) ; 8
(boundp 'foo)
(fboundp 'foo)
(setf (symbol-function '*myfunc*) (adder 3))
(fboundp '*myfunc*) ; => T
(*myfunc* 4) ; => 7
; setf functions ===> a function name can also be a list of two symbols with
; setf as the furst one, and where the first argument if the new value.
;; (defun (setf <name>) (new-value <other arguments>) body)
;; Example ;; particularly used by CLOS methods.
(defparameter *current-name* ""
"A global name.")
(defun hellof (name)
(format t "hello ~a~&" name))
(defun (setf hellof) (new-value)
(hello new-value)
(setf *current-name* new-value)
(format t "current name is now ~a~&" new-value))
(setf (hello) "Alice")
; Currying
(defun curry (function &rest args)
(lambda (&rest more-args)
(apply function (append args more-args))))
(funcall (curry #'+ 3) 5) ;===> 8
(funcall (curry #'+ 3) 6) ;===> 9
(setf (symbol-function 'power-of-ten) (curry #'expt 10))
(power-of-ten 3) ; ===> 1000
; With the alexandria library
(ql:quickload :alexandria)
(defun adder (foo bar)
"Add the two arguments."
(+ foo bar))
(defvar add-one (alexandria:curry #'adder 1) "Add 1 to the argument.")
(funcall add-one 10) ;; => 11
(setf (symbol-function 'add-one) add-one)
(add-one 10) ;; => 11
| 3,653 | Common Lisp | .lisp | 105 | 32.92381 | 79 | 0.674716 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | a5d5a14fd6663bcad054ab573eccbdceb1f8f8d3d44466288e1414414733e450 | 39,956 | [
-1
] |
39,957 | cumsum.lisp | TralahM_lisp_programs/cumsum.lisp | (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))
(cumsum '(1 2 3 4 5 6 7 8 9 10) :smsf 1)
| 486 | Common Lisp | .lisp | 8 | 56.5 | 252 | 0.632353 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | cbb1b935a59f0e39998778945bcf183bbd6e6261239cefc273ca735afe5bbe89 | 39,957 | [
-1
] |
39,958 | first.lisp | TralahM_lisp_programs/first.lisp | ;Function definition, closures,scope,#'functions
(defun dbl (x) (* x 2))
(defun add-two (x) (mapcar #'(lambda (x) (+ 2 x)) x))
(let ((counter 0))
(defun new-id () (incf counter))
(defun reset-id () (setq counter 0)))
(print (remove-if #'evenp '(1 2 3 4 5 6 7 8 9 10)))
(print (add-two '(43 34)))
(print (mapcar #'(lambda (x) (+ x 10)) '(1 2 3)))
(print (dbl 322))
(print "Hello TralahTek")
(print (dbl 29))
| 416 | Common Lisp | .lisp | 12 | 32.916667 | 53 | 0.609023 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | e376d035dd487b252a9fcaad31bbad57469458ec756cd3eb093cae5e76d7fd3d | 39,958 | [
-1
] |
39,960 | list_operations.lisp | TralahM_lisp_programs/utilities/list_operations.lisp | ; Utility Functions for Operations on Lists
; 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.
; Small Functions which operate on lists
(proclaim '(inline last1 single append1 conc1 mklist))
;; last element in a list
(defun last1 (lst) (car (last lst)))
;; test whether lst is a list of one element
(defun single (lst) (and (consp lst) (not (cdr lst))))
;; attach a new element to end of a list non-destructively
(defun append1 (lst obj) (append lst (list obj)))
;; attach a new element to end of a list destructively
(defun conc1 (lst obj) (nconc lst (list obj)))
;; Ensure obj is a list
(defun mklist (obj) (if (listp obj) obj (list obj)))
; Longer Functions That Operate on Lists
;; Check whether a list x is longer than a list y
(defun longer (x 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)))))
;; Apply filter function fn to list lst
(defun filter (fn lst)
(let ((acc nil))
(dolist (x lst)
(let ((val (funcall fn x)))
(if val (push val acc))))
(nreverse acc)))
;; Groups List into Sublists of Length n, remainder stored in last sublist
(defun group (source n)
(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)))
; Doubly Recursive List Utilities
;; Flatten List lst with Nested Lists
(defun flatten (x)
(labels ((rec (x acc)
(cond ((null x) acc)
((atom x) (cons x acc))
(t (rec (car x) (rec (cdr x) acc))))))
(rec x nil)))
;; Prune List with Nested Lists using the function test
(defun prune (test tree)
(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)))
| 3,446 | Common Lisp | .lisp | 74 | 39.256757 | 78 | 0.632568 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 220c49fba2d8b22b106c49e0c01e71091bd5606c63e80f31ef8acd1b1e92544c | 39,960 | [
-1
] |
39,961 | symbols_and_strings.lisp | TralahM_lisp_programs/utilities/symbols_and_strings.lisp | ;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)
(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))))
;; 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))))
;; 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)
| 1,081 | Common Lisp | .lisp | 24 | 42.041667 | 80 | 0.719617 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 01dc27dbc24c76e0072580cd8c84ca924fd2da5ed450da450d847756e08e096e | 39,961 | [
-1
] |
39,962 | mapping_functions.lisp | TralahM_lisp_programs/utilities/mapping_functions.lisp | ;; 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))
(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)
(defun map0-n (fn n)
(mapa-b fn 0 n))
(defun map1-n (fn n)
(mapa-b fn 1 n))
;; (map0-n #'1+ 5); ===> (1 2 3 4 5 6)
;; (map1-n #'1+ 5); ===> (2 3 4 5 6)
(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)
(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))
;; 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)
(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)))
| 1,769 | Common Lisp | .lisp | 44 | 36.045455 | 80 | 0.62595 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 9dfff94784e64e7d94b004df3dca9e7bfb84417a63970a0ceed287f3bd258e0e | 39,962 | [
-1
] |
39,963 | function_utils.lisp | TralahM_lisp_programs/utilities/function_utils.lisp | (defun cmplmnt (fn)
#'(lambda (&rest args) (not (apply fn args))))
;; (remove-if (cmplmnt #'oddp) '(1 2 3 4 5 6)) ;=> (1 3 5)
;;
; # 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)
(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)))))))
;; (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)
(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)))))
(defun fint (fn &rest fns)
fn
(let ((chain (apply #'fint fns)))
#'(lambda (x)
(and (funcall fn x) (funcall chain x))))
)
(defun fun (fn &rest fns)
if (null fns)
fn
(let ((chain (apply #'fun fns)))
#'(lambda (x)
(or (funcall fn x) (funcall chain x)))))
| 1,777 | Common Lisp | .lisp | 54 | 27.907407 | 83 | 0.566883 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 7a2c08fe4eee47a1d66975dc8da560024333aefeabaf461c63b5f312d2fff14b | 39,963 | [
-1
] |
39,964 | IO_utils.lisp | TralahM_lisp_programs/utilities/IO_utils.lisp |
;;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)
(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
| 1,300 | Common Lisp | .lisp | 35 | 32.971429 | 79 | 0.628185 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 7e5836dc2e807be75b4c0217d8b43bb395c74a06c9bf84f517788aabc621d789 | 39,964 | [
-1
] |
39,965 | search_utils.lisp | TralahM_lisp_programs/utilities/search_utils.lisp | ; 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)
(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 '(a)) ; ==> 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)
(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))
;;; => (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
(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
| 2,362 | Common Lisp | .lisp | 70 | 26.928571 | 74 | 0.496709 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | efb2f912bd4467f9084101afd9d487f6d4692720c6ac331be5029253def1db28 | 39,965 | [
-1
] |
39,966 | gps.lisp | TralahM_lisp_programs/gps/gps.lisp | (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,555 | Common Lisp | .lisp | 150 | 37.313333 | 108 | 0.638234 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | ad1a18bac0025b2180944cbe3ff944e071b24e2bb21c6f03b71957ebb6f35813 | 39,966 | [
-1
] |
39,967 | tralahtek-utils.asd | TralahM_lisp_programs/tralahtek-utils.asd | (defsystem tralahtek-utils
:author "Tralah M Brian <[email protected]>"
:maintainer "Tralah M Brian <[email protected]>"
:homepage "https://github.com/TralahM/lisp_programs"
:version "0.1"
:depends-on ()
:components ((:module "utilities"
:serial t
:components
((:file "tralahtek-utils"))))
:description "Getting Started with Lisp and Lisp Packaging"
:long-description
#.(uiop:read-file-string
(uiop:subpathname *load-pathname* "README.md"))
:in-order-to ((test-op (test-op tralahtek-utils-test))))
| 615 | Common Lisp | .asd | 15 | 33.533333 | 61 | 0.643333 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | df0627ddda58952db4d2171bfe0c0c20512fbb044f649bcf8ef9d3412e4d1ff9 | 39,967 | [
-1
] |
39,968 | tralahtek-utils-test.asd | TralahM_lisp_programs/tralahtek-utils-test.asd | (defsystem tralahtek-utils-test
:author "Tralah M Brian <[email protected]>"
:license "GPLv3"
:depends-on (:tralahtek-utils
;:some-test-framework
)
:components ((:module "tests"
:serial t
:components
((:file "tralahtek-utils")))))
| 327 | Common Lisp | .asd | 10 | 23.1 | 56 | 0.55836 | TralahM/lisp_programs | 0 | 0 | 0 | GPL-3.0 | 9/19/2024, 11:47:27 AM (Europe/Amsterdam) | 940664637d9c4b83ee8ff32495b3582154bde1dcfb3e2ba9d9feacec33d7ebaa | 39,968 | [
-1
] |
39,980 | list_operations.fasl | TralahM_lisp_programs/utilities/list_operations.fasl | #!/usr/bin/sbcl --script
# FASL
compiled from "/home/african/Desktop/Lisp/programs/utilities/list_operations.lisp"
using SBCL version 2.0.8
ˇ X86-64N 2.0.8 (GENCGC SB-THREAD SB-UNICODE)MPROCLAIMM
INLINESCOMMON-LISP-USEROLAST1O
SINGLEOAPPEND1OCONC1O
MKLISTÜ8SSB-IMPLO
%DEFUN>S SB-KERNELO
%LAST1"I$ OLSTÅSSB-INTOSFUNCTIONÅÉ+ ë áÄÌ
\ëdB/home/african/Desktop/Lisp/programs/utilities/list_operations.lisp"ì≤„ n0"$ +±g%B@+±ˇ NSTANDARD"d " x
\+±g4ƒ ֶу§¢%",f r0u0\ "Í m0x 5
èEHɢuCHçeHãÚHâuIãEHâE¯HÉÏHã÷π Hâ,$HãÏË HãuçB˘®u
HãR˘Hã¯]√ÃGà % &8
>'MBOOLEANÉ+ë¡ÜèãÅ\ë"$ +±g0B7+±ˇ "f "
\+±g8ƒ уÑÑ%"0h 0 0""™
#0p Ñ 5
èEHɢu=Hçe¯Hã⁄IãEHâE¯HÅ˚PtçC˘®t∫PHã¯]√HãCH=PuÈ∫OPÎÁà 3 48
>5SSB-VMO5CONS->R11"< |