gpt4 book ai didi

f# - 如何计算字符串中特定字符的出现次数

转载 作者:行者123 更新时间:2023-12-01 06:05:16 25 4
gpt4 key购买 nike

我不确定从哪里开始检查字符串是否出现了 n 次特定字符。我已经列出了我认为是函数框架的基本轮廓,但我不确定的内容是什么?

let countCharFromNth (getStr : string)(chkdChar : char) = 
if getStr.Length >=1 then

else printfn "Not enough arguments"

最佳答案

TL;博士

“最惯用的”方式可能是@Mark Seemanns:

let count x = Seq.filter ((=) x) >> Seq.length

电话 oo L 部分

请注意,此函数是完全通用的: x:'a -> (seq<'a> -> int) when 'a : equality ,即它计算任何 x 的出现次数在 'a 的序列中s,只要 'a支持平等。由于右侧是一个函数,我们也不需要指定字符串参数。这叫做 point-free风格。
该函数是通过转动 =来构造的。将运算符括在括号中(想想 (=) = fun x y -> x = y ),用这个谓词过滤序列并计算结果 seq s 长度,即
let count x xs =
xs
|> Seq.filter (fun x' -> x' = x)
|> Seq.length

这是
let count x xs =
Seq.length(Seq.filter (fun x' -> x' = x) xs)

当然,您也可以利用“C# 方式”:
let count' x xs = System.Linq.Enumerable.Count(xs, fun x' -> x' = x)

在这里你不能只转动相等运算符 (=)变成谓词,因为 F# 编译器需要做一些魔法来转换 F# 'a -> boolFunc<'a, bool> .

用法完全一样:
count 'a' "abbbac"

或(更易读)
"abbbac" |> count 'a'
"abbac" |> count' 'b'

这(以及更好的可组合性)是函数式程序员倾向于颠倒参数顺序( count x xscount xs x )的原因。

更奇特(且性能更差)的解决方案:
let count'' (c : char) str =
(System.Text.RegularExpressions.Regex.Matches(str, string c)).Count

let count''' (c : char) str =
(String.length str) - (str.Replace(string c, "") |> String.length)

关于f# - 如何计算字符串中特定字符的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40022846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com