Search code examples
dictionaryswi-prolog

SWI-Prolog: Looking for a way to print dictionary values in seperate lines


I am searching a way to print some dictionary values in a way every value is on a separate line in the terminal.

For example if I have

X = abc{a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10}.

The output itself is:

?- X = abc{a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:10}.
X = abc{a:1, b:2, c:3, d:4, e:5, f:6, g:7, h:8, i:9, j:10}.

For purpose of clarity my aim now is to get the following output:

X = abc{
a:1, 
b:2, 
c:3, 
d:4, 
e:5, 
f:6, 
g:7, 
h:8, 
i:9, 
j:10
}.

or alternatively simple

a:1
b:2 
c:3 
d:4
e:5 
f:6
g:7 
h:8 
i:9 
j:10

Is their a way to do that?


Solution

  • It is possible to provide a custom portray/1 hook for dictionaries. As an example:

    portray(Term) :-
        is_dict(Term),
        dict_pairs(Term, Tag, Pairs),
        writef("%p{\n", [Tag]),
        foreach(member(Key-Value, Pairs), writef("\t%p: %p\n", [Key, Value])),
        write("}").
    

    This will also work on nested terms (though more care could be added to indent nested terms correctly). Example output:

    ?- X = abc{a:1,b:2,c:3,d:4,e:5,f:6,g:7,h:8,i:9,j:foo{bar:10, baz:11}}.
    X = abc{
            a: 1
            b: 2
            c: 3
            d: 4
            e: 5
            f: 6
            g: 7
            h: 8
            i: 9
            j: foo{
            bar: 10
            baz: 11
    }
    }.
    

    If the portray/1 hook is not already enabled for answers to the terminal (it was for me) you may need to adjust the answer_write_options flag.