因为完全没有必要使用'let'或'def',所以我必须同意amalloy关于Bart J的答案。当然,它是值得赞赏的,因为它是有用的信息,但它不是正确的答案。
实际上,定义函数是没用的,因为(sort ilist)会做到这一点。函数的结果是你想要的'对象'。也就是说,除非你想使用多重次不同位置的函数体的结果。在这种情况下,将sort的结果绑定到函数局部变量。
如果你只需要一次,不要打扰它的绑定,但只是将它嵌套在其他函数中。例如,如果你想用它独特的功能里面(我猜是你想要做什么):
(defn uniq
"Get only unique values from a list"
[ilist]
; remove nils from list
(filter #(not(nil? %))
; the list of intermediate results from (reduce comppair sortedlist)
; (includes nils)
(reductions
; function to extract first and second from a list and compare
(fn comppair
[first second & rest]
(if (not= first second) second))
; the original sort list function
(sort ilist))))
(uniq '(1,2,3,6,1,2,3))
(1 2 3 6)
再说,你也可以只使用内置的独特功能,并采取看看它的来源:
(distinct '(1,2,3,6,1,2,3))
(1 2 3 6)
(source distinct)
(defn distinct
"Returns a lazy sequence of the elements of coll with duplicates removed"
{:added "1.0"}
[coll]
(let [step (fn step [xs seen]
(lazy-seq
((fn [[f :as xs] seen]
(when-let [s (seq xs)]
(if (contains? seen f)
(recur (rest s) seen)
(cons f (step (rest s) (conj seen f))))))
xs seen)))]
(step coll #{})))
你想要什么输出?集合的独特元素? –
不,现在,只有排序列表 – 0xAX
要存储和返回变量,可以使用let。你应该这样做:(let [sorted(sort list-elements)] sorted –