简体   繁体   中英

List in SWI-Prolog

Please help me! I do not understand SWI-Prolog

From the list L1 to list L2, another element which is equal to the arithmetic average of the next three items in the list L1. If the number of L1 elements are not divisible by 3, then the last item in the list L2 is obtained by dividing by 3 the sum of one or two recent items list L1. List L1 is introduced for prompt screen. As a result, the program should output input L1 and L2 resulting lists.

List items are available under request.

This question translates to Prolog almost word-for-word.

First, add the base case, saying that an empty list translates to an empty list:

by_three([], []).

Now add the main rule for grabbing the initial items, H1 , H2 , and H3 , in groups of three, and averaging them:

by_three([H1,H2,H3|T],[A|RT]) :- A is (H1+H2+H3) / 3, by_three(T, RT).

Note the recursive invocation here: the tail T of the original list is converted to RT in the call of by_three/2 at the end of the rule.

Finally, add two more cases for one-element list and for two-element list:

by_three([H],[A]) :- A is H / 3.
by_three([H1,H2],[A]) :- A is (H1+H2) / 3.

That's it, you are done!

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