-2

Given the following PROLOG predicate definition f(integer, integer), with the flow model (i, o):

f(0, -1) :- !.
f(I,Y):-
  J is I-1,
  f(J,V),
  V > 0,
  !,
  K is J,
  Y is K+V.
f(I,Y):-
  J is I-1,
  f(J,V),
  Y is V+I.

Rewrite the definition in order to avoid the recursive call f(J,V) in both clauses. Do NOT redefine the predicate. Justify your answer

lambda.xy.x
  • 4,918
  • 24
  • 35
yay19
  • 5
  • 1
  • 3
    How far did you get in your attempts? Have you found out what the predicate `f` describes? That's probably the first step. – lambda.xy.x Jan 08 '22 at 12:25
  • Have you tried running it to see what the output is? Then you can reverse engineer the output back into code instead of trying to do it mentally by staring at code all day. – Guy Coder Jan 08 '22 at 12:45
  • this is an example of exercise for my exam,i cannot use the pc for solving this type of exercises during the exam. – yay19 Jan 08 '22 at 12:52
  • 1
    Then make a table of input values, run the code by hand and record the output. That will give you some idea of what the code is doing. This is obviously written to be hard to keep track of mentally. Also give the variable names something more meaningful like count_down, count_up, increment, counter, halt_value, etc. – Guy Coder Jan 08 '22 at 13:01
  • To bad you can not use OEIS. ([ref](https://oeis.org/search?q=2%2C4%2C7%2C11%2C16&sort=&language=english&go=Search)) – Guy Coder Jan 08 '22 at 13:39

1 Answers1

-1

With inspiration from question:

ffast(0, -1) :- !.
ffast(1, 0) :- !.
ffast(2, 2) :- !.
ffast(X, Y) :-
    X0 is X - 1,
    ffast(X0, Y0),
    Y is Y0 + X0.

... and then to:

ffast2(0, Y) :- !, Y = -1.
ffast2(1, Y) :- !, Y = 0.
ffast2(X, Y) :- Y is ((X * (X - 1)) / 2) + 1.

(Guarding against Y being an input, as per best-practices.)

brebs
  • 3,462
  • 2
  • 3
  • 12