PDA

View Full Version : All substrings of a string


woodwind
06-07-2004, 03:38 AM
Hey. I'm trying to write a function (really, a set of functions) to return all substrings of a given string. I have what you say see below so far, but it isn't elegant.


(* All substrings of a given length, len *)
fun f s len foo =
if (foo <= size(s)-len) then (substring(s,foo,len)::(f s len (foo+1)))
else []

(* All substrings of a string *)
fun allSubstrings s 0 = []
| allSubstrings s l = ((f s l 0)@(allSubstrings s (l-1)))


One thing I'd like to do is make it so that l (length) does not have to be passed to allSubstrings. I could do something like:

let
fun allSubstrings' s 0 = []
| allSubstrings' s l = ((f s l 0)@(allSubstrings s (l-1)))
in
fun allSubstrings s = allSubstrings' s (size s)
end

But that doesn't seem very elegant.

Any suggestions?