Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 在Prolog中将列表元素更改为带空格的字符串_String_List_Recursion_Prolog_Swi Prolog - Fatal编程技术网

String 在Prolog中将列表元素更改为带空格的字符串

String 在Prolog中将列表元素更改为带空格的字符串,string,list,recursion,prolog,swi-prolog,String,List,Recursion,Prolog,Swi Prolog,在Prolog中,如果我将[hello,this,is,a,句子]这样的列表作为谓词的参数,那么如何获取返回值Y,以便它将该列表作为带空格的字符串返回?e、 g.[你好,这是一个句子]将返回你好,这是一个句子 makesentence([H|T],Y):- % some code here 我能够递归地运行列表,并让Y返回相同的列表输入,如下所示: makesentence([],[]). % base case returns an empty list makesentenc

在Prolog中,如果我将[hello,this,is,a,句子]这样的列表作为谓词的参数,那么如何获取返回值Y,以便它将该列表作为带空格的字符串返回?e、 g.[你好,这是一个句子]将返回你好,这是一个句子

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
但是,当我尝试在没有列表和空格的情况下生成输出时,我会使用faulter。我试过这个:

makesentence([],'').
makesentence([X],X).
makesentence([H|T],Y):-
    makesentence(T,Result),
    append(H,Result,Y).

我认为这与Prolog中的
append
谓词只处理追加列表这一事实有关,但我不确定。我该怎么办?提前谢谢。

在丹尼尔的帮助下解决了这个问题。要将列表放入带有空格的字符串中,请使用
atomics\u To\u string/3
。就我而言:

makesentence([X],X).
makesentence([H|T],Y):-
    makesentence(T,Result),
    atomics_to_string([H,Result],' ',Y).

原子到字符串([H,Result],'',Y.
行中,第一个参数是列表,第二个是我想在每个条目之间添加的,在本例中是空格
'
,第三个参数是输出赋值,在我的例子中是Y。感谢Daniel为我指出了正确的方向。

SWI Prolog为此专门内置了一个:/3

可能是你的票。
?- atomic_list_concat([hello,this,is,a,sentence],' ',A).
A = 'hello this is a sentence'.