Clojure - 正确显示一些输出

时间:2012-10-20 18:08:39

标签: clojure

我对clojure很新,所以还在努力学习......很多东西。现在我一直试图让一些输出正确显示。这是我的功能:

;function 7 - display the board
(defn display [small medium large]
(let [board (loop [i 0 boardVector [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
          ;(prn (bit-test small i)(bit-test medium i)(bit-test large i))
          (if (< i 16)
           (cond
             ;nothing exists
             (and (not(bit-test small i))(not(bit-test medium i))(not(bit-test large i)))
               (recur (+ i 1) (assoc boardVector i (+ (nth boardVector i) 0)))
             ;only small bit exists
             (and (bit-test small i)(not(bit-test medium i))(not(bit-test large i)))
               (recur (+ i 1) (assoc boardVector i (+ (nth boardVector i) 1)))
             ;small and medium exists on square
             (and (bit-test small i)(bit-test medium i)(not(bit-test large i)))
               (recur (+ i 1) (assoc boardVector i (+ (nth boardVector i) 3)))
             ;only medium exists on square
             (and (not(bit-test small i))(bit-test medium i)(not(bit-test large i)))
               (recur (+ i 1) (assoc boardVector i (+ (nth boardVector i) 2)))
             ;medium and large exists on square
             (and (not(bit-test small i))(bit-test medium i)(bit-test large i))
               (recur (+ i 1) (assoc boardVector i (+ (nth boardVector i) 6)))
             ;only large exists on square
             (and (not(bit-test small i))(not(bit-test medium i))(bit-test large i))
               (recur (+ i 1) (assoc boardVector i (+ (nth boardVector i) 4)))
             ;all three exists on square
             (and (bit-test small i)(bit-test medium i)(bit-test large i))
               (recur (+ i 1) (assoc boardVector i (+ (nth boardVector i) 7)))
               )
           boardVector)
         )
    ]
(prn  board)
)
)

以下是我用来作为参数传递的内容:

(display 2r1001000100 2r101001000 2r111000000)

此函数接受位变量(长度不超过16个......),并根据设置的位计算最终向量。一个小的值1,中值2,大值4.这就是为什么我有条件声明概述了每个不同的可能性,排除了同时具有小型和大型的可能性。

无论如何,如果这些都没有意义,那么这里是实际的问题: 如何将当前输出显示为:

[0 0 1 2 0 0 7 4 6 1 0 0 0 0 0 0]
nil

要让它显示如下吗?

0 0 1 2
0 0 7 4
6 1 0 0
0 0 0 0

我尝试过使用诸如apply,map,str,interpose之类的功能......但是我从来都不知道我对他们做错了什么。目前我将输出显示为副作用(我认为这是正确的名称......),但它总是从prn函数的输出返回nil。不知道怎么摆脱那个。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

将其分成4组,然后打印每组:

(dorun (map #(apply println %) (partition-all 4 r)))
0 0 1 2
0 0 7 4
6 1 0 0
0 0 0 0

或使用for表达式:

(dorun (for [line (partition-all 4 r)] (apply println line)))
0 0 1 2
0 0 7 4
6 1 0 0
0 0 0 0

或使用doseq

(doseq [line (partition-all 4 r)] (apply println line))
0 0 1 2
0 0 7 4
6 1 0 0
0 0 0 0
dorundoall示例需要

for(或map)因为这些是懒惰的,否则实际上不会打印任何内容,除非他们返回的序列被消耗。使用apply调用println并且序列使得println将序列的内容作为参数而不是它自己的序列来获取,这使得它不会打印额外的parens。