Created
February 4, 2011 17:45
-
-
Save atifaziz/811438 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
let sliceClip len index = | |
match index with | |
| _ when index < 0 -> | |
let index = len + index | |
if index < 0 then 0 else index | |
| _ when index > len -> len | |
| _ -> index | |
let rec slice (str : string) start stop = | |
match str with | |
| null -> raise (ArgumentNullException("str")) | |
| _ -> | |
match stop with | |
| None -> slice str start (Some(str.Length)) | |
| Some(stop) -> | |
let clipper = sliceClip str.Length | |
let start, stop = clipper start, clipper stop | |
let len = stop - start | |
if len > 0 then str.Substring(start, len) else String.Empty | |
type String with | |
member self.Slice(start) = | |
slice self start None | |
member self.Slice(start, stop) = | |
slice self start (Some(stop)) | |
let sample = "F# is cool" | |
let tests = [ | |
sample.Slice(0), "F# is cool"; | |
sample.Slice(-4), "cool"; | |
sample.Slice(3, 5), "is"; | |
sample.Slice(-7, -5), "is"; | |
sample.Slice(3), "is cool"; | |
sample.Slice(0, 2), "F#"; | |
sample.Slice(0, -8), "F#"; | |
] | |
let print = printfn "%-4s : Expected <%-10s> Actual <%-10s>" | |
for actual, expected in tests do | |
print (if expected = actual then "OK" else "FAIL") expected actual |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment