3c61c70e4bae35bb3f7d3288d9e15d5bc450a1cb
[clinton/parenscript.git] / runtime / ps-runtime-lib.lisp
1 (in-package :parenscript)
2
3 ;;; Script of library functions you can include with your own code to
4 ;;; provide standard Lisp functionality.
5
6 (defparameter *ps-lisp-library*
7 '(progn
8 (defun mapcar (fun &rest as)
9 (let ((result-array (make-array)))
10 (if (= 1 (length as))
11 (dolist (element (aref as 0))
12 (result-array.push (fun element)))
13 (dotimes (i (length (aref as 0)))
14 (let ((args-array (mapcar (lambda (a) (return (aref a i))) as)))
15 (result-array.push (fun.apply fun args-array)))))
16 (return result-array)))
17
18 (defun map-into (fn arr)
19 "Call FN on each element in ARR, replace element with the return value."
20 (let ((idx 0))
21 (dolist (el arr)
22 (setf (aref arr idx) (fn el))
23 (setf idx (1+ idx))))
24 (return arr))
25
26 (defun map (fn arr)
27 "Call FN on each element in ARR and return the returned values in a new array."
28 ;; In newer versions of ECMAScript, this may call Array.map, too
29 (let ((idx 0)
30 (result (array)))
31 (dolist (el arr)
32 (setf (aref result idx) (fn el))
33 (setf idx (1+ idx)))
34 (return result)))
35
36 (defun map-until (fn arr)
37 "Call FN on each element in ARR until it returns something. If so return that value."
38 (let ((result))
39 (dolist (el arr)
40 (setf result (fn el))
41 (unless (= result undefined)
42 (return result)))))
43
44 (defun member (item arr)
45 "Check if ITEM is a member of ARR."
46 (dolist (el arr)
47 (if (= el item)
48 (return true)))
49 (return false))
50
51 (defun append (arr1 arr2)
52 "Return a new array with the contents of ARR1 and ARR2. If ARR2 is not an array
53 then append it as a member."
54 (let ((result (array))
55 (idx 0))
56 (dolist (el arr1)
57 (setf (aref result idx) el)
58 (setf idx (1+ idx)))
59 (unless (= arr2 undefined)
60 (if (instanceof arr2 *array)
61 (dolist (el arr2)
62 (setf (aref result idx) el)
63 (setf idx (1+ idx)))
64 (setf (aref result idx) arr2))))
65 (return result))
66
67 (defun set-difference (arr arr-to-sub)
68 "Return a new array with only those elements in ARR that are not in ARR-TO-SUB."
69 (let ((idx 0)
70 (result (array)))
71 (dolist (el arr)
72 (unless (member el arr-to-sub)
73 (setf (aref result idx) el)
74 (setf idx (1+ idx))))
75 (return result)))
76
77 (defun reduce (func list &optional init) ;; the use of init here is actually a bit broken wrt null
78 (let* ((acc))
79 (do* ((i (if init -1 0) (1+ i))
80 (acc (if init init (elt list 0)) (func acc (elt list i))))
81 ((>= i (1- (length list)))))
82 (return acc)))))