Record Casting
Hello, I am working on a project where I need to ensure that some record that is optional in most cases, has a subset of those values populated in a specific instance. My thought was that there might be a way to cast an instance of the OptionalRecord into the RequiredRecord, and if successful you could return True, and if it fails then return False. I’m not sure how to write such a function, or if there is a better approach? There are 7-8 fields in my real records where I would like to use such a function, and on multiple different records so I do not want to manually check the fields, and so would like to make this function generic as well, where I can pass in a record type to try to cast the record instance into.
data OptionalRecord = OptionalRecord with
field1 : Optional Text
field2 : Optional Text
data RequiredRecord = RequiredRecord with
field1 : Text
field2 : Optional Text
ensureRecordHasRequiredFields : OptionalRecord -> Bool
ensureRecordHasRequiredFields recordInstance = do
???
???
There are no casts in Daml but you can just write a conversion function. I wouldn’t return a Bool thought and instead return an Optional RequiredRecord. do syntax + record wildcards makes this relatively nice to write:
data OptionalRecord = OptionalRecord with
field1 : Optional Text
field2 : Optional Text
data RequiredRecord = RequiredRecord with
field1 : Text
field2 : Optional Text
validateRecord : OptionalRecord -> Optional RequiredRecord
validateRecord optR@OptionalRecord with .. = do
field1 <- optR.field1
pure (RequiredRecord with ..)
Thanks Moritz! This should work for me with isSome!
testValidation : Script ()
testValidation = do
let optRec1 = OptionalRecord with field1 = Some "foo", field2 = None
let optRec2 = OptionalRecord with field1 = None, field2 = Some "bar"
let optRec1Bool = isSome $ validateRecord optRec1
let optRec2Bool = isSome $ validateRecord optRec2
isSome works but in most cases you are probably better off pattern matching on the result.