简体   繁体   English

在Javascript Interop中使用Clojurescript线程优先宏

[英]Using Clojurescript thread-first macros with Javascript Interop

Is it possible to use the "thread-first" macro if any of the required forms are part of a Javascript interop? 如果任何必需的形式是Javascript互操作的一部分,是否可以使用“线程优先”宏?

For example, if you wanted to group inputs in ranges of size 10, you might have something like the following: 例如,如果要对大小为10的范围内的输入进行分组,则可能会有以下内容:

(defn get-size [i]
  (-> i
      (/ 10)
      (.ceil js/Math)))

However, this doesn't work as presumably the result after division gets passed to .ceil as if it were a function. 但是,这可能不起作用,因为除法运算后将结果传递给.ceil就好像它是一个函数一样。 Wrapping the last form in extra parenthesis to try and have it evaluated as a single function expression also does not seem to work. 将最后一个形式包装在额外的括号中以尝试将其作为单个函数表达式进行评估似乎也不起作用。

-> & friends don't care whether the expressions they operate on are related to interop or not – they only see the forms as data structures and transform them according to simple rules. -> &朋友不在乎他们操作的表达式是否与互操作相关-他们只将表单视为数据结构,并根据简单规则对其进行转换。

The reason your example doesn't work is that it attempts to call a method called ceil on the number with js/Math as the argument rather than calling the method Math.ceil on the number: 您的示例不起作用的原因是,它尝试使用js/Math作为参数在数字上调用名为ceil的方法,而不是在数字上调用Math.ceil方法:

  1. (-> i (/ 10) (.ceil js/Math))

  2. (-> (/ i 10) (.ceil js/Math))

  3. (.ceil (/ i 10) js/Math)

This would work: 这将工作:

(-> i (/ 10) (->> (.ceil js/Math)))

As would the anonymous function approach with the correct argument order: 正如匿名函数采用正确的参数顺序一样:

(-> i (/ 10) (#(.ceil js/Math %)))

For more complex cases with initial arguments to -> more complex than just i you might find as-> quite useful. 对于带有->i更复杂的初始参数的更复杂的情况,您可能会发现as->非常有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM