Вопрос

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)))))
Это было полезно?

Решение 2

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))))

Другие советы

In elisp, you're looking for C-hf number-sequence RET.

The code that you give in your question is in a very messy state. Emacs can highlight parens for you. That was enough for me to fix your code without any debugging:

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

This is how you turn on highlighting:

(setq show-paren-mode t)

Do most of your editing in *scratch* or ielm - they make things easier.

If you need help with your function I suggest you use cons instead of list and make it from end to start with an accumulator.

(defun xtoy (from to &optional acc)
  (if (> from to)
      acc
      (xtoy from (- to 1) (cons to acc))))
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top