:- module(write_to_atom, [write_to_atom/2]).

write_to_atom(Atom, Goal) :-
	new_memory_file(MemFile),
	open_memory_file(MemFile, write, TmpOut),
	current_output(OldOut),
	set_output(TmpOut),
	(   catch(call(Goal), E, true)
	->  true
	;   E = failed
	),
	set_output(OldOut),
	close(TmpOut),
	!,
	(   var(E)
	->  memory_file_to_atom(MemFile, Atom),
	    free_memory_file(MemFile)
	;   free_memory_file(MemFile),
	    (   E = failed
	    ->  fail
	    ;   throw(E)
	    )
	).

