代码之家  ›  专栏  ›  技术社区  ›  Andrej Korowacki

OCaml:和关键字语法错误

  •  1
  • Andrej Korowacki  · 技术社区  · 7 年前

    我已经编写了这个mergesort实现,如果我将divide函数放在mergesort函数之外,它会很好地工作。但是,当我试图将divide作为mergesort的内部函数时,我遇到了一个语法错误。

    我知道,一定有一些非常简单的解释。我在网上找遍了,但什么也没找到。

    let mergesort list = 
      let rec sort lists acc = (
        let rec merge sublist1 sublist2 merged_list =
        match sublist1 with
          |[] -> merged_list @ sublist2
          |hd1 :: tl1 -> 
            match sublist2 with
              |[] -> merged_list @ sublist1
              |hd2 :: tl2 -> 
                if hd1 < hd2 then merge tl1 sublist2 (merged_list @ hd1::[])
                else merge sublist1 tl2 (merged_list @ hd2::[])
        in match lists with 
          |[] -> 
            (match acc with
              |[] -> []
              |hd :: [] -> hd
              |_ -> sort acc [])
          |hd :: tl -> sort (List.tl tl) ((merge (List.hd tl) hd [])::acc)  
      )
      and rec divide list list_of_lists = (
        match list with
          [] -> list_of_lists
          |hd :: tl -> divide tl ((hd :: []) :: list_of_lists)
      )
      in sort (divide list []) []
    ;; 
    

    结果是:

    Characters 567-570:
    and rec divide list list_of_lists = (
        ^^^
    Error: Syntax error
    
    2 回复  |  直到 7 年前
        1
  •  2
  •   ivg    7 年前

    A. local definition 在OCaml中具有以下语法:

    let [rec] pattern1 =  expr1 and … and  patternN =  exprN in expr
    

    因此,额外 rec 不允许在 and 关键字,并且仅在第一个 let . 这个 标志扩展到本地定义中定义的所有值,因此您只需要删除这个错误的 rec公司 之后 .

        2
  •  1
  •   Nick Zuber    7 年前

    您只需删除 rec 关键字从您的定义那里。

    这是因为当你使用 and let rec .

    因此,您当前的实现实际上与以下内容相同: let rec rec