Reputation: 351
Sorry for the easy question it's just I'm extremely new to haskell..
I'm trying to write a function "order" which will sort a list of tuples produced by another function "frequency" (frequency counts the number of distinct elements in a list a gives one such result, say > frequency "aabbbccc", would incur the result, [(2,a),(3,b),(3,c)]) into ascending order. I can't work out how to write it.
If I write >sort (frequency score) into the prelude it will sort it (score being a list of grades, i.e ["a", "b", "c", "c"].
But when I try to write a function..
results :: [a] -> [(Int, a)]
results = sort (frequency score)
It sadly does not work saying that sort is applied to too many arguments.
Sorry for the obvious question and thanks in advance.
Upvotes: 3
Views: 2274
Reputation: 139840
You forgot to make your function take an argument.
results :: [a] -> [(Int, a)]
results score = sort (frequency score)
Without it, the compiler sees your type signature and infers that in order to return something of type [a] -> [(Int, a)]
, sort
must take another argument, which it doesn't.
However, the next problem is then that you can't sort a list of tuples with arbitrary component types. See @luqui's answer for how to deal with that.
Upvotes: 9
Reputation: 60463
Are you sure it says sort
is applied too many arguments? To me, it looks like you have given the wrong type signature. This may work easily:
results :: (Ord a) => [a] -> [(Int, a)]
(i.e. you can't sort a list of [(Int, a)]
unless a
is a type that has an Ord
ering, that is you can compare elements).
However, this signature is not really necessary, you could also sortBy (\x y -> compare (fst x) (fst y))
, which has a number of idiomatic succinct ways of it, but for newbies I think it's better to be explicit. This way does not need to compare a
s, as it only looks at the Int
s.
Edit: oh yeah, I see why it would say sort
is applied too many arguments. See @hammar's answer.
Upvotes: 4