Reputation: 5073
Is it to possible to create N
elements of 0
array in another way than the following one:
makeInitialArray(N, A) :-
N > 0,
Nn is N-1,
makeInitialArray(Nn, B),
append([0], B, A).
makeInitialArray(0, []).
It is a poor way on my eye because of the fact of recurrence. I suppose that will be made to call very often operation like that.
Upvotes: 1
Views: 44
Reputation: 18726
Keep it simple! How? Delegate the "recursive part" to built-in / library predicates!
Based on length/2
, meta-predicate maplist/2
, and (=)/2
define n_zeroes/2
:
:- use_module(library(lists), [maplist/2]). n_zeroes(N, Zs) :- length(Zs, N), maplist(=(0), Zs).
Sample queries using SICStus Prolog 4.3.2:
| ?- n_zeroes(10, Zs).
Zs = [0,0,0,0,0,0,0,0,0,0] ? ;
no
| ?- n_zeroes(N, Zs).
N = 0, Zs = [] ? ;
N = 1, Zs = [0] ? ;
N = 2, Zs = [0,0] ? ;
N = 3, Zs = [0,0,0] ? ;
N = 4, Zs = [0,0,0,0] ? ;
N = 5, Zs = [0,0,0,0,0] ?
... % ...goes on forever and ever...
Upvotes: 3