[英]Change list elements to a string with spaces in Prolog
在Prolog中,如果我将[hello,this,is,a,sentence]等列表作为谓词的参数,如何获得返回值Y,以便将该列表作为带空格的字符串返回? 例如[hello,this,is,a,sentence]将返回你好这是一个句子 。
makesentence([H|T],Y):- % some code here
我能够递归地遍历列表并让Y返回相同的列表输入:
makesentence([],[]). % base case returns an empty list
makesentence([X],[X]). % one list element returns that element in a list
makesentence([H|T],Y):- % a list of more than one element
makesentence(T,Result), % recursively call function on the tail
append([H],Result,Y). % append the head to the rest of the list
但是当我尝试使用没有列表和空格的输出时,我会出错。 我试过这个:
makesentence([],'').
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
append(H,Result,Y).
我认为它与Prolog中的append
谓词仅涉及附加列表这一事实有关,但我不确定。 我该怎么办? 提前致谢。
SWI-Prolog有一个专门的内置: atomic_list_concat / 3
?- atomic_list_concat([hello,this,is,a,sentence],' ',A).
A = 'hello this is a sentence'.
在丹尼尔的帮助下想出来了。 要将列表放入带空格的字符串中,请使用atomics_to_string/3
。 就我而言:
makesentence([X],X).
makesentence([H|T],Y):-
makesentence(T,Result),
atomics_to_string([H,Result],' ',Y).
在atoms_to_string([H,Result],' ',Y).
,第一个参数是列表,第二个是我要在每个条目之间添加的内容,在这种情况下是空格' '
,第三个参数是输出的赋值,在我的情况下是Y.感谢Daniel指着我正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.