Date as MapKey

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.

2 Likes

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
4 Likes

@bernhard Thank you very much for your prompt answer!

1 Like

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’.

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
1 Like