tags:

views:

161

answers:

5

I am developing a small program in Scheme but I got stuck. Is there anything similar to Java's indexOf() that I could use in Scheme?

+1  A: 

There may be, but typically professors want you to write your own.

Here is C style psuedo code since I don't want to remember the syntax.

int indexOf(element, list, i)
{
    if car(list) == element then
        return i+1;
    else
        indexOf(element, cdr(list), i+1);
}

Note that calling it requires passing in 0 for i (You could write a wrapper if you like), and that this is 1 based indexing, change the return to be i if you want 0 based indexing

Guvante
A: 

It's not clear from your question what Scheme implementation you're using.

If it's PLT Scheme, you're probably looking for something like "regexp-match-positions".

(car (car (regexp-match-positions (regexp-quote "zip") "zapzipdingzip")))

=>

3
John Clements
+1  A: 

Assuming you're trying to search in strings (and that it's not an assignment intended to help you grok recursion) then you might try the functions here:

http://okmij.org/ftp/Scheme/util.html

Ryan
The site you sent me is really helpful.Thank you!
Charles Brow Jr.
A: 

For instance in PLT-Scheme, the way to go is to convert the string to a list using string->list and then operating on the list with one of the many available methods. Convert the list back to a string when done.

Confusion
A: 

Searching list (pretty safe):

(define indexOf
  (lambda (element lst)
    (indexOfHelper element lst 0)))

(define indexOfHelper
  (lambda (e l i)
    (cond
      [(null? l) -1]
      [(equal? e (car l)) i]
      [else (indexOfHelper e (cdr l) (+ i 1))])))
danielrsmith