You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Hy文档示例代码时出现with_gensyms未定义错误

解决Hylang中with_gensyms未定义的问题

问题原因

with-gensyms 是 hyrule.macros 子模块下的宏,你当前仅导入了 hyrule 顶层模块,并未导入该宏,因此触发未定义错误。

修复方案

你需要显式导入 with-gensyms 宏,有两种方式可以实现:

方式一:导入指定宏

修改导入部分代码,直接从 hyrule.macros 导入 with-gensyms:

(import hy)
(import [hyrule.macros [with-gensyms]])

(defmacro nif [expr pos-form zero-form neg-form]
  (with-gensyms [g]
    `(do
       (setv ~g ~expr)
       (cond (> ~g 0) ~pos-form
             (= ~g 0) ~zero-form
             (< ~g 0) ~neg-form))))

(nif 0 (print "Positive") (print "Zero") (print "Negative"))

方式二:导入hyrule所有宏

使用 require 导入 hyrule.macros 模块,这样就能使用该模块下的所有宏:

(import hy)
(require hyrule.macros)

(defmacro nif [expr pos-form zero-form neg-form]
  (with-gensyms [g]
    `(do
       (setv ~g ~expr)
       (cond (> ~g 0) ~pos-form
             (= ~g 0) ~zero-form
             (< ~g 0) ~neg-form))))

(nif 0 (print "Positive") (print "Zero") (print "Negative"))

补充说明

Hy中宏不会随模块自动加载,必须显式导入宏所在的子模块或具体宏。官方文档可能省略了这一步骤,默认用户了解宏的导入规则。

内容的提问来源于stack exchange,提问作者jmwright

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 06:24:59