Sort a list of tuples by their first index in Elm

Assuming I have a list of tuples that resemble the following example:

[(5, "a"), (1, "c"), (7, "d")] 

in Elm, how do I start sorting the list in ascending order by their first elements so that we get the following result?

[(1, "c"), (5, "a"), (7, "d")]

Using the Documentation Elm a List , it seems like sortByand sortWithfunctions will be helpful in this case. My implementation attempt is as follows:

maxTuples : Tuple(a, b) -> Tuple(a, b) -> Tuple(a, b)
maxTuples t1 t2 = 
    case compare t1 t2 of 
        ((Tuple.first t1) >= (Tuple.first t2)) -> GT
         _                                     -> LT


sortByFirst : List (Tuple (a, b)) -> List (Tuple (a, b))
sortByFirst lst = 
    List.sortWith maxTuples lst

However, I get compiler errors of the following nature:

I ran into something unexpected when parsing your code!

99|         ((Tuple.first t1) >= (Tuple.first t2)) -> GT
                ^
I am looking for one of the following things:

an upper case name

My hunch is that the compiler is looking for GT/ LT/ EQfor the library API List, but if this is the case, I'm not sure how we can use either sortByor sortWithto sort the list of tuples into a knit by the first index of each element.

+4
3

. :

  • (a, b), Tuple(a, b).
  • t1 t2, . compare (Tuple.first t1) (Tuple.first t2)
  • case ->. - EQ, compare, Order.

:

maxTuples : (comparable, b) -> (comparable, b) -> (comparable, b)
maxTuples t1 t2 = 
    case compare (Tuple.first t1) (Tuple.first t2) of 
        GT -> GT
        EQ -> EQ
         _ -> LT

, compare.

maxTuples t1 t2 = 
    compare (Tuple.first t1) (Tuple.first t2)

:

sortByFirst lst = 
    List.sortWith (\t1 t2 -> compare (Tuple.first t1) (Tuple.first t2)) lst

, , . Elm - sortBy. :

sortBy f lst =
    List.sortWith (\a b -> compare (f a) (f b)) lst

sortBy, :

sortByFirst : List (comparable, b) -> List (comparable, b)
sortByFirst =
    sortBy Tuple.first
+4

, , , List.sort (sort , , , .. ) List.sort [(5, "a"), (1, "c"), (1, "a"), (7, "d")] == [(1,"a"),(1,"c"),(5,"a"),(7,"d")]

sortBy .

+3

, compare case compare t1 t2 of, if case ( Tuple.first, ):

maxTuples ( val1, _ ) ( val2, _ ) =
    if val1 >= val2 then
        GT
    else
        LT

I have a full working example at https://ellie-app.com/ZZ9Hzhg7yva1/2 (some changes were also made to the type annotations that needed to be done to compile)

However, this sortByis a simpler option, because it can simply be taken Tuple.firstto sort by everything that is there:

sortByFirst lst =
    List.sortBy Tuple.first lst

This version is at https://ellie-app.com/ZZ9Hzhg7yva1/3

0
source

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


All Articles