Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* Exercice 1 *)
- type natural = Z | S of natural
- let rec addition n m =
- match n with
- Z -> m
- | S n' -> S (addition n' m)
- let rec addition' n m =
- match n with
- Z -> m
- | S n' -> addition' n' (S m)
- let rec multiplication n m =
- match m with
- Z -> Z
- | S m' -> addition (multiplication n m') n
- let rec factorial n =
- match n with
- Z | (S Z) -> S Z
- | S n' -> multiplication n (factorial n')
- (* Exercice 2 *)
- let rec string_of_natural n =
- match n with
- Z -> "0"
- | S n' -> "S"^(string_of_natural n')
- let rec natural_of_string s =
- try
- if String.get s 0 = '0'
- then Z
- else
- let n = String.length s in
- let s' = String.sub s 1 (n - 1) in
- S (natural_of_string s')
- with Invalid_argument _ ->
- failwith "format invalide"
- let rec natural_of_int i =
- if i > 0 then S (natural_of_int (i - 1))
- else Z
- let rec int_of_natural n =
- match n with
- Z -> 0
- | S n -> (int_of_natural n) + 1
- type pile = natural list
- let string_of_pile s =
- String.concat "\n"
- (List.mapi
- (fun i n ->
- (string_of_int i)^" : "^
- (string_of_natural n))
- s)
- let _ =
- print_string
- (string_of_pile
- [natural_of_int 2;
- natural_of_string "SSSS0";
- S(Z)])
- (* Exercice 4 *)
- type calculator_input =
- Natural of natural
- | Addition
- | Multiplication
- | Factorial
- | Clear
- let calculator (s : pile) o : pile =
- match (s, o) with
- (_, Natural n) -> n::s
- | (n1::n2::s', Addition) ->
- (addition n1 n2)::s'
- | (n1::n2::s', Multiplication) ->
- (multiplication n1 n2)::s'
- | (n::s', Factorial) ->
- (factorial n)::s'
- | (_, Clear) -> []
- let input_of_string s =
- if s = "C" then Clear
- else if s = "+" then Addition
- else if s = "*" then Multiplication
- else Natural (natural_of_string s)
- let rec toplevel p =
- let _ =
- print_string (string_of_pile p)
- in let c =
- input_of_string (read_line ())
- in let p' =
- calculator p c
- in toplevel p'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement