[英]How to print list as int in OCaml?
Say I have any list, for example 举例来说,我有任何清单
let lista = [1;2;3;4;5;6]
How do I write this as 我怎么写成
int = 123456
so that i can later pass it to a function? 这样我以后才能将其传递给函数?
I tried 我试过了
let rec print lista =
match lista with
[]->()
|a::lista ->print_int a; print lista;;
but i dont get expected result, only 但我没有得到预期的结果
- : unit = ()
I know about int_of_string, so whether my function returns string or int doesnt really matter. 我知道int_of_string,所以我的函数返回string还是int并不重要。
A possible solution : 可能的解决方案:
lista
|> List.fold_left (fun a x -> a * 10 + x) 0;;
the accumulator is multiplied by 10 and we add the current element of the list 累加器乘以10,然后将列表的当前元素相加
the second parameter for initializing the accumulator to 0. 第二个参数,用于将累加器初始化为0。
List.fold_left is very useful for processing a list. List.fold_left对于处理列表非常有用。
If you need to print the result modify the code adding the line to print directly the result : 如果需要打印结果,请修改代码,并添加以下行以直接打印结果:
lista
|> List.fold_left (fun a x -> a * 10 + x) 0
|> print_int;;
You're quite close to a solution: instead of print
ing the solution to the standard output, you should produce a string for each number and append them together. 您已经很接近解决方案了:您应该为每个数字生成一个字符串并将其附加在一起,而不是将解决方案
print
到标准输出中。 Here are functions you will need: 这是您需要的功能:
val string_of_int : int -> string
and 和
val (^) : string -> string -> string val(^):字符串->字符串->字符串
Alternatively, you could bypass int_of_string
and implement a direct solution by noticing that: 或者,您可以通过注意以下内容来绕过
int_of_string
并实现直接解决方案:
to_int [a; b; ...; c; d] = ab...cd
= d + 10 * (c + 10 * (... + 10 * (b + 10 * c)))
ie that this has a neat recursive structure. 即,它具有简洁的递归结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.