【问题标题】:Get a char at a specified position in the string获取字符串中指定位置的字符
【发布时间】:2017-09-30 06:51:55
【问题描述】:

如何以 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'

【问题讨论】:

  • 如何使用.[index] 一个“肮脏的黑客”?这是获得 O(1) 访问权限的方法。
  • @Lee 因为那时我需要在函数中添加显式类型注释,而我暂时不能。

标签: .net string f# functional-programming seq


【解决方案1】:

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]

【讨论】:

  • 我建议将它们分别命名为 tryItemitem,以便与 SeqListArray 模块中的等效功能保持一致。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 2013-09-22
  • 1970-01-01
  • 2022-10-31
  • 2015-05-17
  • 1970-01-01
相关资源
最近更新 更多