首页 > 解决方案 > Prolog - 列表中每个元素的 split_string

问题描述

我正在尝试通过在列表中的split_string每个元素上使用来以列表的形式清理一些数据。

让我举一个例子来说明我的意思

输入:

[
 'p1\tp2\t100\tStorgatan', 
 'p1\tp3\t200\tLillgatan', 
 'p2\tp4\t100\tNygatan', 
 'p3\tp4\t50\tKungsgatan', 
 'p4\tp5\t150\tKungsgatan'
]

清理后我期望的结果:

[
 [p1, p2, 100, Storgatan], 
 [p1, p3, 200, Lillgatan], 
 [p2, p4, 100, Nygatan], 
 [p3, p4, 50, Kungsgatan], 
 [p4, p5, 150, Kungsgatan]
]

我试图编写一个谓词来执行此操作,但由于某种原因,我的谓词不会返回结果(输出只是“真”):

data_cleanup([], Res).   
data_cleanup([H|T], Res):-
    split_string(H, "\t", "", L),
    append([L], Res, NewRes),
    data_cleanup(T, NewRes).

我对 Prolog 很陌生,所以我很难弄清楚我在这里做错了什么。帮助?

谢谢!

标签: stringlistsplitprolog

解决方案


试试这样:

data_cleanup([], []).   
data_cleanup([H|T], [A|B]):-
    split_string(H, "\t", "", A),
    data_cleanup(T, B).

现在它做了一些事情:

?- 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"]].

练习:使用 . 定义这个谓词maplist

编辑:或者如果您仍然使用 SWI-Prolog,并且如果您更喜欢原子而不是字符串,则可以使用atomic_list_concat/3

split_atom(Delimiter, Atom, List) :- atomic_list_concat(List, Delimiter, Atom).

接着

?- 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']].

推荐阅读