我对 Ocaml 函数有一些“问题”。
定义 function all_odd
,它对于给定的矩阵作为参数检查所有元素是否都是奇数。
val all_odd : int list list -> bool = <fun>
例子:
#let matrix1 = [[1; 2]; [3; 4]];;
val matrix1 : int list list = [[1; 2]; [3; 4]]
#all_odd matrix1;;
- : bool = false;
You can solve that problem in many way, but the best approach would be to decomposite the problem into simple ones.
Step 1: What's smallest problem to solve? How to check if a number is odd
x mod 2 != 0
Step 2: How to use it for a whole list of numbers
let isOdd list = List.for_all (fun x -> x mod 2 != 0) list
let all_odd matrix =
let isOdd list = List.for_all (fun x -> x mod 2 != 0) list in
List.for_all isOdd matrix
Makes sense?