【问题标题】:This expression was expected to have type string -> int but here has type int该表达式的类型应为 string -> int,但此处的类型为 int
【发布时间】: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,它将接受字符串(名称)数组并执行以下操作:

  1. 通过仅返回以 M 开头的名称来过滤数组
  2. 按名称长度排序
  3. 打印结果

现在这几乎可以工作了(除了排序部分,它根本不排序,目前还可以)但我对以下内容感到困惑 - 如果我将第 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#


    【解决方案1】:

    使用此签名进行排序的函数

    Array.sortWith : ('T -> 'T -> int) -> 'T [] -> 'T []
    

    然后你的 lambda 需要有一个

    的签名
    ('T -> 'T -> int)
    

    但你的只是

    'T -> int
    

    你可能想要sortBy,因为 sortwith 需要一个比较函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多