榆树 - 结合和分类多种类型

Koe*_*tyn 4 combinations types elm

上周我正在试验榆树(所以考虑我是初学者)并且想知道以下情况,

我已经定义了多个类型Foo和Bar,例如都有一个日期字段.

type alias Foo = 
{
    date : String,
    check : Bool
}
Run Code Online (Sandbox Code Playgroud)

type alias Bar = 
{
    date : String,
    check : Bool,
    text : String
}
Run Code Online (Sandbox Code Playgroud)

是否可以通过使用排序来组合和排序两个列表?(排序)我想这样做来创建一个列表来呈现所有项目.

谢谢!

Cha*_*ert 7

您可以创建一个联合类型,允许您具有混合Foo和Bar的列表:

type Combined
  = FooWrapper Foo
  | BarWrapper Bar
Run Code Online (Sandbox Code Playgroud)

现在您可以组合两个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
Run Code Online (Sandbox Code Playgroud)