Ask Your Question
0

Can you provide a LISP code that displays the even numbers from a list that has 10 values?

asked 2023-05-28 01:52:31 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-05-28 02:19:02 +0000

david gravatar image

Yes, here is an example LISP code to display the even numbers from a list of 10 values:

(defun even-numbers (lst)
  (cond ((null lst) nil)
        ((evenp (car lst)) (cons (car lst) (even-numbers (cdr lst))))
        (t (even-numbers (cdr lst)))))

(setq lst '(1 2 3 4 5 6 7 8 9 10))

(print (even-numbers lst))

Explanation:

  1. We define a function called even-numbers which takes a single argument lst. This function will use recursion to traverse the list and find the even numbers.

  2. In the first line inside the function, we check if the input list is null. If it is, we return nil.

  3. The evenp function takes a single argument and checks if it is even. We use it to check if the first element of lst is even or not.

  4. If it is even, we add it to the list of even numbers by using the cons function, and then call even-numbers again with the rest of the list (i.e., without the first element).

  5. If the first element is not even, we call even-numbers again with the rest of the list.

  6. Finally, we call the print function to display the list of even numbers.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-28 01:52:31 +0000

Seen: 1 times

Last updated: May 28 '23