Currying with Mathematica

后端 未结 5 1125
無奈伤痛
無奈伤痛 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:14

    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]
    

    It results in the desired carrying:

    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]
    

    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)
    

提交回复
热议问题