tags:

views:

68

answers:

3

How do I check, in DrScheme, whether a string contains a given character / substring? How do I include the proper module if it is defined in a module?

A: 

There is no standard procedure to do this. SRFI 13 contain the procedure you need (string-index). Please check if your Scheme implements this SRFI.

Vijay Mathew
A: 

Here is a quick hack. It returns the index (0 based) of string s in string t. Or #f if not found. Probably not the best way to do it if your Scheme has SRFI-13 support, or other built-in support.

Code edited. Thanks to Eli for suggestions.

(define (string-index s t)
  (let* ((len (string-length s))
        (max (- (string-length t) len)))        
    (let loop ((i 0))
      (cond ((> i max) 
             #f)
            ((string=? s
                       (substring t i (+ i len)))
             i)
            (else (loop (+ i 1)))))))
z5h
In Scheme we use `else`, not `#t`. Also, why would you want to return -1 if it's not found?
Eli Barzilay
-1 is an every-other-language-other-than-scheme-ism. My bad. There is something I personally like about #t. A saved keystroke. A certain symmetry. I didn't mean to offend.
z5h
I know how other languages use -1 -- there are two reasons for this: (a) in some languages you must return a specific type, so you need to find an integer that cannot be a normal result; (b) there are languages that allow returning a value of any type, but make "false" be the same as zero. Scheme doesn't suffer from either problem.As for the `else` thing -- you should at least be aware of the expansion being different: with `#t` you basically get `(if #t ...)` which not all schemes optimize away.
Eli Barzilay
All good information. Thank you.
z5h
I have a one-liner that does this by using string->list and foldl, but I was looking for a cleaner way. This looks more cumbersome
Claudiu
+1  A: 

In DrScheme, assuming the language is set to "Module", the following will work

#lang scheme
(require (lib "13.ss" "srfi"))

(string-contains "1234abc"  "abc")
z5h