سؤال

I have got a method length(list,var) which gives me the length of a list but i want to find the length of a String, anyone with a solution ?

هل كانت مفيدة؟

المحلول 3

was just playing with it and i gave the predicate as

?- length("hello", R).
R = 5.

surprisingly it worked :)

نصائح أخرى

If you would like to go ISO Prolog, then you wouldn't use the name/2 predicate.

ISO Prolog offers you atom_codes/2 and atom_chars/2. They offer you the functionaliy of converting an atom back forth to either a list of codes or a list of characters. Atoms are the strings of a Prolog system, and characters are simply atoms of length 1. Here are some example invokations of the two predicates:

?- atom_codes(ant, L).
L = [97,110,116]
?- atom_codes(X, [97,110,116]).
X = ant
?- atom_chars(ant, X).
X = [a,n,t]
?- atom_chars(X,[a,n,t]).
X = ant

Now you wonder how to determine the length of a string aka atom. One way to go would be to first determine the codes or characters, and then compute the length of this list. But ISO also offers an atom_length/2 predicate. It works as follows:

?- atom_length(ant,X).
X = 3

Many Prolog systems provide this set of built-in predicates, namely SWI Prolog, GNU Prolog, Jekejeke Prolog etc.. The available character code range and encoding depends on the Prolog system. Some allow only 8-bit codes, some 16-bit codes and some 32-bit codes.

Also the maximum length of an atom might differ, and sometimes there is an extra string type which is not tabled compared with the atom type which is often. But this extra type is usually not the same as a double quote enclosed string, which is only a shorthand for a character list.

Bye

Since strings are atoms, you can't manipulate them directly to get the length, extract substrings, etc. First you have to convert them to character lists with atom_chars/2:

atom_chars(StrVar, ListVar), length(ListVar, LengthVar).

Maybe this:

string_length(+String, -Length)

from Prolog manual.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top