我已经编写了此F#代码以计算列表中的单词频率,并将元组返回给C#。您能否告诉我如何使代码更高效或更短?

let rec internal countword2 (tail : string list) wrd ((last : string list), count) =
match tail with
| [] -> last, wrd, count
| h::t -> countword2 t wrd (if h = wrd then last, count+1 else last @ [h], count)

let internal countword1 (str : string list) wrd =
let temp, wrd, count = countword2 str wrd ([], 0) in
temp, wrd, count

let rec public countword (str : string list) =
match str with
| [] -> []
| h::_ ->
  let temp, wrd, count = countword1 str h in
       [(wrd, count)] @ countword temp

最佳答案

如果您要计算字符串列表中的单词频率,则您的方法似乎有些过激。 Seq.groupBy非常适合此目的:

let public countWords (words: string list) =
   words |> Seq.groupBy id
         |> Seq.map (fun (word, sq) -> word, Seq.length sq)
         |> Seq.toList

10-02 03:06