初学者序言:数据结构

beginner prolog: data structures

我正在努力了解 Prolog,但我在数据结构方面有些吃力。

我想取一个 point(X,Y) 并沿着 "diagonal" X=Y 反射它,所以 point(-5,8) 变成 point(8,-5)

/* the following line is what I've gotten so far, 
   but I don't know how to manipulate the data inside the structures. */
reflection(X,Y) :- =(Y,X).

test_answer :-
    reflection(point(-5,8), point(X,Y)),
    write(point(X, Y)).
test_answer :-
    write('Wrong answer!').

应该输出point(8,-5).

这种东西还需要数据结构还是我想多了?

你可以只写:

reflection(point(A,B), point(B,A)).

如果在文件 reflection.prolog 中,则:

$ gprolog --consult-file reflection.prolog
...
| ?- reflection( point(1,2), X).
X = point(2,1)
yes 

我使用的 prolog 版本 (Strawberry Prolog) 不允许我使用 = 的前缀表示法,所以除非你的 prolog 对 = 有不同的含义,否则看起来你的代码是这样的:

reflection(X,Y):- Y = X.

这意味着reflection只有在XY可以统一时才会统一。

因此您的代码应该生成 point(-5,8) 而不是 point(8,-5),因为 point(-5, 8)X = -5Y = 8 时与 point(X, Y) 是统一的。你没有说你在问题中得到了什么。

您需要使用此规则才能使其生效:

reflection(point(X,Y),point(Y,X)).