简体   繁体   中英

Prolog list consecutive pairs

If I have a list [1,2,3,4,5], how can I get consecutive pairs and perform an operation on them? For example, I want to get (1,2) and perform doSomething on them. In the next iteration, I want to get (2,3), and so on. This is what I have so far:

listpairs([H1,H2|T]):-doSomething(H1,H2), listpairs([H2,H3|T]).

I can do the first iteration but I'm stuck when comparing H2 and H3.

Firstly, if you've got [1,2,3,4,5] , then [H1,H2|T] sets H1 = 1 , H2 = 2 , T = [3,4,5] . H1 and H2 are the two numbers you want to work on. [H2|T] = [2,3,4,5] makes the list that you can proceed to calculate on. (It starts with 2,3 after all, so recursing on it will give you the two next numbers you want.)

So your recursive case should be:

listpairs([H1,H2|T]) :- doSomething(H1,H2), listpairs([H2|T]).

Ie: Take H1 and H2 out, do something with them, then put H2 back and recurse.

Secondly, you need a base case for only having one element left:

listpairs([H]).

If you omit this, you'll never reach a base case if the list has eg 5 elements, since we always put 1 back. (Ie, the list you recurse on will never be empty.)

您可以使用这种惯用的方法,而不是显式的“循环”:

forall(append(_,[X,Y|_],List), doSomething(X,Y)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM