在Clojure中:为什么在此上下文中无法解析symbol:hdcit
我试图在一个列表中求解find two number索引,其中在Clojure中:为什么在此上下文中无法解析symbol:hdcit,clojure,Clojure,我试图在一个列表中求解find two number索引,其中nums[I]+nums[j]==target: (defn two-sum [nums target] "Find sum of two numbers equals to target" (if (<= 1 (count nums)) nil) (let [hdict (hash-map)] (for [i (range 1 (count nums))] (if (get hdict
nums[I]+nums[j]==target
:
(defn two-sum [nums target]
"Find sum of two numbers equals to target"
(if (<= 1 (count nums))
nil)
(let [hdict (hash-map)]
(for [i (range 1 (count nums))]
(if (get hdict (nums i))
[(get hdict (nums i)) i] ;return hdict[nums[i]] and i
(assoc hdcit (- target (nums i)) i)))))
我很困惑:我一直把bind
hdict
理解为一个hash-map
,为什么仍然无法解决呢?这个错误只是一个简单的输入错误,不过还有几点值得考虑:
- Clojure
表达式始终返回一个值,如果未指定else子句(第二个表达式),则默认为如果
nil
(if contition
nil ;; the true case
nil ;; the false case)
总是返回零。虽然由于它不是函数中的最后一个表达式,该值将被忽略,因为:
- 函数(和大多数其他表达式)的返回值是表达式中的最后一个值
)
移动到函数末尾的nil
之后
- Clojure数据结构是不可变的,在映射上调用
会生成一个新映射,该映射具有附加值,而旧映射保持不变,因为其他人可能正在处理它assoc
assoc
将不会做任何事情
不是一个“for循环”,而是基于一个非常强大的表达式“mini language”(DSL),缓慢地生成一系列新值for
for
循环将不会运行。REPL将打印此文件,并使此功能仅在开发中起作用。我称之为“懒虫”
不可变数据是Clojure中的一个核心概念,基本上所有语言的优点(至少部分)都来自它
Clojure的
for
表达式功能强大,足以完全解决此问题:
您在最后一行转置了
i
和c
。还有几个问题值得解释,谢谢你的解释。糟糕的是,我没有指出数字列表很大——大约12500项;需要编号位置/索引,而不是编号本身。这就是为什么我考虑使用<代码>哈希映射< /代码>的原因。循环的for
时间是O(n^2)
,使用has map
aboutO(n)
。在这种情况下,您需要重新构造代码(可能是递归),以便将assoc生成的不可变哈希映射添加到,值得重申的是,正如@Arthur Ulfeldt所指出的那样,for
在clojure中不是一个循环,而是一个不可变值的惰性生成器。
(if contition
nil ;; the true case
nil ;; the false case)
user> (let [data [1 2 3 4 5 6 7 42 12]
target 12]
(for [x data
y data
:when (= (+ x y) target)]
[x y]))
([5 7] [6 6] [7 5])