Thanks to everyone for their implementations. They are all both insightful and humbling. :)

Jim

By on 12/18/2007 5:00 PM ()

Hi, I see that Julien was faster :-) anyway, my implementation is a bit different, so it might be useful to see them both. In my example, the inner recursive function (reverseAux) is using direct access to the string character at specified index and is generating list of characters (char list) and finally creates a string from this list of characters.

1
2
3
4
5
let reverse (s:string) =
  let rec reverseAux idx acc =
    if (idx = s.Length) then acc
    else reverseAux (idx+1) ((s.[idx])::acc)
  new string(Array.of_list (reverseAux 0 []))

A few things to note - concatation of strings in .NET is a bit inefficient, since it is creating a copy of the whole string (though it will not be problem for short strings), so the sample is creating a list of characters (where append to the beginning should be more efficient).

By on 12/16/2007 4:25 AM ()

I really don't see why you shouldn't do this the obvious way

1
2
3
4
5
6
7
8
 
let reverse s =
    let n = String.length s
    let cs = Array.zero_create n
    for i = 1 to n do
        cs.[i - 1] <- s.[n - i]
    done
    new string(cs)
By on 12/16/2007 4:34 AM ()

As string implements seq<char>, you can also use

1
2
3
4
5
 

let reverse (s:string) = new string(s |> Seq.to_array |> Array.rev)

By on 12/18/2007 4:11 PM ()
1
2
3
4
5
6
7
  let reverse s =
    let rec reverse s acc =
      match s with
      | "" -> acc
      | s -> reverse (String.sub s 1 (String.length s - 1)) (String.sub s 0 1 :: acc)
    reverse s [] |> (String.concat "")
      
By on 12/16/2007 4:07 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper