clojure 中的条件来构建字符串并更新变量

Fra*_*man 1 loops clojure multiple-conditions

我想尝试一下 clojure,做一个拼图,打印从开始到目标的路径。我的尝试是不打印任何内容。

我知道我已经以程序方式编写了此内容,但不确定考虑以功能方式编写此内容的最佳方法。所以我想了解为什么这不打印任何内容,如何让条件执行 2 个操作(即:将方向添加到字符串并更新位置。我在网上找到的所有示例仅执行 1 个操作),以及如何真正使这项工作发挥作用。理想情况下,如何使我的方法发挥作用,以及理想的 clojure 方法是什么。

(defn -main [& args]
  (def x 2)
  (def y 3)
  (def t_x 10)
  (def t_y 15)
  (while true
    (let [m ""]
      (cond
        (> y t_y) (let [m (str m "N")])(- y 1)
        (< y t_y) (let [m (str m "S")])(+ y 1)
        (> x t_x) (let [m (str m "W")])(- x 1)
        (< x t_x) (let [m (str m "E")])(+ x 1))

      ; A single line providing the move to be made: N NE E SE S SW W or NW
      (println m)))))
Run Code Online (Sandbox Code Playgroud)

谢谢。

Ste*_*ott 5

该解决方案不使用循环或递归,而是使用sequence,这是 Clojure 中流行的抽象:

(defn axis-steps [a b axis axis']
  (concat
    (cond
      (< a b) (repeat (- b a) axis)
      (< b a) (repeat (- a b) axis'))
    (repeat nil)))

(defn path [x y tx ty]
  (let [ns (axis-steps y ty "S" "N")            ; = ("N" "N" nil nil nil ...)
        ew (axis-steps x tx "E" "W")            ; = ("E" "E" "E" nil nil nil ...)
        nsew (map str ns ew)                    ; = ("NE" "NE" "E" "" "" "" ... )
        steps (take-while seq nsew)]            ; = ("NE" "NE" "E")
    (clojure.string/join " " steps)))           ; = "NE NE E"
Run Code Online (Sandbox Code Playgroud)
(path 2 3 10 15) ; => "SE SE SE SE SE SE SE SE S S S S"
Run Code Online (Sandbox Code Playgroud)