ProgTutorial/Solutions.thy
changeset 271 949957531f63
parent 270 bfcabed9079e
child 272 2ff4867c00cf
equal deleted inserted replaced
270:bfcabed9079e 271:949957531f63
     4 
     4 
     5 chapter {* Solutions to Most Exercises\label{ch:solutions} *}
     5 chapter {* Solutions to Most Exercises\label{ch:solutions} *}
     6 
     6 
     7 text {* \solution{fun:revsum} *}
     7 text {* \solution{fun:revsum} *}
     8 
     8 
       
     9 ML{*fun rev_sum((p as Const(@{const_name plus},_)) $ t $ u) = p $ u $ rev_sum t
       
    10   | rev_sum t = t *}
       
    11 
       
    12 text {* \solution{fun:revsum typed} *}
       
    13 
     9 ML{*fun rev_sum t =
    14 ML{*fun rev_sum t =
    10 let
    15 let
    11   fun dest_sum (Const (@{const_name plus}, _) $ u $ u') = u' :: dest_sum u
    16   fun dest_sum (Const (@{const_name plus}, _) $ u $ u') = u' :: dest_sum u
    12     | dest_sum u = [u]
    17     | dest_sum u = [u]
    13 in
    18 in
    14    foldl1 (HOLogic.mk_binop @{const_name plus}) (dest_sum t)
    19    foldl1 (HOLogic.mk_binop @{const_name plus}) (dest_sum t)
    15 end *}
    20 end *}
    16 
    21 
    17 (* Alternative Solution:
    22 
    18 fun rev_sum((plus as Const(@{const_name plus},_)) $ t $ u) = plus $ u $ rev_sum t
       
    19   | rev_sum t = t
       
    20 *)
       
    21 
    23 
    22 text {* \solution{fun:makesum} *}
    24 text {* \solution{fun:makesum} *}
    23 
    25 
    24 ML{*fun make_sum t1 t2 =
    26 ML{*fun make_sum t1 t2 =
    25       HOLogic.mk_nat (HOLogic.dest_nat t1 + HOLogic.dest_nat t2) *}
    27       HOLogic.mk_nat (HOLogic.dest_nat t1 + HOLogic.dest_nat t2) *}