代码之家  ›  专栏  ›  技术社区  ›  Lars Westergren

部分Clojure cond的评估

  •  6
  • Lars Westergren  · 技术社区  · 16 年前

    尝试使用Clojure进行“计算机程序的结构和解释”中的练习1.16(fast exp的迭代版本),我得出以下结论:

    (defn fast-it-exp [base exp res]
      (cond (= exp 0) res
      (odd? exp) fast-it-exp base (- exp 1) (* base res)
      :else fast-it-exp base (/ exp 2) (* base base res)))
    

    试一试:

    user=> (fast-it-exp 0 0 10)
    10   ;yep
    user=> (fast-it-exp 2 2 2)
    1     ;no...
    user=> (fast-it-exp 1 1 1)
    #<user$fast_it_exp__59 user$fast_it_exp__59@138c63>    ;huh?!
    

    cond表达式的“奇数”部分似乎返回一个函数而不是求值。为什么? 我试着在谓词后的表达式周围加上括号,但这似乎是不正确的语法,这是我能想到的最好的方法。

    2 回复  |  直到 16 年前
        1
  •  11
  •   Shannon Severance    9 年前

    试试这个:

     (defn fast-it-exp [base exp res]
      (cond (= exp 0) res
            (odd? exp) (fast-it-exp base (- exp 1) (* base res))
            :else (fast-it-exp base (/ exp 2) (* base base res))))
    

    我手边没有回复,但看起来像你想要的。

        2
  •  6
  •   Chris Turner    16 年前

    (defn fast-it-exp [base exp res]
      (cond
        (= exp 0) res
        (odd? exp) fast-it-exp
        base (- exp 1)
        (* base res) :else
        fast-it-exp base
        (/ exp 2) (* base base res)))
    

    因此:

    user=> (fast-it-exp 0 0 10) ; (= exp 0) => res
    10   ;yep
    user=> (fast-it-exp 2 2 2)  ; base => (- exp 1)
    1     ;no...
    user=> (fast-it-exp 1 1 1)  ; (odd? exp) => fast-it-exp
    #<user$fast_it_exp__59 user$fast_it_exp__59@138c63>    ;huh?!