1:- module(lm, []).    2:- reexport(library(mathml)).    3
    4:- multifile math_hook/2.    5
    6% A + B + C => [C, B, A]
    7summands(A + B, X) :-
    8    var(X),
    9    !,
   10    summands(A, Rest),
   11    X = [B | Rest].
   12
   13% A + B + C <= [C, B, A]
   14summands(S + A, [A, B | Rest]) :-
   15    summands(S, [B | Rest]).
   16
   17% Base case
   18summands(A, [A]).
   19
   20mathml:math_hook(LM, M) :-
   21    compound(LM),
   22    LM =.. [lm, ~(Y, Sum) | _Tail],
   23    summands(Sum, Predictors),
   24    findall(subscript(b, X) * X, member(X, Predictors), Terms),
   25    summands(Model, Terms),
   26    M = (Y == subscript(b, 0) + Model + epsilon)