【问题标题】:how to eval a cond case and return function object?如何评估条件案例并返回函数对象?
【发布时间】:2018-08-03 14:57:55
【问题描述】:

得到 TypeError: 不知道如何包装 : . at 0x000001B879FD3D08>

运行时

;a fn object
(setv a_fn (fn [x] (+ 1 x)))
;a mock predicator
(setv predicator True)
;inject predicator and a_fn into a (cond ..)
(setv cond_expr `(cond [(~predicator) [~a_fn]]))
;eval at another place 
(eval cond_expr)

如何创建 "cond_expr" 以获得结果 [a_fn] ?

【问题讨论】:

    标签: hy


    【解决方案1】:

    为了evalHyExpression 它必须首先被编译成 Python ast。虽然您可以将任意对象放入HyExpression,但这并不意味着您可以编译它。 (simulating this feature已经有一点讨论了,但目前还没有。)

    Hy 编译器只能对称为 Hy 模型类型的特定数据类型集执行此操作,或者对可以自动转换为这些 Hy 模型的少数其他类型执行此操作。

    Python ast 中没有明显的方法来表示函数object,因此没有Hy 模型。但是你可以编译一个函数定义

    => (setv a-fn '(fn [x] (+ 1 x)))
    => (setv cond-expr `(cond [True ~a-fn]))
    => (eval cond-expr)
    <function <lambda> at 0x0000020635231598>
    

    或函数的符号

    => (defn b-fn [x] (- x 1))
    => (setv cond-expr2 `(cond [True b-fn]))
    => (eval cond-expr)
    <function <lambda> at 0x0000020635208378>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多