# Arithmatic on Lists 1

Status
Not open for further replies.

##### Programmer
This may be a simple problem but I am completely new to prolog.

I am attempting to generate a predicate minus(A,B) where A is an initial state in a list [7,3,12,1] and B is what i am attemping to get to. So minus[7,3] would be acceptable. however i can only minus the numbers 4 and 2 so [7,4] is not acceptable. Could someone please help with how i could do this. Thank you all!

I don't understand what your attempting.

You want:
minus(A,B)

Where both A and B are lists? And then it prints out what you would have to take away from A to get to B?

Sorry after reading it again its not clear at all.

If I state 1 bit it might be easier.

I have a list [9,8,7,3] or along those lines.

I need a predicate minus(A,B) which will list the moves possible. The only moves can be to subtract 4 or 2 so i would get the answer

A = 9 B = 5 ;
A = 9 B = 7 ;
A = 8 B = 4 ;
A = 8 B = 6 ;
...
A = 3 B = 1;

I can't seem to figure our the predicate.

You can use a predicate with 3 args to tackle the problem more broadly.

minus(+FirstList, +ListOfNumbersToSubstract, -ListResult).

For each number of FirstList, you add all the numbers get with ListOfNumberstoSubstract to ListResult.

Is there anyway to use only 2 arguments?

Yes : minus(+FirstList, -ListResult).

Thanks for your help. So far I have

minus(X,Y) :- Y > X, fail.
minus(X,Y) :- Y is X-1;
minus(X,Y) :- Y is X-2;
minus(X,Y) :- Y is X-3.

but I'm not sure how to implement this using a list of numbers. I have a list [9,8,7,3] and I want to see all the moves available if minus is a move. I think it has to be done recursively but how would I go about this? Thanks

I'm no sure to really understand what you need, but I give you two ways to do that :
minus1 which writes the answer on the console and minus2 which memorize the answer in a list.

Code:
``````minus1([A | T]) :-
(   A >= 4 -> B is A - 4, format('A= ~w B = ~w~n', [A, B]); true),
(   A >= 2 -> C is A - 2, format('A= ~w B = ~w~n', [A, C]); true),
minus1(T).

minus1([]).

test :-
minus1([9,8,7,3,1]),
nl,
minus2([9,8,7,3,1], L),
maplist(affiche, L).

minus2([], []).

minus2([H | T], [H1 | T1]) :-
minus2(T, T1),
(   H >= 4 -> A is H - 4, B is H - 2, H1 = [H, A,B];
H >= 2 -> A is H - 2, H1 = [H, A]; H1 = []).

affiche([H, A,B]) :-
format('A= ~w B = ~w~n', [H, A]),
affiche([H, B]).

affiche([H, A]) :-
format('A= ~w B = ~w~n', [H, A]).

affiche([]).``````

The result is
4 ?- test.
A= 9 B = 5
A= 9 B = 7
A= 8 B = 4
A= 8 B = 6
A= 7 B = 3
A= 7 B = 5
A= 3 B = 1

A= 9 B = 5
A= 9 B = 7
A= 8 B = 4
A= 8 B = 6
A= 7 B = 3
A= 7 B = 5
A= 3 B = 1
true ;

Thank you all for your help, I've used bits from all comments!

Status
Not open for further replies.

Replies
2
Views
29
Replies
2
Views
29
Replies
6
Views
63
Replies
0
Views
20
Replies
3
Views
26