Skip to content
Discussions/App Development/Date as MapKeyForum ↗

Date as MapKey

App Development5 posts375 views8 likesLast activity Feb 2021
ML
mlyczakOP
Feb 2021

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.

BE
bernhard
Feb 2021

From version 1.9 there is a new type GenMap in 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 daysSinceEpochToDate and dateToDaysSinceEpoch to convert between Date and Int and parseInt and show to convert between Int and Text.

So in short:

instance MapKey Date where
  keyToText = show . dateToDaysSinceEpoch
  keyFromText = daysSinceEpochToDate . fromSome . parseInt
ML
mlyczak
Feb 2021

@bernhard Thank you very much for your prompt answer!

LU
Luciano
Feb 2021
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 saying Module ‘DA.Map’ does not export ‘Map’.

CO
cocreature
Feb 2021

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
← Back to Discussions