pattern-matching - Ocaml 中的嵌套模式匹配

标签 pattern-matching ocaml 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

问题:当它被调用时,无论我们匹配什么四元组,它都会返回原始列表。
此外,问题是它返回警告,即行(警告)处的 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/

相关文章:

haskell - 我什么时候应该使用 as-patterns 来识别常见的子表达式?

PostgreSQL:匹配带或不带子域的电子邮件地址

ios - 使用变量时NSString中的“Expression myExpression未使用”

suppress-warnings - 在 Kotlin 中标记未使用的参数

c - "Pattern matching"并在 C 中提取

scala - 如何系统地避免 Scala 中的不安全模式匹配?

list - ocaml 使用 List.map 遍历列表

haskell - OCaml 有融合定律吗

functional-programming - 禁止OCaml中的详尽匹配警告

c++ - “(void) cast”和 “__attributes__”在沉默未使用的参数警告方面有什么功能区别?