Skip to content

Instantly share code, notes, and snippets.

@nisbus
Last active December 12, 2015 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nisbus/4733580 to your computer and use it in GitHub Desktop.
Save nisbus/4733580 to your computer and use it in GitHub Desktop.
Learning prolog...
%%% Why does this return X = [something,something,something,something|_G610].
%%% when I call it with
%%% ?- add_elems(5,X).
%%%
%%% What is the uninstantiated variable at the end and how do I get rid of it?
add_elems(0,_).
add_elems(N,Out) :-
NewN is N-1,
Add = something,
add_elems(NewN,R),
Out = [Add|R],!.
@ricardobcl
Copy link

That "_G610" at the end is some random garbage, because return "_" when add_elems receives 0.
You should instead return an empty list, because when you add to the head with [Add | R], R is supposed to be a list. You want it to do something like this: ...[something | [something | [] ]]...

Here is the correct version:

add_elems(0,[]).
add_elems(N,Out) :-
    NewN is N-1,
    Add = something,
    add_elems(NewN,R),
    Out = [Add|R].
?- add_elems(5,X).
X = [something, something, something, something, something] 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment