0

Lisp programming You would need to create a code that will loop through the integer and will create a triangle with the integer provided. Again the question is "Write a lisp function triangle that takes an odd number as the argument (n) and shows a triangle of printed odd numbers as shown in the following samples. If the input is even, decimal or string, it should print an appropriate message". It should show an error for decimal numbers (which I did) and also for even number but not so sure compute that in my code.

This code works and creates a triangle but it does not do it for ONLY odd numbers. ex: 1

1 3

1 3 5

1 3 5 7

1 3 5 7 9

my code output (triangle 3):

1

12

123

(defun triangle (n)
    (if (typep n'integer)
        (loop for i from 1 to n
              do (loop for j from 1 to i
                       do (write j)
                       )
              (write-line "")
        )
    (write-line "Decimal numbers are not valid input, Please enter an integer"))
    )
(triangle 3)

i except the out to have only odd numbers and give an error for decimal and even numbers.

2 Answers2

3

Hints:

  • is there a predicate which tells you if a number is odd (have a look at the code below for a clue)?
  • can you work out how to get loop to count by intervals other than 1, because if you can count by 2 then you can enumerate odd numbers.

But sometimes I just can't resist an answer you can't (and should not) submit:

(defun triangle (n)
  (assert (typep n '(and (integer 1)
                         (satisfies oddp)))
      (n) "~S is not a positive odd integer" n)
  ((lambda (c) (funcall c c n))
   (lambda (c m)
     (when (> m 1)
       (funcall c c (- m 2)))
     (format t "~{~D~^ ~}~%"
             ((lambda (c) (funcall c c m '()))
              (lambda (c i a)
                (if (< i 1)
                    a
                  (funcall c c (- i 2) (cons i a))))))
     m)))
0

I am not quite sure if i understood your question, but here is a solution that print the odd number from 1 to N as a triangle. You need to use the BY keyword in your loop as a step between your numbers, then all works. Also you can use the ASSERT function for making any assertions before you perform any further actions:

(defun triangle (N)
  ;; Use ASSERT for checking prerequisites before the opration starts
  ;; More on ASSERT here: http://clhs.lisp.se/Body/m_assert.htm
  (assert (and (integerp 8) (oddp N)) (N) "~A is not an odd integer" N)
  ;; You should add the steps to keep numbers odd with BY
  (loop for i from 1 to N by 2
     do (loop for j from 1 to i by 2
       do (princ j))
    (terpri))) 

Now this prints what you want:

(triangle 9)
; 1
; 13
; 135
; 1357
; 13579
;  => NIL

You can also check my answer to basically same question, which is solved recursively: Trying to print a triangle recursively in lisp

Student
  • 708
  • 4
  • 11