Hai
Hai

Reputation: 4886

Haskell sort function

Why does Haskell's sort of Data.List ignore the third digit?

Prelude>sort ["1","200","234","30"]

["1","200","234","30"]

EDIT: Sorry, I did not realize those were strings. My fault.

Upvotes: 6

Views: 16913

Answers (4)

C. A. McCann
C. A. McCann

Reputation: 77374

You're sorting strings, not number--it's ordering them "alphabetically", so it sorts by the first character, then the next, and so on. It's the same reason that you'll often see files with names like "File 1", "File 2", ... "File 10", and such sorted "incorrectly".

Upvotes: 2

Benjamin Oakes
Benjamin Oakes

Reputation: 12782

I'm no Haskell expert, but it would seem to be doing a lexical sort on strings. Can you make them integers instead? (Maybe something like [1, 200, 234, 30]?)

Upvotes: 8

luiscubal
luiscubal

Reputation: 25121

You are using strings, not numbers. You should consider parsing the strings to numbers. Try removing the "" characters and see if it starts working.

Upvotes: 2

Dario
Dario

Reputation: 49208

No, but it does sorts strings as it's supposed to do: Lexicographically

The relation "200" < "30" holds for the same reason as "Hello" < "World" does.

So if you want Haskell to sort by the numeric value, you'll have to sort actual numbers.

import Data.List
import Data.Function

sortNumeric = sortBy (compare `on` (read :: String -> Int))

sortNumeric ["1", "200", "234", "30"]

But: Why does your list full of "numbers" contain strings? Consider using a proper [Int] instead.

Upvotes: 31

Related Questions