/ / 2次元配列を印刷する方法 - 配列、リスト、印刷、浮動小数点、ocaml

2D配列を印刷する方法 - 配列、リスト、印刷、浮動小数点、ocaml

ここで何が間違っていますか?

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は2

私はあなたのコードについていくつかアドバイスをしたいのですが。

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.