I came across this natural number evaluation of logical numbers in a tutorial and it's been giving me some headache:
natural_number(0).
natural_number(s(N)) :- natural_number(N).
The rule roughly states that: if N
is 0
it's natural, if not we try to send the contents of s/1
back recursively to the rule until the content is 0
, then it's a natural number if not then it's not.
So I tested the above logic implementation, thought to myself, well this works if I want to represent s(0)
as 1
and s(s(0))
as 2
, but I´d like to be able to convert s(0)
to 1
instead.
I´ve thought of the base rule:
sToInt(0,0). %sToInt(X,Y) Where X=s(N) and Y=integer of X
So here is my question: How can I convert s(0) to 1 and s(s(0)) to 2?
Has been answered
Edit: I modified the base rule in the implementation which the answer I accepted pointed me towards:
decode(0,0). %was orignally decode(z,0).
decode(s(N),D):- decode(N,E), D is E +1.
encode(0,0). %was orignally encode(0,z).
encode(D,s(N)):- D > 0, E is D-1, encode(E,N).
So I can now use it like I wanted to, thanks everyone!
No problemo with meta-predicate
nest_right/4
in tandem with Prolog lambdas!Sample queries:
This is a standard task - a solution is here: http://www.docstoc.com/docs/82593705/Prolog-%E2%80%93-Family-Tree (page 109).
The key insight is that the value of
s(N)
is 1+ the value ofN
, and that ifN
is 0, the value is0
.Here is another solution that works "both ways" using
library(clpfd)
of SWI, YAP, or SICStus