HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Add spaces before uppercase letters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uppercasespacesbeforeaddletters

Problem

I'm trying to convert some very simple C# string utility functions to F# as a learning exercise. Ignore the fact that the C# version is implemented as an extension method for the moment.

The function adds a blank space before any upper case letters (with the exception of the very first char) - so, "ATestString" becomes "A Test String":

return string.Concat(str.Select(x => Char.IsUpper(x) ? " " + x : x.ToString())).TrimStart(' ');


My first pass using F#:

let padWithSpace str = 
    (str |> Seq.fold (fun acc elm -> if Char.IsUpper(elm) then acc + (sprintf " %c" <| elm) else acc + (string elm)) "").TrimStart([| ' ' |])


Is there a more concise, or more importantly, idiomatic way to do this in F#?

Solution

String.collect is equivalent to Select+Concat.

let padWithSpace = 
    String.collect (fun c -> (if Char.IsUpper c then " " else "") + string c) 
    >> fun s -> s.TrimStart()

Code Snippets

let padWithSpace = 
    String.collect (fun c -> (if Char.IsUpper c then " " else "") + string c) 
    >> fun s -> s.TrimStart()

Context

StackExchange Code Review Q#69873, answer score: 4

Revisions (0)

No revisions yet.