F# 如何创建一个列表来检查字符串中的字符,并返回每个字符的计数和剩余字母的0?

F# 如何创建一个列表来检查字符串中的字符,并返回每个字符的计数和剩余字母的0?,f#,F#,我需要写一个函数来计算字符串中每个字母的出现次数 到目前为止,我已经能够获取一个字符串,然后返回一个列表,其中包含字符串中字符的出现次数。(例如,如果我打印直方图(“Absbs”),函数将返回[1;2;2])。但是,如果字符串中没有出现字符,则函数需要返回0。 我该怎么做 let histogram (src:string) = let dat = src.ToLower() |> Seq.countBy id |> Seq.map snd |> Seq.toList

我需要写一个函数来计算字符串中每个字母的出现次数

到目前为止,我已经能够获取一个字符串,然后返回一个列表,其中包含字符串中字符的出现次数。(例如,如果我打印直方图(“Absbs”),函数将返回[1;2;2])。但是,如果字符串中没有出现字符,则函数需要返回0。 我该怎么做

let histogram (src:string) =
    let dat = src.ToLower() |> Seq.countBy id |> Seq.map snd |> Seq.toList

此外,我不能使用循环或可变变量

这可能不是最快的方法,但它会起作用:

let histogram (src:string) =
    let dat = src.ToLower() |> Seq.countBy id 
    [ 'a' .. 'z' ]
        |> List.map (fun x -> match dat |> Seq.tryFind (fun (c,_) -> x = c) with
                                    | Some (p,q) -> (p,q)
                                    | _ -> (x,0) )

let bars = histogram "test this"

for c,i in bars do
    printfn "%c : %i" c i

您可能需要研究
groupJoin
查询语法,该语法基于键的相等性将两个s的元素关联起来,并对结果进行分组。组的长度是匹配数

let histogram (alphabet : seq<_>) (source : seq<_>) = query{
    for letter in alphabet do
    groupJoin element in source on (letter = element) into group
    select (Seq.length group) }
// val histogram : alphabet:seq<'a> -> source:seq<'a> -> seq<int>

histogram {'a'..'z'} "test this" |> Seq.toList
// val it : int list =
//   [0; 0; 0; 0; 1; 0; 0; 1; 1; 0; 0; 0; 0; 0; 0; 0; 0; 0; 2; 3; 0; 0; 0; 0; 0;
//    0]
let histogram (alphabet : seq<_>) (source : seq<_>) = query{
    for letter in alphabet do
    groupJoin element in source on (letter = element) into group
    select (Seq.length group) }
// val histogram : alphabet:seq<'a> -> source:seq<'a> -> seq<int>

histogram {'a'..'z'} "test this" |> Seq.toList
// val it : int list =
//   [0; 0; 0; 0; 1; 0; 0; 1; 1; 0; 0; 0; 0; 0; 0; 0; 0; 0; 2; 3; 0; 0; 0; 0; 0;
//    0]
let histogramLinq alphabet source =
    System.Linq.Enumerable.GroupJoin(
        alphabet, 
        source, 
        (fun letter -> letter), 
        (fun element -> element), 
        fun _ group -> Seq.length group )
// val histogramLinq :
//   alphabet:System.Collections.Generic.IEnumerable<'a> ->
//     source:System.Collections.Generic.IEnumerable<'a> ->
//       System.Collections.Generic.IEnumerable<int>