不知道如何从以下位置创建 ISeq:Java.lang.Long

Don't know how to create ISeq from: Java.lang.Long

在递归和映射实现方面进行一些练习,以消除 Clojure 的一些缺陷。我在这里只使用列表,所以我如何尝试混合 seq 和不可 seqable 的东西?

(defn mapset
  ([operator operand] (mapset operator operand '()))
  ([operator operand finished-set]
   (if (empty? operand)
     '(finished-set)
     (mapset operator (rest operand) (into finished-set (operator (first operand)))))))

回复:

namespace.name> (mapset + '(1 3 4 6 5))
Execution error (IllegalArgumentException) at tester.core/mapset (core.clj:38).
Don't know how to create ISeq from: java.lang.Long

这个错误意味着当它需要一个序列(列表、向量等)时,你不小心给了它一个整数:

demo.core=> (first 5)
Execution error (IllegalArgumentException) at demo.core/eval2055 (form-init5218243389029929734.clj:1).
Don't know how to create ISeq from: java.lang.Long

一些错误:

  • '(finished-set)替换为finished-set
  • into adds elements from one collection to another, I think you're looking for conj(这是IllegalArgumentException的来源)
  • 如果你要使用 conj,你必须使用 [] 作为初始 finished-set,因为 conj 将元素添加到列表的开头,但是在矢量的结尾

你的函数,变化很小:

(defn mapset
  ([operator operand] (mapset operator operand []))
  ([operator operand finished-set]
   (if (empty? operand)
     finished-set
     (mapset operator (rest operand) (conj finished-set (operator (first operand)))))))

测试:

(mapset inc '(1 3 4 6 5))
; => [2 4 5 7 6]

(mapset dec '(1 3 4 6 5))
; => [0 2 3 5 4]

你也可以只用两个参数来写,使用 cons:

(defn mapset [operator operand]
  (if (empty? operand) 
    '()
    (cons (operator (first operand))
          (mapset operator (rest operand)))))

请注意,这两个版本都不是惰性版本,需要添加 lazy-seq.