Reputation: 940
I have to write the predicate identity/2
which receives a number n
, and makes an identity matrix [n x n]
.
Example:
identity(3,I).
I = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
For this one I do not even know how to start. At least an insight on how to build a simple list of n
elements could provide me a good starting point! Thank you!
Upvotes: 1
Views: 313
Reputation: 22803
Well, the first thing you need to do is worry about your base case, which I'll just give you:
identity(1, [[1]]).
Now you need to make it work inductively for the rest.
Personally, I would write some helper predicates, like this to produce a list of zeroes:
zeroes(0, []).
zeroes(N, [0|Rest]) :- succ(N0, N), zeroes(N0, Rest).
You can also generate lists of arbitrary size using length/2
:
?- length(X, 3).
X = [_G1563, _G1566, _G1569].
Other predicates that might be helpful to you: nth1/3
:
?- length(X, 3), nth1(1, X, foo), nth1(3, X, bar).
X = [foo, _G1658, bar].
And don't forget you can prepend to a list just by using [X|Rest]
. :) Good luck!
Upvotes: 3