Tomer
Tomer

Reputation: 559

Getting the first N chars of a String in prolog

I am trying to get the first N chars of a string. From looking at the following question I understand I can use

> sub_atom(str, X, Y, W, Z).

Getting last char of a string in Prolog

The problem is that I can't find good documentation for this function, here is the formal doc: http://www.swi-prolog.org/pldoc/man?predicate=sub_atom/5

I will be happy for a link or explanation for how this func works. Also, I will be happy for help on the following example: How to get all chars that are before "/" in "prolog/a" that will work something like this:

sub_atom(prolog/a, X , Y , W, Z). => prolog

Upvotes: 2

Views: 2833

Answers (1)

coder
coder

Reputation: 12972

I think the documentation is clear enough:

sub_atom(+Atom, ?Before, ?Len, ?After, ?Sub)
  • Atom is the initial atom from which you ant to deduct the Subatom.
  • Before is the position that the subatom starts, counting starts from 1.
  • Len is the length of the Subatom
  • After is the length of the the remaining subatom, e.g sub_atom(abc, 1, 1, After, b). gives After = 1 (remaining is c which is of length 1)
  • Sub is the Subatom acquired from the initial atom.

In your example the problem is that prolog/r is not an atom but a compound term because it contains '/'. Though "prolog/r" (in double quotes as a string) is an atom.

I suggest to use atomic_list _concat/3 in order to achieve that

?- atomic_list_concat(L, '/', "prolog/r").
L = [prolog, r].

Upvotes: 3

Related Questions