Ami*_*min 4 ocaml pattern-matching unused-variables
我想在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
Run Code Online (Sandbox Code Playgroud)
问题:当它被调用时,无论我们匹配什么四倍,它都会返回原始列表.此外,问题是返回警告,行,(警告)的x,y,r 未使用.
正如吉安所说,警卫是你问题的解决方案.好消息是代码可以更接近您的书面规范:
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
;;
Run Code Online (Sandbox Code Playgroud)
微小的测试:
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)]
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以使用List.filter:
let constrained_by (x,y,z,_) = List.filter (fun (x',y',z',_) -> x = x' or y=y' or z=z');;
Run Code Online (Sandbox Code Playgroud)