Pouknouki

Arbre expression arithmétique

Oct 2nd, 2016
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.54 KB | None | 0 0
  1. type 'a operation = {f: 'a -> 'a -> 'a; nom: string};;
  2. type 'a expression = EV of 'a | E of 'a expression * 'a operation * 'a expression;;
  3. let rec evalue expression = match expression with
  4.     | EV(a) -> a
  5.     | E(a, o, b) -> o.f (evalue a) (evalue b);;
  6.  
  7. let fPlus a b = a + b;;
  8. let fMoins a b = a - b;;
  9. let fMult a b = a * b;;
  10. let fDiv a b = a / b;;
  11.  
  12. let plus = {f = fPlus; nom = "+"};;
  13. let moins = {f = fMoins; nom = "-"};;
  14. let fois = {f = fMult; nom = "*"};;
  15. let div = {f = fDiv; nom = "/"};;
  16.  
  17. let e = E(E(E(EV(2), plus, EV(3)), fois, EV(4)), plus, E(EV(5), moins, EV(3)));;
  18. evalue e;;
  19.  
  20. let rec imprime_infixe e = match e with
  21.     | E(a, o, b) -> print_string "(";
  22.             imprime_infixe a;
  23.             print_string ")";
  24.             print_string o.nom;
  25.             print_string "(";
  26.             imprime_infixe b;
  27.             print_string ")";
  28.             ();
  29.     | EV(a) -> print_int a;;
  30. imprime_infixe e;;
  31.  
  32. (* Ici, les parenthèses ne sont pas nécessaires.
  33.    En effet, il suffit d'évaluer de la gauche vers la droite.
  34.    Dès qu'on a un signe, on calcule l'opération et on retient le résultat.
  35.    Par exemple
  36.    3 4+ 5*
  37.    Ne pose pas de problème d'ambiguïté, puisqu'on fait
  38.    3; 4; + -> 3 + 4 = 7
  39.    7; 5; * -> 7 * 5 = 35
  40.    En utilisant l'infixe, on aurait eu
  41.    3 + 4 * 5
  42.    Ce qui aurait été ambigu (puisqu'on ne sait pas si on doit faire
  43.    3 + (4 * 5) ou (3 + 4) * 5 *)
  44.  
  45. let rec imprime_postfixe e = match e with
  46.     | E(a, o, b) -> imprime_postfixe a;
  47.             print_string " ";
  48.             imprime_postfixe b;
  49.             print_string o.nom;
  50.     | EV(a) -> print_int a;;
  51.  
  52. imprime_postfixe e;;
Advertisement
Add Comment
Please, Sign In to add comment