【发布时间】:2017-09-30 06:51:55
【问题描述】:
如何以 FP 方式获取字符串中指定位置的字符(即没有脏 .[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'
【问题讨论】:
-
如何使用
.[index]一个“肮脏的黑客”?这是获得 O(1) 访问权限的方法。 -
@Lee 因为那时我需要在函数中添加显式类型注释,而我暂时不能。
标签: .net string f# functional-programming seq