2017-05-02 55 views
0

如何在FP方式的字符串中的指定位置獲取字符(即沒有骯髒的.[index]黑客)?在字符串中的指定位置獲取字符

如果我使用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' 
+7

如何使用'。[index]'「骯髒的黑客」?這是獲得O(1)訪問權限的方式。 – Lee

+0

@Lee因爲然後我需要添加明確的類型註釋的功能,我暫時不能。 – MiP

回答

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] 
+0

我建議分別命名這些'tryItem'和'item',以便與'Seq','List'和'Array'模塊中的等價函數保持一致。 – Tarmil