Currying with Mathematica

后端 未结 5 1119
無奈伤痛
無奈伤痛 2020-12-23 07:30

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

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

Allowing one to do, for

5条回答
  •  情话喂你
    2020-12-23 08:12

    I don't think there is any way to have attributes apply to the later parts of such an "upvalue" pattern definition.

    One alternative is to use pure functions with attributes. Not as convenient as pattern matching, but when you evaluate f[2+2][8/4], it actually gives a result Curry would have liked. ("Function" is Mathematica's "lambda", if you're familiar with lambda calculus.)

    f = Function[a,Function[b,Function[c,HoldForm@{a,b,c},HoldAll],HoldAll],HoldAll]

    I presume you want to be able to do something like the following:

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

    If you're going to do this sort of thing often, you can make it slightly easier to type in:

    hf[args_,body_]:=Function[args,body,HoldAll]; SetAttributes[hf,HoldAll];

    f = hf[a, hf[b, hf[c, HoldForm@{a, b, c}]]]

    The Mathematica Cookbook presents a rather different approach to Currying on pages 73-77.

    As a general guideline, if you try to control when Mathematica evaluates expressions, you will make yourself miserable. A better approach in many situations is to use symbols as placeholders for the expressions you don't want evaluated yet, and then when the time comes to evaluate one, you can substitute the desired expression for the symbol.

提交回复
热议问题