Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 220
Hai Avatar asked Nov 26 '22 23:11

Hai


2 Answers

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.

like image 76
Dario Avatar answered Dec 31 '22 05:12

Dario


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]?)

like image 42
Benjamin Oakes Avatar answered Dec 31 '22 07:12

Benjamin Oakes