Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type key = Plus | Minus | Times | Div | Equals | Digit of int | Store | Recall | Clear | Off ;;
- type state = {
- mutable lastComputation:int;
- mutable lastKeyActivated:bool;
- mutable lastOperator:key;
- mutable valuePrinted:int;
- mutable memory:int
- } ;;
- exception Invalid_key ;;
- exception Key_off ;;
- let translation c = match c with
- '+' -> Plus
- | '-' -> Minus
- | '*' -> Times
- | '/' -> Div
- | '=' -> Equals
- | 'C' | 'c' -> Clear
- | 'M' -> Store
- | 'm' -> Recall
- | 'O' | 'o' -> Off
- | '0'..'9' as c -> Digit ((Char.code c) - (Char.code '0'))
- | _ -> raise Invalid_key ;;
- let transition state key = match key with
- Clear -> state.valuePrinted <- 0
- | Digit n -> state.valuePrinted <- (if state.lastKeyActivated then state.valuePrinted * 10 + n else n) ;
- state.lastKeyActivated <- true
- | Store -> state.lastKeyActivated <- false ;
- state.memory <- state.valuePrinted
- | Recall -> state.lastKeyActivated <- false ;
- state.valuePrinted <- state.memory
- | Off -> raise Key_off
- | _ -> let lastComputation = match state.lastOperator with
- Plus -> state.lastComputation + state.valuePrinted
- | Minus -> state.lastComputation - state.valuePrinted
- | Times -> state.lastComputation * state.valuePrinted
- | Div -> state.lastComputation / state.valuePrinted
- | Equals -> state.valuePrinted
- | _ -> failwith "transitional: imposible match"
- in
- state.lastComputation <- lastComputation ;
- state.lastKeyActivated <- false ;
- state.lastOperator <- key ;
- state.valuePrinted <- lastComputation ;;
- let go () =
- let state = {
- lastComputation = 0 ;
- lastKeyActivated = false ;
- lastOperator = Times ;
- valuePrinted = 0 ;
- memory = 0
- }
- in try
- while true do
- try
- let input = translation (input_char stdin)
- in
- transition state input ;
- print_newline () ;
- print_string "result: " ;
- print_int state.valuePrinted ;
- print_newline () ;
- with
- Invalid_key -> ()
- done
- with
- Key_off -> () ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement