61 lines
1.1 KiB
Markdown
61 lines
1.1 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 sef_of_time h m s =
|
|
h*3600 + m*60 + s ;;
|
|
|
|
let time_of_sec s =
|
|
let hours = s/3600 and minutes = s mod 60 and seconds = s mod 3600 in (hours, minutes, seconds)
|
|
|
|
```
|