Getting last char of a string in Prolog

*爱你&永不变心* 提交于 2019-12-19 09:49:21

问题


I need to get the last char of a string. For example:

?- last_char('abde', X).
X = 'e'

?- last_char('abdef', X).
X = 'f'

Could someone help me, please? I'm new to Prolog.


回答1:


with a little help from sub_atom/5, a really handy ISO builtin:

?- sub_atom(abdef, _, 1, 0, C).
C = f.



回答2:


You could use name and reverse to convert the string to a list and back:

last_char(S, X) :-
    name(S, N),
    reverse(N, [F|_]),
    name(X, [F]).

Depending on your Prolog version you might have to import a list library for the reverse predicate, e.g. :- use_module(library(lists)). for SICStus.



来源:https://stackoverflow.com/questions/19734799/getting-last-char-of-a-string-in-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!