-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhw22.ml
35 lines (30 loc) · 914 Bytes
/
hw22.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
world*)
type crazy2 = NIL | ZERO of crazy2 | ONE of crazy2 | MONE of crazy2
let is_even n = (n mod 2 = 0)
let pow base exponent =
if exponent <0 then invalid_arg "exponent cannot be negative" else
let rec aux accumulator base = function
| 0 -> accumulator
| 1 -> base * accumulator
| e when is_even e -> aux accumulator (base * base) (e/2)
| e-> aux(base * accumulator)(base*base)((e-1)/2) in
aux 1 base exponent
(*
let _ = print_endline(string_of_int(pow 2 5))
*)
let rec find_depth l =
match l with
| NIL -> 0
| MONE(l') -> 1 + find_depth l'
| ONE(l') -> 1+ find_depth l'
| ZERO(l') -> 1+find_depth l'
(*
let _ = print_endline(string_of_int(find_depth(ZERO(ONE(MONE NIL)))))
*)
let rec crazy2val x =
let sam = find_depth x in
match x with
| NIL -> 0
| MONE(x') -> (pow 2 (sam-1))*(-1)+crazy2val(x')
| ONE(x') -> (pow 2 (sam-1))*1 + crazy2val(x')
| ZERO(x') -> crazy2val(x')