Advertisement
Guest User

Reverse Polish notation

a guest
Feb 4th, 2017
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.20 KB | None | 0 0
  1. #load "str.cma";;
  2.  
  3. let string_to_tokens = Str.split (Str.regexp " +");;
  4.  
  5. let push nombre liste = nombre::liste;;
  6.  
  7. let pop = function
  8.     | [] ->failwith "Pile vide ! "
  9.     | head::tail -> (head,tail);;
  10.  
  11. let is_operator = function
  12.     |"+"|"-"|"/"|"*" -> true
  13.     | _ -> false
  14.  
  15. let operator_to_function = function
  16.     | "+" -> ( + )
  17.     | "-" -> ( - )
  18.     | "/" -> ( / )
  19.     | "*" -> ( * )
  20.     | _ -> failwith "Operateur inconnu !";;
  21.  
  22. let rec parse liste pile =
  23.     match liste with
  24.     | [] -> let (reponse,pilevide) = pop pile in
  25.         reponse
  26.     | token::reste -> Printf.printf "Token:%s \n" token;
  27.               let pilenew = if (is_operator token) then
  28.                 let (b,pileun) = pop pile in
  29.                 let (a,piledeux) = pop pileun in
  30.                 push ((operator_to_function token) a b) piledeux
  31.               else push (int_of_string token) pile in
  32.               parse reste pilenew;;
  33.  
  34.  
  35.  
  36. let () =
  37.   if (Array.length Sys.argv = 2) then
  38.       let arg = Sys.argv.(1) in
  39.       let chaine = string_to_tokens arg in
  40.       try (
  41.       let result = parse chaine [] in
  42.       Printf.printf "\n==> Resultat : %d\n\n" result;
  43.       exit 0
  44.       ) with
  45.         | Failure a -> Printf.printf "[Erreur] %s\n" (if (a="int_of_string") then "conversion en nombre impossible !" else a)
  46.   else exit 1;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement