使用 Mathematica 进行柯里化 [英] Currying with Mathematica

查看:26
本文介绍了使用 Mathematica 进行柯里化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在 Mathematica 中实现有限形式的柯里化,使用这个结构:

One may implement a limited form of Currying in Mathematica, using this construct:

f[a_][b_][c_] := (a^2 + b^2)/c^2

允许一个人做,例如:

f[4][3] /@ Range@5

  {25, 25/4, 25/9, 25/16, 1}

<小时>

有一个问题:Attributes 仅适用于第一(组)参数.考虑:


There is a problem: Attributes only apply to the first (set of) argument(s). Consider:

ClearAll[f]
SetAttributes[f, HoldAllComplete]

f[a_][b_][c_] :=
  {ToString@Unevaluated@a,
   ToString@Unevaluated@b,
   ToString@Unevaluated@c}

f[2 + 2][ 8/4 ][3 + 5]

   {"2 + 2", "2", "8"}  

我的意图是在列表中返回 "8/4""3 + 5".

My intent was to return "8 / 4" and "3 + 5" in the list.

因此:

  • 有没有办法将属性扩展到这个结构?

  • Is there a way to extend attributes to this construct?

还有其他方便的结构来实现这一点吗?

Is there another convenient construct to achieve this?

除了属性之外,还有其他方法可以在 Mathematica 中扩展柯里化吗?

Are there other ways, besides attributes, to extend Currying within Mathematica?

推荐答案

对于可能不相关的评论,我们深表歉意.我刚刚搜索了 «currying with Mathematica»,这个问题是 Google 列表中的第一个.虽然它已经有 1 年的历史并且已经得到了答案,但我发现所提出的解决方案并不是很优雅恕我直言.对初始代码的简单修改应该如下:

Sorry for a probably unrelated comment. I just searched «currying with Mathematica» and this question was the first in Google list. Although, it is 1 year old and already got answer, I found that the solutions presented are not quite elegant imho. The simple modification of the initial code should be as follows:

ClearAll[f]
SetAttributes[f, HoldAllComplete]
f[a_, b_, c_] := {ToString@Unevaluated@a, ToString@Unevaluated@b,
ToString@Unevaluated@c}
f[a__] := Function[x, f[a, x], HoldAll]

它导致了所需的携带:

f[2+2][2+1]/@ Unevaluated@{1+1, 3+3}{{2+2, 2+1, 1+1}, {2+2, 2+1, 3+3}}

它适用于三个可能的参数分区

It works fine for three possible partitions of arguments

f[1 + 1, 2 + 2, 6 + 1]
f[1 + 1, 2 + 2][6 + 1]
f[1 + 1][2 + 2][6 + 1]

并给出正确的结果:{"1+1", "2+2", "6+1"}},但对于 f[1 + 1][2 + 2, 6 + 1] 失败.对于这个,可以使用更高级的版本:

and gives the correct result: {"1+1", "2+2", "6+1"}}, but it fails for f[1 + 1][2 + 2, 6 + 1]. For this one, one can use a little bit more advanced version:

ClearAll[f, g]
SetAttributes[f, HoldAllComplete]
SetAttributes[g, HoldAllComplete]
f[a_, b_, c_] := (ClearAll[g]; SetAttributes[g, HoldAllComplete]; 
  Thread[Hold[{a, b, c}]] /. {Hold[e_] :> ToString@Unevaluated[e]})
f[a__] := (g[x__] := f[a, x]; g)

这篇关于使用 Mathematica 进行柯里化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆