4
\$\begingroup\$

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#?

jsanc623
2,86416 silver badges22 bronze badges
asked Nov 14, 2014 at 18:10
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

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()
answered Nov 14, 2014 at 20:25
\$\endgroup\$
1
  • \$\begingroup\$ Ah function composition, never thought of that. Hence my status as newbie ;) I think I like this better. \$\endgroup\$ Commented Nov 14, 2014 at 21:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.