user1353742
user1353742

Reputation: 351

Function to sort a list of tuples - Haskell

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

Answers (2)

hammar
hammar

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

luqui
luqui

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 Ordering, 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 as, as it only looks at the Ints.

Edit: oh yeah, I see why it would say sort is applied too many arguments. See @hammar's answer.

Upvotes: 4

Related Questions