【问题标题】:How do I sort a list by some custom criteria in DAML?如何按 DAML 中的一些自定义条件对列表进行排序?
【发布时间】:2019-01-22 16:54:22
【问题描述】:

假设我有一个名为 Mortgage 的自定义类型列表,定义如下:

data Mortgage = Mortgage {
  rate: Decimal; 
  issuedDate: Datetime;
  amount: Decimal
} deriving (Eq, Show)

在这种特殊的一次性情况下,我想根据issuedDate 对列表进行降序排序。我怎样才能做到这一点?

【问题讨论】:

    标签: daml


    【解决方案1】:

    在标准库的模块DA.List 中,您会找到函数sortBysortOn,它们可以满足您的需求。

    具体来说,使用sortOn

    sortMortgages: [Mortgage] -> [Mortgage] = reverse . sortOn (\m -> m.issuedDate)

    一个完整的例子:

    daml 1.2
    module Main where
    
    import DA.Date
    import DA.List
    
    data Mortgage = Mortgage {
      rate: Decimal;
      issuedDate: Time;
      amount: Decimal
    } deriving (Eq, Show)
    
    sortMortgages: [Mortgage] -> [Mortgage] = reverse . sortOn (\m -> m.issuedDate)
    
    testSortMortgages = scenario
      let
        mort1 = Mortgage with rate = 0.3; issuedDate = datetime 2007 Apr 5 14 30 05 ; amount = 1.0
        mort2 = Mortgage with rate = 0.2; issuedDate = datetime 2007 Apr 5 14 30 15 ; amount = 2.0
        mort3 = Mortgage with rate = 0.1; issuedDate = datetime 2007 Apr 5 14 30 10 ; amount = 3.0
        mortgages = [ mort1, mort2, mort3 ]
        expected = [ mort2, mort3, mort1 ]
      in
        assert $ sortMortgages mortgages == expected
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-09
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 2020-03-12
      • 1970-01-01
      相关资源
      最近更新 更多