0
votes

I'm very new to Scheme and am working on a problem defined as follows:

Write a scheme function find-loc which takes two parameters, a list lst and an atom atm, and returns the index of the first location where atm occurs in the list. The location index is 1-relative. If atm does not occur in the list, the function returns n + 1, where n is the length of the list.

what I've got so far is:

(define (find-loc list atm)
  (if (not(list? list))
     0 
    (cond
      ((null? list)
        1)
      ((eq? (car list)atm)
        1))
       (else (+ (find-loc (cdr list atm) 1) )))

I feel that I'm close but am a bit stuck. My main questions are as follows:

  1. how do I define what the atom is?

  2. why am I getting the following error? "define: expected only one expression for the function body, but found 1 extra part"

1

1 Answers

1
votes

An atom is defined by this predicate:

(define (atom? x)
  (and (not (null? x))
       (not (pair? x))))

The error you're receiving is because the syntax of the if expression is incorrect - it must have two parts after the condition (consequent and alternative), and you wrote three. A few comments:

  • It's better to use a cond when testing for multiple conditions
  • Don't name a variable as list, it clashes with a built-in procedure of the same name
  • Better use equal? for testing equality, it's more general
  • We should use our new and shiny atom? predicate, as per the requirements - even though the null? check is redundant at this point

This is what I mean:

(define (find-loc lst atm)
  (cond ((not (list? lst)) 0)
        ((null? lst) 1)
        ((and (atom? (car lst)) (equal? (car lst) atm)) 1)
        (else (+ 1 (find-loc (cdr lst) atm)))))