简体   繁体   中英

Prolog procedure

I will begin by saying that I am very new to Prolog, and that it is still very hard for me to come up with a solution and not think it in a procedural or a functional way.

The context of the problem is as follows: I have to move in four directions starting from the initial position (0,0). When I move up I update my position to (0,1), down to (0, -1), left to (-1,0) and right to (1, 0). At some point I have to go back to my initial position.

I have solved the problem by memorizing all the moves that I do to a certain point and then do the reverse. So if the moves I did were down, left I just go up, west. The solution works, but it is very inefficient and dumb.

So the thing I want to do is to make a procedure that takes the current position (X,Y) and evaluates to one of the four moves if by updating the position I am closer to (0,0).

I have tried to write some code, but the truth is that I don't really know how to think the problem in Prolog. Can someone give me some hints how I can solve it ? Thank you!

First, you need a way to represent the legal directions to where you can move. A simple solution is to use the atoms up , down , left , and right . Next, you can define a predicate that, given a position and a direction, computes the resulting position. For example:

move((X,Y), up, (X,NewY)) :- NewY is Y + 1.
...

If you want to perform a sequence of moves, eg [up, left, up, up, right, down] , you can define another predicate that takes a sequence and an initial position and computes the final position while keeping track of all intermediate positions (using an additional argument). You can also, in alternative, work the sequence backwards, back-tracing your moves. Can you try it and update your question with the results?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM