質問

I am new to prolog. I have learned that ,though it is a declarative language, prolog can be used as a general purpose programming language, just like C. So, whatever problems you can solve in C, you can solve in prolog as well, even though its run-time may not be as good. Since there are no pointers in prolog (as far as i know), I am wondering if i can write an equivalent program in prolog for the following code written in C :-

#include <stdio.h>

int main()
{
    int a = 5;
    int *p;
    p = &a;
    printf("The address of a is %d.", p);
    return 0;
}
役に立ちましたか?

解決

You're trying to drive in a nail using a screwdriver, to use a popular analogy. Prolog is not C and solving problems in Prolog is fundamentally different from solving them in C.

Printing the value of a variable is easy to do, for example:

main :-
    X = 5,
    io:format("X = ~w~n", [X]).

but you can't get the address of X like you can in C. And why would you want to? The address could be different next time since Prolog has automatic garbage collection.

If you want to learn Prolog, forget about trying to write Prolog programs which look like C programs, and try to solve actual problems instead. You could try out the Project Euler series of problems, for example.

他のヒント

Apart from the comments and the existing answer, here is more:

Ask yourself: what is the use of the C program that you have shown? What problem does it solve? I can't answer this question, and I suspect you can't answer it either. In isolation, this program has no useful application whatsoever! So despite C being a general purpose programming language, you can write programs without any purpose, general or domain-specific.

The same, of course, is true of Prolog.

To pointers in particular: they are a very thin abstraction over absolute memory addresses. You can use (and abuse) pointers in many ways, and, if your algorithms are correct for the problem you are currently solving, the compiler can generate very efficient machine code. The same, however, is true of Prolog. The paradigms, however, will be very different.

In summary, you have managed to write a question so devoid of meaning that you provoked me to answer it without any code.

P.S. Or you have just trolled us with moderate success.

Well, since you tagged your question, I can show the code I used to exchange Qt GUI objects (just pointers, you know...) with the Prolog engine.

/** get back an object passed by pointer to Prolog */
template<typename Obj> Obj* pq_cast(T ptr) {
  return static_cast<Obj*>(static_cast<void*>(ptr));
}

to be used, for instance in swipl-win, where _read_f is really a C callback:

/** fill the buffer */
ssize_t Swipl_IO::_read_f(void *handle, char *buf, size_t bufsize) {
    auto e = pq_cast<Swipl_IO>(handle);
    return e->_read_(buf, bufsize);

swipl-win has found its way as the new console in SWI-Prolog.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top