-2

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)))))
Deepak
  • 1,503
  • 3
  • 22
  • 45
  • 3
    what is the question? – Rainer Joswig Oct 22 '13 at 21:04
  • the code was not working which i pasted along with the question but its solved now – Deepak Oct 23 '13 at 00:14
  • 1
    @shunya: Please not that elisp and common-lisp are **different** languages which both are in the lisp family. If you are going to ask a question please tag with the language the problem is in. – Baggers Oct 24 '13 at 07:20
  • @Baggers sorry i just started learning lisp i was not aware that elisp is a different language than common lisp. i removed the tag of elisp now – Deepak Nov 13 '13 at 04:23
  • 1
    @shunya: No worries! reading my comment again now it seems a bit stern so sorry about that. – Baggers Nov 13 '13 at 10:48

4 Answers4

3

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

phils
  • 71,335
  • 11
  • 153
  • 198
2

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.

abo-abo
  • 20,038
  • 3
  • 50
  • 71
  • No, the OP just had a confusion about the invocation syntax, which is `(xtoy (1+ x))` and not `x2y(1+ x)`. I see this confusion extraordinarily frequently in the questions I see here on SO. – C. K. Young Oct 22 '13 at 21:10
  • @ChrisJester-Young, there's still two extra closing parens in the question code. – abo-abo Oct 22 '13 at 21:18
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))))
uselpa
  • 18,732
  • 2
  • 34
  • 52
1

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))))
Sylwester
  • 47,942
  • 4
  • 47
  • 79