在 Mathematica 中以编程方式创建多元函数 [英] Programmatically creating multivariate functions in Mathematica
问题描述
这是对之前问题的讨论的分离.
This is a split from discussion on earlier question.
假设我需要定义一个函数 f 来检查给定的图形标签是否正确着色.换句话说,我们为每个节点分配了一个整数,并且没有两个相邻的节点得到相同的答案.例如,对于 {"Path",3},f[{1,2,3}] 返回 True,f[{1,1,2}] 返回 False.我将如何为任意图形创建这样的函数?
Suppose I need to define a function f which checks if given labeling of a graph is a proper coloring. In other words, we have an integer assigned to every node and no two adjacent nodes get the same answer. For instance, for {"Path",3}, f[{1,2,3}] returns True and f[{1,1,2}] returns False. How would I go about creating such a function for arbitrary graph?
以下内容基本上满足了我的需要,但会生成零件警告.
The following does essentially what I need, but generates Part warnings.
g[edges_] := Function @@ {{x}, And @@ (x[[First[#]]] != x[[Last[#]]] & /@ edges)}
f = g[GraphData[{"Path", 3}, "EdgeIndices"]];
f[{1, 2, 1}]==False
这是我经常遇到的一个玩具实例问题——我需要以编程方式创建一个多元函数 f,并最终得到 1) 部分警告 2) 推迟对 g 的评估直到对 f 的评估
This is a toy instance problem I regularly come across -- I need to programmatically create a multivariate function f, and end up with either 1) part warning 2) deferring evaluation of g until evaluation of f
推荐答案
这里有一些东西.当没有其他工作时,Hold
和规则通常可以完成工作.我不确定它会产生正确的结果 w.r.t.您的图形着色问题,但希望为您提供一个起点.我最终使用 Slot
而不是命名变量,因为存在一些范围问题(也出现在我之前的建议中,x$
vs. x
)当我使用了一个我没有花时间尝试解决的命名变量时.
Here's something. When nothing else is working, Hold
and rules can usually get the job done. I'm not sure it produces the correct results w.r.t. your graph-coloring question but hopefully gives you a starting place. I ended up using Slot
instead of named variable because there were some scoping issues (also present in my previous suggestion, x$
vs. x
) when I used a named variable that I didn't spend the time trying to work around.
g[edges_] :=
With[{ors = (Hold @@ edges) /. {a_, b_} :> #[[a]] == #[[b]]},
Function[!ors] /. Hold -> Or
]
In[90]:= f = g[GraphData[{"Path", 3}, "EdgeIndices"]]
Out[90]= !(#1[[1]] == #1[[2]] || #1[[2]] == #1[[3]]) &
In[91]:= f[{1, 2, 3}]
Out[91]= True
In[92]:= f[{1, 1, 2}]
Out[92]= False
我觉得它缺乏典型的 Mathematica 优雅,但它确实有效.如果我受到更美的启发,我会更新.
I feel like it lacks typical Mathematica elegance, but it works. I'll update if I'm inspired with something more beautiful.
这篇关于在 Mathematica 中以编程方式创建多元函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!