在 Prolog 中将列表元素更改为带空格的字符串
Change list elements to a string with spaces in Prolog
在 Prolog 中,如果我将 [hello,this,is,a,sentence] 之类的列表作为谓词的参数,我如何获得 return 值 Y 以便它将return 那个列表是一个带空格的字符串?例如[你好,这是一个句子] 将 return 你好,这是一个句子。
makesentence([H|T],Y):- % some code here
我能够 运行 递归地遍历列表并使用 Y return 相同的列表输入:
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
谓词仅处理附加列表这一事实有关,但我不确定。我将如何进行?提前致谢。
在丹尼尔的帮助下弄明白了。要将列表放入带有 space 的字符串中,请使用 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).
中,第一个参数是列表,第二个是我想在每个条目之间添加的内容,在本例中是 space ' '
和第三个参数是输出的赋值,在我的例子中是Y。感谢Daniel给我指明了正确的方向。
SWI-Prolog 有专门的内置函数:atomic_list_concat/3
?- atomic_list_concat([hello,this,is,a,sentence],' ',A).
A = 'hello this is a sentence'.
在 Prolog 中,如果我将 [hello,this,is,a,sentence] 之类的列表作为谓词的参数,我如何获得 return 值 Y 以便它将return 那个列表是一个带空格的字符串?例如[你好,这是一个句子] 将 return 你好,这是一个句子。
makesentence([H|T],Y):- % some code here
我能够 运行 递归地遍历列表并使用 Y return 相同的列表输入:
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
谓词仅处理附加列表这一事实有关,但我不确定。我将如何进行?提前致谢。
在丹尼尔的帮助下弄明白了。要将列表放入带有 space 的字符串中,请使用 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).
中,第一个参数是列表,第二个是我想在每个条目之间添加的内容,在本例中是 space ' '
和第三个参数是输出的赋值,在我的例子中是Y。感谢Daniel给我指明了正确的方向。
SWI-Prolog 有专门的内置函数:atomic_list_concat/3
?- atomic_list_concat([hello,this,is,a,sentence],' ',A).
A = 'hello this is a sentence'.