[m-users.] Safely downcasting from supertype to subtype.

Charlie McGee <[email protected]> Wed, 19 Jun 2024 09:34:55 -0400
Newsgroups gmane.comp.lang.mercury.general
Message-ID <CALtU=q7BYrYYSw1_wnJoEmLYueAe1S1koTXgk+ZQRBAJ6ydC4g@mail.gmail.com>
I've been thoroughly kicking the tires on the subtyping feature of Mercury
... and I've been learning a lot in the process ... including some of the
nuances of how the inst and mode system works.

I was initially confused as to how to safely coerce a supertype down to a
subtype, struggling with how to get a variable bound to the inst tree of
the subtype, rather than just ground in a semi deterministic manner.   I'd
forgotten some of the expressive power of the mode system.

What I learned is that you can use a mode to make that transformation of
the inst to allow the safe coercion.

:- type foobar
  --->  foo
  ;  bar.

:- inst foo ---> foo.

:- type foo =< foobar ---> foo.

:- mode is_foo == ground >> foo.

:- pred is_foo(foobar::is_foo) is semidet.

is_foo(Foo) :- Foo = foo.

:- func downcast_foo(foobar) = foo is semidet.

downcast_foo(Foo) = coerce(Foo) :- is_foo(Foo).

It took me far too long to realize I could use a mode such as is_foo/0 to
tell the mode checker that a variable was safe to coerce to a subtype.

_______________________________________________
users mailing list
[email protected]
https://lists.mercurylang.org/listinfo/users