【问题标题】:recursive function that iterates through a list of tuples (int * int) and adds the second value遍历元组列表 (int * int) 并添加第二个值的递归函数
【发布时间】:2018-04-07 07:29:52
【问题描述】:

我想编写一个函数,它遍历一个元组列表 (int * int),如果元组的第一个值是 int 0,则添加元组的第二个值。然而,我想出了以下代码,它在每种情况下都会引发异常,有人能指出函数中的错误是什么吗?提前致谢!

let rec tup x = match x with (a,b)::t -> if a > 0 then b + tup(t) else 0 + tup(t) | []->failwith("a");;    

test case: (int * int) list = [(0, 2); (1, 10); (0, 20)] should return 10 

【问题讨论】:

    标签: list tuples ocaml


    【解决方案1】:

    您将此函数设计为递归的,因此它的最后一次调用将始终与[] 匹配。如果您将failwith("a") 更改为0,函数将按预期工作:

    let rec tup x = match x with 
        (a,b)::t -> if a > 0 then b + tup(t) else tup(t) 
        | [] -> 0
    ;;    
    

    结果:

    # tup [(0,2); (1,10); (0,20)];;
    - : int = 10
    # tup [(3,4); (1,10); (0,20)];;
    - : int = 14
    # tup [];;  (* You don't want to fail in this case *)
    - : int = 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 2023-01-31
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多