我想在 Ocaml 中编写一个函数,给出一个四元组列表和一个四元组 (x,y,z,f),返回一个包含元组 (x',y',z',g) 的列表,使得 x = x' 或 y=y' 或 z = z'(这些是整数)。这是我的第一次尝试
let rec constrained_by c list =
match s with
| []-> []
| hd :: tl ->
begin
let Cell(x,y,r,_)= c in (*warning*)
begin
match hd with
| Cell(x,_,_,Some(_))-> hd::constrained_by c tl
| Cell(_, y, _,Some(_)) -> hd::constrained_by c tl
| Cell(_, _, r,Some(_)) -> hd::constrained_by c tl
| _ -> constrained_by c tl
end
end
问题:当它被调用时,无论我们匹配什么四元组,它都会返回原始列表。
此外,问题是它返回警告,即行(警告)处的 x、y、r 未使用。
最佳答案
正如 Gian 所说, guard 可以解决您的问题。好消息是代码可以更接近您的书面规范:
let rec constrained_by ((x,y,z,_) as c) list = match list with
| [] -> []
| ((x',y',z',_) as c') :: tl when x = x' or y=y' or z=z' ->
c' :: constrained_by c tl
| hd :: tl -> constrained_by c tl
;;
小测试:
let _ = constrained_by (1,2,3,"foo") [1,0,0,0; 0,2,0,0; 0,0,3,0; 0,0,0,0];;
- : (int * int * int * int) list = [(1, 0, 0, 0); (0, 2, 0, 0); (0, 0, 3, 0)]
请注意,您也可以使用
List.filter
:let constrained_by (x,y,z,_) = List.filter (fun (x',y',z',_) -> x = x' or y=y' or z=z');;
关于pattern-matching - Ocaml 中的嵌套模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15543788/