【问题标题】:clojure.lang.PersistentList cannot be cast to clojure.lang.IFnclojure.lang.PersistentList 不能转换为 clojure.lang.IFn
【发布时间】:2018-01-14 02:45:44
【问题描述】:

您好,作为the 4Clojure problem set 的一部分,我正在尝试返回前 N 个斐波那契数的列表。我已经使用非匿名函数成功实现了这一点:

(defn nth-fibo [i]
  (cond
    (= i 1) 1
    (= i 2) 1
    :else (+ (nth-fibo (- i 1)) (nth-fibo (- i 2)))))

(defn fibos [i]
  (loop [x i]
    (when (> x 0)
      (cons (nth-fibo x) (fibos (- x 1))))))

(reverse (fibos 5))

但是,我必须向 4Clojure 评估器提供一个可调用函数才能通过测试。我这样做的尝试:

#(
  (letfn [
          (nth-fibo [i]
            (cond
              (= i 1) 1
              (= i 2) 1
              :else (+ (nth-fibo (- i 1)) (nth-fibo (- i 2)))))
          (fibos [i]
            (loop [x i]
              (when (> x 0)
                (cons (nth-fibo x) (fibos (- x 1))))))
          ]
    (reverse (fibos %))))

导致错误:

java.lang.ClassCastException: clojure.lang.PersistentList 不能 转换为 clojure.lang.IFn

【问题讨论】:

    标签: clojure


    【解决方案1】:

    导致问题的匿名函数周围有一组额外的括号。看看这是否有效:

    #(letfn [(nth-fibo [i]
               (cond
                 (= i 1) 1
                 (= i 2) 1
                 :else (+ (nth-fibo (- i 1)) (nth-fibo (- i 2)))))
             (fibos [i]
               (loop [x i]
                 (when (> x 0)
                   (cons (nth-fibo x) (fibos (- x 1))))))]
       (reverse (fibos %)))
    

    同一问题的较小复制:

    #(str %)
    => #object[playground.so$eval1751$fn__1752 0x718c0dd5 "playground.so$eval1751$fn__1752@718c0dd5"]
    (*1 1)
    => "1"
    #((str %))
    => #object[playground.so$eval1767$fn__1768 0x5375a819 "playground.so$eval1767$fn__1768@5375a819"]
    (*1 1)
    ClassCastException java.lang.String cannot be cast to clojure.lang.IFn  playground.so/eval1767/fn--1768 (so.clj:21)
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多