如何以FP方式在字符串中的指定位置获取char(即没有脏.[index]
hack)?
如果我使用Seq.item
,它将迭代所有索引,直到n
元素,因此每次都使该函数运行得非常慢。
在下面的示例中,如果source
是string
,则会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'
答案 0 :(得分:2)
String
中的FSharp.Core
模块实际上并不是非常全功能,但您可以创建自己的模块并包含一些可以与类型推断很好地兼容的可重用函数,然后您只需要编写显式类型注释一次,您可以在其他地方使用类型推断。
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]