We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,539 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Prolog Help

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 :)

2
Contributors
4
Replies
1 Day
Discussion Span
1 Year Ago
Last Updated
5
Views
Question
Answered
phorce
Master Poster
738 posts since Jul 2011
Reputation Points: 63
Solved Threads: 91
Skill Endorsements: 16

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

pyTony
pyMod
Moderator
6,299 posts since Apr 2010
Reputation Points: 879
Solved Threads: 984
Skill Endorsements: 26

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..

phorce
Master Poster
738 posts since Jul 2011
Reputation Points: 63
Solved Threads: 91
Skill Endorsements: 16

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).
pyTony
pyMod
Moderator
6,299 posts since Apr 2010
Reputation Points: 879
Solved Threads: 984
Skill Endorsements: 26

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).

phorce
Master Poster
738 posts since Jul 2011
Reputation Points: 63
Solved Threads: 91
Skill Endorsements: 16
Question Answered as of 1 Year Ago by pyTony

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0606 seconds using 2.63MB