Midhun
Midhun

Reputation: 744

How to populate a list in prolog at the end of recursion?

I'm trying to implement a cantor set using prolog. The problem is defined in this link. I have implemented the code like this.

create_cantor_set(X, Y, D, List):-
    cantor(D, X, Y, Temp), % Depth, X, Y, temporary list
    reverse(List, Temp).  

% base condition
cantor(1, X, Y, [[X|Y]|_]).


cantor(D, X, Y, Temp):-
    X1 is X + ((Y - X) / 3),
    Y1 is Y - ((Y - X) / 3),
    decrement(D, D1),
    cantor(D1, X, X1, [[X|X1]|Temp]),
    cantor(D1, Y1, Y, [[Y1|Y]|Temp]).

% Decrement helper
decrement(N, N1):-
    N1 is N-1.

However, I'm getting an output like this:

List = [] ;
List = [_4770] ;
List = [_4770, _4776] ;
List = [_4770, _5442, _4776] ;
List = [_4770, _5442, _5448, _4776] ;
List = [_4770, _5442, _6114, _5448, _4776]

I'm not able to understand why it is giving placeholder variables rather than the actual values. I'm trying to add the set [X|Y] when D = 0. The answer should be one final list. Thank you for your help.

EDIT:

sample query: create_cantor_set(0, 1, 2, List).

expected output: [[0, 0.333],[0.666, 1]]

Upvotes: 1

Views: 67

Answers (1)

rajashekar
rajashekar

Reputation: 3753

div_interval(N, X-Y, Xn-Yn) :-
    Xn is X/N, Yn is Y/N.

add_interval(A, X-Y, Xa-Ya) :-
    Xa is X + A, Ya is Y + A.

step_cantor(Ii, Io) :-
    maplist(div_interval(3), Ii, Io1),
    maplist(add_interval(2/3), Io1, Io2),
    union(Io1, Io2, Io).

cantor(0, [0-1]).
cantor(N, X) :-
    N > 0, N1 is N - 1, cantor(N1, X1),
    step_cantor(X1, X).

cantor_len(S, L) :-
    foldl([X-Y, A, O]>>(O is (A+Y-X)), S, 0, L).

I am representing an interval [a, b] with a pair a-b.

?- cantor(0, X), cantor_len(X, Y).
X = [0-1],
Y = 1 

?- cantor(1, X), cantor_len(X, Y).
X = [0-0.3333333333333333, 0.6666666666666666-1.0],
Y = 0.6666666666666666 

?- cantor(2, X), cantor_len(X, Y).
X = [0-0.1111111111111111, 0.2222222222222222-0.3333333333333333, 0.6666666666666666-0.7777777777777777, 0.8888888888888888-1.0],
Y = 0.4444444444444444 

Upvotes: 2

Related Questions