Commits

Joby Poriyath  committed 620b1f2

Calculator with memory (example from Ch 3)

  • Participants
  • Parent commits 3f465fe

Comments (0)

Files changed (1)

+(* Calculator with Memory *)
+
+exception Invalid_key
+
+type key = Plus | Minus | Times | Div 
+           | Equals | Memory | Recall 
+           | Clear | Off
+           | Digit of int
+
+let translation = function
+  | '+' -> Plus
+  | '-' -> Minus
+  | '*' -> Times
+  | '/' -> Div
+  | '=' -> Equals
+  | 'M' -> Memory
+  | 'm' -> Recall
+  | 'C' | 'c' -> Clear
+  | 'O' | 'o' -> Off
+  | '0'..'9' as c -> Digit (Char.code c - Char.code '0')
+  | _ -> raise Invalid_key
+
+type state = { mutable lcd : int; (* last computation done *)
+               mutable vpr : int; (* value printed *)
+               mutable lda : bool; (* flag to indicate whether last key entered was a digit *)
+               mutable loa : key; (* last operator activated *)
+               mutable mem : int; (* memory of calculator *) }
+
+exception Key_off
+
+let transition st = function 
+  | Digit n -> st.vpr <- (if st.lda then st.vpr * 10 + n else n); st.lda <- true
+  | Memory -> st.mem <- st.vpr; st.lda <- false
+  | Recall -> st.vpr <- st.mem; st.lda <- false
+  | Clear -> st.vpr <- 0; 
+  | Off -> raise Key_off
+  | op -> 
+    let lcd = match st.loa with
+      | Plus -> st.lcd + st.vpr
+      | Minus -> st.lcd - st.vpr
+      | Times -> st.lcd * st.vpr
+      | Div -> st.lcd * st.vpr
+      | Equals -> st.vpr
+      | _ -> failwith "transition: impossible match"
+    in
+    st.lcd <- lcd;
+    st.lda <- false;
+    st.loa <- op;
+    st.vpr <- lcd
+
+let go () = 
+  let state = {lcd=0; loa=Equals; vpr=0; mem=0; lda=false} in
+  try
+    while true 
+    do
+      try 
+        let input = translation (input_char stdin) in
+        transition state input;
+        print_newline ();
+        print_string "result: ";
+        print_int state.vpr;
+        print_newline ()
+      with Invalid_key -> ()
+    done
+  with
+    | Key_off -> ()
+    | _ -> ()
+      
+
+let _ = go ()