检查矩阵是否包含数字
Check if a matrix contains a number
我想检查 [[a,b,c][d,e,f]] 类型的矩阵是否包含特定数字。
我无法访问列表中的列表。
let matrix = [[1;2;3]; [4;5;6]];;
let rec contains mat x = match mat with
| [] -> false
| h::t -> if (h=x) then true else contains t x;;
这适用于一维列表,但我只是一个新手,无法让它适用于二维列表。
首先,你的函数 contains
是标准库中的 List.mem
(并不是说重新实现它来学习 OCaml 有什么问题)。
另外,if (h=x) then true else contains t x
通常写成(h=x) || contains t x
。
至于你的问题,你需要遍历矩阵的每个子列表(大概代表一行),并为每一行检查它是否包含你要查找的数字:
# let rec mat_contains mat x = match mat with
| [] -> false
| row::tl -> contains row x || mat_contains tl x;;
val mat_contains : 'a list list -> 'a -> bool = <fun>
# mat_contains matrix 4;;
- : bool = true
顺便说一句,这里是使用标准库中的函数编写的:
# let mat_contains2 mat x = List.exists (List.mem x) mat;;
val mat_contains2 : 'a list list -> 'a -> bool = <fun>
# mat_contains2 matrix 4;;
- : bool = true
我想检查 [[a,b,c][d,e,f]] 类型的矩阵是否包含特定数字。 我无法访问列表中的列表。
let matrix = [[1;2;3]; [4;5;6]];;
let rec contains mat x = match mat with
| [] -> false
| h::t -> if (h=x) then true else contains t x;;
这适用于一维列表,但我只是一个新手,无法让它适用于二维列表。
首先,你的函数 contains
是标准库中的 List.mem
(并不是说重新实现它来学习 OCaml 有什么问题)。
另外,if (h=x) then true else contains t x
通常写成(h=x) || contains t x
。
至于你的问题,你需要遍历矩阵的每个子列表(大概代表一行),并为每一行检查它是否包含你要查找的数字:
# let rec mat_contains mat x = match mat with
| [] -> false
| row::tl -> contains row x || mat_contains tl x;;
val mat_contains : 'a list list -> 'a -> bool = <fun>
# mat_contains matrix 4;;
- : bool = true
顺便说一句,这里是使用标准库中的函数编写的:
# let mat_contains2 mat x = List.exists (List.mem x) mat;;
val mat_contains2 : 'a list list -> 'a -> bool = <fun>
# mat_contains2 matrix 4;;
- : bool = true