我需要这样的 DSL:
defmodule SomeModule do
use SomeMacros
# sample shipping DSL
rule is_north_america do
calculate_shipping_cost_with usps
end
rule is_north_america and november_or_december do
calculate_shipping_cost_with ups
end
rule is_south_america do
calculate_shipping_cost_with fedex
end
rule is_somewhere_else do
calculate_shipping_cost_with dhl
end
end
并将每个调用转换为规则宏(我已经定义了)并让它在 SomeModule
模块中定义一个函数。像这样:
def is_north_america_rule(Address[continent: "North America"] = address) do
# do something
end
我想对传递给宏生成的函数的参数使用模式匹配。我已经看到如何在宏中定义自定义函数,但我不确定如何在宏生成的函数中实现模式匹配和守卫。
提前致谢!
最佳答案
这是一个如何实现类似目标的示例:
https://gist.github.com/josevalim/7432084
我本来打算添加更多信息,但我决定提供一个简单示例,然后再回答您可能提出的任何其他问题。不过请注意,尽量使此规则 DSL 尽可能简单,如果您看到宏代码开始变得越来越复杂,则简单地使用 cond
(明确地)会更好。
关于function - Elixir 使用模式匹配构建自定义函数并使用宏进行保护?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19917502/