f#在char数组中查找字符串的索引

f#在char数组中查找字符串的索引,f#,F#,嘿,我对F#是新来的 我试图找到一个字符数组中所有出现的字符串的起始索引 e、 g。 字符数组['a';'b';'b';'a';'b';'b';'b';'b';'b';'a';'b'] 如果搜索字符串“ab”,将返回0、3和9这里我不想做一个完整的示例,下面是提示: let rec match (l:char seq) i= match seq.tryFindindex ... (*the part you have already done goes here*)with |

嘿,我对F#是新来的

我试图找到一个字符数组中所有出现的字符串的起始索引

e、 g。 字符数组['a';'b';'b';'a';'b';'b';'b';'b';'b';'a';'b']


如果搜索字符串“ab”,将返回0、3和9

这里我不想做一个完整的示例,下面是提示:

let rec match (l:char seq) i= 
    match seq.tryFindindex ... (*the part you have already done goes here*)with
    |None -> []
    |Some(t) ->i+t::(match (Seq.skip t l) (i+t)

基本上,我们只是重复应用
Findindex
,直到它停止匹配。

下面是一个使用递归函数的解决方案:

/// Wraps the recursive findMatches function defined inside, so that you don't have to seed it with the "internal" paramters
let findMatches chars str =
  /// Returns whether or not the string matches the beginning of the character array
  let rec isStartMatch chars (str: string) =
    match chars with
    | char :: rest when str.Length > 0 ->
      char = str.[0] && (isStartMatch rest str.[1..(str.Length - 1)])
    | _ -> str.Length = 0
  /// The actual function here
  let rec findMatches matchedIndices i chars str =
    match chars with
    | _ :: rest ->
      if isStartMatch chars str
      then findMatches (i :: matchedIndices) (i + 1) rest str
      else findMatches matchedIndices (i + 1) rest str
    | [] -> matchedIndices

  findMatches [] 0 chars str

不是最有效的,因为如果字符是匹配的一部分,它会在字符上迭代两次,但这并不是什么大问题。

你能指出你的困境吗?我曾尝试使用List.FindIndex,但它只返回第一个索引,是否也返回9?这可以通过多种方式解决-也许最好先看看你可以使用的不同算法,以便你对你要做的事情有所了解:让rec-find(l:char-seq)i=match-seq.tryFindIndex(fun a->String.Compare(a,searchSeq)=0)与| None->【】Some(t)->i+t::(find(seq.skip tl)(i+t))表示None不是真的int。我如何允许这种结果?