如何打印二维数组
How to Print 2D array
这里有什么问题?
let elem = function(list)-> (List.map string_of_int list);;
let rec row = function (list)->if elem(List.hd list)::row(List.tl list);;
我想对您的代码提出一些建议:
1 - 当参数没有歧义时,我们不会将参数放在括号之间:
let elem = fun l -> String.concat " " (List.map string_of_float l)
2 - 而不是使用 if
then
else
,在列表上使用模式匹配。它更高效,您的代码将更具可读性:
let rec row = function
| [] -> []
| x :: tl -> elem x :: row tl
这个函数不是尾递归的(改成它可以作为你的练习)
我也把你的最后一个函数放在这里:
let print = fun l -> print_string (String.concat "\n" (row l))
let () =
(print [[0.2;-0.2;0.2];[0.1;-0.1;0.1];[0.5;-0.5;0.5]])
这是我的版本:
let string_of_float_list l = String.concat " " (List.map string_of_float l)
let float_list_to_string l = String.concat "\n" (List.map string_of_float_list l)
let () =
Printf.printf "%s" (float_list_to_string [[1.0;2.0;3.0];[1.0;2.0;3.0];[1.0;2.0;3.0]])
输出:
1. 2. 3.
1. 2. 3.
1. 2. 3.
这里有什么问题?
let elem = function(list)-> (List.map string_of_int list);;
let rec row = function (list)->if elem(List.hd list)::row(List.tl list);;
我想对您的代码提出一些建议:
1 - 当参数没有歧义时,我们不会将参数放在括号之间:
let elem = fun l -> String.concat " " (List.map string_of_float l)
2 - 而不是使用 if
then
else
,在列表上使用模式匹配。它更高效,您的代码将更具可读性:
let rec row = function
| [] -> []
| x :: tl -> elem x :: row tl
这个函数不是尾递归的(改成它可以作为你的练习)
我也把你的最后一个函数放在这里:
let print = fun l -> print_string (String.concat "\n" (row l))
let () =
(print [[0.2;-0.2;0.2];[0.1;-0.1;0.1];[0.5;-0.5;0.5]])
这是我的版本:
let string_of_float_list l = String.concat " " (List.map string_of_float l)
let float_list_to_string l = String.concat "\n" (List.map string_of_float_list l)
let () =
Printf.printf "%s" (float_list_to_string [[1.0;2.0;3.0];[1.0;2.0;3.0];[1.0;2.0;3.0]])
输出:
1. 2. 3.
1. 2. 3.
1. 2. 3.