Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 获取字符串中指定位置的字符_.net_String_F#_Functional Programming_Seq - Fatal编程技术网

.net 获取字符串中指定位置的字符

.net 获取字符串中指定位置的字符,.net,string,f#,functional-programming,seq,.net,String,F#,Functional Programming,Seq,如何以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]

如何以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'
让getItem索引源=
将框源与
| :? 字符串为字符串->打印FN“字符串”;字符串。[索引]
|_u->printfn“Seq”;Seq.item索引源
让stringChar3=getItem 3“ABCD”
让seqChar3=getItem 3[对于['A'..'D']中的c,不产生c]
val getItem:index:int->source:seq->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]
模块字符串=
let tryGetCharacter索引(str:string)=
如果索引>=0&&index
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]
模块字符串=
let tryGetCharacter索引(str:string)=
如果索引>=0&&index
如何使用
[index]
一个“肮脏的黑客”?这就是获得O(1)访问权限的方法。@Lee,因为我需要向函数添加显式类型注释,但我暂时无法添加。如何使用
[index]
这一“肮脏的黑客”呢?这是获得O(1)访问权限的方法。@Lee,因为我需要向函数添加显式类型注释,目前我无法添加。我建议分别命名那些
tryItem
item
,以与
Seq
中的等效函数保持一致,
List
Array
模块。我建议分别命名
tryItem
item
,以与
Seq
List
Array
模块中的等效函数保持一致。