Optimization of file manipulation F #

I am just learning F # and converting a library of C # extension methods to F #. I am currently working on the implementation of the ConvertFirstLetterToUppercase function based on the C # implementation below :

public static string ConvertFirstLetterToUppercase(this string value) { if (string.IsNullOrEmpty(value)) return value; if (value.Length == 1) return value.ToUpper(); return value.Substring(0, 1).ToUpper() + value.Substring(1); } 

F # implementation

 [<System.Runtime.CompilerServices.ExtensionAttribute>] module public StringHelper open System open System.Collections.Generic open System.Linq let ConvertHelper (x : char[]) = match x with | [| |] | null -> "" | [| head; |] -> Char.ToUpper(head).ToString() | [| head; _ |] -> Char.ToUpper(head).ToString() + string(x.Skip(1).ToArray()) [<System.Runtime.CompilerServices.ExtensionAttribute>] let ConvertFirstLetterToUppercase (_this : string) = match _this with | "" | null -> _this | _ -> ConvertHelper (_this.ToCharArray()) 

Can someone show me a more concise implementation using the more natural F # syntax?

+6
string f #
source share
4 answers

Something like that?

 [<System.Runtime.CompilerServices.ExtensionAttribute>] module public StringHelper = [<System.Runtime.CompilerServices.ExtensionAttribute>] let ConvertFirstLetterToUppercase (t : string) = match t.ToCharArray() with | null -> t | [||] -> t | x -> x.[0] <- Char.ToUpper(x.[0]); System.String(x) 
+5
source share
 open System type System.String with member this.ConvertFirstLetterToUpperCase() = match this with | null -> null | "" -> "" | s -> s.[0..0].ToUpper() + s.[1..] 

Using:

 > "juliet".ConvertFirstLetterToUpperCase();; val it : string = "Juliet" 
+17
source share

Try to execute

 [<System.Runtime.CompilerServices.ExtensionAttribute>] module StringExtensions = let ConvertFirstLetterToUpperCase (data:string) = match Seq.tryFind (fun _ -> true) data with | None -> data | Some(c) -> System.Char.ToUpper(c).ToString() + data.Substring(1) 

The tryFind function will return the first element for which lambda returns true . Since it always returns true, it simply returns the first element or None . After you have created, there is at least one element that, as you know, data not null and, therefore, can call a substring

+4
source share

There is nothing wrong with using .NET library functions from the .NET language. Perhaps a direct translation of your C # extension method is most suitable, especially for such a simple function. Although I will be tempted to use the cut syntax, as Juliet does, just because it's cool.

 open System open System.Runtime.CompilerServices [<Extension>] module public StringHelper = [<Extension>] let ConvertFirstLetterToUpperCase(this:string) = if String.IsNullOrEmpty this then this elif this.Length = 1 then this.ToUpper() else this.[0..0].ToUpper() + this.[1..] 
+2
source share

All Articles