问题
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:
- Filter array by returning only names that start with M
- Sort by length of the name
- 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