string - 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 很陌生,所以我很难弄清楚我在这里做错了什么。帮助?
谢谢!
解决方案
试试这样:
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']].
推荐阅读
- javascript - Chartist.js - 为什么圆环图的中心是黑色的?
- javascript - 使用装饰器设置初始类属性值
- android - 在 Activity 中使用 androidTestImplementation 类
- python - 匹配两个不同 DataFrames Pandas 中的字符串值
- amazon-web-services - 如何在 CloudFront 中以 Web 服务器作为后端托管 SPA?
- github - 使用电子应用报告 GitHub 问题
- java - 使用 @Query 和 @Modifying 的 Spring 数据 JPA PSQLException
- facebook - Ionic Facebook 无效密钥哈希
- axios - axios 发布请求失败,请求错误
- php - 无法让 mcrypt 在 OS X High Sierra 和 PHP 7.1 上工作