I am trying to cleanup some data in the form of a list by using split_string
on every element on the list.
Let me give you an example of what I mean
Input:
[
'p1\tp2\t100\tStorgatan',
'p1\tp3\t200\tLillgatan',
'p2\tp4\t100\tNygatan',
'p3\tp4\t50\tKungsgatan',
'p4\tp5\t150\tKungsgatan'
]
The result I expect after cleanup:
[
[p1, p2, 100, Storgatan],
[p1, p3, 200, Lillgatan],
[p2, p4, 100, Nygatan],
[p3, p4, 50, Kungsgatan],
[p4, p5, 150, Kungsgatan]
]
I have tried to write a predicate that does this but for some reason my predicate won't return a result (output is just 'true'):
data_cleanup([], Res).
data_cleanup([H|T], Res):-
split_string(H, "\t", "", L),
append([L], Res, NewRes),
data_cleanup(T, NewRes).
I am quite new to Prolog so I am having a hard time figuring out what I've done wrong here. Help?
Thanks!
Try like this:
data_cleanup([], []).
data_cleanup([H|T], [A|B]):-
split_string(H, "\t", "", A),
data_cleanup(T, B).
Now it does something:
?- data_cleanup(['p1\tp2\t100\tStorgatan', 'p1\tp3\t200\tLillgatan', 'p2\tp4\t100\tNygatan', 'p3\tp4\t50\tKungsgatan', 'p4\tp5\t150\tKungsgatan'], Result).
Result = [["p1", "p2", "100", "Storgatan"], ["p1", "p3", "200", "Lillgatan"], ["p2", "p4", "100", "Nygatan"], ["p3", "p4", "50", "Kungsgatan"], ["p4", "p5", "150", "Kungsgatan"]].
Exercise: define this predicate using maplist
.
EDIT: or if you are anyway using SWI-Prolog, and if you prefer atoms and not strigs, you could use atomic_list_concat/3
:
split_atom(Delimiter, Atom, List) :- atomic_list_concat(List, Delimiter, Atom).
and then
?- maplist(split_atom('\t'), ['p1\tp2\t100\tStorgatan', 'p1\tp3\t200\tLillgatan', 'p2\tp4\t100\tNygatan', 'p3\tp4\t50\tKungsgatan', 'p4\tp5\t150\tKungsgatan'], L).
L = [[p1, p2, '100', 'Storgatan'], [p1, p3, '200', 'Lillgatan'], [p2, p4, '100', 'Nygatan'], [p3, p4, '50', 'Kungsgatan'], [p4, p5, '150', 'Kungsgatan']].