0
votes

I have a very simple Prolog function but Prolog always returns false from the comparison and I can't work out why. I want to take N letters of the alphabet and put them in a list. So if I call it with N=6, I want [A,B,C,D,E,F]. Can anyone tell me what I'm doing wrong please?

create([],_,_,[]).
create([X|XS],Length,Acc,[X|NewList]) :-
    Acc<Length, create(XS,Length,Acc+1,NewList).

I get this when I run it using SWIPL:

?- create([A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z],6,0,Nodes).
false.

But if I take out the Acc<Length it creates a list of 26 letters:

?- create([A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z],6,0,Nodes).
NewList = [A, B, C, D, E, F, G, H, I|...].
1
Have you looked at the tracer? it is funny how you use "Acc+1", but never mind. - tiffi
Second comment: you get Variables, not letters. - tiffi
Third comment: you need to specify what should happen if Length is equal to Acc, sorry evaluates to the same value as Acc. - tiffi
I see. I get it now. It almost works but gives me a weird number at the end: NewList = = [A, B, C, D, E, F|_25614]. Do you know what might cause that? - theWhiteKnight
Great, thanks for your time, it's great that you can help beginners. - theWhiteKnight

1 Answers

0
votes

This is a solution that summarizes our discussion in the comments, but uses beautiful pattern matching:

create(_,Length,Length,[]).
create([Head|Tail],Length,Acc,[Head|NewList]):- 
    Acc<Length, 
    Acc1 is Acc + 1,
    create(Tail,Length,Acc1,NewList).

As a bonus, here is another solution:

create(List, Length, Solution):-
    length(Solution, Length),
    append(Solution, _, List).

Edit: Rethinking it, I am not so sure any more that this is what you want, since probably with your first clause, you want to specify what is supposed to happen when List has less members than Length and that is to return the full list.

Ok, then correct answers would be:

create([],_,_,[]).
create(_,Length,Length,[]).
create([Head|Tail],Length,Acc,[Head|NewList]):- 
    Acc<Length, 
    Acc1 is Acc + 1,
    create(Tail,Length,Acc1,NewList).

and

create(List, Length, Solution):-
    length(Solution, Length),
    append(Solution, _, List), 
    !.
create(List, _, List).