Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Clojure中:为什么在此上下文中无法解析symbol:hdcit_Clojure - Fatal编程技术网

在Clojure中:为什么在此上下文中无法解析symbol:hdcit

在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

我试图在一个列表中求解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))
        [(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基本上表示:

 (if contition 
   nil ;; the true case
   nil ;; the false case)
总是返回零。虽然由于它不是函数中的最后一个表达式,该值将被忽略,因为:

  • 函数(和大多数其他表达式)的返回值是表达式中的最后一个值
您很可能希望将
移动到函数末尾的
nil
之后

  • Clojure数据结构是不可变的,在映射上调用
    assoc
    会生成一个新映射,该映射具有附加值,而旧映射保持不变,因为其他人可能正在处理它
因此,最后一行上的
assoc
将不会做任何事情

  • for
    不是一个“for循环”,而是基于一个非常强大的表达式“mini language”(DSL),缓慢地生成一系列新值
这意味着它只在读取时产生一个值。因此,除非有什么东西打印出值,否则这个
for
循环将不会运行。REPL将打印此文件,并使此功能仅在开发中起作用。我称之为“懒虫”

不可变数据是Clojure中的一个核心概念,基本上所有语言的优点(至少部分)都来自它


Clojure的
for
表达式功能强大,足以完全解决此问题:


您在最后一行转置了
i
c
。还有几个问题值得解释,谢谢你的解释。糟糕的是,我没有指出数字列表很大——大约12500项;需要编号位置/索引,而不是编号本身。这就是为什么我考虑使用<代码>哈希映射< /代码>的原因。循环的
for
时间是
O(n^2)
,使用
has map
about
O(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])