Last active
August 17, 2020 10:02
-
-
Save kryptt/7a29081e577bf73abd2dc38744695749 to your computer and use it in GitHub Desktop.
Useful Lenses
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BalanceSheet { | |
val froms: List[Transaction] | |
val toss: List[Transaction] | |
/* ... */ | |
} | |
class Transaction { | |
val issue: DateTime | |
val acknowledge: DateTime | |
/* ... */ | |
} | |
val sheetTransactionsLens: Traversal[BalanceSheet, Transaction] = | |
Traversal.applyN( | |
GenLens[BalanceSheet](_.froms), | |
GenLens[BalanceSheet](_.tos), | |
) | |
val transactionTimesLens: Traversal[Transaction, DateTime] = | |
Traversal.applyN( | |
GenLens[Transaction](_.isue), | |
GenLens[Transaction](_.aknowledge), | |
) | |
val sheetTimes: Traversal[BalanceSheet, DateTime] = | |
sheetTransactionsLens | |
.composeTraversal(each) | |
.composeTraversal(transactionTimesLens) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We can re-use a simple function that goes from Time to a new Time | |
val adjustTime: DateTime => DateTime = ??? | |
// And use the lense to build a function that goes from BalanceSheet to a new BalanceSheet. | |
val adjustSheetTimes: BalanceSheet => BalanceSheet = | |
sheetTimes.modify(adjustTime) | |
// This is a concrete alternative to adjustTime, we just increment it by duration: | |
def increaseTimeBy(duration: FiniteDuration): DateTime => DateTime = | |
_.add(duration) | |
// and re-use the same lense, to update the time on on transactions in a balance sheet adding to them a fixed amount. | |
def increaseSheetTimes(duration: FiniteDuration): BalanceSheet => BalanceSheet = | |
sheetTimes.modify(increaseTimeBy(duration)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment