i want to know if there are any methods to achieve an iteration in Prolog passing an empty input. For example I would like to have 0 on the first iteration, 1 on the next one, 2 on the second one and so on.
From your comment:
Example: iterate() is my query and every time i call it i want that the output is 0 first time 1 second time and so on.
Shouldn't be any more difficult than this:
increment(N) :- inc(0,1,N).
inc(C , _ , C ) .
inc(C , S , N ) :- C1 is C+S, inc(C1,S,N).
To break it down, a very common idiom in Prolog programming is the use of helper predicates. Since prolog doesn't have any sort of iteration construct, it just has recursion and backtracking, often to do something useful, you'll need to carry additional state as you go: things like the current value of a counter, etc.
So . . .
We have our increment/1 predicate. All it does is invoke a helper predicate, inc/3. It carries, in addition to the variable from the calling predicate (N), two additional pieces of state:
The current value (C) of a counter, and
The step value (S), that value by which the counter should be incremented in each recursive call.
Those bits of state are initialized with 0 and 1 respectively.
inc/3, our helper predicate has just two clauses:
inc(C , _ , C ) .
inc(C , S , N ) :- C1 is C+S, inc(C1,S,N).
What it does is this:
On initial entry to the predicate, the 1st clause of the predicate is entered, and current value of the counter is unified with N, the desired value, and succeeds.
On backtracking, that unification is undone, and the 2nd clause of the predicate is entered. That does the following:
The next value (C1) is computed as the sum of the current and step values.
inc/3 is recursively invoked, passing C1, S, and N.
You might note that this predicate is non-terminating: If you were to run inc(0,1,N), writeln(N), fail, your CPU would spin to 100% as it started writing to the console
0
1
2
3
4
. . .
Similar question
With succ/2:
nat(N) :-
nat(0, N).
nat(N, N).
nat(N0, N) :-
succ(N0, N1),
nat(N1, N).
Or with call_nth/2:
nat(0).
nat(N) :-
call_nth(repeat, N).
Now, all natural numbers:
?- nat(N).
Example: iterate() is my query and every time i call it i want that the output is 0 first time 1 second time and so on.
If you store the state in the Prolog database and don't mind the output being by side effect and can deal with not using () when calling it, then:
:- dynamic(iterate_counter/1).
iterate_counter(0).
iterate() :-
iterate_counter(X),
writeln(X),
succ(X, Y),
retract(iterate_counter(X)),
assert(iterate_counter(Y)).
?- iterate, iterate, iterate.
0
1
2
incrementing(Lower, Increment, N) :-
integer(Lower),
integer(Increment),
% Fast integer comparison
Increment #>= 1,
incrementing_(Lower, Increment, N).
incrementing_(Lower, Increment, N) :-
nonvar(N), !,
integer(N),
% Can calculate, faster than iterating
N #>= Lower,
Diff is N - Lower,
divmod(Diff, Increment, _, 0).
incrementing_(Lower, Increment, N) :-
incrementing_loop_(Lower, Increment, N).
incrementing_loop_(Lower, _Increment, Lower).
incrementing_loop_(Lower, Increment, N) :-
Lower1 is Lower + Increment,
incrementing_loop_(Lower1, Increment, N).
Results in swi-prolog:
?- incrementing(5, 3, N).
N = 5 ;
N = 8 ;
N = 11 ;
N = 14 ...
?- incrementing(5, 3, 11).
true.
?- incrementing(5, 3, 12).
false.
Could wrap this, for convenience, e.g.:
iterate(N) :-
incrementing(0, 1, N).
Results:
?- iterate(-1).
false.
?- iterate(2).
true.
?- iterate(N).
N = 0 ;
N = 1 ;
N = 2 ;
N = 3 ...
How could the following function be written using iteration instead of recursion?
function mystery(b)
{
if b == 0 then
return 0
if (b / 2 == 0)
return mystery (b-1) + 3
else
return mystery (b-1) + 2
}
I assume that when you are doing b / 2 == 0 you are checking whether the number b is even or odd otherwise that is true only for case where b= 0,1.
Recursive function
def mystery(b):
if b == 0:
return 0
if b % 2 == 0:#check if b is even
return mystery(b-1)+3
else: return mystery(b-1)+ 2
Iterative function
def mystery_iter(b):
result= 0
while b > 0:
if b % 2 == 0:#check if b is even
result += 3
b= b-1
else:
result += 2
b= b-1
return result
At least two people suggest you reformulate the recursion as a loop. I instead suggest you first try to understand the mathematics of what the function is doing before considering unwinding the implicit recursive loop into an explicit iterative loop. Doing so in this case, you get a simpler answer:
def mystery(b):
if b == 0:
return 0
if b % 2 == 0:
return b // 2 * 5
return b // 2 * 5 + 2
This could be further reduced code-wise, possibly to a one-liner, if one desires. (Like #AkhileshPandey, I'm assuming that the division in (b / 2 == 0) was supposed to be a modulus operation (b % 2 == 0)) The above example is Python 3 as it wasn't clear what language the OP used, nor that the given code would run correctly in said language due to inconsistent use of then.
I wanted to calculate the number of solutions of the equation, but I am unable to get any lead. The equation is:
All I could get is by doing something like,
But I don't know how to proceed on this.
I'd try solving this by using dynamic programming.
Here's some pseudocode to get you started:
Procedure num_solutions(n, k, m):
# Initialize memoization cache:
if this function has been called for the first time:
initialize memo_cache with (n+1)*(k+1)*(m+1) elements, all set to -1
# Return cached solution if available
if memo_cache[n][k][m] is not -1:
return memo_cache[n][k][m]
# Edge case:
if m is equal to 1:
# Solution only exists if 1 <= m <= k
if n >= 1 and n <= k, set memo_cache[n][k][m] to 1 and return 1
otherwise set memo_cache[n][k][m] to 0 and return 0
# Degenerate case: No solution possible if n<m or n>k*m
if n < m or n > k * m:
set memo_cache[n][k][m] to 0 and return 0
# Call recursively for a solution with m-1 elements
set sum to 0
for all i in range 1..k:
sum = sum + num_solutions(n - i, k, m - 1)
set memo_cache[n][k][m] to sum and return sum
I am trying to sum numbers according to their sign in SQLite. I can write two separate commands:
SELECT sum(x) FROM table WHERE x >= 0;
SELECT sum(x) FROM table WHERE x < 0;
Is there a way to combine it into one command? Two separate commands seem to be inefficient (as we are checking conditions twice).
Make a conditional SUM
SELECT sum(case when x > 0 then x else 0 end) as positives,
sum(case when x < 0 then x else 0 end) as negatives
FROM your_table
I have the following recursion rules which returns the sum of a number, but I don't know how does it return the sum:
sum(1,1).
sum(A,Result) :-
A > 0,
Ax is A - 1,
sum(Ax,Bx),
Result is A + Bx.
now when you execute the following command in Prolog:
sum(3,X).
the answer will be 5, but as I look into the rules, I can't see how does these rules return values and sum the. How is the value of Bx is calculated ?
sum(3,X). actually gives a result of X = 6. This predicate (sum(N, X)) computes the sum of integers from 1 to N giving X:
X = 1 + 2 + 3 + ... + N.
So it is the sum of the integers from 1 to N.
sum(1,1) says the sum of 1 by itself is just 1. This is true. :)
The second clause should compute the sum for A > 1, but it's actually not totally properly written. It says A > 0 which is ignoring the fact that the first clause already takes care of the case for 1. I would have written it with A > 1. It will work as is, but be a little less efficient.
sum(A,Result) :-
A > 0,
Ax is A - 1,
sum(Ax, Bx), % Recursively find the sum of integers 1 to A-1
% Instantiate Bx with that sum
Result is A + Bx. % Result is A plus sum (in Bx) from 1 to A-1
This clause recursively says that the sum of integers from 1 to A is Result. That Result is the sum of A and the sum of integers from 1 to A-1 (which is the value Ax is unified to). The Bx is the intermediate sum of integers 1 through Ax (A-1). When it computes the sum(Ax, Bx), the value of Ax is 1 less than A. It will continue calling this second clause recursively until the first parameter goes down to 1, at which point the first clause will provide the value for the sum, and the recursion will unravel from there, summing 1, 2, 3, ...
EDIT: More Details on the Recursion
Let's look at sum(3,X) as an example.
sum(3,X) doesn't match sum(1,1). so that clause is skipped and Prolog looks at sum(A, Result). Prolog matches this by instantiating A as 3 and Result as X and steps through the statements making up the clause:
% SEQUENCE 1
% sum(A, Result) query issued with A = 3
3 > 1, % true
Ax is 3 - 1, % Ax is instantiated as the value 2
sum(2, Bx), % recursive call to `sum`, `Ax` has the value of 2
Result is 3 + Bx. % this statement is awaiting the result of `sum` above
At this point, Prolog suspends computing Result is A + Bx in order to make the recursive call. For the recursive call, Prolog can't match sum(Ax, Bx) to sum(1,1) because Ax is instantiated as 2. So it goes on to the next clause, sum(A, Result) and can match if it instantiates A as 2 and Result as Bx (remember, this is a new call to this clause, so these values for A and Result are a different copy than the ones we "suspended" above). Now Prolog goes through sum(A, Result) statements again, this time with the new values:
% SEQUENCE 2
% sum(A, Result) query issued with A = 2
2 > 0, % true
Ax is 2 - 1, % Ax is instantiated to the value 1
sum(1, Bx), % recursive call to `sum`, `Ax` has the value of 1
Result is 2 + Bx. % this statement is awaiting the result of `sum` above
Now Prolog has sum(1, Bx) (Ax is instantiated with 1). This will match sum(1,1) and instantiate Bx with 1 in the last query to sum above in SEQUENCE 2. That means Prolog will complete the sequence:
Result is 2 + 1. % `A` is 2 and `Bx` is 1, so `Result` is 3
Now that this result is complete, the recursive query to sum in the prior execution in SEQUENCE 1 will complete in a similar fashion. In this case, it is instantiated Bx with 3:
Result is 3 + 3. % `A` is 3 and `Bx` is 3 (from the SEQUENCE 2 query)
% so `Result` is 6
And finally, the original query, sum(3, X) completes, where X is instantiated with the result of 6 and you get:
X = 6.
This isn't a perfect explanation of how the recursion works, and there are some texts around with graphical representations that help. But I hope this provides some insight into how it operates.