1

If an integers is defined like this in Prolog:

nat(0).
nat(s(X)) :- nat(X).

How do I convert such a number to a decimal number?

The input is for example:

s(s(s(0)))

I probably should add that I am very new to Prolog.

EDIT: I tried it this way:

nat(0).
nat(s(X)) :- nat(X).

convert(N, C) :-
    C is C + 1,
    nat(N),
    convert(N, C).
false
  • 10,264
  • 13
  • 101
  • 209
Willi
  • 361
  • 6
  • 18

1 Answers1

1

There are basically two cases you need to cover:

  1. the base case 0 that maps on 0; and
  2. the recursive case s(X) that makes use of the result for X.

The base case thus looks like:

convert(0, 0).

the recursive case thus looks like:

convert(S(X), N) :-
    convert(X, N1),
    ….

where is thus a step you need to do to determine N given N1. I leave this as an exercise.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thanks, I am just going to throw out this recursive definition of numbers in the entire code base since I can't properly calculate with it. – Willi Jun 16 '20 at 21:09
  • It would be possible to write enough functions to calculate with them - that's the whole point of this model for basic mathematics - but it would be neither convenient nor efficient. – aschepler Jun 16 '20 at 22:19