将/ Cast浮动列表转换为int列表

问题描述 投票:0回答:2

如果我有一个清单:

[1.0;2.0;3.0;...]

是否可以将其转换或转换为整数列表:

[1;2;3;...] 

我查看了List库,似乎找不到这个函数

ocaml
2个回答
1
投票

你可以尝试使用List.mapint_of_float将浮点数转换为整数。

例:

let float_list = [1.0; 2.0; 3.0] in
let int_list = List.map (fun x -> int_of_float x) float_list in
(* int_list is [1; 2; 3] *)
...

3
投票
utop # List.map;;
- : ('a -> 'b) -> 'a list -> 'b list = <fun>

采用函数f : 'a -> 'b,它将'a类型的值带到类型为'b的值,并将'as列表中的函数返回到'bs列表:

utop # List.map int_of_float;;
- : float list -> int list = <fun>

在这种情况下,int_of_float : int -> float是我们的f,所以我们从floats列表到ints列表中得到一个函数。

utop # List.map int_of_float [1.0;2.0;3.0];;
- : int list = [1; 2; 3]
© www.soinside.com 2019 - 2024. All rights reserved.