vault backup: 2023-10-06 14:47:45
This commit is contained in:
parent
fd901fb644
commit
890ea1b07b
@ -44,23 +44,17 @@ val search 'a -> 'a list -> bool = <fun>
|
||||
|
||||
## 1.4 - $n^{th}$
|
||||
```Ocaml
|
||||
# let rec length l =
|
||||
if l = [] then
|
||||
0
|
||||
# let nth l n =
|
||||
if n <= 0 then
|
||||
invalid_arg "n <= 0"
|
||||
else
|
||||
let e::t = l in
|
||||
1 + length t;;
|
||||
# let rec nth x n =
|
||||
if (x = [] || n =< 0) then
|
||||
Invalid_arg "The number of element in the list is 0"
|
||||
else if length x < n then
|
||||
Failwith "The list is too short"
|
||||
else
|
||||
let e::t = x in
|
||||
if n = 0
|
||||
return e
|
||||
else
|
||||
nth t (n-1) ;;
|
||||
let rec nthrec = function
|
||||
| ([],_) -> failwith "list too short"
|
||||
| (h::_,1)-> h
|
||||
| (_::t, n) -> nthrec(t, n-1)
|
||||
in
|
||||
ntrec(l, n);;
|
||||
val nth 'a list -> 'a -> int = <fun>
|
||||
|
||||
```
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user