cit*_*kid 5 f# compiler-errors
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
Run Code Online (Sandbox Code Playgroud)
为什么只有最后一行无法编译:
错误FS0002:此函数需要太多参数,或者在不期望函数的上下文中使用
我认为这是关于成员重载的类型推断的边缘情况。Count和之间的区别Where在于前者有两个参数数量不同的重载。
您可以通过指定从 F# 函数到 的转换来解决此问题System.Func<_, _>:
s.Count(Func<_, _>(Char.IsLetter))
Run Code Online (Sandbox Code Playgroud)
当然,它比对应的版本还要丑:
s.Count(fun c -> Char.IsLetter(c))
Run Code Online (Sandbox Code Playgroud)
您可以在https://visualfsharp.codeplex.com/workitem/list/basic提交错误,以便可以在 F# vNext 中修复该错误。
请注意,在 F# 中,您不经常使用 Linq 函数。你可以这样做:
s |> Seq.sumBy (fun c -> if Char.IsLetter c then 1 else 0)
Run Code Online (Sandbox Code Playgroud)
或者
s |> Seq.filter Char.IsLetter |> Seq.length
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
243 次 |
| 最近记录: |