【发布时间】:2012-02-24 19:07:24
【问题描述】:
在此处包含的两个函数中,哪一个更惯用?两者都不代表可以被认为是好的 Clojure 的东西吗?有没有更优雅的方式来实现这一点?寻找一些关于风格/方向的建设性批评。
(在github上:https://github.com/jtrim/clojure-sandbox/blob/master/bit-sandbox/src/bit_sandbox/core.clj#L25)
这个函数的两个版本都采用数字表示的字节向量,并且 将字节转换为数字。例如
(bytes-to-num [0 0 0 0]) ;=> number `0`
(bytes-to-num [0 0 0 255]) ;=> number `255`
(bytes-to-num [0 0 1 0]) ;=> number `256`
; etc...
v1:循环/重复
在每个递归级别,有问题的字节 左移一个对应于字节数的数字 给定的递归级别,然后添加到运行总和中 返回或传递到另一个级别。
(defn bytes-to-num-v1 [vec-bytes]
(loop [sum 0, the-bytes vec-bytes]
(if (empty? the-bytes)
sum
(recur
(+ sum (shifted-byte (first the-bytes) (count (rest the-bytes))))
(rest the-bytes)))))
v2:减少
v2 使用 [sum position] 的累加器减少字节向量,其中:
- sum:移位字节的运行总和
- 位置:从零开始的索引(注意:从右侧开始,而不是从左侧开始) 向量中的当前字节。用于确定要左移多少位 有问题的字节。
:
(defn bytes-to-num-v2 [vec-bytes]
(first (reduce
(fn [acc, the-byte]
[(+ (first acc) (shifted-byte the-byte (last acc))) (dec (last acc))])
[0 (dec (count vec-bytes))]
vec-bytes)))
为了完整性,shifted-byte 函数的来源:
(defn shifted-byte [num-byte-value, shift-by]
(bit-shift-left
(bit-and num-byte-value 0xFF)
(* shift-by 8)))
【问题讨论】:
标签: coding-style recursion clojure idioms reduce