0

Well, I'm very new in prolog and I'm trying to solve some simple recursive problems like the following.

Implement firstKCharacters(Str, K, L) function which gets the first K characters of string Str in the result string L. I've figured out the following solution:

firstKCharacters(_, 0, _):- !.
firstKCharacters([X|L1], K, L):- append([X], S1, L),
    X1 is K - 1, firstKCharacters(L1, X1, S1).

I'm confused about result:

?- firstKCharacters([a,b,c,d,e,f,g], 1, X).
X = [a|_1174]

Can someone explain what is the _1174 and why I'm getting a|_1174 isntead of a?

Narek Atayan
  • 1,479
  • 13
  • 27

1 Answers1

2

Your error is in the terminal version of firstKCharacters/3; writing

firstKCharacters(_, 0, _):- !.

you forget to fix the output list to a empty list; you should write it as follows

firstKCharacters(_, 0, []) :- !.

Without fixing it, remain a variable (the _ in third position) that isn't unified: your _1174.

A (off topic, I suppose) suggestion: avoid append and simply translate X from the left to the right list. I mean: write the other version of firstKCharacters/3 as follows

firstKCharacters([X|L1], K, [X|L]):-
    X1 is K - 1, firstKCharacters(L1, X1, L).

Because I donk like the cut, I propose you a version without it

firstKCharacters(_, 0, []).

firstKCharacters([X|L1], K, [X|L]):- 
    K > 0,
    Km1 is K - 1,
    firstKCharacters(L1, Km1, L).
max66
  • 65,235
  • 10
  • 71
  • 111