Jy2500
Jy2500

Reputation: 21

Number from a string of numbers-prolog

I would like to get a number within a string like 1100010 I would like to get the last two digits How would I do that If I dunno the the length of the given String

forFun("",0).
forFun(Str,N) :- Str1 is Str - 1,
                 forFun(Str1,N1),
                 N is N1 + 1.

is that a possible code ?

Upvotes: 0

Views: 107

Answers (1)

Isabelle Newbie
Isabelle Newbie

Reputation: 9378

First (unfortunately) we need to agree what we mean by "string". For many purposes the best and most portable representation is a list of "chars" (one-character atoms), though your Prolog might need to be told that this is really the representation you want:

?- set_prolog_flag(double_quotes, chars).
true.

Now, for example:

?- Number = "12345".
Number = ['1', '2', '3', '4', '5'].

To get the last two elements of a list, you can use the widely supported (though not standard) append/3 predicate. You can ask Prolog a question that amounts to "are there some list _Prefix (that I do not care about) and a two-element list LastDigits that, appended together, are equal to my Number?".

?- Number = "12345", LastDigits = [X, Y], append(_Prefix, LastDigits, Number).
Number = ['1', '2', '3', '4', '5'],
LastDigits = ['4', '5'],
X = '4',
Y = '5',
_Prefix = ['1', '2', '3'] ;
false.

The last two digits of this number are ['4', '5'].

Upvotes: 1

Related Questions