预期该表达式的类型为字符串

预期该表达式的类型为字符串

本文介绍了预期该表达式的类型为字符串->. int,但这里的类型为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,这个问题真的很傻,刚开始让我对F#感到不快(来自C#).

Sorry if this question is really silly, just started to get my feet wet with F# (Coming from 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,该函数将接受字符串(名称)数组并执行以下操作:

Here I'm trying to define/(declare?) a function Foo which will accept array of strings (names) and perform the following:

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

现在这几乎可以工作了(除了排序部分,它根本不排序,这现在还可以),但是我对以下内容感到困惑-如果我将第5、6行替换为以下内容:

Now this almost works (except of sorting part, it doesn't sort at all, which is fine for now) but I'm confused with following - if I replace lines #5, 6 with following:

let sortedNamesByLegth : string[] =
    Array.sortWith(fun name -> sortByLengthOfName name) favNames

编译器开始抱怨This expression was expected to have type string -> int but here has type int.现在这对我来说很混乱,因为对我来说sortByLegnthOfNamestring -> int.我尝试了这些方法

Compiler starts to complain with This expression was expected to have type string -> int but here has type int. Now this is confusing for me because sortByLegnthOfName to me is string -> int. I tried something along these lines

let sortedNamesByLegth : string[] =
    Array.sortWith(fun name -> (sortByLengthOfName name)) favNames

但是我仍然收到相同的消息.

But I'm still getting the same message.

谁能解释一下这里出了什么问题?编译一个和不编译之间有什么区别?更重要的是,我在哪里可以了解有关此行为的更多信息?

Can anyone please explain what is wrong here? What's the difference between compiling one and non-compiling? And more importantly, where can I read more about this behavior?

推荐答案

使用此签名进行排序的功能

The function for sortwith this signature

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

您的lambda然后需要具有

Your lambda then needs to have a signature of

('T -> 'T -> int)

但是你只是

'T -> int

您可能希望使用sortBy,因为sortwith需要比较器功能

You probably want sortBy instead as sortwith needs a comparer function

这篇关于预期该表达式的类型为字符串->. int,但这里的类型为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:30