#|
utility.lisp
> Extra functions not defined in the CL standard that I find helpful
Copyright (C) 2008 Jake Voytko
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.
|#
(defun coin-flip ()
"Returns true or false with equal probability on the assumption
that Lisp's RNG has an equal distribution."
(eql 0 (random 2)))
(defun at-least-once (f)
"Calls 'f' at least once and returns a list of the results.
Additional function calls determined by 'coin-flip'."
(labels ((at-least-once-helper (f)
(cons (funcall f)
(if (coin-flip)
(at-least-once-helper f)
nil))))
(at-least-once-helper f)))
(defun random-array-element (array)
"Returns a random element of 'array'."
(aref array (random (length array))))
(defmacro swap (item1 item2)
"Swaps the contents of item1 and item2."
(let ((tmp (gensym)))
`(progn
(setf ,tmp ,item1)
(setf ,item1 ,item2)
(setf ,item2 ,tmp))))
(defun random-subsequence (list)
"Returns a random subsequence from list 'list'. Should work on any sequence,
but the tests aren't in place yet, so I won't guarantee this."
(cond ((null list) nil)
((eql 1 (length list)) list)
(t ; Start: can't be last element. End: picked from start+1->end
(let* ((start (random (length list)))
(end
(+ (random (- (length list) start))
1 start)))
(subseq list start end)))))
(defun splice (list1 list2 start end)
"Replaces the elements of 'list1' in indices [start,end) with the contents
of list2"
(cond ((>= start (length list1))
(append list1 list2))
((eql 0 start) (append list2 (subseq list1 end)))
(t (append (subseq list1 0 start)
list2
(subseq list1 end)))))