Lisp randomize and using two functions to pull from list into another

自闭症网瘾萝莉.ら 提交于 2019-12-02 03:30:33

coredump already answered your question.

You can write your code a bit shorter:

(defvar *candy-color*
  #(yellow red blue green pink orange))    ; a vector

(defun generate-candy-supply (size)
  (loop repeat size
        collect (elt *candy-color*
                     (random (length *candy-color*)))))

(defun candy-machine (supply-of-candy)
  (lambda ()
    (pop supply-of-candy)))               ; use POP

Finding wrong number of arguments:

Just compile your code:

[2]> (compile ' generate-candy-supply)
WARNING: in GENERATE-CANDY-SUPPLY : CONS was called with 1 arguments, but it
         requires 2 arguments.

Above warning clearly tells you what is wrong with the code. Since most Common Lisp implementations have one or more compilers, it's useful to actually use them. Depending on the compiler, they can find various problems like wrong argument lists, unused variables, undeclared variables and more.

Yes, you do have few argument in your call to cons here:

(defun generate-candy-supply (size)
  (if ( = 0 size)
    (cons (nth( random (length candy-color)) candy-color))
    ;;    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ <= HERE
    (generate-candy-supply ( - size 1))))

cons needs two arguments, when you giving it just one. So with what are you cosing your color?

Also indent your code properly, now it's really difficult to read.

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