[m-users.] Converting types to printable form

Volker Wysk post at volker-wysk.de
Wed May 12 10:48:56 AEST 2021


Am Dienstag, den 11.05.2021, 21:10 +0100 schrieb Sean Charles
(emacstheviking):
> How do you convert a discriminated union to a printable string? I have this:
> 
>     % Character classification types.
> :- type char_type ---> ws; chr; op; cp; ol; cl; om; cm; sq; dq; tk.
> :- type tokstate
>         --->    skip_ws
>         ;       eat_token.
> 
> Do I have to explicitly code a predicate for each type I define or not? In
> Haskell I can just add (show) to the definition and it does the write(!)
> thing. Can Mercury do that other than using io.print_line, sometimes I
> don’t want a new line!


% Write any value to a string, using the write/3 predicate.
:- pred write_str(T::in, string::out) is det.
:- func write_str(T::in) = (string::out) is det.

write_str(T, Txt) :-
   Zust1 = string.builder.init,
   stream.string_writer.write(string.builder.handle, T, Zust1, Zust2),
   Txt = string.builder.to_string(Zust2).

write_str(T) = Txt :-
    write_str(T, Txt).


Bye,
Volker


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: This is a digitally signed message part
URL: <http://lists.mercurylang.org/archives/users/attachments/20210512/dbfcf901/attachment.sig>


More information about the users mailing list