0
votes

I need help with one issue: I can't handle how to get the first atom from the list in SCHEME language. I think I should make a loop, something like "while" and compare each element on boolean (?atom) and print first matched item. Unfortunately, It's difficult for me to handle scheme syntax. Please, can you propose any solution for me?

define func ?atom:
(define (atom? x) (not (or (pair? x) (null? x))))
2

2 Answers

0
votes

Recursion is not that different from the usual way yo solve problems - you just have to be careful and set some meaningful base cases. For instance, how would you solve this problem in Java? by traversing all the list, and stoping when either 1) we found the element that matches the condition or 2) there are no more elements. This is exactly what we need to do:

(define (first-atom lst)
  (cond ((null? lst) #f)           ; there are no more elements in the list
        ((atom? (car lst))         ; current element is an atom
         (car lst))                ; return it
        (else                      ; otherwise
         (first-atom (cdr lst))))) ; look in the rest of the list

It works as expected:

(first-atom '((2) 42 (3)))
=> 42
(first-atom '((1) (2)(3)))
=> #f
0
votes

In your question you have the definition to atom? that returns #t if the argument is an atom and #f otherwise.

The function should handle the empty list. eg. What should happen when you do this:

(first-atom '())

Thus you need to check if the argument is the empty list and return whatever you supposed to return when there are no atoms in the arguments. Then you'll have a else expression that handles the rest.

You can use first to get the first element to check if it is an atom and then return it or you recure with the rest of the list.

Now here is something very similar that finds the number of elements in a list:

(define (length lst)
  (if (null? lst)
      0                          ; obviously a 0 length list
      (+ 1 (length (cdr lst))))) ; obviously one plus whatever length the rest is

Imagine what happens if you do (length '(1 2)). It does (+ 1 (length '(2))) which again does (+ 1 (+ 1 (length '()))) which again does (+ 1 (+ 1 0)). Simple as that. All loops are recursive functions in Scheme.

You reference to while indicates you might be familiar with other programming languages. I knew C, C++, Pascal, perl, PHP, and Java when starting to learn Lisp and I suddenly realized all the languages I knew were only subtle dialects of one language, Algol. I wasn't learning my sixth language, but my second. Scheme doesn't have a while loop. It has recursion. you need to get a book and start at the first page as if you didn't know how to program at all as assimilation from Algol will point you in the wrong direction.