获取字符串中指定位置的一个char

Get a char at a specified position in the string

如何以 FP 方式获取字符串中指定位置的字符(即没有脏 .[index] hack)?

如果我使用 Seq.item 它将迭代所有索引直到 n 元素,所以每次都使函数 运行 非常慢。

在下面的示例中,如果 sourcestring,它将是 O(1) 访问权限,否则它将是 O(n) 访问权限。

let getItem index source =
    match box source with
    | :? string as string -> printfn "String"; string.[index]
    | _ -> printfn "Seq<char>"; Seq.item index source
let stringChar3 = getItem 3 "ABCD"
let seqChar3 = getItem 3 [ for c in ['A'..'D'] do yield c ]

val getItem : index:int -> source:seq<char> -> char
val stringChar3 : char = 'D'
val seqChar3 : char = 'D'

FSharp.Core 中的 String 模块功能不是很齐全,但您可以创建自己的模块并包含一些可与类型推断很好地配合使用的可重用函数,然后您只需编写显式类型注释一次,您就可以在其他地方使用类型推断。

module String =
    let tryGetCharacter index (str : string) =
        if index >= 0 && index < str.Length then
            Some str.[index]
        else
            None

    let getCharacter index (str : string) =
        str.[index]