lispcommon-lisppractical-common-lispansi-common-lisp

a function in lisp called xtoy which returns a list from x to y


I am very new to lisp. I am trying to write a function named x2y which takes 2 arguments x and y which are integers and return a list of integers which starts from x and ends at y

(defun xtoy (X Y)
  (cond ((> X Y) (list nil))
        ((= X Y) (list Y)))
        (T (append (list X) x2y(+ 1 X) Y)))))

Solution

  • Starting with abo-abo's version, you can simplify a lot:

    1) get rid of (= X Y) and replace (list nil) by nil in (> X Y)

    (defun xtoy (X Y)
      (cond ((> X Y) nil)
            (t (append (list X) (xtoy (+ 1 X) Y)))))
    

    2) simplify cond to an ifstatement

    (defun xtoy (X Y)
      (if (<= X Y)
        (append (list X) (xtoy (+ 1 X) Y))
        nil))
    

    3) leave out the final nil, because that's what's implicitly returned when the condition doesn't match

    (defun xtoy (X Y)
      (if (<= X Y)
        (append (list X) (xtoy (+ 1 X) Y))))
    

    4) use cons instead of append

    (defun xtoy (X Y)
      (if (<= X Y)
        (cons X (xtoy (+ 1 X) Y))))