the1337sauce
the1337sauce

Reputation: 549

How do I sort a list by some custom criteria in DAML?

Say I have a List of a custom type called Mortgage as defined below:

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

And in this particular one-off case I want to sort the list in descending order based on the issuedDate. How can I accomplish this?

Upvotes: 3

Views: 151

Answers (1)

Recurse
Recurse

Reputation: 3585

In the module DA.List in the standard library, you will find the functions sortBy and sortOn which will do what you want.

Specifically, using sortOn:

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

A full example:

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

Upvotes: 4

Related Questions