Search code examples
smlsmlnj

Ideas for reversing strings in SML


I'm very new to SML, and have some background in C/C++. I've been trying to write a function called reverseString, which receives a string to reverse. Pretty straightforward. Using an auxiliary function, I was able to write a function which reverses any given string, with an extra character added to the result. For example:

- reverseString("hello");
val it = "ollehh" : string

Any help with how to overcome this obstacle will be extremely helpful. Please keep in mind that I'm trying to implement the function without any additional function (that is, functions which haven't been used in my broken implementation):

fun reverseAux(s:string, i:int) : string = 
    if i = 0 then str(String.sub(s, 0)) 
    else str(String.sub(s, i-1)) ^ reverseAux(s, i-1);

fun reverseString(s:string) : string = 
    reverseAux(s, size(s));

Solution

  • In addition to my comment, this is an easier solution once you know about pattern matching:

    fun helper [] = []
    | helper [x] = [x]
    | helper (l::ls) = (helper ls) @ [l];
    
    fun reverse s = implode (helper (explode s));
    

    explode and implode are functions that respectively convert a string into a char list and vice versa. A list is easier to traverse than a string.