Re: OOP experiments in Mathematica- The Stack
- To: mathgroup at smc.vnet.net
- Subject: [mg38660] Re: OOP experiments in Mathematica- The Stack
- From: "Steve S. Shaw" <steve at shawstudio.com>
- Date: Fri, 3 Jan 2003 00:16:47 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
A series of OOP experiments in Mathematica. msg#2 - The Stack, part#5: plain text version of the input lines of the notebook in message part#4. For your perusal, if Mathematica is not handy. ----------------------------------------------------------------- (* Quiet the warnings about similarly spelled variables. *) Off[General::spell]; Off[General::spell1]; (*=======================================\[Equal]*) (*-- AXIOMS- True for all stacks. --*) axiom1[]:=empty[ new[] ]; axiom2[ s_STACK, x_ ]:=!empty[ push[ s, x ] ]; axiom3[ s_STACK, x_ ]:=(top[ push[ s,x ] ]==x); axiom4[ s_STACK, x_ ]:=(drop[ push[ s,x ] ]==s); allAxioms[ s_STACK, x_ ]:=( axiom1[] && axiom2[ s,x ] && axiom3[ s,x ] && axiom4[ s,x ]); (*=======================================\[Equal]*) (*-- an example of stack usage --*) s1=new[]; s2=push[ push[ push[ s1,x1 ],x2],x3 ]; s3=drop[ s2 ]; s4=new[]; s5=push[ push[ s4,x4 ],x5 ]; s6=drop[ s5 ]; v1=top[ s6 ]; s7=push[ s3,v1 ]; s8=push[ s7,x6 ]; s9=drop[ s8 ]; s10=push[ s9,x7 ]; s11=drop[ s10 ]; result1=top[ s11 ]; result1 (* MUST BE TRUE for any implementation of STACK *) stackVerify=(result1\[Equal]x4); (* TBD - throw exception? Unless "test" is True, report error. *) assert[ test_,message_ ]:=If[ !TrueQ[ test ], "***Error: "<>ToString[ message ]//Print ]; (*=======================================\[Equal]*) (*-- "Prepend" Implementation of Stack --*) Clear[ empty, top, new, push, drop ]; (*-- Queries --*) empty[ s_STACK ]:=(Length[ s ]\[Equal]0); top[ s_STACK ]:=( assert[ !empty[ s ],"stack.top- empty" ]; First[ s ] ); (*-- Changes --*) new[]:=STACK[]; push[ s_STACK,x_ ]:=Prepend[ s,x ]; drop[ s_STACK ]:=( assert[ !empty[ s ],"stack.drop- empty" ]; Drop[ s,1 ] ); s1 s2 result1 assert[ stackVerify,"Bad Stack Implementation" ]; allAxioms[ new[], xx ] allAxioms[ s1, xx ] allAxioms[ s11, xx ] (* Deliberate errors *) top[ s1 ] drop[ s1 ] (*=======================================\[Equal]*) (*-- "Append" Implementation of Stack --*) Clear[ empty, top, new, push, drop ]; (*-- Queries --*) empty[ s_STACK ]:=(Length[ s ]\[Equal]0); top[ s_STACK ]:=( assert[ !empty[ s ],"stack.top- empty" ]; Last[ s ] ); (*-- Changes --*) new[]:=STACK[]; push[ s_STACK,x_ ]:=Append[ s,x ]; drop[ s_STACK ]:=( assert[ !empty[ s ],"stack.drop- empty" ]; Drop[ s,-1 ] ); s1 s2 result1 assert[ stackVerify,"Bad Stack Implementation" ]; allAxioms[ new[], xx ] allAxioms[ s1, xx ] allAxioms[ s11, xx ] (* Deliberate errors *) top[ s1 ] drop[ s1 ]