0
votes

I'm working on a Prolog application that will go through a list of values and copy the values to another list. If a value is a number, then I want to square that number, otherwise, copy the value.

So given the input:

 [k, 4, 9, b]

It should yield:

 [k, 16, 81, b]

Here is what I have:

squareMe(X, P) :- P is X * X.

boogie([],[]).
% The next line is where I'm having problems
boogie([X|T], [X|Result]):-
    number(X),
    boogie(T,Result).
boogie([ThrowAway|Tail], [ThrowAway|Result]):-
    boogie(Tail,Result).

Right now, this almost works. So the first thing I tried was:

boogie([X|T], [X*X|Result):-

Prolog would not evaluate the expression because you need "is". So I tried:

boogie([X|T], [Y is X*X|Result):-

That didn't work. I tried:

boogie([k, 4, 9, b], T).

My output was:

T = [k, _G3648 is 4*4, _G3657 is 9*9, b].

Is there a way that I can obtain the square of a number within the list? i.e.

boogie([X|T], [Square of X|Result]):-
2

2 Answers

1
votes

What about

boogie([X|T], [Y|Result]):-
    number(X),
    Y is X*X,
    boogie(T,Result).

?

0
votes

I will admit I haven't done prolog in years, but your approach confuses me a bit. Wouldn't it be easier to simply have a predicate that 'processes' individual tokens, and then use it to recursively process each token in the input list? e.g.

%% In file 'boogie.pl'

% 'processToken' predicate
processToken( Unprocessed, Processed )   :- number( Unprocessed ), 
                                            Processed is Unprocessed ^ 2, 
                                            !.
processToken( Unprocessed, Processed )   :- not( number( Unprocessed )),
                                            Processed = Unprocessed.

% 'processList' predicate
processList( [], [] ).   % Base case
processList( InputList, OutputList ) :- [H_in  | T_in  ] = InputList, 
                                        [H_out | T_out ] = OutputList,
                                        processToken( H_in, H_out ),
                                        processList( T_in, T_out ),
                                        !.

Then at your prolog console:

?- consult( 'boogie.pl' ).
% boogie.pl compiled 0.00 sec, 1 clauses
true.

?- processList( [1, 2, a, v, 'hi there', '5', 6], Out ).
Out = [1, 4, a, v, 'hi there', '5', 36].