Going through lists Prolog

北城以北 提交于 2019-12-24 10:15:07

问题


I'm trying to work in Prolog and I'm having trouble understanding how to solve my problem. What I am trying to do is create tuples of 3 elements each one from a different list. What I need to do is make a tuple of three for every possible combination out of three lists. My plan is to take the first element in two of the lists and then go thru every element in the third list creating a tuple for each. Then take the first element in the first list and the second element in the second list and go thru each element in the third list again. I understand this may be hard to follow. My overall goal is to create a bunch of tuples for each possible combinations from the three lists. The first element in the tuple is from the first list, the second element is from the second list, and the third element is from the third list.

I'm a beginner in prolog so I'm a little confused on what direction I need to go and how to write my thoughts in code. So any help would be greatly appreciated.

Thank you


回答1:


Are you able to solve this for two lists? If so, then you are able to solve it for any number of them:

pairup_lists( [A, B | T] ,    X ):-
   pairup_lists( [B | T] , Y),
   pairup_two_lists( A,    Y, X).

You will need to add some corner case(s) here, and implement the pairup_two_lists/3 predicate.

Knowing in advance there will be only three of them, you can inline the recursion and fuse everything into one predicate, pairup_three_lists/4.

How, then, to solve the pairup_two_lists/3 problem?

If the first list is a singleton list, doesn't the problem then become equivalent to another, simpler, pair_up_an_element_and_a_list/3 problem?

And if the first list has more elements in it, so it can be split into a head and a tail, doesn't that same logic apply to dealing with the tail list, element by element, until there are no more elements to deal with?



来源:https://stackoverflow.com/questions/52788655/going-through-lists-prolog

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