3 (* reverse polish calculator *)
7 let wow _ = prerr_endline "Wow!"; ()
9 let stack = Stack.create () in
13 GWindow.window ~border_width: 10 ~title:"Reverse Polish Calculator" () in
14 window#connect#destroy ~callback:Main.quit;
18 let vbx = GPack.vbox ~packing:window#add () in
22 GEdit.entry ~text:"0" ~editable:false ~max_length: 20 ~packing: vbx#add () in
24 (* BackSpace, Clear, All Clear, Quit *)
25 let table0 = GPack.table ~rows:1 ~columns:4 ~packing:vbx#add () in
26 let bs_clicked _ = begin
27 let txt = entry#text in
28 let len = String.length txt in
31 else entry#set_text (String.sub txt ~pos:0 ~len:(len-1))
33 let c_clicked _ = entry#set_text("0") in
34 let ac_clicked _ = Stack.clear stack; entry#set_text("0") in
35 let labels0 = [("BS", bs_clicked) ; ("C", c_clicked);
36 ("AC", ac_clicked); ("Quit", window#destroy)] in
37 let rec loop0 labels n =
42 GButton.button ~label:lbl
43 ~packing:(table0#attach ~left:n ~top:1 ~expand:`BOTH) () in
44 button#connect#clicked ~callback:cb;
49 let table1 = GPack.table ~rows:4 ~columns:5 ~packing:vbx#add () in
50 let labels1 = ["7"; "8"; "9"; "4"; "5"; "6"; "1"; "2"; "3"; "0"] in
52 let txt = entry#text in
58 let rec loop1 labels n =
59 match labels with [] -> ()
61 let button = GButton.button ~label:(" "^lbl^" ")
62 ~packing:(table1#attach ~left:(n mod 3) ~top:(n/3) ~expand:`BOTH)
64 button#connect#clicked ~callback:(numClicked lbl);
70 let txt = entry#text in
71 if (String.contains txt '.') then begin
76 entry#append_text "." in
77 (GButton.button ~label:" . "
78 ~packing:(table1#attach ~left:1 ~top:3 ~expand:`BOTH) ())
79 #connect#clicked ~callback:periodClicked;
83 let txt = entry#text in
84 let n = float_of_string txt in begin
88 (GButton.button ~label:"Ent"
89 ~packing:(table1#attach ~left:2 ~top:3 ~expand:`BOTH) ())
90 #connect#clicked ~callback:enterClicked;
94 let n1 = float_of_string (entry#text) in
95 let n2 = Stack.pop stack in
96 entry#set_text (string_of_float (op n2 n1))
99 let n1 = float_of_string (entry#text) in
100 entry#set_text (string_of_float (op n1))
103 let n1 = int_of_string (entry#text) in
104 let n2 = truncate (Stack.pop stack) in
105 entry#set_text (string_of_int (n2 mod n1))
107 let labels2 = [(" / ", op2Clicked (/.)); (" * ", op2Clicked ( *. ));
108 (" - ", op2Clicked (-.)); (" + ", op2Clicked (+.));
109 ("mod", modClicked); (" ^ ", op2Clicked ( ** ));
110 ("+/-", op1Clicked (~-.));
111 ("1/x", op1Clicked (fun x -> 1.0/.x))] in
112 let rec loop2 labels n =
116 let button = GButton.button ~label:lbl
117 ~packing:(table1#attach ~left:(3 + n/4) ~top: (n mod 4)
120 button#connect#clicked ~callback:cb;
125 (* show all and enter event loop *)
129 let _ = Printexc.print main()