Guarding against errant field accessors/ record selectors
App Development3 posts193 views2 likesLast activity Jan 2022
LE
Leonid_RozenbergOP
Jan 2022Consider
data W
= WithoutField
| WithField with
field : Int
getMyField : W -> Int
getMyField a = a.field
t : Script ()
t = do
let w = WithField 10
debug $ getMyField w
let wo = WithoutField
debug $ getMyField wo
The code above compiles, but the script will fail with an error.
- AFAIK, there’s no way to turn this into an error, and I can’t find a warning. Is that correct?
- Is there any way to statically check for usage of missing record selectors? I know that I (
) would never write such code, so asking for a friend.
CO
cocreature
Jan 2022You are correct that there is no warning for this unfortunately and we don’t have any separate static checks for this either. Your best option is to not define those types in the first place and instead split your records and variants:
data W = WithoutField | WithField WithField
data WithField = WithFieldR with field : Int
Then you cannot use the field on the wrong constructor without getting a type error. Of course that just brings back the question of how you can enforce this …
LE
Leonid_Rozenberg
Jan 2022Thank you.