问题
I am try to create a function with two arguments x and y
which creates a list of y times repeated elements X
but im getting confused on how to do it which or which method to use i think list compression can do but i want a shorter and simple method for example i want my simple code to be like this
if y = 4
and x = 7
result is list of elements (7, 7, 7, 7)
how can i go about it any ideas?? books links or anything that will give me a clue i tried searching but i have not been lucky
回答1:
Try this, it's in Scheme but the general idea should be easy enough to translate to Common Lisp:
(define (repeat x y)
(if (zero? y)
null
(cons x
(repeat x (sub1 y)))))
EDIT:
Now, in Common Lisp:
(defun repeat (x y)
(if (zerop y)
nil
(cons x
(repeat x (1- y)))))
回答2:
You can use make-list with the initial-element key:
CL-USER> (make-list 10 :initial-element 8)
(8 8 8 8 8 8 8 8 8 8)
While a good example of how you can code such a function by yourself is provided by Óscar answer.
来源:https://stackoverflow.com/questions/13442008/repeating-elements-in-common-lisp