优化F#字符串操作

Nor*_*n H 6 string f#

我刚学习F#并且已经将C#扩展方法库转换为F#.我目前正在基于下面C#实现来实现一个名为ConvertFirstLetterToUppercase的函数:

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);
}
Run Code Online (Sandbox Code Playgroud)

F#实现

[<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())
Run Code Online (Sandbox Code Playgroud)

有人能用更自然的F#语法向我展示更简洁的实现吗?

Jul*_*iet 17

open System

type System.String with
    member this.ConvertFirstLetterToUpperCase() =
        match this with
        | null -> null
        | "" -> ""
        | s -> s.[0..0].ToUpper() + s.[1..]
Run Code Online (Sandbox Code Playgroud)

用法:

> "juliet".ConvertFirstLetterToUpperCase();;
val it : string = "Juliet"
Run Code Online (Sandbox Code Playgroud)


des*_*sco 5

像这样的东西?

[<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)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个,只需注意,您可以将空数组或空数组检查与以下内容组合以减少行数:| null | [||] - >这个 (2认同)