Skip to content

Instantly share code, notes, and snippets.

@thezerobit
Created September 12, 2013 13:22
Show Gist options
  • Save thezerobit/6537188 to your computer and use it in GitHub Desktop.
Save thezerobit/6537188 to your computer and use it in GitHub Desktop.
knights moves in Prolog
% example: move([0,0],[X,Y],7,7).
% because this is not right: https://github.com/clojure/core.logic/wiki/Translations-from-prolog
move([X, Y], [A, B], Xmax, Ymax) :-
member([Dx,Dy],[[1,2],[2,1],[2,-1],[1,-2],[-1,-2],[-2,-1],[-2,1],[-1,2]]),
A is X + Dx,
B is Y + Dy,
between(0, Xmax, A),
between(0, Ymax, B).
@swannodette
Copy link

And an experienced core.logic user might write it this way:

(defne move [xy ab xm ym]
  ([[x y] [a b] _ _]
    (membero [dx dy] [[1 2] [2 1] [2 -1] [1 -2] [-1 -2] [-2 -1] [-2 1] [-1 2]])
    (project [x dx y dy]
      (== a (+ x dx)) (== b (+ y dy)))
    (between 0 xm a)
    (between 0 ym b)))

We try our best - it's true that Prolog programs often turn out a little bit shorter.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment