gpt4 book ai didi

function - Clojure 函数定义中的运算符优先级是什么?

转载 作者:行者123 更新时间:2023-12-05 01:29:06 25 4
gpt4 key购买 nike

假设我们定义函数如下,Clojure 中的运算符优先级是什么?

(defn leap-year? [input-year] (or (and (= (rem input-year 4) 0) (> (rem input-year 100) 0)) (= (rem input-year 400) 0)))

最佳答案

S-expressions明确具有优先级和结合性,因为它们代表一棵树。

像许多 LISP 方言一样,Clojure 以“许多恼人的多余括号”直截了本地暴露了这些问题:

In computing, s-expressions, sexprs or sexps (for "symbolic expression") are a notation for nested list (tree-structured) data, invented for and popularized by the programming language Lisp, which uses them for source code as well as data. In the usual parenthesized syntax of Lisp, an s-expression is classically defined inductively as

  • an atom, or
  • an expression of the form (x . y) where x and y are s-expressions.

就优先级和结合性而言,“运算符”与任意函数调用(或宏)没有什么不同。也就是说,Clojure 代码有效地开始生命 Abstract Syntax Tree并且 (+ a b) 的形式本质上与 (fn a b) 没有区别 - + 标记,如 fnadd,只是生成的 S 表达式中的一个 atom

格式化代码应该更多地显示树结构(并且可以扩展这种格式化,直到一行只包含一个原子和 0..n 括号):

(defn leap-year? [input-year]
(or
(and (= (rem input-year 4) 0)
(> (rem input-year 100) 0))
(= (rem input-year 400) 0)))

虽然源形式和扩展形式仍然是 S 表达式,但是andormacros . 的实现是:

(defmacro and
"Evaluates exprs one at a time, from left to right. If a form
returns logical false (nil or false), and returns that value and
doesn't evaluate any of the other expressions, otherwise it returns
the value of the last expr. (and) returns true."
{:added "1.0"}
([] true)
([x] x)
([x & next]
`(let [and# ~x]
(if and# (and ~@next) and#))))

这允许 (和 ..)(通过宏的递归扩展),但不允许在产生式中允许“或”项,因为形式是 < em>已经由外层S表达式树建立。

此外,从实现中可以看出,与许多其他流行语言一样,逻辑条件形式也是从左到右惰性求值

关于function - Clojure 函数定义中的运算符优先级是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20822229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com