Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.99 KB | None | 0 0
  1. type key = Plus | Minus | Times | Div | Equals | Digit of int | Store | Recall | Clear | Off ;;
  2.  
  3. type state = {
  4.     mutable lastComputation:int;
  5.     mutable lastKeyActivated:bool;
  6.     mutable lastOperator:key;
  7.     mutable valuePrinted:int;
  8.     mutable memory:int
  9. } ;;
  10.    
  11. exception Invalid_key ;;
  12. exception Key_off ;;
  13.  
  14. let translation c = match c with
  15.   '+' -> Plus
  16. | '-' -> Minus
  17. | '*' -> Times
  18. | '/' -> Div
  19. | '=' -> Equals
  20. | 'C' | 'c' -> Clear
  21. | 'M' -> Store
  22. | 'm' -> Recall
  23. | 'O' | 'o' -> Off
  24. | '0'..'9' as c -> Digit ((Char.code c) - (Char.code '0'))
  25. | _ -> raise Invalid_key ;;
  26.  
  27. let transition state key = match key with
  28.   Clear -> state.valuePrinted <- 0
  29. | Digit n -> state.valuePrinted <- (if state.lastKeyActivated then state.valuePrinted * 10 + n else n) ;
  30.              state.lastKeyActivated <- true
  31. | Store -> state.lastKeyActivated <- false ;
  32.            state.memory <- state.valuePrinted
  33. | Recall -> state.lastKeyActivated <- false ;
  34.             state.valuePrinted <- state.memory
  35. | Off -> raise Key_off
  36. | _ -> let lastComputation = match state.lastOperator with
  37.     Plus -> state.lastComputation + state.valuePrinted
  38.   | Minus -> state.lastComputation - state.valuePrinted
  39.   | Times -> state.lastComputation * state.valuePrinted
  40.   | Div -> state.lastComputation / state.valuePrinted
  41.   | Equals -> state.valuePrinted
  42.   | _ -> failwith "transitional: imposible match"
  43.     in
  44.   state.lastComputation <- lastComputation ;
  45.   state.lastKeyActivated <- false ;
  46.   state.lastOperator <- key ;
  47.   state.valuePrinted <- lastComputation ;;
  48.  
  49. let go () =
  50.   let state = {
  51.     lastComputation = 0 ;
  52.     lastKeyActivated = false ;
  53.     lastOperator = Times ;
  54.     valuePrinted = 0 ;
  55.     memory = 0
  56.   }
  57.   in try
  58.     while true do
  59.       try
  60.     let input = translation (input_char stdin)
  61.     in
  62.     transition state input ;
  63.     print_newline () ;
  64.     print_string "result: " ;
  65.     print_int state.valuePrinted ;
  66.     print_newline () ;
  67.       with
  68.     Invalid_key -> ()
  69.     done
  70.   with
  71.     Key_off -> () ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement