1

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.

Willem Van Onsem
  • 397,926
  • 29
  • 362
  • 485
Gilgamesz
  • 4,328
  • 3
  • 23
  • 53
  • Recurrence is not something wrong at all .. There may be another way to do it but it would also be based on a recurrence at some point. – meucaa Jun 03 '16 at 22:42

1 Answers1

3

Keep it simple! How? Delegate the "recursive part" to built-in / library predicates!

Based on length/2, 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...
Community
  • 1
  • 1
repeat
  • 19,674
  • 4
  • 52
  • 161