gpt4 book ai didi

clojure - clojure 中的函数定义宏

转载 作者:行者123 更新时间:2023-12-01 09:58:23 25 4
gpt4 key购买 nike

我正在尝试制作一个转换它的宏:

(defn-check my-checked-function
check-function
[a A
b B]
(do-something a b))

进入:

(defn my-checked-function [a b]
{:pre [(= (check-function a) A)
(= (check-function b) B)]}
(do-something a b))

我是 Clojure 的新手,谁能告诉我该怎么做?

最佳答案

(defmacro defn-check [name check-fn args & tail]
(let [docstring (if (string? (first tail)) (first tail))
tail (if docstring (next tail) tail)
params (take-nth 2 args)
checks (take-nth 2 (next args))
cf (gensym "cf__")]
`(let [~cf ~check-fn]
(defn ~name
~@(if docstring [docstring])
~(vec params)
{:pre ~(mapv (fn [p c]
`(= (~cf ~p) ~c))
params
checks)}
~@tail))))

这允许您根据需要指定文档字符串,但不能指定属性映射(请参阅 (doc defn);添加对此的支持会很简单)。

例子:

user> (defn-check funky-add odd? [x true y false] "foo" (+ x y))
#'user/funky-add
user> (doc funky-add)
-------------------------
user/funky-add
([x y])
foo
nil
user> (funky-add 1 2)
3
user> (funky-add 2 1)
AssertionError Assert failed: (clojure.core/= (cf__2268 x) true) user/eval2269/funky-add--2270 (form-init1446120099766722611.clj:1)

关于clojure - clojure 中的函数定义宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20790960/

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