Search code examples
prologargumentsinstantiation-error

Prolog Arguments are not sufficiently instantiated, R is [H|R1]


I've read a few questions that are an identical question but different code, sadly another one is being posted.

I'm following my professors notes and modeling my insert statement identical to their factorial function as seen here.

factorial(0, 1).
factorial(N, F) :-  
   N > 0,
   N1 is N – 1,
   factorial(N1, F1),
   F is N * F1.

and my insert function is

insertPos(V, 0, [H|T], [V|[H|T]]).
insertPos(V, N, [H|T], R) :-
   N > 0, 
   N1 is N-1,
   insertPos(V, N1, T, R1),
   R is [H|R1].

The error is being thrown on R is [H|R1] which I was hoping to retrieve the R1 from my insertPos/4 and append the head onto it.

My query is:

?- insertPos(D, 1, [A,B,C], L).

Solution

  • You can't use is/2 for unifying variable R with list [H|R1], is/2 is used for arithmetic expression evaluation.

    Instead you can use unification operator =/2 by writing:

    R = [H|R1]
    

    or by pattern matching on arguments:

    insertPos(V, N, [H|T], [H|R1]) :-
       N > 0, 
       N1 is N-1,
       insertPos(V, N1, T, R1).