Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

prolog - Get elements from list of lists

is it possible to get all elements from list of lists in Prolog?

Something like: We have getElements([[[a,b,[c]],d,e],f,g,[h,[i,j]]],S) and the result is: S = [a,b,c,d,e,f,g,h,i,j] ...

Thanks for help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You asked for all elements of a list of lists. That is, for [[1,2,3],[4]] this would be the list [1,2,3,4]. However, for [[[1],[3]]] this would be the list [[1],[3]] since [1] and [3] are elements. For this reason, flatten/2 is incorrect it gives you [1,3] as an answer. Also, for 1 it gives [1]...

Here is a solution using :

seq([]) --> [].
seq([E|Es]) --> [E], seq(Es).

seqq([]) --> [].
seqq([Es|Ess]) --> seq(Es), seqq(Ess).

?- phrase(seqq([[[1],[3]]]), Xs).
Xs = [[1],[3]].

?- phrase(seqq(1), Xs).
false.

This solution now works also for cases like the following:

?- phrase(seqq([S1,S2]), [1,2]).
S1 = [],
S2 = [1,2] ;
S1 = [1],
S2 = [2] ;
S1 = [1,2],
S2 = [] ;
false.

Whereas flatten/2 is completely wrong:

?- flatten([S1,S2],[1,2]).
S1 = 1,
S2 = 2.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...