代码之家  ›  专栏  ›  技术社区  ›  Teodor Kostovski

OCaml中的嵌套函数及其参数

  •  0
  • Teodor Kostovski  · 技术社区  · 3 年前

    我对如何在OCaml中实现嵌套函数有一个问题,我需要一个函数的输出(列表)作为另一个函数的输入。两者都应该是递归的。问题是我一直在玩弄这些参数,但它们并没有正常输入:

    let toComb sentence =  
      let rec listCleanup sentence = 
        match sentence with
        | [] -> []
        | h::t when h = "" -> listCleanup t
        | h::t -> h::listCleanup t
      in
      let rec toString listCleanup sentence = 
        match listCleanup sentence  with
        | [] -> ""
        | [element] -> element
        | h::t -> h ^ " " ^ toString listCleanup sentence  
      in 
      toString listCleanup sentence;;
    

    如果我使用函数及其参数作为参数,会出现堆栈溢出,但如果只使用没有参数的函数,则会出现参数不匹配。这里该怎么解决?

    1 回复  |  直到 3 年前
        1
  •  2
  •   jthulhu    3 年前

    要更正代码,以下是正确工作的方法:

    let to_comb sentence =
      let rec cleanup s = match s with
        | [] -> []
        | ""::tail -> cleanup tail
        | hd::tail -> hd::cleanup tail in
      let rec to_string s = match s with
        | [] -> ""
        | [x] -> x
        | hd::tail -> hd ^ " " ^ to_string tail in
      to_string (cleanup s)
    

    请注意,我只打电话 cleanup 一次,因为你只需要清理整个序列一次。然而,事实证明,使用预定义的OCaml函数可以更简单地表达这两个函数:

    let to_comb sentence =
      sentence
      |> List.filter (fun s -> s <> "")
      |> String.concat " "
    

    你几乎可以大声读出这段代码来描述它的功能。它从一个句子开始,过滤其中的空单词,然后用空格连接它们。