【问题标题】:Nested pattern matching in OcamlOcaml 中的嵌套模式匹配
【发布时间】:2013-03-21 09:35:18
【问题描述】:

我想在 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

问题:当它被调用时,无论我们匹配什么四元组,它都会返回原始列表。 此外,问题在于它返回警告,即第 (warning) 行的 x,y, r 未使用。

【问题讨论】:

    标签: pattern-matching ocaml unused-variables


    【解决方案1】:

    正如 Gian 所说,守卫是解决问题的方法。好消息是代码可以更接近您的书面规范:

    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');;
    

    【讨论】:

      【解决方案2】:

      我认为您在那里误用了模式匹配。像Cell(x,_,_,Some(_)) 这样的模式将匹配任何内容,因为它正在重新绑定x。在作用域中有一个变量x 的事实并不意味着它会坚持认为该元组元素与x 具有相同的值。您的三个模式在结果匹配上是完全等价的。

      如果您希望通过这种方式完成任务,您可能需要考虑使用守卫。

      【讨论】:

        猜你喜欢
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-31
        • 1970-01-01
        • 2022-08-06
        • 1970-01-01
        • 2011-03-03
        相关资源
        最近更新 更多