Clarified that the license is BSD 3-clause. Added SPDX identifiers
[parenscript.git] / runtime / ps-runtime-lib.lisp
blobbe3cbbbbba9fad9856bed0859abf464acbf22fe9
1 ;; SPDX-License-Identifier: BSD-3-Clause
3 (in-package #:parenscript)
5 ;;; Script of library functions you can include with your own code to
6 ;;; provide standard Lisp functionality.
8 (defparameter *ps-lisp-library*
9 '(progn
10 (defun mapcar (fun &rest arrs)
11 (let ((result-array (make-array)))
12 (if (= 1 (length arrs))
13 (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))
20 (defun map-into (fn arr)
21 "Call FN on each element in ARR, replace element with the return value."
22 (let ((idx 0))
23 (dolist (el arr)
24 (setf (aref arr idx) (fn el))
25 (setf idx (1+ idx))))
26 arr)
28 (defun map (fn arr)
29 "Call FN on each element in ARR and return the returned values in a new array."
30 ;; In newer versions of ECMAScript, this may call Array.map, too
31 (let ((idx 0)
32 (result (array)))
33 (dolist (el arr)
34 (setf (aref result idx) (fn el))
35 (setf idx (1+ idx)))
36 result))
38 (defun member (item arr)
39 "Check if ITEM is a member of ARR."
40 (dolist (el arr)
41 (if (= el item)
42 (return-from member true)))
43 false)
45 (defun set-difference (arr arr-to-sub)
46 "Return a new array with only those elements in ARR that are not in ARR-TO-SUB."
47 (let ((idx 0)
48 (result (array)))
49 (dolist (el arr)
50 (unless (member el arr-to-sub)
51 (setf (aref result idx) el)
52 (setf idx (1+ idx))))
53 result))
55 (defun reduce (func list &optional init) ;; the use of init here is actually a bit broken wrt null
56 (let* ((acc))
57 (do* ((i (if init -1 0) (1+ i))
58 (acc (if init init (elt list 0)) (func acc (elt list i))))
59 ((>= i (1- (length list)))))
60 acc))
62 (defun nconc (arr &rest arrs)
63 (when (and arr (> (length arr) 0))
64 (loop :for other :in arrs :when (and other (> (length other) 0)) :do
65 ((@ arr :splice :apply) arr
66 (append (list (length arr) (length other)) other))))
67 arr)))