This expression was expected to have type string -> int but here has type int

♀尐吖头ヾ 提交于 2019-12-23 16:19:51

问题


Sorry if this question is really silly, just started to get my feet wet with F# (Coming from C#).

Suppose I have following:

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

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

  1. Filter array by returning only names that start with M
  2. Sort by length of the name
  3. Print out the results

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

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?


回答1:


The function for sortwith this signature

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

Your lambda then needs to have a signature of

('T -> 'T -> int)

but yours is just

'T -> int

You probably want sortBy instead as sortwith needs a comparer function



来源:https://stackoverflow.com/questions/34321963/this-expression-was-expected-to-have-type-string-int-but-here-has-type-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!