0
votes

Good Day,

I have a task (not homework), but test preparation question. Given a value of n where n > 0. I need to find out what 3**n value is. I do have something that works.

% expo
expo([],[]).
expo([X|T], [Y|Result]):-
    number(X),
    Y is 3 ^ X,
    expo(T,Result).
expo([ThrowAway|Tail], [ThrowAway|Result]):-
    expo(Tail,Result).

last([X]):-
    write("M = "),
    write(X).

last([Y|Tail]):-
    last(Tail).

do_list(N) :-
    findall(Num, between(0, N, Num), L),
    expo(L, E),
    last(E).  

When I run this at the console:

do_list(4).
M = 81
true.

So it does give me what I want. But is a recursive solution necessary? I just want to generate a sequence of numbers and use those numbers as my exponent which I have done, but I had to create two lists to this.

Ideally, I'd like to do:

do_list(4, M).
M = 81
true.

Is this possible to do this without two lists? Is it possible without recursion? I'm new to Prolog, so it's taking me a little getting used to "thinking" in Prolog.

TIA,

coson

1
Again, I am stymied. To me it seems that you are simply raising 3 to a non-negative power, and X is 3**N is all you need. Why did you bring lists and recursion into this? My confusion is even stronger because you asked a similarly strange question before, and never reacted to the feedback you received. - user1812457
@Boris, this is exactly my point. I'm new to Prolog so perhaps I'm not expressing myself properly. But that was part of my question. Are lists and recursion necessary to solve this problem. As far as your earlier point about the other question I asked, I realized it wasn't properly phrased. I apologize for not getting back. - coson

1 Answers

0
votes

If you want to do something in all elements of a list then yes most of the times you need recursion (except from cases like when you use predicates like fundall/3 which does the recursion ...).

If you want to return your result in an argument and not just print it then you need for the above predicate two lists (one is the input and the other one is the output).

Though I don't understand why not just writing:

find_pow(Input,Output):-Output is 3^Input.

From what I understood you calculate 3^i for every i<=n and keep last element which could be done independently. So if I understood corrctly what you're trying to do, this could be done without using lists and recursion (if you use predefined pow function ^ else if you write a predicate that computes the power 3^n then you would use recursion... ).

Example:

?- find_pow(4,X).
X = 81.