Search code examples
prolog

Prolog function to create multiplication tables


I am trying to create a prolog function that gets a small multiplication table based on the first value pased to the function.

My code is currently as follows:

mult(n, [[[n, 1], n*1], [[n,2], n*2], [[n,3], n*3]]).

So for example I would like a query such as:

?- mult(5, R).

To display something like:

R = [[[5,1],5], [[5,2],10], [[5,3], 15]]

However, currently this query only returns false, how could I fix my code?


Solution

  • For example, like this. The capital letters for variable names are mandatory.

    mult(N, [[[N, 1], N1], [[N,2], N2], [[N,3], N3]]) :-
        N1 is 1*N,
        N2 is 2*N,
        N3 is 3*N.
    

    or maybe:

    mult(N, R) :-
        numlist(1, 3, M),
        maplist(x(N), M, R).
    
    x(N, M, [[N, M], P]) :-
        P is N * M.
    

    You could also abuse findall to get the same result in a one-liner.

    ?- findall([[5,X],P], ( between(1, 3, X), P is 5*X ), R).
    R = [[[5, 1], 5], [[5, 2], 10], [[5, 3], 15]].