Advertisement
Keodedad

TP5

Apr 5th, 2019
1,139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 2.04 KB | None | 0 0
  1. (* Exercice 1 *)
  2.  
  3. type natural = Z | S of natural
  4.  
  5. let rec addition n m =
  6.   match n with
  7.     Z -> m
  8.   | S n' -> S (addition n' m)
  9.  
  10. let rec addition' n m =
  11.   match n with
  12.     Z -> m
  13.   | S n' -> addition' n' (S m)
  14.  
  15. let rec multiplication n m =
  16.   match m with
  17.     Z -> Z
  18.   | S m' -> addition (multiplication n m') n
  19.  
  20. let rec factorial n =
  21.   match n with
  22.     Z | (S Z) -> S Z
  23.   | S n' -> multiplication n (factorial n')
  24.  
  25. (* Exercice 2 *)
  26.  
  27. let rec string_of_natural n =
  28.   match n with
  29.     Z -> "0"
  30.   | S n' -> "S"^(string_of_natural n')
  31.  
  32. let rec natural_of_string s =
  33.   try
  34.     if String.get s 0 = '0'
  35.     then Z
  36.     else
  37.       let n = String.length s in
  38.       let s' = String.sub s 1 (n - 1) in
  39.       S (natural_of_string s')
  40.   with Invalid_argument _ ->
  41.     failwith "format invalide"
  42.    
  43. let rec natural_of_int i =
  44.   if i > 0 then S (natural_of_int (i - 1))
  45.   else Z
  46.  
  47. let rec int_of_natural n =
  48.   match n with
  49.     Z -> 0
  50.   | S n -> (int_of_natural n) + 1
  51.  
  52. type pile = natural list
  53.  
  54. let string_of_pile s =
  55.   String.concat "\n"
  56.     (List.mapi
  57.        (fun i n ->
  58.           (string_of_int i)^" : "^
  59.           (string_of_natural n))
  60.        s)
  61.  
  62. let _ =
  63.   print_string
  64.     (string_of_pile
  65.        [natural_of_int 2;
  66.         natural_of_string "SSSS0";
  67.         S(Z)])
  68.  
  69. (* Exercice 4 *)
  70.  
  71. type calculator_input =
  72.     Natural of natural
  73.   | Addition
  74.   | Multiplication
  75.   | Factorial
  76.   | Clear
  77.  
  78. let calculator (s : pile) o : pile =
  79.   match (s, o) with
  80.     (_, Natural n) -> n::s
  81.   | (n1::n2::s', Addition) ->
  82.     (addition n1 n2)::s'
  83.   | (n1::n2::s', Multiplication) ->
  84.     (multiplication n1 n2)::s'
  85.   | (n::s', Factorial) ->
  86.     (factorial n)::s'
  87.   | (_, Clear) -> []
  88.  
  89. let input_of_string s =
  90.   if s = "C" then Clear
  91.   else if s = "+" then Addition
  92.   else if s = "*" then Multiplication
  93.   else Natural (natural_of_string s)
  94.  
  95. let rec toplevel p  =
  96.   let _ =
  97.     print_string (string_of_pile p)
  98.   in let c =
  99.        input_of_string (read_line ())
  100.   in let p' =
  101.        calculator p c
  102.   in toplevel p'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement