repeating elements in common lisp [closed]

北城以北 提交于 2019-12-13 13:17:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!