7

So as the title says - how do you convert a string into an integer? the idea is something like this:

convert(String,Integer).

examples:
convert('1',1).
convert('33',33).

I'm using swi prolog

Matt Ellen
  • 10,460
  • 4
  • 67
  • 85
Iva
  • 71
  • 1
  • 1
  • 2
  • 3
    possible duplicate of [Parsing numbers with multiple digits in Prolog](http://stackoverflow.com/questions/3279822/parsing-numbers-with-multiple-digits-in-prolog) – Ted Hopp Jul 21 '11 at 20:05
  • 2
    @Ted Hopp: not a dupe, the other question has the specific context of DCGs. This can be done more easily. The OP has to decide whether a string or an atom is given, though. – Fred Foo Jul 21 '11 at 20:24

5 Answers5

15

Use atom_number/2. E.g:

  atom_number('123', X).
  X = 123.
gusbro
  • 21,302
  • 34
  • 45
12

Assuming you really meant a string and not an atom, use number_codes.

?- number_codes(11, "11").
true.

?- number_codes(11, Str).
Str = [49, 49].            % ASCII/UTF-8

?- number_codes(N, "11").
N = 11.
Fred Foo
  • 342,876
  • 71
  • 713
  • 819
5

Perhaps use of atom_codes(?Atom, ?String) and number_chars(?Number, ?CharList) would do it.

MRAB
  • 19,740
  • 5
  • 38
  • 31
0

Quite an old, but there is a predicate in SWI Prolog: number_string(N, S).

Docs

number_string(123, S).
S = "123".

For those who are still looking for it.

Omar
  • 85
  • 1
  • 3
  • 11
-1

in Visual Prolog convert:

X=toTerm(real,H).

real/integer/unsigned...

Drovosek
  • 99
  • 4