1,105,328 Community Members

Prolog Help

Member Avatar
phorce
Veteran Poster
1,006 posts since Jul 2011
Reputation Points: 105 [?]
Q&As Helped to Solve: 133 [?]
Skill Endorsements: 29 [?]
Featured
 
0
 

Hello, I need some help please..

I need to write a recursive predicate in Prolog that subtracts two numbers until number 2 is higher than the result.

I have completed the logic in C++:

#include <iostream>

using namespace std;
int mod3(int a, int b)
{
	int intResult = a-b;

	if(intResult > b)
	{
		return mod3(intResult, b);
	}

	return intResult;
}
int main(int argc, char *argv[]) {
	
	cout << mod3(23, 5);
	
	return 0;
}

BUT putting it into Prolog is doing my brain in.. This is what I've got so far:

modulo(X, M, Y) :-

Y is (X-M),
(Y > M),
modulo(X, M, Y).

Could someone give me some help/pointers on what I'm doing wrong?

Thanks :)

Member Avatar
pyTony
pyMod
6,103 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

Without actually running it, looks infinite recursion as last predicate is same as lhs of the rule Put another variable there, same variable can not unify with two values (forget assignment same varible name means exactly same value in Prolog) actually thinking about it the last statement is junk, remove it. Only add ground rule when Y <= M

Member Avatar
phorce
Veteran Poster
1,006 posts since Jul 2011
Reputation Points: 105 [?]
Q&As Helped to Solve: 133 [?]
Skill Endorsements: 29 [?]
Featured
 
0
 

Hello thanks for your reply.

Do you mean something like this:

checkNum(Num1, Num2) :-
    Num1 > Num2.

modulo(A, B, Result) :-

    Result is (A-B),
    checkNum(Result, B),

?
BEGIN

Result = A-B,
check to see if the result is more than be,
[CONFUSED WHAT TO DO HERE]
END

I think you have to put result back modulo, because it takes 5 from the result..

Member Avatar
pyTony
pyMod
6,103 posts since Apr 2010
Reputation Points: 818 [?]
Q&As Helped to Solve: 1,056 [?]
Skill Endorsements: 42 [?]
Moderator
Featured
 
0
 

Basic logical definition of mod/3 is

mod(X, Y, X) :- X < Y.
mod(X, Y, Z) :- plus(X1, Y, X),  mod(X1, Y, Z).
Member Avatar
phorce
Veteran Poster
1,006 posts since Jul 2011
Reputation Points: 105 [?]
Q&As Helped to Solve: 133 [?]
Skill Endorsements: 29 [?]
Featured
 
0
 

Hello,

Thanks for the reply.

This code:

mod(X, Y, X) :- X < Y.
mod(X, Y, Z) :- plus(X1, Y, X),  mod(X1, Y, Z).

Would I need another predicate called Plus? Wouldn't that just a infinite loop (so to speak).

Question Answered as of 2 Years Ago by pyTony
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article