81 lines
1.6 KiB
Markdown
81 lines
1.6 KiB
Markdown
## Exercise 2.2 (Power)
|
|
|
|
```Ocaml
|
|
(*First version ; 6 multiplications*)
|
|
# let power28(x) =
|
|
let x2 = x + x in
|
|
let x4 = x2*x2 in
|
|
let x8 = x4*x4 in
|
|
let x16 = x8*x8 in
|
|
x16*x8*x4 ;;
|
|
|
|
(*Second version ; 27 multiplications*)
|
|
# let power28(x) = x*x*x*x*x*x...*x ;;
|
|
|
|
(*Third version ; 11 multiplications*)
|
|
# let power28(x) =
|
|
let sq(x) = x*x in
|
|
let pow4(x) = sq(sq(x)) in
|
|
pow4(pow4(x))*sq(pow4(x))*pow4(x);;
|
|
|
|
(*Fourth version ; 7 multiplications*)
|
|
# let power28(x)=
|
|
let sq(x) = x+x in
|
|
let p4=sq(sq(x)) in
|
|
sq(sq(p4))*sq(p4)*p4;;
|
|
```
|
|
|
|
## Exercise 2.3
|
|
|
|
```Ocaml
|
|
# (*my verison*)
|
|
# let mirror(n) = let diz = n/10 and uni = n mod 10 in uni*10 + diz;;
|
|
val mirror : int -> int = <fun>
|
|
|
|
# (*teatcher version*)
|
|
# let mirror n = 10 *(n mod 10)+n/10;;
|
|
val mirror : int -> int = <fun>
|
|
```
|
|
|
|
```Ocaml
|
|
# let abba(n) = n*100 + mirror(n) ;;
|
|
val abba: int -> int = <fun>
|
|
```
|
|
|
|
```Ocaml
|
|
# let stammer(n) = abba(mirror(n)) * 10 000 + abba(n) ;;
|
|
val stammer: int -> int = <fun>
|
|
```
|
|
|
|
|
|
|
|
## Exercice 2.6
|
|
```Ocaml
|
|
let sec_of_time h m s =
|
|
h*3600 + m*60 + s ;;
|
|
|
|
let time_of_sec s =
|
|
let hours = s/3600 in let minutes = (s - hours*3600)/60 in let seconds = s - hours *3600 - minutes * 60 in (hours, minutes, seconds);;
|
|
|
|
let add_times h1 m1 s1 h2 m2 s2 =
|
|
let sec1 = sec_of_time h1 m1 s1 and sec2 = sec_of_time h2 m2 s2 in let resultsec = sec1 + sec2 in time_of_sec resultsec ;;
|
|
|
|
```
|
|
|
|
## Exercise 3.1
|
|
```Ocaml
|
|
let f a b c =
|
|
(if a > b && if b > c then
|
|
a + b else c + a
|
|
else if a > c then a + b else b + c)*
|
|
(if a > b && b > c then
|
|
a - b else a - c
|
|
else if a > c then a-b else b-c);;
|
|
```
|
|
|
|
### Exercise 3.2
|
|
```OCaml
|
|
if a && b then
|
|
true
|
|
else false
|