Elm - Combine and Sort by Multiple Types

Last week I experimented with elms (they consider me a novice) and wondered about the following,

I have defined several types of Foo and Bar, for example, with a date field.

type alias Foo = 
{
    date : String,
    check : Bool
}

and

type alias Bar = 
{
    date : String,
    check : Bool,
    text : String
}

Is it possible to combine and sort both lists with sorting? ( sort ) I would like to do this to create one list to represent all the elements.

Thanks!

+4
source share
1 answer

You can create a union type that allows you to have a list that mixes both Foo and Bar:

type Combined
  = FooWrapper Foo
  | BarWrapper Bar

Foos Bars, case sortBy:

combineAndSort : List Foo -> List Bar -> List Combined
combineAndSort foos bars =
  let
    combined =
      List.map FooWrapper foos ++ List.map BarWrapper bars
    sorter item =
      case item of
        FooWrapper foo -> foo.date
        BarWrapper bar -> bar.date
  in
    List.sortBy sorter combined
+7

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


All Articles