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...
+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
2009-11-01 04:41:11
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
2009-11-01 05:57:44
+1 for showing typical recursive function structure, but -2 for coming up with an O(n) solution to an O(1) problem
Brian
2009-11-01 06:06:47
Why should this be O(1)?
Dario
2009-11-01 16:51:48
Oops, I mean O(N^2) versus O(N).
Brian
2009-11-02 05:19:19
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
2009-11-01 16:25:37