我需要帮助翻译IndexOfAny for string的自定义扩展,因为现有框架没有匹配字符串值的IndexOfAny.已经翻译了我自己的.但是我不知道如何通过返回值突破循环.任何想法如何摆脱循环或更好的解决方案.以下是我的翻译.
C#
public static int IndexOfAnyCSharp(this string str, string[] anyOff) {
if (str != null && anyOff != null)
foreach (string value in anyOff) {
int index = str.IndexOf(value);
if (index > -1) return index;
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
F#
[<Extension>]
static member public IndexOfAnyFSharp(str:string, anyOff:string[]) =
match str <> null && anyOff <> null with
| true ->
let mutable index = -1
for value in anyOff do
if index = -1 then
index <- str.IndexOf(value)
index
| false -> -1
Run Code Online (Sandbox Code Playgroud)
Seq.tryFind
是你的朋友.一个基本的构建块就像是
let IndexOfAny (s: string, manyStrings: string seq) =
manyStrings
|> Seq.map (fun m -> s.IndexOf m)
|> Seq.tryFind (fun index -> index >= 0)
Run Code Online (Sandbox Code Playgroud)
None
如果没有匹配,这将返回- 这比返回-1更加惯用F#:编译器将强制您考虑没有匹配的情况.
更新:您可能更喜欢:
let IndexOfAny (s: string, manyStrings: string seq) =
manyStrings
|> Seq.tryPick (fun m ->
match s.IndexOf m with
| -1 -> None
| i -> Some i
)
Run Code Online (Sandbox Code Playgroud)