代码之家  ›  专栏  ›  技术社区  ›  charelf

ocaml错误:需要语法错误:“)”,但找不到

  •  0
  • charelf  · 技术社区  · 7 年前

    这是我的代码:

    type noeud = Lettre of (char * bool * arbre_lex)
    and arbre_lex = noeud list
    
    exception Deja_defini of string
    
    
    
    let rec ajoute mot arbre n =
        if existe mot arbre then raise (Deja_defini mot) else
        match arbre with
            | [] ->
                begin
                    if n+1 = String.length mot then [ Lettre( mot.[n] , true , [] ) ]
                    else [ Lettre ( mot.[n] , false, ajoute mot arbre (n+1) ) ]
                end
            | head::tail ->
                begin
                    match head with 
                        | Lettre (mot.[n], b, a) -> (*line 19, source of error*)
                            begin
                                if n+1 = String.length mot then [ Lettre ( mot.[n] , true , a ) ]::tail 
                                else [ Lettre ( mot.[n] , b , ajoute mot a (n+1) ) ]::tail
                            end
                        | Lettre (_, b, a) -> ajoute mot tail n
                end
    

    编译时,出现以下错误:

    $ocamlc -o main *.ml
    File "main.ml", line 19, characters 21-22:
    Error: Syntax error: ')' expected
    File "main.ml", line 19, characters 17-18:
    Error: This '(' might be unmatched
    

    现在我知道我可以改进我的代码,我可以在第一个代码中包含第二个匹配项, 我特别想找出错误的根源 . 我试了很多方法,但没有一个能改变错误。

    所以可以随意发布改进,但我最感兴趣的是如何运行这段精确的代码来帮助避免将来出现错误

    0 回复  |  直到 7 年前
        1
  •  2
  •   glennsl Namudon'tdie    7 年前

    箭头左侧的句法结构不是一个普通的表达式,而是一个模式。为了方便起见,它看起来非常像一个表达式,但其行为却非常不同。它也是一个纯编译时构造。

    例如,模式 a ,就像 Lettre (_, b, a) 不会计算为 ,或匹配 根据名为 . 相反,它将生成一个名为 指的是 ,并隐藏该名称以前的任何绑定。

    例如,如果你要匹配的值是 Lettre ('a', true, []) , 将,在箭头的右侧,参考值 [] . 和 b 将参考 true .

    除了可以方便地将值绑定到模式中的名称之外,不允许模式中的运行时值还允许编译器保证模式匹配的详尽性,并在编译时对其进行优化。如果模式中允许运行时值,则必须始终提供通配符模式来捕获其余的可能性,因为在编译时无法知道哪些可能性在运行时可能匹配。

    我希望你现在明白为什么不允许像 mot.[n] ,甚至是绑定到 [n] ,在模式中。

    然而,有一个独立于模式的构造允许在模式匹配中使用运行时条件,称为“guards”或“when”子句。用你的例子:

    match head with 
        | Lettre (ch, b, a) when ch = mot.[n] -> ...
    

    这确实需要一个用通配符代替 ch 把警卫不匹配的箱子都盖上。但既然你已经拥有了,你就应该做个好人。