我不知道从哪里开始检查字符串是否出现n个特定字符.我已经列出了我认为是函数框架但我不确定的内容的基本轮廓?
let countCharFromNth (getStr : string)(chkdChar : char) =
if getStr.Length >=1 then
else printfn "Not enough arguments"
Run Code Online (Sandbox Code Playgroud)
Car*_*Dev 12
TL; DR
"最惯用"的方式可能是@Mark Seemanns:
let count x = Seq.filter ((=) x) >> Seq.length
Run Code Online (Sandbox Code Playgroud)
所述Ť oo的大号翁部分
请注意,此函数是完全通用的:x:'a -> (seq<'a> -> int) when 'a : equality即,只要支持相等,它就会计算s x序列中任何一个的出现次数.由于右侧是函数,我们也不需要指定字符串参数.这称为无点样式.通过将操作符包装在括号中(think = )将操作符转换为函数,使用此谓词过滤序列并计算得到的s长度,即构造函数.'a'a=(=)fun x y -> x = yseq
let count x xs =
xs
|> Seq.filter (fun x' -> x' = x)
|> Seq.length
Run Code Online (Sandbox Code Playgroud)
是的
let count x xs =
Seq.length(Seq.filter (fun x' -> x' = x) xs)
Run Code Online (Sandbox Code Playgroud)
当然你也可以利用'C#方式':
let count' x xs = System.Linq.Enumerable.Count(xs, fun x' -> x' = x)
Run Code Online (Sandbox Code Playgroud)
在这里,您不能只将等于运算符(=)转换为谓词,因为F#编译器需要做一些魔术才能将F#'a -> bool转换为a Func<'a, bool>.
用法完全相同:
count 'a' "abbbac"
Run Code Online (Sandbox Code Playgroud)
或(更可读)
"abbbac" |> count 'a'
"abbac" |> count' 'b'
Run Code Online (Sandbox Code Playgroud)
这(以及更好的可组合性)是功能程序员倾向于颠倒参数顺序(count x xs相对count 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2424 次 |
| 最近记录: |