我有这个问题仍然困扰我很多。我有(string * string list) list
,我想将其转换为布尔矩阵。
转换时我有一个特殊情况。例如,我有这个列表:
let entries = [("name", ["string"; "label"]); ("label", ["int"; "name"]);
("symbol", ["string"])]
其中“string
”和“int
”是未定义类型,未定义类型,因为在我的实际数据中,我没有描述此类型的定义。所以我构建了一个未定义类型的列表。
let undefined = ["string"; "int"]
列表中的第一个位置(“name
”,“label
”,“symbol
”是定义的类型,定义的类型是我在数据中定义的类型
let defined = ["name"; "label"; "symbol"]
我正在尝试这样做:从entries
,位置应该是:
name: 2; string: 0; label: 3; int: 1; symbol: 4
当从列表entries
显示依赖关系时,它不会改变它们的位置。例如:name(2)
链接到string(0)
和label(3)
,而label (3)
的边缘为int(1)
和name (2)
,`等等。
我让这些函数在列表中返回一个位置(num_of_name
)和元素(name_of_num
)。
let rec position x = function
| [] -> raise Not_found
| y :: ys -> if x = y then 0 else 1 + position x ys
let len_undefined = List.length undefined
let num_of_name defined undefined len_undefined s =
try (position s defined) + len_undefined;
with Not_found -> position s undefined
let name_of_num defined undefined len_undefined k =
if k < len_undefined then
List.nth undefined k else
List.nth defined (k - len_undefined)
因此,从entries
列表中我想构建一个布尔矩阵,使用函数num_of_name
显示关系。所以我写了我的功能:
let matrix =
let len = List.length defined + len_undefined in
let boolmat = Array.make_matrix len len false in
List.iter (fun (s, strs) ->
let pos1 = num_of_name defined undefined len_undefined s in
List.iter (fun t ->
let pos2 = num_of_name defined undefined len_undefined t in
boolmat.(pos1).(pos2) <- true) strs) entries;
boolmat
let print_mat m =
for i = 0 to Array.length m - 1 do
for j = 0 to Array.length m.(0) - 1 do
print_string (string_of_bool m.(i).(j));
Printf.printf " ";
done;
Printf.printf " \n";
done;
;;
let test_print = print_mat matrix
返回错误“Fatal error: exception Not_found
”
我需要你的帮助。 非常感谢!!
答案 0 :(得分:1)
正如我在评论中所说,您的num_of_name
函数很脆弱,因为当它的输入不是Not_found
或defined
的元素时会抛出undefined
异常。一种解决方法是使用Option
类型:
let num_of_name defined undefined len_undefined s =
try
let p = position s defined in
Some (p + len_undefined)
with Not_found ->
try
let p = position s undefined in
Some p
with Not_found -> None
和matrix
计算如下:
let matrix =
let len = List.length defined + len_undefined in
let boolmat = Array.make_matrix len len false in
List.iter (fun (s, strs) ->
match num_of_name defined undefined len_undefined s with
| Some pos1 -> List.iter (fun t ->
match num_of_name defined undefined len_undefined t with
| Some pos2 -> boolmat.(pos1).(pos2) <- true
| None -> ()) strs
| None -> ()
) entries;
boolmat
当然,如果您通过从defined
中提取undefined
和entries
来强制执行您的程序,那么您的代码是正确的。