Whats wrong with s.Count(Char.IsLetter)

随声附和 提交于 2019-12-23 10:18:00

问题


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

Why does only the last line fail to compile:

Error FS0002: This function takes too many arguments, or is used in a context where a function is not expected


回答1:


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.

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))

You could file a bug at https://visualfsharp.codeplex.com/workitem/list/basic so that it may be fixed in the F# vNext.

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)

or

s |> Seq.filter Char.IsLetter |> Seq.length



回答2:


Daniel appears to be correct about the type inference problem.

It doesn't look as nice, but the following appears to work.

Char.IsLetter |> s.Count


来源:https://stackoverflow.com/questions/23960985/whats-wrong-with-s-countchar-isletter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!