Prolog-列表中每个元素的split_string [英] Prolog - split_string on every element in list

查看:110
本文介绍了Prolog-列表中每个元素的split_string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过对列表中的每个元素使用split_string清理列表形式的某些数据.

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

输入:

[
 '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]
]

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

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).

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

I am quite new to Prolog so I am having a hard time figuring out what I've done wrong here. Help?

谢谢!

推荐答案

尝试如下:

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

锻炼:使用maplist定义此谓词.

Exercise: define this predicate using maplist.

或者如果您仍在使用SWI-Prolog,并且您更喜欢原子而不是strigs,则可以使用atomic_list_concat/3:

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).

然后

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

这篇关于Prolog-列表中每个元素的split_string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆