Skip to main content

programming - Does every Symbol in Mathematica induce a monad?


From my question about types in Mathematica, I assume that every Symbol in Mathematica is a type if it appears as a Head of some expression.


So I can implement operators for monad associated with that Symbol (let it be F for instance):



  1. monad lift function (return in Haskell notation) is just return[p_] = F[p];

  2. monad bind function (>>= in Haskell notation) is just a rule bind[F[p_], f_] := F[f[p]] (as monad Maybe is for example).


From point of view of category theory, in Mathematica one can define some common rules for symbols to model monad multiplication (just flatten of repeating Head): monadMultiplyRule = {p_[p_[params___]] -> p[params]}. So expression F[F[F[p_]]] //. monadMultiplyRule will be just F[p].


Also all monad axioms are satisfied:




  1. return acts as a neutral element of bind: bind[return[p], f] is F[f[p]] and bind[F[p], Identity] is F[p];

  2. sequential bind of two functions f and q is the same as a single bind with their "composition" Bind[F[f[p]], q]: Bind[Bind[F[p], f], q] and Bind[F[f[p]], q] produce both the same result F[q[f[p]]].


So, does Mathematica provide a natural maybe-like monad for every symbol and does it provide a natural framework for any explicit monadic computations?



Answer



Mathematica provides a perfect way to define monad by setting UpValues and DownValues of some symbol. Please, find specifications for monads Maybe and State below.




  1. Monad Maybe:



    DownValues[Just] = {Just[(a: Just[x_])] :> Just[x]};
    UpValues[Just] =
    {(expr: (op: Except[Just | List | Trace | UpValues | DownValues])[
    a___, Just[b_], c___]) /;
    !MatchQ[
    Unevaluated[expr],
    HoldPattern[If[__, __, Just[x_]] | If[__, Just[x_], __]]
    ] :> Just[op[a, b, c]]};

    Rule from DownValues[Just] stands for monad Maybe multiplication law. That is removing of head duplicates. Rule from UpValues[Just] stands for bind operation of monad Maybe. One need to use special pre-condition for this pattern because Mathematica uses some wrapping code to convert evaluating/reducing expression in standard form by low-level call MakeBoxes. For example, let's see this wrapping code:



    Hold[
    If[False, 3,
    With[{OutputSizeLimit`Dump`boxes$ =
    Block[{$RecursionLimit = Typeset`$RecursionLimit},
    MakeBoxes[Just[3], StandardForm]
    ]
    },
    OutputSizeLimit`Dump`loadSizeCountRules[];
    If[TrueQ[BoxForm`SizeCount[OutputSizeLimit`Dump`boxes$, 1048576]],
    OutputSizeLimit`Dump`boxes$,

    OutputSizeLimit`Dump`encapsulateOutput[
    Just[3],
    $Line,
    $SessionID,
    5
    ]
    ]
    ],
    Just[3]
    ]

    ]

    That's why rule from UpValues[Just] has special pre-condition for being inside of condition expression. Now one can use symbol Just as a head for computations with exceptions:


    UpValues[Nothing] = {_[___, Nothing, ___] :> Nothing};
    Just[Just[123]]
    (*
    ==> Just[123]
    *)

    Just[123] + Just[34] - (Just[1223]/Just[12321])*Just[N[Sqrt[123]]]

    (*
    ==> Just[155.899]
    *)

    Thanks to @celtschk for great comments of this point.




  2. Monad State:


    return[x_] := State[s \[Function] {x, s}];
    bind[m_State, f_] := State[r \[Function] (f[#[[1]]][#[[2]]] & @ Part[m, 1][r])];

    runState[s_, State[f_]] := f[s];

    For monad State I didn't use UpValues and DownValues just for similarity with Haskell notation. Now, one can define some sequential computation as State value with complex state logics as a monadic computation by using return and bind operations. Please, see an example:


    computation =
    Fold[bind, return[1],
    Join[{a \[Function] s \[Function] {a, a + s},
    b \[Function] s \[Function] {b, s + b/(3 s)},
    c \[Function] s \[Function] {c, s + (s^2 + c)}},
    Array[x \[Function] a \[Function] s \[Function] {a, s}, 300]
    ]

    ];

    To get more effective computation one can use runState operation:


    Fold[#2[#1[[1]]][#1[[2]]] &, runState[23, return[1]], 
    Join[{a \[Function] s \[Function] {a, a + s},
    b \[Function] s \[Function] {b, s + b/(3 s)},
    c \[Function] s \[Function] {c, s + (s^2 + c)}},
    Array[x \[Function] a \[Function] s \[Function] {a, s}, 3000]
    ]
    ]

    (*
    ==> {1, 3119113/5184}
    *)


Conclusion:



  1. Ideas of rule-based programming and using Head as type identifier allow user to express any(?) programming concept in Mathematica. For example, as it has just been shown, monads State and Maybe from Haskell;

  2. Using of UpValues and DownValues for assigning rules to symbols and using of generalized operations (such as bind is) allow user to put expressions in different monadic environments.



Comments

Popular posts from this blog

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1....