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:这个函数有太多的参数,或者在不期望函数的上下文中使用
我认为这是类型推断wrt成员重载的一个边缘情况。Count
和Where
的区别在于前者有两个参数数量不同的重载。
您可以通过指定从f#函数到System.Func<_, _>
的转换来解决这个问题:
s.Count(Func<_, _>(Char.IsLetter))
当然,它比对应的版本更丑:
s.Count(fun c -> Char.IsLetter(c))
你可以在https://visualfsharp.codeplex.com/workitem/list/basic上提交一个bug,这样它可能会在f# vNext中修复。
请注意,在f#中,您不经常使用Linq函数。你可以这样做:
s |> Seq.sumBy (fun c -> if Char.IsLetter c then 1 else 0)
或
s |> Seq.filter Char.IsLetter |> Seq.length
Daniel似乎对类型推断问题是正确的。
它看起来不那么好,但是下面的代码似乎可以工作。
Char.IsLetter |> s.Count