Haskell Sort Function

Why sort Data.Listdoes Haskell ignore the third digit?

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

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

EDIT: Sorry, I didn’t understand that these were lines. My fault.

+3
source share
4 answers

No, but he sorts the strings as he should have done: Lexicographically

The relationship "200" < "30"is performed for the same reason as "Hello" < "World".

So, if you want Haskell to sort by a numerical value, you have to sort the 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 lines? Use instead [Int].

+24
source

Haskell, , , . ? ( , - [1, 200, 234, 30]?)

+7

, . . "" , .

+2

, , " ", , . , , " 1", " 2", " 10" "".

+2

Source: https://habr.com/ru/post/1730232/


All Articles