kinetics.pl 1.4 KB
Newer Older
Thierry Martinez's avatar
Thierry Martinez committed
1 2 3 4 5 6 7
:- module(
  kinetics,
  [
    kinetics/3
  ]
).

Thierry Martinez's avatar
Thierry Martinez committed
8 9
kinetics(Reactants, single_reactant, Value) :-
  !,
Thierry Martinez's avatar
Thierry Martinez committed
10
  (
Thierry Martinez's avatar
Thierry Martinez committed
11
    Reactants = [Value]
Thierry Martinez's avatar
Thierry Martinez committed
12
  ->
Thierry Martinez's avatar
Thierry Martinez committed
13
    true
14
  ;
Thierry Martinez's avatar
Thierry Martinez committed
15
    throw(error(not_single_reactant_reaction))
Thierry Martinez's avatar
Thierry Martinez committed
16 17
  ).

Thierry Martinez's avatar
Thierry Martinez committed
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
kinetics(Reactants, product(Pattern in List, Expression), Value) :-
  !,
  (
    Pattern = S * O
  ->
    true
  ;
    throw(error(invalid_pattern))
  ),
  (
    List = [reactants]
  ->
    true
  ;
    throw(error(invalid_list))
  ),
  make_product(Reactants, S, O, Expression, Value).

kinetics(Reactants, FunctionApplication, Expression) :-
  callable(FunctionApplication),
  functor(FunctionApplication, Functor, Arity),
  item([kind: function, key: Functor, item: (function(Head = Body))]),
  !,
  functor(Head, Functor, ApplicationArity),
  (
    Arity = ApplicationArity
  ->
    true
  ;
    throw(error(arity_mismatch(Functor, Arity, ApplicationArity)))
  ),
  Head =.. [Functor | Parameters],
  FunctionApplication =.. [Functor | Arguments],
  substitute(Parameters, Arguments, Body, NewBody),
  kinetics(Reactants, NewBody, Expression).
Thierry Martinez's avatar
Thierry Martinez committed
53

Thierry Martinez's avatar
Thierry Martinez committed
54 55
kinetics(Reactants, Callable, Expression) :-
  term_morphism(kinetics(Reactants), Callable, Expression).
Thierry Martinez's avatar
Thierry Martinez committed
56 57


Thierry Martinez's avatar
Thierry Martinez committed
58
make_product([], _S, _O, _Expression, 1).
Thierry Martinez's avatar
Thierry Martinez committed
59

Thierry Martinez's avatar
Thierry Martinez committed
60 61 62 63
make_product([RS * RO | Tail], S, O, Expression, Product) :-
  substitute([S, O], [RS, RO], Expression, SubstitutedExpression),
  Product = SubstitutedExpression * TailProduct,
  make_product(Tail, S, O, Expression, TailProduct).