:- module serialize_btree.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is cc_multi.
:- implementation.
:- import_module int, string, list.
:- type btree(T) --->
nil;
node(btree(T), T, btree(T))
.
:- pragma promise_pure(splitjoin/3). % what even impure? :/
:- pred splitjoin(string, string, list(string)).
:- mode splitjoin(in, in, out) is det.
:- mode splitjoin(in, out, in) is det.
splitjoin(Separator::in, String::in, List::out) :-
List = split_at_string(Separator, String).
splitjoin(Separator::in, String::out, List::in) :-
String = join_list(Separator, List).
:- pred serialize(int, btree(string), string).
:- mode serialize(in, in, out) is det.
:- mode serialize(in, out, in) is nondet. % why can't semidet??
serialize(Level, Node, String) :-
(
Node = nil, String = "nil"
;
Node = node(Left, Value, Right),
serialize(Level + 1, Left, LeftString),
serialize(Level + 1, Right, RightString),
Separator = "|" ++ int_to_string(Level) ++ "|",
splitjoin(Separator, String, [LeftString, Value, RightString])
).
% i pretty much broke all the mercury rules, haven't i?
main(!IO) :-
Example = node(
node(
node(nil, "left.left", nil),
"left",
nil
),
"root",
node(
nil,
"right",
nil
)
),
serialize(0, Example, Serialized),
print(Serialized, !IO), nl(!IO), nl(!IO),
(serialize(0,GotBack,Serialized)
-> (Example = GotBack
-> print("got the tree back!\n", !IO)
; print("didn't get the tree back O:", !IO)
)
; print("couldn't even parse D:", !IO)
),
true.