Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm - Combining and sorting over multiple types

The last week I'm experimenting with elm (so consider me a beginner) and was wondering about the following,

I have defined multiple types Foo and Bar for example both 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 by using sort?(sort) I would like to do this to create one list to present all items.

Thanks!

like image 574
Koen Certyn Avatar asked Mar 14 '23 23:03

Koen Certyn


1 Answers

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

Now you can combine two lists of Foos and Bars, then use a case statement as the sortBy parameter:

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
like image 199
Chad Gilbert Avatar answered Mar 23 '23 00:03

Chad Gilbert