Reputation: 23
How can i get number(int) from int list?
Example: I have list of int l=[1;2;3;4;5]
and i want to get number n=54321
.
This is my code:
let rec number ls =
match ls with
|[]->[]
|(h::t)->h*10**(List.length t) + number t
;;
When i compile it, i get this error:
Error: This expression has type int but an expression was expected of type float
Upvotes: 1
Views: 2297
Reputation: 4441
The easiest way to do it is to use an iterator in a tail-recursive way
List.fold_left f a [b1; ...; bn] is f (... (f (f a b1) b2) ...) bn
.
let number_tr ls =
let n, _ = List.fold_left (
fun (n, pow) e -> (e * pow + n, pow * 10) (0, 1) ls in
ls
The accumulator contains two integers, the number that we are computing and the actual power. For each new element, we increment the number and then multiply the number by 10.
Another version uses a non tail-recursive iterator
List.fold_right f [a1; ...; an] b is f a1 (f a2 (... (f an b) ...))
let number_ntr ls =
List.fold_right (fun e n -> e + n * 10) ls 0
Runs :
number_tr [1; 2; 3]
> acc = (0, 1), e = 1 -> new acc = (1 * 1 + 0, 1 * 10)
> acc = (1, 10), e = 2 -> new acc = (2 * 10 + 1, 10 * 10)
> acc = (21, 100), e = 3 -> new acc = (3 * 100 + 21, 100 * 10)
> acc = (321, 1000) -> returns 321
number_ntr [1; 2; 3]
> acc = 0, e = 3 -> new acc = 3 + 0 * 10
> acc = 3, e = 2 -> new acc = 2 + 3 * 10
> acc = 32, e = 1 -> new acc = 1 + 32 * 10
> acc = 321 -> returns 321
Upvotes: 1
Reputation: 332
You can also do it using tail recursion:
let f l =
let rec f_helper l num =
match l with
| [] -> num
| (h::t) -> f_helper t ((num * 10 ) + h)
in f_helper (List.rev l) 0
;;
Upvotes: 0