代码之家  ›  专栏  ›  技术社区  ›  Jose V

模式匹配多参数函数

  •  0
  • Jose V  · 技术社区  · 7 年前

    我试图使这个递归函数 int x x 列表中的元素数量:

    let rec nthcdr int_t list_t =
      match int_t with
      | 0 -> list_t 
      | _ -> (match list_t with
              | [] -> [] 
              | h::tail -> nthcdr (int_t -1) tail)
      ;;
    

    但它不起作用, h::tail []

    1 回复  |  直到 7 年前
        1
  •  1
  •   Pandemonium    7 年前

    我想对代码进行改进作为答案(因为OP已经找到了解决方案)。

    模式匹配一个整数感觉是多余的 int_t if..else 因为整数使代码更干净,并区分基本情况和归纳情况。

    let rec drop n li =
      if n = 0 then li else
      match li with
      | [] -> [] 
      | h::t -> drop (n-1) t