Currying with Mathematica

后端 未结 5 1032
后悔当初
后悔当初 2020-12-23 07:31

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:05

    I'm not aware of any way to extend attributes to the second or later curried argument lists -- although I'd love to hear about one.

    You can implement definitions for expressions with the same appearance as the curried expression by using pure functions (although I would hesitate to call it "convenient"):

    ClearAll[f, f1, f2]
    SetAttributes[{f, f1, f2}, HoldAllComplete]
    f[a_] := Function[b, f1[a, b], HoldAllComplete]
    f1[a_, b_] := Function[c, f2[a, b, c], HoldAllComplete]
    f2[a_, b_, c_] :=
      { ToString@Unevaluated@a
      , ToString@Unevaluated@b
      , ToString@Unevaluated@c
      }
    
    f[2+2][8/4][3+5]
    

    It is possible to pattern match a curried expression using the now undocumented symbol HeadCompose:

    In[65]:= MatchQ[g[x][y][z], HeadCompose[g, x_, y_, z_]]
    Out[65]= True
    

    ... although this capability does not help in the matter at hand. HeadCompose was deprecated a few versions ago, to the point of it finally being removed from the documentation. But I am not aware of any other way to pattern-match curried expressions. I speculate that it was deprecated precisely because one cannot effectively attach attributes and definitions to it, giving it that dreaded status: This symbol has not been fully integrated into the long-term Mathematica system, and is subject to change.

提交回复
热议问题