[m-users.] Safely downcasting from supertype to subtype.
Charlie McGee
c4cypher at gmail.com
Wed Jun 19 23:34:55 AEST 2024
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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mercurylang.org/archives/users/attachments/20240619/3116e191/attachment.html>
More information about the users
mailing list