What does “upvalue” mean in Mathematica and when to use them?

后端 未结 3 1483
猫巷女王i
猫巷女王i 2021-01-30 11:32

To me, g /: f[g[x_]] := h[x] is just verbose equivalent of f[g[x_]] := h[x]. Can you raise an example that you have to use /:?

3条回答
  •  独厮守ぢ
    2021-01-30 12:21

    Rcollyer has already given an excellent answer but here is an example of when you might use UpValues: when you are defining a particular data structure, with its own Head, and you want to defining how built in operations like arithmetic work with that structure. I once did this for a timeSeries data structure where, for example, addition would match up the dates in the first columns and add the corresponding pairs of values in the second columns. Adding T * 2 vectors with dates in the first column would give nonsense dates if you hadn't defined such an operation using an UpValue.

提交回复
热议问题