views:

308

answers:

5

I'm trying to write some code to remove the first N characters in a string. I could have done this in an imperative manner already, but I would like to see it done in the spirit of functional programming. Being new to F# and functional programming, I'm having some trouble...

+13  A: 
"Hello world".[n..];;
Jeff
+1  A: 

As @Jeff has shown, you can do this in six characters, so this is not necessarily the best question to ask to see how to "do it in the spirit of functional programming".

I show another way, which is not particularly "functional" (as it uses arrays, but at least it doesn't mutate any), but at least shows a set of steps.

let s = "Hello, world!"
// get array of chars
let a = s.ToCharArray()
// get sub array (start char 7, 5 long)
let a2 = Array.sub a 7 5
// make new string
let s2 = new string(a2)
printfn "-%s-" s2  // -world-
Brian
A: 
let rec remove_first_n (str:string) (n:int) =
  match str, n with
  | _, n when n <= 0 -> str
  | "", _ -> ""
  | _ -> remove_first_n (str.Remove(0,1)) (n-1)
jason
+1 for showing typical recursive function structure, but -2 for coming up with an O(n) solution to an O(1) problem
Brian
Why should this be O(1)?
Dario
Oops, I mean O(N^2) versus O(N).
Brian
A: 

Another way to do it (not particularly functional either). In fact it uses features of both world: mutation and lambda:

let remove_first_n (s:string) (n:int) =
    let arr = Array.create (s.Length-n) '0'
    String.iteri (fun i c -> if i>=n then arr.[i-n] <- c else ()) s
    new string(arr)

That being said, I think the best way is Jeff's solution.

One more thing to keep in mind is that Strings are immutable in .NET (a string value cannot be modified once built) and that F# strings are actually .NET Strings.

Stringer Bell
A: 
"Hello world".Substring 3
The_Ghost