How to multiply all elements of two lists with each other in Prolog

后端 未结 5 1131
终归单人心
终归单人心 2021-01-22 00:12

I am thinking how to multiply all elements of two list with each other. Then I want to put all results in List3. For example,

List1 = [1,3,5].
List         


        
5条回答
  •  一向
    一向 (楼主)
    2021-01-22 01:04

    A simple solution not requiring any Prolog extensions (but, of course, loosing the potential benefits of using CLP(FD)) would be:

    product(List1, List2, Product) :-
        % save a copy of the second list
        product(List1, List2, List2, Product).
    
    product([], _, _, []).
    product([X| Xs], List2, Rest2, Product) :-
        (   Rest2 == [] ->
            product(Xs, List2, List2, Product)
        ;   Rest2 = [Y| Ys],
            Z is X * Y,
            Product = [Z| Zs],
            product([X| Xs], List2, Ys, Zs)
        ).
    

    This solution is tail-recursive and doesn't leave spurious choice-points.

提交回复
热议问题