I have an iterator called myfor such that when I call myfor(3,7,X). I want it to return X = [3, 4, 5, 6, 7]. However, this code only returns X = [4, 5, 6, 7]. It skips out on the first. Can anyone tell me what’s wrong?
myfor(A, A, []) :- !.
myfor(Start,End, Z) :-
End > Start,
NewValue is Start+1,
myfor(NewValue,End, L),
append([NewValue], L, Z).
Trying to implement a for/next loop in prolog is a strong indication that you are thinking in terms of imperative programming, where you tell the computer what to do, rather than in terms of declarative programming, where you describe the solution and let Prolog’s inference engine figure it out.
If, however, you want to generate a list containing an ordered range of numbers, something like the following will “git’er done” with the magic of a difference list: