【发布时间】:2018-06-15 05:38:49
【问题描述】:
对不起,如果这个问题真的很愚蠢,我刚开始用 F#(来自 C#)弄湿我的脚。
假设我有以下内容:
1: let Foo (names : string[]) =
2: let favNames : string[] =
3: Array.filter(fun name -> name.StartsWith("M")) names
4: let sortByLengthOfName (x : string) : int = x.Length
5: let sortedNamesByLegth : string[] =
6: Array.sortWith(fun name -> fun n -> n.Length) favNames
7: Array.iter(fun name -> printfn "%s" name) sortedNamesByLegth
我在这里尝试定义/(声明?)一个函数Foo,它将接受字符串(名称)数组并执行以下操作:
- 通过仅返回以 M 开头的名称来过滤数组
- 按名称长度排序
- 打印结果
现在这几乎可以工作了(除了排序部分,它根本不排序,目前还可以)但我对以下内容感到困惑 - 如果我将第 5、6 行替换为以下内容:
let sortedNamesByLegth : string[] =
Array.sortWith(fun name -> sortByLengthOfName name) favNames
编译器开始抱怨This expression was expected to have type string -> int but here has type int。现在这让我感到困惑,因为sortByLegnthOfName 对我来说是string -> int。我尝试了一些类似的方法
let sortedNamesByLegth : string[] =
Array.sortWith(fun name -> (sortByLengthOfName name)) favNames
但我仍然收到相同的消息。
谁能解释一下这里出了什么问题?编译和不编译有什么区别?更重要的是,我在哪里可以了解有关此行为的更多信息?
【问题讨论】:
标签: f#