Date as MapKey
- mlyczakOP 2
Hi,
I’d like to use a map where keys are Date instances.
I understand that I need to write my own
instance MapKey Date where…
with definitions for ‘keyToText’, ‘keyFromText’.What is the best way to implement ‘keyFromText’ given a Date instance?
Is there anything else I should include in such a MapKey definition?
Thank you very much for your guidance.
- bernhard 4
From version 1.9 there is a new type
GenMapin Beta, which can take keys of any serializable type. This feature will become stable with the upcoming 1.10 release (February 2021). If you are not tied to an SDK or Daml-LF version, I’d recommend simply using that.Otherwise, you can use the functions
daysSinceEpochToDateanddateToDaysSinceEpochto convert betweenDateandIntandparseIntandshowto convert betweenIntandText.So in short:
instance MapKey Date where keyToText = show . dateToDaysSinceEpoch keyFromText = daysSinceEpochToDate . fromSome . parseInt - mlyczak 1
@bernhard Thank you very much for your prompt answer!
- Luciano
bernhard:If you are not tied to an SDK or Daml-LF version, I’d recommend simply using that.
Hey @bernhard, is there some special flag we need to pass to the compiler to enable this? I’m on
1.10.0-snapshot.20210209.6265.0.19bf4031, but getting errors sayingModule ‘DA.Map’ does not export ‘Map’. - cocreature 1
SDK 1.10 still defaults to LF 1.8. You need LF 1.11 here. To enable that, add the following to your
daml.yaml:build-options: - --target=1.11