src/Tools/isac/Knowledge/Rational.thy
author Walther Neuper <walther.neuper@jku.at>
Wed, 13 May 2020 16:10:22 +0200
changeset 59973 8a46c2e7c27a
parent 59962 6a59d252345d
child 59997 46fe5a8c3911
permissions -rw-r--r--
shift code from Specify to Problem, Method, Test_Tool
     1 (* rationals, fractions of multivariate polynomials over the real field
     2    author: isac team
     3    Copyright (c) isac team 2002, 2013
     4    Use is subject to license terms.
     5 
     6    depends on Poly (and not on Atools), because 
     7    fractions with _normalised_ polynomials are canceled, added, etc.
     8 *)
     9 
    10 theory Rational 
    11 imports Poly GCD_Poly_ML
    12 begin
    13 
    14 section \<open>Constants for evaluation by "Rule.Eval"\<close>
    15 consts
    16 
    17   is'_expanded    :: "real => bool" ("_ is'_expanded")     (*RL->Poly.thy*)
    18   is'_ratpolyexp  :: "real => bool" ("_ is'_ratpolyexp") 
    19   get_denominator :: "real => real"
    20   get_numerator   :: "real => real"
    21 
    22 ML \<open>
    23 (*.the expression contains + - * ^ / only ?.*)
    24 fun is_ratpolyexp (Free _) = true
    25   | is_ratpolyexp (Const ("Groups.plus_class.plus",_) $ Free _ $ Free _) = true
    26   | is_ratpolyexp (Const ("Groups.minus_class.minus",_) $ Free _ $ Free _) = true
    27   | is_ratpolyexp (Const ("Groups.times_class.times",_) $ Free _ $ Free _) = true
    28   | is_ratpolyexp (Const ("Prog_Expr.pow",_) $ Free _ $ Free _) = true
    29   | is_ratpolyexp (Const ("Rings.divide_class.divide",_) $ Free _ $ Free _) = true
    30   | is_ratpolyexp (Const ("Groups.plus_class.plus",_) $ t1 $ t2) = 
    31                ((is_ratpolyexp t1) andalso (is_ratpolyexp t2))
    32   | is_ratpolyexp (Const ("Groups.minus_class.minus",_) $ t1 $ t2) = 
    33                ((is_ratpolyexp t1) andalso (is_ratpolyexp t2))
    34   | is_ratpolyexp (Const ("Groups.times_class.times",_) $ t1 $ t2) = 
    35                ((is_ratpolyexp t1) andalso (is_ratpolyexp t2))
    36   | is_ratpolyexp (Const ("Prog_Expr.pow",_) $ t1 $ t2) = 
    37                ((is_ratpolyexp t1) andalso (is_ratpolyexp t2))
    38   | is_ratpolyexp (Const ("Rings.divide_class.divide",_) $ t1 $ t2) = 
    39                ((is_ratpolyexp t1) andalso (is_ratpolyexp t2))
    40   | is_ratpolyexp _ = false;
    41 
    42 (*("is_ratpolyexp", ("Rational.is'_ratpolyexp", eval_is_ratpolyexp ""))*)
    43 fun eval_is_ratpolyexp (thmid:string) _ 
    44 		       (t as (Const("Rational.is'_ratpolyexp", _) $ arg)) thy =
    45     if is_ratpolyexp arg
    46     then SOME (TermC.mk_thmid thmid (UnparseC.term_in_thy thy arg) "", 
    47 	         HOLogic.Trueprop $ (TermC.mk_equality (t, @{term True})))
    48     else SOME (TermC.mk_thmid thmid (UnparseC.term_in_thy thy arg) "", 
    49 	         HOLogic.Trueprop $ (TermC.mk_equality (t, @{term False})))
    50   | eval_is_ratpolyexp _ _ _ _ = NONE; 
    51 
    52 (*("get_denominator", ("Rational.get_denominator", eval_get_denominator ""))*)
    53 fun eval_get_denominator (thmid:string) _ 
    54 		      (t as Const ("Rational.get_denominator", _) $
    55               (Const ("Rings.divide_class.divide", _) $ _(*num*) $
    56                 denom)) thy = 
    57       SOME (TermC.mk_thmid thmid (UnparseC.term_in_thy thy denom) "", 
    58 	            HOLogic.Trueprop $ (TermC.mk_equality (t, denom)))
    59   | eval_get_denominator _ _ _ _ = NONE; 
    60 
    61 (*("get_numerator", ("Rational.get_numerator", eval_get_numerator ""))*)
    62 fun eval_get_numerator (thmid:string) _ 
    63       (t as Const ("Rational.get_numerator", _) $
    64           (Const ("Rings.divide_class.divide", _) $num
    65             $denom )) thy = 
    66     SOME (TermC.mk_thmid thmid (UnparseC.term_in_thy thy num) "", 
    67 	    HOLogic.Trueprop $ (TermC.mk_equality (t, num)))
    68   | eval_get_numerator _ _ _ _ = NONE; 
    69 \<close>
    70 
    71 section \<open>Theorems for rewriting\<close>
    72 
    73 axiomatization (* naming due to Isabelle2002, but not contained in Isabelle2002; 
    74                   many thms are due to RL and can be removed with updating the equation solver;
    75                   TODO: replace by equivalent thms in recent Isabelle201x *) 
    76 where
    77   mult_cross:      "[| b ~= 0; d ~= 0 |] ==> (a / b = c / d) = (a * d = b * c)" and
    78   mult_cross1:     "   b ~= 0            ==> (a / b = c    ) = (a     = b * c)" and
    79   mult_cross2:     "           d ~= 0    ==> (a     = c / d) = (a * d =     c)" and
    80                   
    81   add_minus:       "a + b - b = a"(*RL->Poly.thy*) and
    82   add_minus1:      "a - b + b = a"(*RL->Poly.thy*) and
    83                   
    84   rat_mult:        "a / b * (c / d) = a * c / (b * d)"(*?Isa02*)  and
    85   rat_mult2:       "a / b *  c      = a * c /  b     "(*?Isa02*) and
    86 
    87   rat_mult_poly_l: "c is_polyexp ==> c * (a / b) = c * a /  b" and
    88   rat_mult_poly_r: "c is_polyexp ==> (a / b) * c = a * c /  b" and
    89 
    90 (*real_times_divide1_eq .. Isa02*) 
    91   real_times_divide_1_eq:  "-1 * (c / d) = -1 * c / d " and
    92   real_times_divide_num:   "a is_const ==> a * (c / d) = a * c / d " and
    93 
    94   real_mult_div_cancel2:   "k ~= 0 ==> m * k / (n * k) = m / n" and
    95 (*real_mult_div_cancel1:   "k ~= 0 ==> k * m / (k * n) = m / n"..Isa02*)
    96 			  
    97   real_divide_divide1:     "y ~= 0 ==> (u / v) / (y / z) = (u / v) * (z / y)" and
    98   real_divide_divide1_mg:  "y ~= 0 ==> (u / v) / (y / z) = (u * z) / (y * v)" and
    99 (*real_divide_divide2_eq:  "x / y / z = x / (y * z)"..Isa02*)
   100 			  
   101   rat_power:               "(a / b)^^^n = (a^^^n) / (b^^^n)" and
   102 
   103   rat_add:         "[| a is_const; b is_const; c is_const; d is_const |] ==> 
   104 	           a / c + b / d = (a * d + b * c) / (c * d)" and
   105   rat_add_assoc:   "[| a is_const; b is_const; c is_const; d is_const |] ==> 
   106 	           a / c +(b / d + e) = (a * d + b * c)/(d * c) + e" and
   107   rat_add1:        "[| a is_const; b is_const; c is_const |] ==> 
   108 	           a / c + b / c = (a + b) / c" and
   109   rat_add1_assoc:   "[| a is_const; b is_const; c is_const |] ==> 
   110 	           a / c + (b / c + e) = (a + b) / c + e" and
   111   rat_add2:        "[| a is_const; b is_const; c is_const |] ==> 
   112 	           a / c + b = (a + b * c) / c" and
   113   rat_add2_assoc:  "[| a is_const; b is_const; c is_const |] ==> 
   114 	           a / c + (b + e) = (a + b * c) / c + e" and
   115   rat_add3:        "[| a is_const; b is_const; c is_const |] ==> 
   116 	           a + b / c = (a * c + b) / c" and
   117   rat_add3_assoc:   "[| a is_const; b is_const; c is_const |] ==> 
   118 	           a + (b / c + e) = (a * c + b) / c + e"
   119 
   120 section \<open>Cancellation and addition of fractions\<close>
   121 subsection \<open>Conversion term <--> poly\<close>
   122 subsubsection \<open>Convert a term to the internal representation of a multivariate polynomial\<close>
   123 ML \<open>
   124 fun monom_of_term vs (c, es) (t as Const _) =
   125     (c, list_update es (find_index (curry op = t) vs) 1)
   126   | monom_of_term  vs (c, es) (t as Free (id, _)) =
   127     if TermC.is_num' id 
   128     then (id |> TermC.int_opt_of_string |> the |> curry op * c, es) (*several numerals in one monom*)
   129     else (c, list_update es (find_index (curry op = t) vs) 1)
   130   | monom_of_term  vs (c, es) (Const ("Prog_Expr.pow", _) $ (t as Free _) $ Free (e, _)) =
   131     (c, list_update es (find_index (curry op = t) vs) (the (TermC.int_opt_of_string e)))
   132   | monom_of_term vs (c, es) (Const ("Groups.times_class.times", _) $ m1 $ m2) =
   133     let val (c', es') = monom_of_term vs (c, es) m1
   134     in monom_of_term vs (c', es') m2 end
   135   | monom_of_term _ _ t = raise ERROR ("poly malformed 1 with " ^ UnparseC.term t)
   136 
   137 fun monoms_of_term vs (t as Const _) =
   138     [monom_of_term  vs (1, replicate (length vs) 0) t]
   139   | monoms_of_term vs (t as Free _) =
   140     [monom_of_term  vs (1, replicate (length vs) 0) t]
   141   | monoms_of_term vs (t as Const ("Prog_Expr.pow", _) $ _ $  _) =
   142     [monom_of_term  vs (1, replicate (length vs) 0) t]
   143   | monoms_of_term vs (t as Const ("Groups.times_class.times", _) $ _ $  _) =
   144     [monom_of_term  vs (1, replicate (length vs) 0) t]
   145   | monoms_of_term vs (Const ("Groups.plus_class.plus", _) $ ms1 $ ms2) =
   146     (monoms_of_term vs ms1) @ (monoms_of_term vs ms2)
   147   | monoms_of_term _ t = raise ERROR ("poly malformed 2 with " ^ UnparseC.term t)
   148 
   149 (* convert a term to the internal representation of a multivariate polynomial;
   150   the conversion is quite liberal, see test --- fun poly_of_term ---:
   151 * the order of variables and the parentheses within a monomial are arbitrary
   152 * the coefficient may be somewhere
   153 * he order and the parentheses within monomials are arbitrary
   154 But the term must be completely expand + over * (laws of distributivity are not applicable).
   155 
   156 The function requires the free variables as strings already given, 
   157 because the gcd involves 2 polynomials (with the same length for their list of exponents).
   158 *)
   159 fun poly_of_term vs (t as Const ("Groups.plus_class.plus", _) $ _ $ _) =
   160     (SOME (t |> monoms_of_term vs |> order)
   161       handle ERROR _ => NONE)
   162   | poly_of_term vs t =
   163     (SOME [monom_of_term vs (1, replicate (length vs) 0) t]
   164       handle ERROR _ => NONE)
   165 
   166 fun is_poly t =
   167   let
   168     val vs = TermC.vars_of t
   169   in 
   170     case poly_of_term vs t of SOME _ => true | NONE => false
   171   end
   172 val is_expanded = is_poly   (* TODO: check names *)
   173 val is_polynomial = is_poly (* TODO: check names *)
   174 \<close>
   175 
   176 subsubsection \<open>Convert internal representation of a multivariate polynomial to a term\<close>
   177 ML \<open>
   178 fun term_of_es _ _ _ [] = [] (*assumes same length for vs and es*)
   179   | term_of_es baseT expT (_ :: vs) (0 :: es) = [] @ term_of_es baseT expT vs es
   180   | term_of_es baseT expT (v :: vs) (1 :: es) = v :: term_of_es baseT expT vs es
   181   | term_of_es baseT expT (v :: vs) (e :: es) =
   182     Const ("Prog_Expr.pow", [baseT, expT] ---> baseT) $ v $  (Free (TermC.isastr_of_int e, expT))
   183     :: term_of_es baseT expT vs es
   184   | term_of_es _ _ _ _ = raise ERROR "term_of_es: length vs <> length es"
   185 
   186 fun term_of_monom baseT expT vs ((c, es): monom) =
   187     let val es' = term_of_es baseT expT vs es
   188     in 
   189       if c = 1 
   190       then 
   191         if es' = [] (*if es = [0,0,0,...]*)
   192         then Free (TermC.isastr_of_int c, baseT)
   193         else foldl (HOLogic.mk_binop "Groups.times_class.times") (hd es', tl es')
   194       else foldl (HOLogic.mk_binop "Groups.times_class.times") (Free (TermC.isastr_of_int c, baseT), es') 
   195     end
   196 
   197 fun term_of_poly baseT expT vs p =
   198   let val monos = map (term_of_monom baseT expT vs) p
   199   in foldl (HOLogic.mk_binop "Groups.plus_class.plus") (hd monos, tl monos) end
   200 \<close>
   201 
   202 subsection \<open>Apply gcd_poly for cancelling and adding fractions as terms\<close>
   203 ML \<open>
   204 fun mk_noteq_0 baseT t = 
   205   Const ("HOL.Not", HOLogic.boolT --> HOLogic.boolT) $ 
   206     (Const ("HOL.eq", [baseT, baseT] ---> HOLogic.boolT) $ t $ Free ("0", HOLogic.realT))
   207 
   208 fun mk_asms baseT ts =
   209   let val as' = filter_out TermC.is_num ts (* asm like "2 ~= 0" is needless *)
   210   in map (mk_noteq_0 baseT) as' end
   211 \<close>
   212 
   213 subsubsection \<open>Factor out gcd for cancellation\<close>
   214 ML \<open>
   215 fun check_fraction t =
   216   let val Const ("Rings.divide_class.divide", _) $ numerator $ denominator = t
   217   in SOME (numerator, denominator) end
   218   handle Bind => NONE
   219 
   220 (* prepare a term for cancellation by factoring out the gcd
   221   assumes: is a fraction with outmost "/"*)
   222 fun factout_p_ (thy: theory) t =
   223   let val opt = check_fraction t
   224   in
   225     case opt of 
   226       NONE => NONE
   227     | SOME (numerator, denominator) =>
   228       let
   229         val vs = TermC.vars_of t
   230         val baseT = type_of numerator
   231         val expT = HOLogic.realT
   232       in
   233         case (poly_of_term vs numerator, poly_of_term vs denominator) of
   234           (SOME a, SOME b) =>
   235             let
   236               val ((a', b'), c) = gcd_poly a b
   237               val es = replicate (length vs) 0 
   238             in
   239               if c = [(1, es)] orelse c = [(~1, es)]
   240               then NONE
   241               else 
   242                 let
   243                   val b't = term_of_poly baseT expT vs b'
   244                   val ct = term_of_poly baseT expT vs c
   245                   val t' = 
   246                     HOLogic.mk_binop "Rings.divide_class.divide" 
   247                       (HOLogic.mk_binop "Groups.times_class.times"
   248                         (term_of_poly baseT expT vs a', ct),
   249                        HOLogic.mk_binop "Groups.times_class.times" (b't, ct))
   250                 in SOME (t', mk_asms baseT [b't, ct]) end
   251             end
   252         | _ => NONE : (term * term list) option
   253       end
   254   end
   255 \<close>
   256 
   257 subsubsection \<open>Cancel a fraction\<close>
   258 ML \<open>
   259 (* cancel a term by the gcd ("" denote terms with internal algebraic structure)
   260   cancel_p_ :: theory \<Rightarrow> term  \<Rightarrow> (term \<times> term list) option
   261   cancel_p_ thy "a / b" = SOME ("a' / b'", ["b' \<noteq> 0"])
   262   assumes: a is_polynomial  \<and>  b is_polynomial  \<and>  b \<noteq> 0
   263   yields
   264     SOME ("a' / b'", ["b' \<noteq> 0"]). gcd_poly a b \<noteq> 1  \<and>  gcd_poly a b \<noteq> -1  \<and>  
   265       a' * gcd_poly a b = a  \<and>  b' * gcd_poly a b = b
   266     \<or> NONE *)
   267 fun cancel_p_ (_: theory) t =
   268   let val opt = check_fraction t
   269   in
   270     case opt of 
   271       NONE => NONE
   272     | SOME (numerator, denominator) =>
   273       let
   274         val vs = TermC.vars_of t
   275         val baseT = type_of numerator
   276         val expT = HOLogic.realT
   277       in
   278         case (poly_of_term vs numerator, poly_of_term vs denominator) of
   279           (SOME a, SOME b) =>
   280             let
   281               val ((a', b'), c) = gcd_poly a b
   282               val es = replicate (length vs) 0 
   283             in
   284               if c = [(1, es)] orelse c = [(~1, es)]
   285               then NONE
   286               else 
   287                 let
   288                   val bt' = term_of_poly baseT expT vs b'
   289                   val ct = term_of_poly baseT expT vs c
   290                   val t' = 
   291                     HOLogic.mk_binop "Rings.divide_class.divide" 
   292                       (term_of_poly baseT expT vs a', bt')
   293                   val asm = mk_asms baseT [bt']
   294                 in SOME (t', asm) end
   295             end
   296         | _ => NONE : (term * term list) option
   297       end
   298   end
   299 \<close>
   300 
   301 subsubsection \<open>Factor out to a common denominator for addition\<close>
   302 ML \<open>
   303 (* addition of fractions allows (at most) one non-fraction (a monomial) *)
   304 fun check_frac_sum 
   305     (Const ("Groups.plus_class.plus", _) $ 
   306       (Const ("Rings.divide_class.divide", _) $ n1 $ d1) $
   307       (Const ("Rings.divide_class.divide", _) $ n2 $ d2))
   308     = SOME ((n1, d1), (n2, d2))
   309   | check_frac_sum 
   310     (Const ("Groups.plus_class.plus", _) $ 
   311       nofrac $ 
   312       (Const ("Rings.divide_class.divide", _) $ n2 $ d2))
   313     = SOME ((nofrac, Free ("1", HOLogic.realT)), (n2, d2))
   314   | check_frac_sum 
   315     (Const ("Groups.plus_class.plus", _) $ 
   316       (Const ("Rings.divide_class.divide", _) $ n1 $ d1) $ 
   317       nofrac)
   318     = SOME ((n1, d1), (nofrac, Free ("1", HOLogic.realT)))
   319   | check_frac_sum _ = NONE  
   320 
   321 (* prepare a term for addition by providing the least common denominator as a product
   322   assumes: is a term with outmost "+" and at least one outmost "/" in respective summands*)
   323 fun common_nominator_p_ (_: theory) t =
   324   let val opt = check_frac_sum t
   325   in
   326     case opt of 
   327       NONE => NONE
   328     | SOME ((n1, d1), (n2, d2)) =>
   329       let
   330         val vs = TermC.vars_of t
   331       in
   332         case (poly_of_term vs d1, poly_of_term vs d2) of
   333           (SOME a, SOME b) =>
   334             let
   335               val ((a', b'), c) = gcd_poly a b
   336               val (baseT, expT) = (type_of n1, HOLogic.realT)
   337               val [d1', d2', c'] = map (term_of_poly baseT expT vs) [a', b', c]
   338               (*----- minimum of parentheses & nice result, but breaks tests: -------------
   339               val denom = HOLogic.mk_binop "Groups.times_class.times" 
   340                 (HOLogic.mk_binop "Groups.times_class.times" (d1', d2'), c') -------------*)
   341               val denom =
   342                 if c = [(1, replicate (length vs) 0)]
   343                 then HOLogic.mk_binop "Groups.times_class.times" (d1', d2')
   344                 else
   345                   HOLogic.mk_binop "Groups.times_class.times" (c',
   346                   HOLogic.mk_binop "Groups.times_class.times" (d1', d2')) (*--------------*)
   347               val t' =
   348                 HOLogic.mk_binop "Groups.plus_class.plus"
   349                   (HOLogic.mk_binop "Rings.divide_class.divide"
   350                     (HOLogic.mk_binop "Groups.times_class.times" (n1, d2'), denom),
   351                   HOLogic.mk_binop "Rings.divide_class.divide" 
   352                     (HOLogic.mk_binop "Groups.times_class.times" (n2, d1'), denom))
   353               val asm = mk_asms baseT [d1', d2', c']
   354             in SOME (t', asm) end
   355         | _ => NONE : (term * term list) option
   356       end
   357   end
   358 \<close>
   359 
   360 subsubsection \<open>Addition of at least one fraction within a sum\<close>
   361 ML \<open>
   362 (* add fractions
   363   assumes: is a term with outmost "+" and at least one outmost "/" in respective summands
   364   NOTE: the case "(_ + _) + _" need not be considered due to iterated addition.*)
   365 fun add_fraction_p_ (_: theory) t =
   366   case check_frac_sum t of 
   367     NONE => NONE
   368   | SOME ((n1, d1), (n2, d2)) =>
   369     let
   370       val vs = TermC.vars_of t
   371     in
   372       case (poly_of_term vs n1, poly_of_term vs d1, poly_of_term vs n2, poly_of_term vs d2) of
   373         (SOME _, SOME a, SOME _, SOME b) =>
   374           let
   375             val ((a', b'), c) = gcd_poly a b
   376             val (baseT, expT) = (type_of n1, HOLogic.realT)
   377             val nomin = term_of_poly baseT expT vs 
   378               (((the (poly_of_term vs n1)) %%*%% b') %%+%% ((the (poly_of_term vs n2)) %%*%% a')) 
   379             val denom = term_of_poly baseT expT vs ((c %%*%% a') %%*%% b')
   380             val t' = HOLogic.mk_binop "Rings.divide_class.divide" (nomin, denom)
   381           in SOME (t', mk_asms baseT [denom]) end
   382       | _ => NONE : (term * term list) option
   383     end
   384 \<close>
   385 
   386 section \<open>Embed cancellation and addition into rewriting\<close>
   387 ML \<open>val thy = @{theory}\<close>
   388 subsection \<open>Rulesets and predicate for embedding\<close>
   389 ML \<open>
   390 (* evaluates conditions in calculate_Rational *)
   391 val calc_rat_erls =
   392   prep_rls'
   393     (Rule_Def.Repeat {id = "calc_rat_erls", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   394       erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   395       rules = 
   396         [Rule.Eval ("HOL.eq", Prog_Expr.eval_equal "#equal_"),
   397         Rule.Eval ("Prog_Expr.is'_const", Prog_Expr.eval_const "#is_const_"),
   398         Rule.Thm ("not_true", ThmC.numerals_to_Free @{thm not_true}),
   399         Rule.Thm ("not_false", ThmC.numerals_to_Free @{thm not_false})], 
   400       scr = Rule.Empty_Prog});
   401 
   402 (* simplifies expressions with numerals;
   403    does NOT rearrange the term by AC-rewriting; thus terms with variables 
   404    need to have constants to be commuted together respectively           *)
   405 val calculate_Rational =
   406   prep_rls' (Rule_Set.merge "calculate_Rational"
   407     (Rule_Def.Repeat {id = "divide", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   408       erls = calc_rat_erls, srls = Rule_Set.Empty,
   409       calc = [], errpatts = [],
   410       rules = 
   411         [Rule.Eval ("Rings.divide_class.divide", Prog_Expr.eval_cancel "#divide_e"),
   412 
   413         Rule.Thm ("minus_divide_left", ThmC.numerals_to_Free (@{thm minus_divide_left} RS @{thm sym})),
   414           (*SYM - ?x / ?y = - (?x / ?y)  may come from subst*)
   415         Rule.Thm ("rat_add", ThmC.numerals_to_Free @{thm rat_add}),
   416           (*"[| a is_const; b is_const; c is_const; d is_const |] ==> \
   417           \a / c + b / d = (a * d) / (c * d) + (b * c ) / (d * c)"*)
   418         Rule.Thm ("rat_add1", ThmC.numerals_to_Free @{thm rat_add1}),
   419           (*"[| a is_const; b is_const; c is_const |] ==> a / c + b / c = (a + b) / c"*)
   420         Rule.Thm ("rat_add2", ThmC.numerals_to_Free @{thm rat_add2}),
   421           (*"[| ?a is_const; ?b is_const; ?c is_const |] ==> ?a / ?c + ?b = (?a + ?b * ?c) / ?c"*)
   422         Rule.Thm ("rat_add3", ThmC.numerals_to_Free @{thm rat_add3}),
   423           (*"[| a is_const; b is_const; c is_const |] ==> a + b / c = (a * c) / c + b / c"\
   424           .... is_const to be omitted here FIXME*)
   425         
   426         Rule.Thm ("rat_mult", ThmC.numerals_to_Free @{thm rat_mult}), 
   427           (*a / b * (c / d) = a * c / (b * d)*)
   428         Rule.Thm ("times_divide_eq_right", ThmC.numerals_to_Free @{thm times_divide_eq_right}),
   429           (*?x * (?y / ?z) = ?x * ?y / ?z*)
   430         Rule.Thm ("times_divide_eq_left", ThmC.numerals_to_Free @{thm times_divide_eq_left}),
   431           (*?y / ?z * ?x = ?y * ?x / ?z*)
   432         
   433         Rule.Thm ("real_divide_divide1", ThmC.numerals_to_Free @{thm real_divide_divide1}),
   434           (*"?y ~= 0 ==> ?u / ?v / (?y / ?z) = ?u / ?v * (?z / ?y)"*)
   435         Rule.Thm ("divide_divide_eq_left", ThmC.numerals_to_Free @{thm divide_divide_eq_left}),
   436           (*"?x / ?y / ?z = ?x / (?y * ?z)"*)
   437         
   438         Rule.Thm ("rat_power", ThmC.numerals_to_Free @{thm rat_power}),
   439           (*"(?a / ?b) ^^^ ?n = ?a ^^^ ?n / ?b ^^^ ?n"*)
   440         
   441         Rule.Thm ("mult_cross", ThmC.numerals_to_Free @{thm mult_cross}),
   442           (*"[| b ~= 0; d ~= 0 |] ==> (a / b = c / d) = (a * d = b * c)*)
   443         Rule.Thm ("mult_cross1", ThmC.numerals_to_Free @{thm mult_cross1}),
   444           (*"   b ~= 0            ==> (a / b = c    ) = (a     = b * c)*)
   445         Rule.Thm ("mult_cross2", ThmC.numerals_to_Free @{thm mult_cross2})
   446           (*"           d ~= 0    ==> (a     = c / d) = (a * d =     c)*)], 
   447       scr = Rule.Empty_Prog})
   448     calculate_Poly);
   449 
   450 (*("is_expanded", ("Rational.is'_expanded", eval_is_expanded ""))*)
   451 fun eval_is_expanded (thmid:string) _ 
   452 		       (t as (Const("Rational.is'_expanded", _) $ arg)) thy = 
   453     if is_expanded arg
   454     then SOME (TermC.mk_thmid thmid (UnparseC.term_in_thy thy arg) "", 
   455 	         HOLogic.Trueprop $ (TermC.mk_equality (t, @{term True})))
   456     else SOME (TermC.mk_thmid thmid (UnparseC.term_in_thy thy arg) "", 
   457 	         HOLogic.Trueprop $ (TermC.mk_equality (t, @{term False})))
   458   | eval_is_expanded _ _ _ _ = NONE;
   459 \<close>
   460 setup \<open>KEStore_Elems.add_calcs
   461   [("is_expanded", ("Rational.is'_expanded", eval_is_expanded ""))]\<close>
   462 ML \<open>
   463 val rational_erls = 
   464   Rule_Set.merge "rational_erls" calculate_Rational 
   465     (Rule_Set.append_rules "is_expanded" Atools_erls 
   466       [Rule.Eval ("Rational.is'_expanded", eval_is_expanded "")]);
   467 \<close>
   468 
   469 subsection \<open>Embed cancellation into rewriting\<close>
   470 ML \<open>
   471 (**)local (* cancel_p *)
   472 
   473 val {rules = rules, rew_ord = (_, ro), ...} = Rule_Set.rep (assoc_rls' @{theory} "rev_rew_p");
   474 
   475 fun init_state thy eval_rls ro t =
   476   let
   477     val SOME (t', _) = factout_p_ thy t;
   478     val SOME (t'', asm) = cancel_p_ thy t;
   479     val der = Derive.steps_reverse thy eval_rls rules ro NONE t';
   480     val der = der @ 
   481       [(Rule.Thm ("real_mult_div_cancel2", ThmC.numerals_to_Free @{thm real_mult_div_cancel2}), (t'', asm))]
   482     val rs = (Rule.distinct o (map #1)) der
   483   	val rs = filter_out (ThmC.member 
   484   	  ["sym_real_add_zero_left", "sym_real_mult_0", "sym_real_mult_1"]) rs
   485   in (t, t'', [rs(*one in order to ease locate_rule*)], der) end;
   486 
   487 fun locate_rule thy eval_rls ro [rs] t r =
   488     if member op = ((map (Rule.thm_id)) rs) (Rule.thm_id r)
   489     then 
   490       let val ropt = Rewrite.rewrite_ thy ro eval_rls true (Rule.thm r) t;
   491       in
   492         case ropt of SOME ta => [(r, ta)]
   493 	      | NONE => ((*tracing 
   494 	          ("### locate_rule:  rewrite " ^ Rule.thm_id r ^ " " ^ UnparseC.term t ^ " = NONE");*) []) 
   495 			end
   496     else ((*tracing ("### locate_rule:  " ^ Rule.thm_id r ^ " not mem rrls");*) [])
   497   | locate_rule _ _ _ _ _ _ = raise ERROR "locate_rule: doesnt match rev-sets in istate";
   498 
   499 fun next_rule thy eval_rls ro [rs] t =
   500     let
   501       val der = Derive.do_one thy eval_rls rs ro NONE t;
   502     in case der of (_, r, _) :: _ => SOME r | _ => NONE end
   503   | next_rule _ _ _ _ _ = raise ERROR ("next_rule: doesnt match rev-sets in istate");
   504 
   505 fun attach_form (_: Rule.rule list list) (_: term) (_: term) = 
   506   [(*TODO*)]: ( Rule.rule * (term * term list)) list;
   507 
   508 (**)in(**)
   509 
   510 val cancel_p = 
   511   Rule_Set.Rrls {id = "cancel_p", prepat = [],
   512 	rew_ord=("ord_make_polynomial", ord_make_polynomial false thy),
   513 	erls = rational_erls, 
   514 	calc = 
   515 	  [("PLUS", ("Groups.plus_class.plus", (**)eval_binop "#add_")),
   516 	  ("TIMES" , ("Groups.times_class.times", (**)eval_binop "#mult_")),
   517 	  ("DIVIDE", ("Rings.divide_class.divide", Prog_Expr.eval_cancel "#divide_e")),
   518 	  ("POWER", ("Prog_Expr.pow", (**)eval_binop "#power_"))],
   519     errpatts = [],
   520 	scr =
   521 	  Rule.Rfuns {init_state  = init_state thy Atools_erls ro,
   522 		normal_form = cancel_p_ thy, 
   523 		locate_rule = locate_rule thy Atools_erls ro,
   524 		next_rule   = next_rule thy Atools_erls ro,
   525 		attach_form = attach_form}}
   526 (**)end(* local cancel_p *)
   527 \<close>
   528 
   529 subsection \<open>Embed addition into rewriting\<close>
   530 ML \<open>
   531 (**)local (* add_fractions_p *)
   532 
   533 (*val {rules = rules, rew_ord = (_, ro), ...} = Rule_Set.rep (assoc_rls "make_polynomial");*)
   534 val {rules, rew_ord=(_,ro),...} = Rule_Set.rep (assoc_rls' @{theory} "rev_rew_p");
   535 
   536 fun init_state thy eval_rls ro t =
   537   let 
   538     val SOME (t',_) = common_nominator_p_ thy t;
   539     val SOME (t'', asm) = add_fraction_p_ thy t;
   540     val der = Derive.steps_reverse thy eval_rls rules ro NONE t';
   541     val der = der @ 
   542       [(Rule.Thm ("real_mult_div_cancel2", ThmC.numerals_to_Free @{thm real_mult_div_cancel2}), (t'',asm))]
   543     val rs = (Rule.distinct o (map #1)) der;
   544     val rs = filter_out (ThmC.member 
   545       ["sym_real_add_zero_left", "sym_real_mult_0", "sym_real_mult_1"]) rs;
   546   in (t, t'', [rs(*here only _ONE_*)], der) end;
   547 
   548 fun locate_rule thy eval_rls ro [rs] t r =
   549     if member op = ((map (Rule.thm_id)) rs) (Rule.thm_id r)
   550     then 
   551       let val ropt = Rewrite.rewrite_ thy ro eval_rls true (Rule.thm r) t;
   552       in 
   553         case ropt of
   554           SOME ta => [(r, ta)]
   555 	      | NONE => 
   556 	        ((*tracing ("### locate_rule:  rewrite " ^ Rule.thm_id r ^ " " ^ UnparseC.term t ^ " = NONE");*)
   557 	        []) end
   558     else ((*tracing ("### locate_rule:  " ^ Rule.thm_id r ^ " not mem rrls");*) [])
   559   | locate_rule _ _ _ _ _ _ = raise ERROR "locate_rule: doesnt match rev-sets in istate";
   560 
   561 fun next_rule thy eval_rls ro [rs] t =
   562     let val der = Derive.do_one thy eval_rls rs ro NONE t;
   563     in 
   564       case der of
   565 	      (_,r,_)::_ => SOME r
   566 	    | _ => NONE
   567     end
   568   | next_rule _ _ _ _ _ = raise ERROR ("next_rule: doesnt match rev-sets in istate");
   569 
   570 val pat0 = TermC.parse_patt thy "?r/?s+?u/?v :: real";
   571 val pat1 = TermC.parse_patt thy "?r/?s+?u    :: real";
   572 val pat2 = TermC.parse_patt thy "?r   +?u/?v :: real";
   573 val prepat = [([@{term True}], pat0),
   574 	      ([@{term True}], pat1),
   575 	      ([@{term True}], pat2)];
   576 (**)in(**)
   577 
   578 val add_fractions_p =
   579   Rule_Set.Rrls {id = "add_fractions_p", prepat=prepat,
   580     rew_ord = ("ord_make_polynomial", ord_make_polynomial false thy),
   581     erls = rational_erls,
   582     calc = [("PLUS", ("Groups.plus_class.plus", (**)eval_binop "#add_")),
   583       ("TIMES", ("Groups.times_class.times", (**)eval_binop "#mult_")),
   584       ("DIVIDE", ("Rings.divide_class.divide", Prog_Expr.eval_cancel "#divide_e")),
   585       ("POWER", ("Prog_Expr.pow", (**)eval_binop "#power_"))],
   586     errpatts = [],
   587     scr = Rule.Rfuns {init_state  = init_state thy Atools_erls ro,
   588       normal_form = add_fraction_p_ thy,
   589       locate_rule = locate_rule thy Atools_erls ro,
   590       next_rule   = next_rule thy Atools_erls ro,
   591       attach_form = attach_form}}
   592 (**)end(*local add_fractions_p *)
   593 \<close>
   594 
   595 subsection \<open>Cancelling and adding all occurrences in a term /////////////////////////////\<close>
   596 ML \<open>
   597 (*copying cancel_p_rls + add her caused error in interface.sml*)
   598 \<close>
   599 
   600 section \<open>Rulesets for general simplification\<close>
   601 ML \<open>
   602 (*erls for calculate_Rational; make local with FIXX@ME result:term *term list*)
   603 val powers_erls = prep_rls'(
   604   Rule_Def.Repeat {id = "powers_erls", preconds = [], rew_ord = ("dummy_ord",Rewrite_Ord.dummy_ord), 
   605       erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   606       rules = [Rule.Eval ("Prog_Expr.is'_atom", Prog_Expr.eval_is_atom "#is_atom_"),
   607 	       Rule.Eval ("Prog_Expr.is'_even", Prog_Expr.eval_is_even "#is_even_"),
   608 	       Rule.Eval ("Orderings.ord_class.less", Prog_Expr.eval_equ "#less_"),
   609 	       Rule.Thm ("not_false", ThmC.numerals_to_Free @{thm not_false}),
   610 	       Rule.Thm ("not_true", ThmC.numerals_to_Free @{thm not_true}),
   611 	       Rule.Eval ("Groups.plus_class.plus", (**)eval_binop "#add_")
   612 	       ],
   613       scr = Rule.Empty_Prog
   614       });
   615 (*.all powers over + distributed; atoms over * collected, other distributed
   616    contains absolute minimum of thms for context in norm_Rational .*)
   617 val powers = prep_rls'(
   618   Rule_Def.Repeat {id = "powers", preconds = [], rew_ord = ("dummy_ord",Rewrite_Ord.dummy_ord), 
   619       erls = powers_erls, srls = Rule_Set.Empty, calc = [], errpatts = [],
   620       rules = [Rule.Thm ("realpow_multI", ThmC.numerals_to_Free @{thm realpow_multI}),
   621 	       (*"(r * s) ^^^ n = r ^^^ n * s ^^^ n"*)
   622 	       Rule.Thm ("realpow_pow",ThmC.numerals_to_Free @{thm realpow_pow}),
   623 	       (*"(a ^^^ b) ^^^ c = a ^^^ (b * c)"*)
   624 	       Rule.Thm ("realpow_oneI",ThmC.numerals_to_Free @{thm realpow_oneI}),
   625 	       (*"r ^^^ 1 = r"*)
   626 	       Rule.Thm ("realpow_minus_even",ThmC.numerals_to_Free @{thm realpow_minus_even}),
   627 	       (*"n is_even ==> (- r) ^^^ n = r ^^^ n" ?-->discard_minus?*)
   628 	       Rule.Thm ("realpow_minus_odd",ThmC.numerals_to_Free @{thm realpow_minus_odd}),
   629 	       (*"Not (n is_even) ==> (- r) ^^^ n = -1 * r ^^^ n"*)
   630 	       
   631 	       (*----- collect atoms over * -----*)
   632 	       Rule.Thm ("realpow_two_atom",ThmC.numerals_to_Free @{thm realpow_two_atom}),	
   633 	       (*"r is_atom ==> r * r = r ^^^ 2"*)
   634 	       Rule.Thm ("realpow_plus_1",ThmC.numerals_to_Free @{thm realpow_plus_1}),		
   635 	       (*"r is_atom ==> r * r ^^^ n = r ^^^ (n + 1)"*)
   636 	       Rule.Thm ("realpow_addI_atom",ThmC.numerals_to_Free @{thm realpow_addI_atom}),
   637 	       (*"r is_atom ==> r ^^^ n * r ^^^ m = r ^^^ (n + m)"*)
   638 
   639 	       (*----- distribute none-atoms -----*)
   640 	       Rule.Thm ("realpow_def_atom",ThmC.numerals_to_Free @{thm realpow_def_atom}),
   641 	       (*"[| 1 < n; not(r is_atom) |]==>r ^^^ n = r * r ^^^ (n + -1)"*)
   642 	       Rule.Thm ("realpow_eq_oneI",ThmC.numerals_to_Free @{thm realpow_eq_oneI}),
   643 	       (*"1 ^^^ n = 1"*)
   644 	       Rule.Eval ("Groups.plus_class.plus", (**)eval_binop "#add_")
   645 	       ],
   646       scr = Rule.Empty_Prog
   647       });
   648 (*.contains absolute minimum of thms for context in norm_Rational.*)
   649 val rat_mult_divide = prep_rls'(
   650   Rule_Def.Repeat {id = "rat_mult_divide", preconds = [], 
   651       rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   652       erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   653       rules = [Rule.Thm ("rat_mult",ThmC.numerals_to_Free @{thm rat_mult}),
   654 	       (*(1)"?a / ?b * (?c / ?d) = ?a * ?c / (?b * ?d)"*)
   655 	       Rule.Thm ("times_divide_eq_right",ThmC.numerals_to_Free @{thm times_divide_eq_right}),
   656 	       (*(2)"?a * (?c / ?d) = ?a * ?c / ?d" must be [2],
   657 	       otherwise inv.to a / b / c = ...*)
   658 	       Rule.Thm ("times_divide_eq_left",ThmC.numerals_to_Free @{thm times_divide_eq_left}),
   659 	       (*"?a / ?b * ?c = ?a * ?c / ?b" order weights x^^^n too much
   660 		     and does not commute a / b * c ^^^ 2 !*)
   661 	       
   662 	       Rule.Thm ("divide_divide_eq_right", 
   663                      ThmC.numerals_to_Free @{thm divide_divide_eq_right}),
   664 	       (*"?x / (?y / ?z) = ?x * ?z / ?y"*)
   665 	       Rule.Thm ("divide_divide_eq_left",
   666                      ThmC.numerals_to_Free @{thm divide_divide_eq_left}),
   667 	       (*"?x / ?y / ?z = ?x / (?y * ?z)"*)
   668 	       Rule.Eval ("Rings.divide_class.divide", Prog_Expr.eval_cancel "#divide_e")
   669 	       ],
   670       scr = Rule.Empty_Prog
   671       });
   672 
   673 (*.contains absolute minimum of thms for context in norm_Rational.*)
   674 val reduce_0_1_2 = prep_rls'(
   675   Rule_Def.Repeat{id = "reduce_0_1_2", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord),
   676       erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   677       rules = [(*Rule.Thm ("divide_1",ThmC.numerals_to_Free @{thm divide_1}),
   678 		 "?x / 1 = ?x" unnecess.for normalform*)
   679 	       Rule.Thm ("mult_1_left",ThmC.numerals_to_Free @{thm mult_1_left}),                 
   680 	       (*"1 * z = z"*)
   681 	       (*Rule.Thm ("real_mult_minus1",ThmC.numerals_to_Free @{thm real_mult_minus1}),
   682 	       "-1 * z = - z"*)
   683 	       (*Rule.Thm ("real_minus_mult_cancel",ThmC.numerals_to_Free @{thm real_minus_mult_cancel}),
   684 	       "- ?x * - ?y = ?x * ?y"*)
   685 
   686 	       Rule.Thm ("mult_zero_left",ThmC.numerals_to_Free @{thm mult_zero_left}),        
   687 	       (*"0 * z = 0"*)
   688 	       Rule.Thm ("add_0_left",ThmC.numerals_to_Free @{thm add_0_left}),
   689 	       (*"0 + z = z"*)
   690 	       (*Rule.Thm ("right_minus",ThmC.numerals_to_Free @{thm right_minus}),
   691 	       "?z + - ?z = 0"*)
   692 
   693 	       Rule.Thm ("sym_real_mult_2",
   694                      ThmC.numerals_to_Free (@{thm real_mult_2} RS @{thm sym})),	
   695 	       (*"z1 + z1 = 2 * z1"*)
   696 	       Rule.Thm ("real_mult_2_assoc",ThmC.numerals_to_Free @{thm real_mult_2_assoc}),
   697 	       (*"z1 + (z1 + k) = 2 * z1 + k"*)
   698 
   699 	       Rule.Thm ("division_ring_divide_zero",ThmC.numerals_to_Free @{thm division_ring_divide_zero})
   700 	       (*"0 / ?x = 0"*)
   701 	       ], scr = Rule.Empty_Prog});
   702 
   703 (*erls for calculate_Rational; 
   704   make local with FIXX@ME result:term *term list WN0609???SKMG*)
   705 val norm_rat_erls = prep_rls'(
   706   Rule_Def.Repeat {id = "norm_rat_erls", preconds = [], rew_ord = ("dummy_ord",Rewrite_Ord.dummy_ord), 
   707       erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   708       rules = [Rule.Eval ("Prog_Expr.is'_const", Prog_Expr.eval_const "#is_const_")
   709 	       ], scr = Rule.Empty_Prog});
   710 
   711 (* consists of rls containing the absolute minimum of thms *)
   712 (*040209: this version has been used by RL for his equations,
   713 which is now replaced by MGs version "norm_Rational" below *)
   714 val norm_Rational_min = prep_rls'(
   715   Rule_Def.Repeat {id = "norm_Rational_min", preconds = [], rew_ord = ("dummy_ord",Rewrite_Ord.dummy_ord), 
   716       erls = norm_rat_erls, srls = Rule_Set.Empty, calc = [], errpatts = [],
   717       rules = [(*sequence given by operator precedence*)
   718 	       Rule.Rls_ discard_minus,
   719 	       Rule.Rls_ powers,
   720 	       Rule.Rls_ rat_mult_divide,
   721 	       Rule.Rls_ expand,
   722 	       Rule.Rls_ reduce_0_1_2,
   723 	       Rule.Rls_ order_add_mult,
   724 	       Rule.Rls_ collect_numerals,
   725 	       Rule.Rls_ add_fractions_p,
   726 	       Rule.Rls_ cancel_p
   727 	       ],
   728       scr = Rule.Empty_Prog});
   729 
   730 val norm_Rational_parenthesized = prep_rls'(
   731   Rule_Set.Sequence {id = "norm_Rational_parenthesized", preconds = []:term list, 
   732        rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord),
   733       erls = Atools_erls, srls = Rule_Set.Empty,
   734       calc = [], errpatts = [],
   735       rules = [Rule.Rls_  norm_Rational_min,
   736 	       Rule.Rls_ discard_parentheses
   737 	       ],
   738       scr = Rule.Empty_Prog});      
   739 
   740 (*WN030318???SK: simplifies all but cancel and common_nominator*)
   741 val simplify_rational = 
   742     Rule_Set.merge "simplify_rational" expand_binoms
   743     (Rule_Set.append_rules "divide" calculate_Rational
   744 		[Rule.Thm ("div_by_1",ThmC.numerals_to_Free @{thm div_by_1}),
   745 		 (*"?x / 1 = ?x"*)
   746 		 Rule.Thm ("rat_mult",ThmC.numerals_to_Free @{thm rat_mult}),
   747 		 (*(1)"?a / ?b * (?c / ?d) = ?a * ?c / (?b * ?d)"*)
   748 		 Rule.Thm ("times_divide_eq_right",ThmC.numerals_to_Free @{thm times_divide_eq_right}),
   749 		 (*(2)"?a * (?c / ?d) = ?a * ?c / ?d" must be [2],
   750 		 otherwise inv.to a / b / c = ...*)
   751 		 Rule.Thm ("times_divide_eq_left",ThmC.numerals_to_Free @{thm times_divide_eq_left}),
   752 		 (*"?a / ?b * ?c = ?a * ?c / ?b"*)
   753 		 Rule.Thm ("add_minus",ThmC.numerals_to_Free @{thm add_minus}),
   754 		 (*"?a + ?b - ?b = ?a"*)
   755 		 Rule.Thm ("add_minus1",ThmC.numerals_to_Free @{thm add_minus1}),
   756 		 (*"?a - ?b + ?b = ?a"*)
   757 		 Rule.Thm ("divide_minus1",ThmC.numerals_to_Free @{thm divide_minus1})
   758 		 (*"?x / -1 = - ?x"*)
   759 		 ]);
   760 \<close>
   761 ML \<open>
   762 val add_fractions_p_rls = prep_rls'(
   763   Rule_Def.Repeat {id = "add_fractions_p_rls", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   764 	  erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   765 	  rules = [Rule.Rls_ add_fractions_p], 
   766 	  scr = Rule.Empty_Prog});
   767 
   768 (* "Rule_Def.Repeat" causes repeated application of cancel_p to one and the same term *)
   769 val cancel_p_rls = prep_rls'(
   770   Rule_Def.Repeat 
   771     {id = "cancel_p_rls", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   772     erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   773     rules = [Rule.Rls_ cancel_p], 
   774 	  scr = Rule.Empty_Prog});
   775 
   776 (*. makes 'normal' fractions; 'is_polyexp' inhibits double fractions;
   777     used in initial part norm_Rational_mg, see example DA-M02-main.p.60.*)
   778 val rat_mult_poly = prep_rls'(
   779   Rule_Def.Repeat {id = "rat_mult_poly", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   780 	  erls = Rule_Set.append_rules "Rule_Set.empty-is_polyexp" Rule_Set.empty [Rule.Eval ("Poly.is'_polyexp", eval_is_polyexp "")], 
   781 	  srls = Rule_Set.Empty, calc = [], errpatts = [],
   782 	  rules = 
   783 	    [Rule.Thm ("rat_mult_poly_l",ThmC.numerals_to_Free @{thm rat_mult_poly_l}),
   784 	    (*"?c is_polyexp ==> ?c * (?a / ?b) = ?c * ?a / ?b"*)
   785 	    Rule.Thm ("rat_mult_poly_r",ThmC.numerals_to_Free @{thm rat_mult_poly_r})
   786 	    (*"?c is_polyexp ==> ?a / ?b * ?c = ?a * ?c / ?b"*) ], 
   787 	  scr = Rule.Empty_Prog});
   788 
   789 (*. makes 'normal' fractions; 'is_polyexp' inhibits double fractions;
   790     used in looping part norm_Rational_rls, see example DA-M02-main.p.60 
   791     .. WHERE THE LATTER DOES ALWAYS WORK, BECAUSE erls = Rule_Set.empty, 
   792     I.E. THE RESPECTIVE ASSUMPTION IS STORED AND Rule.Thm APPLIED; WN051028 
   793     ... WN0609???MG.*)
   794 val rat_mult_div_pow = prep_rls'(
   795   Rule_Def.Repeat {id = "rat_mult_div_pow", preconds = [], rew_ord = ("dummy_ord",Rewrite_Ord.dummy_ord), 
   796     erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [],
   797     rules = [Rule.Thm ("rat_mult", ThmC.numerals_to_Free @{thm rat_mult}),
   798       (*"?a / ?b * (?c / ?d) = ?a * ?c / (?b * ?d)"*)
   799       Rule.Thm ("rat_mult_poly_l", ThmC.numerals_to_Free @{thm rat_mult_poly_l}),
   800       (*"?c is_polyexp ==> ?c * (?a / ?b) = ?c * ?a / ?b"*)
   801       Rule.Thm ("rat_mult_poly_r", ThmC.numerals_to_Free @{thm rat_mult_poly_r}),
   802       (*"?c is_polyexp ==> ?a / ?b * ?c = ?a * ?c / ?b"*)
   803       
   804       Rule.Thm ("real_divide_divide1_mg", ThmC.numerals_to_Free @{thm real_divide_divide1_mg}),
   805       (*"y ~= 0 ==> (u / v) / (y / z) = (u * z) / (y * v)"*)
   806       Rule.Thm ("divide_divide_eq_right", ThmC.numerals_to_Free @{thm divide_divide_eq_right}),
   807       (*"?x / (?y / ?z) = ?x * ?z / ?y"*)
   808       Rule.Thm ("divide_divide_eq_left", ThmC.numerals_to_Free @{thm divide_divide_eq_left}),
   809       (*"?x / ?y / ?z = ?x / (?y * ?z)"*)
   810       Rule.Eval ("Rings.divide_class.divide", Prog_Expr.eval_cancel "#divide_e"),
   811       
   812       Rule.Thm ("rat_power", ThmC.numerals_to_Free @{thm rat_power})
   813       (*"(?a / ?b) ^^^ ?n = ?a ^^^ ?n / ?b ^^^ ?n"*)
   814       ],
   815     scr = Rule.Empty_Prog});
   816 
   817 val rat_reduce_1 = prep_rls'(
   818   Rule_Def.Repeat {id = "rat_reduce_1", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   819     erls = Rule_Set.empty, srls = Rule_Set.Empty, calc = [], errpatts = [], 
   820     rules = 
   821       [Rule.Thm ("div_by_1", ThmC.numerals_to_Free @{thm div_by_1}),
   822       (*"?x / 1 = ?x"*)
   823       Rule.Thm ("mult_1_left", ThmC.numerals_to_Free @{thm mult_1_left})           
   824       (*"1 * z = z"*)
   825       ],
   826     scr = Rule.Empty_Prog});
   827 
   828 (* looping part of norm_Rational *)
   829 val norm_Rational_rls = prep_rls' (
   830   Rule_Def.Repeat {id = "norm_Rational_rls", preconds = [], rew_ord = ("dummy_ord",Rewrite_Ord.dummy_ord), 
   831     erls = norm_rat_erls, srls = Rule_Set.Empty, calc = [], errpatts = [],
   832     rules = [Rule.Rls_ add_fractions_p_rls,
   833       Rule.Rls_ rat_mult_div_pow,
   834       Rule.Rls_ make_rat_poly_with_parentheses,
   835       Rule.Rls_ cancel_p_rls,
   836       Rule.Rls_ rat_reduce_1
   837       ],
   838     scr = Rule.Empty_Prog});
   839 
   840 val norm_Rational = prep_rls' (
   841   Rule_Set.Sequence 
   842     {id = "norm_Rational", preconds = [], rew_ord = ("dummy_ord", Rewrite_Ord.dummy_ord), 
   843     erls = norm_rat_erls, srls = Rule_Set.Empty, calc = [], errpatts = [],
   844     rules = [Rule.Rls_ discard_minus,
   845       Rule.Rls_ rat_mult_poly,             (* removes double fractions like a/b/c *)
   846       Rule.Rls_ make_rat_poly_with_parentheses,
   847       Rule.Rls_ cancel_p_rls,
   848       Rule.Rls_ norm_Rational_rls,         (* the main rls, looping (#) *)
   849       Rule.Rls_ discard_parentheses1       (* mult only *)
   850       ],
   851     scr = Rule.Empty_Prog});
   852 \<close>
   853 
   854 setup \<open>KEStore_Elems.add_rlss 
   855   [("calculate_Rational", (Context.theory_name @{theory}, calculate_Rational)), 
   856   ("calc_rat_erls", (Context.theory_name @{theory}, calc_rat_erls)), 
   857   ("rational_erls", (Context.theory_name @{theory}, rational_erls)), 
   858   ("cancel_p", (Context.theory_name @{theory}, cancel_p)), 
   859   ("add_fractions_p", (Context.theory_name @{theory}, add_fractions_p)),
   860  
   861   ("add_fractions_p_rls", (Context.theory_name @{theory}, add_fractions_p_rls)), 
   862   ("powers_erls", (Context.theory_name @{theory}, powers_erls)), 
   863   ("powers", (Context.theory_name @{theory}, powers)), 
   864   ("rat_mult_divide", (Context.theory_name @{theory}, rat_mult_divide)), 
   865   ("reduce_0_1_2", (Context.theory_name @{theory}, reduce_0_1_2)),
   866  
   867   ("rat_reduce_1", (Context.theory_name @{theory}, rat_reduce_1)), 
   868   ("norm_rat_erls", (Context.theory_name @{theory}, norm_rat_erls)), 
   869   ("norm_Rational", (Context.theory_name @{theory}, norm_Rational)), 
   870   ("norm_Rational_rls", (Context.theory_name @{theory}, norm_Rational_rls)), 
   871   ("norm_Rational_min", (Context.theory_name @{theory}, norm_Rational_min)),
   872   ("norm_Rational_parenthesized", (Context.theory_name @{theory}, norm_Rational_parenthesized)),
   873  
   874   ("rat_mult_poly", (Context.theory_name @{theory}, rat_mult_poly)), 
   875   ("rat_mult_div_pow", (Context.theory_name @{theory}, rat_mult_div_pow)), 
   876   ("cancel_p_rls", (Context.theory_name @{theory}, cancel_p_rls))]\<close>
   877 
   878 section \<open>A problem for simplification of rationals\<close>
   879 setup \<open>KEStore_Elems.add_pbts
   880   [(Problem.prep_input thy "pbl_simp_rat" [] Problem.id_empty
   881       (["rational","simplification"],
   882         [("#Given" ,["Term t_t"]),
   883           ("#Where" ,["t_t is_ratpolyexp"]),
   884           ("#Find"  ,["normalform n_n"])],
   885         Rule_Set.append_rules "empty" Rule_Set.empty [(*for preds in where_*)], 
   886         SOME "Simplify t_t", [["simplification","of_rationals"]]))]\<close>
   887 
   888 section \<open>A methods for simplification of rationals\<close>
   889 (*WN061025 this methods script is copied from (auto-generated) script
   890   of norm_Rational in order to ease repair on inform*)
   891 
   892 partial_function (tailrec) simplify :: "real \<Rightarrow> real"
   893   where
   894 "simplify term = (
   895   (Try (Rewrite_Set ''discard_minus'') #>
   896    Try (Rewrite_Set ''rat_mult_poly'') #>
   897    Try (Rewrite_Set ''make_rat_poly_with_parentheses'') #>
   898    Try (Rewrite_Set ''cancel_p_rls'') #>
   899    (Repeat (
   900      Try (Rewrite_Set ''add_fractions_p_rls'') #>
   901      Try (Rewrite_Set ''rat_mult_div_pow'') #>
   902      Try (Rewrite_Set ''make_rat_poly_with_parentheses'') #>
   903      Try (Rewrite_Set ''cancel_p_rls'') #>
   904      Try (Rewrite_Set ''rat_reduce_1''))) #>
   905    Try (Rewrite_Set ''discard_parentheses1''))
   906    term)"
   907 setup \<open>KEStore_Elems.add_mets
   908     [Method.prep_input thy "met_simp_rat" [] Method.id_empty
   909       (["simplification","of_rationals"],
   910         [("#Given" ,["Term t_t"]),
   911           ("#Where" ,["t_t is_ratpolyexp"]),
   912           ("#Find"  ,["normalform n_n"])],
   913 	      {rew_ord'="tless_true", rls' = Rule_Set.empty, calc = [], srls = Rule_Set.empty, 
   914 	        prls = Rule_Set.append_rules "simplification_of_rationals_prls" Rule_Set.empty 
   915 				    [(*for preds in where_*) Rule.Eval ("Rational.is'_ratpolyexp", eval_is_ratpolyexp "")],
   916 				  crls = Rule_Set.empty, errpats = [], nrls = norm_Rational_rls},
   917 				  @{thm simplify.simps})]
   918 \<close>
   919 
   920 end