Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type 'a operation = {f: 'a -> 'a -> 'a; nom: string};;
- type 'a expression = EV of 'a | E of 'a expression * 'a operation * 'a expression;;
- let rec evalue expression = match expression with
- | EV(a) -> a
- | E(a, o, b) -> o.f (evalue a) (evalue b);;
- let fPlus a b = a + b;;
- let fMoins a b = a - b;;
- let fMult a b = a * b;;
- let fDiv a b = a / b;;
- let plus = {f = fPlus; nom = "+"};;
- let moins = {f = fMoins; nom = "-"};;
- let fois = {f = fMult; nom = "*"};;
- let div = {f = fDiv; nom = "/"};;
- let e = E(E(E(EV(2), plus, EV(3)), fois, EV(4)), plus, E(EV(5), moins, EV(3)));;
- evalue e;;
- let rec imprime_infixe e = match e with
- | E(a, o, b) -> print_string "(";
- imprime_infixe a;
- print_string ")";
- print_string o.nom;
- print_string "(";
- imprime_infixe b;
- print_string ")";
- ();
- | EV(a) -> print_int a;;
- imprime_infixe e;;
- (* Ici, les parenthèses ne sont pas nécessaires.
- En effet, il suffit d'évaluer de la gauche vers la droite.
- Dès qu'on a un signe, on calcule l'opération et on retient le résultat.
- Par exemple
- 3 4+ 5*
- Ne pose pas de problème d'ambiguïté, puisqu'on fait
- 3; 4; + -> 3 + 4 = 7
- 7; 5; * -> 7 * 5 = 35
- En utilisant l'infixe, on aurait eu
- 3 + 4 * 5
- Ce qui aurait été ambigu (puisqu'on ne sait pas si on doit faire
- 3 + (4 * 5) ou (3 + 4) * 5 *)
- let rec imprime_postfixe e = match e with
- | E(a, o, b) -> imprime_postfixe a;
- print_string " ";
- imprime_postfixe b;
- print_string o.nom;
- | EV(a) -> print_int a;;
- imprime_postfixe e;;
Advertisement
Add Comment
Please, Sign In to add comment