Prolog Beginner: How to make unique values for each Variable in a predicate

前端 未结 3 1397
一个人的身影
一个人的身影 2020-12-21 15:32

I have a prolog predicate:

Add( [A|B] , Answer ) :-
    ...
    ~ Add everything in the list to come up with answer
    ...

I would now lik

3条回答
  •  生来不讨喜
    2020-12-21 16:08

    This is the solution that I came up with. It will only assign the input to be numbers less than ten but works great for that!

    addUnique( A, Answer ) :- 
        used(A,[0,1,2,3,4,5,6,7,8,9],_),
        add(A,Answer).
    
    add( [A|B] , Answer ) :-
        ~ Add everything in the list to come up with answer ~.
    
    
    % ================================
    % Ensures that all variables are unique.  
    % ================================
    
    % Base case: Assigned variables unique values
    used([], Nin, Nin).
    
    % Have already assigned a value to this variable
    used([A|B], Nin, Nout) :-
            integer(A),
            helper(B,Nin,Nout).
    
    % Have not assigned a value to this variable yet
    % Assign it and remove it from the list.  
    used( [A|B] , Nin, Nout) :-
            member(A,Nin),
            delete(Nin,A,Temp),
            helper(B,Temp,Nout).
    

提交回复
热议问题