ps-runtime-lib.lisp 2.26 KB
Newer Older
1
2
;; SPDX-License-Identifier: BSD-3-Clause

3
(in-package #:parenscript)
4
5
6
7
8

;;; Script of library functions you can include with your own code to
;;; provide standard Lisp functionality.

(defparameter *ps-lisp-library*
9
  '(progn
10
    (defun mapcar (fun &rest arrs)
11
      (let ((result-array (make-array)))
12
13
        (if (= 1 (length arrs))
            (dolist (element (aref arrs 0))
14
              ((@ result-array push) (fun element)))
15
            (dotimes (i (length (aref arrs 0)))
16
              (let ((args-array (mapcar (lambda (a) (aref a i)) arrs)))
17
                ((@ result-array push) ((@ fun apply) fun args-array)))))
18
        result-array))
19
20
21
22
23
24
25

    (defun map-into (fn arr)
      "Call FN on each element in ARR, replace element with the return value."
      (let ((idx 0))
        (dolist (el arr)
          (setf (aref arr idx) (fn el))
          (setf idx (1+ idx))))
26
      arr)
27
28
29
30
31
32
33
34
35

    (defun map (fn arr)
      "Call FN on each element in ARR and return the returned values in a new array."
      ;; In newer versions of ECMAScript, this may call Array.map, too
      (let ((idx 0)
            (result (array)))
        (dolist (el arr)
          (setf (aref result idx) (fn el))
          (setf idx (1+ idx)))
36
        result))
37
38
39
40
41

    (defun member (item arr)
      "Check if ITEM is a member of ARR."
      (dolist (el arr)
        (if (= el item)
42
43
            (return-from member true)))
      false)
44
45
46
47
48
49
50
51
52

    (defun set-difference (arr arr-to-sub)
      "Return a new array with only those elements in ARR that are not in ARR-TO-SUB."
      (let ((idx 0)
            (result (array)))
        (dolist (el arr)
          (unless (member el arr-to-sub)
            (setf (aref result idx) el)
            (setf idx (1+ idx))))
53
        result))
54

55
    (defun reduce (func list &optional init)
56
      (let* ((acc))
57
58
59
60
        (do* ((i (if (= (length arguments) 3) -1 0)
                 (1+ i))
              (acc (if (= (length arguments) 3) init (elt list 0))
                   (func acc (elt list i))))
61
             ((>= i (1- (length list)))))
62
        acc))
63
64
65
66
67
68
69

    (defun nconc (arr &rest arrs)
    (when (and arr (> (length arr) 0))
      (loop :for other :in arrs :when (and other (> (length other) 0)) :do
        ((@ arr :splice :apply) arr
         (append (list (length arr) (length other)) other))))
    arr)))
70
v