lundi 5 septembre 2016

New to Racket: why is the if statment effecting the return?

I just started learning Racket so I am still trying to figure out the intricacies of the language. I am trying to implement my own search function in a list. If the function finds it, it returns the index, otherwise it returns -1.

(define (find-index list item)
  (if (equal? (length list) 1)
      (if (equal? (first list) item) 0 1)
      (if (equal? (first list) item)
          0
          (+ 1 (my-search (rest list) item)))))

So the find-index function is a recursive function that walks through the list looking for an item that is equivalent to "item." I have written it so that, if there are 4 elements in a list, the function can return any number between 0-4.

(define (my-search list item)
  (define length (my-length list))
  (define index (find-index list item))
  (if (= index length) -1 index))

My idea is that if the find-index function returns a number equal to the list's length, it means the function did not find the item, therefore my-search function is supposed to return -1.

However, when I put in

(my-search (list "apple" "barbecue" "child" "demon" "enter") "fire")

the result I get is 3, instead of -1. If I print index before the if statement the index is 3 instead of 5. If

(if (= index length) -1 index))

is not part of the my-search function then everything is fine.

What I think is going on is that index is the id for the function itself, not the result of the function. However, I don't see why that effects the returning result of my-search. Is anyone willing to shed some light on this question?

Also, any style critique is welcome. I would like to know if I am not following conventions.

Aucun commentaire:

Enregistrer un commentaire