s.Count(Char.IsLetter)有什么问题 [英] Whats wrong with s.Count(Char.IsLetter)
问题描述
F#
let s = "bugs 42 bunny"
s.Count(fun c -> Char.IsLetter(c))
s.Where(fun c -> Char.IsLetter(c)).ToArray()
s.Where(Char.IsLetter).ToArray()
s.Count(Char.IsLetter) // error
为什么仅最后一行无法编译:
错误FS0002:该函数接受了太多参数,或者在没有该函数的情况下使用预期的
Error FS0002: This function takes too many arguments, or is used in a context where a function is not expected
推荐答案
我认为这是类型推断的一个极端案例,成员重载。 Count
和 Where
之间的区别在于,前者有两个带有不同数量参数的重载。
I think it's an edge case of type inference wrt member overloading. The difference between Count
and Where
is that the former has two overloads with different number of arguments.
您可以通过指定从F#函数到 System.Func< _,_>
:
You can work around by specifying conversion from F# function to System.Func<_, _>
:
s.Count(Func<_, _>(Char.IsLetter))
当然,它比相应的版本还要丑:
Of course, it's even uglier than the corresponding version:
s.Count(fun c -> Char.IsLetter(c))
您可以在 https://visualfsharp.codeplex.com/workitem/list/basic ,以便对其进行修复
You could file a bug at https://visualfsharp.codeplex.com/workitem/list/basic so that it may be fixed in the F# vNext.
请注意,在F#中,您并不经常使用Linq函数。您可以执行以下操作:
Note that in F#, you don't often use Linq functions. You can either do:
s |> Seq.sumBy (fun c -> if Char.IsLetter c then 1 else 0)
或
s |> Seq.filter Char.IsLetter |> Seq.length
这篇关于s.Count(Char.IsLetter)有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!