从int列表转换为int Ocaml

时间:2017-05-26 12:39:16

标签: list ocaml

如何从int列表中获取数字(int)?

示例:我有一个int l=[1;2;3;4;5]列表,我希望得到号码n=54321

这是我的代码:

let rec number ls =
match ls with
    |[]->[]
    |(h::t)->h*10**(List.length t) +  number t
;;

当我编译它时,我收到此错误:

  

错误:此表达式的类型为int,但需要表达式   类型            浮

2 个答案:

答案 0 :(得分:1)

最简单的方法是以尾递归的方式使用迭代器

  

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

累加器包含两个整数,我们正在计算的数字和实际功率。对于每个新元素,我们递增数字,然后将数字乘以10。

另一个版本使用非尾递归迭代器

  

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

运行:

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

答案 1 :(得分:0)

您也可以使用尾递归来实现:

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
;;