syntaxocaml

Syntax error regarding line 15 characters 27-34 in an OCaml tree search function


I wrote the function below to look through a tree and return a list in increasing order that contains all the indexes/subscripts of even elements in the tree. However I am getting a syntax error at the line let rec GetSubEvenGen tree counter list = about the argument counter. When prompting chat GPT about this it failed to spot any errors. I'd appreciate any advice on why a syntax error is being raised.

 type 'a tree = 
  |Lf 
  |Br of 'a * 'a tree * 'a tree;; 

exception Subscript
let rec look = function
  | Lf, _ -> raise Subscript 
  | Br (v, t1, t2), k ->
      if k = 1 then v
      else if k mod 2 = 0 then
        look (t1, k / 2)
      else
        look (t2, k / 2);; 

let rec GetSubEvenGen tree counter list = 
  try
    let element = look (tree, counter) in
    if element mod 2 = 0 then
      GetSubEvenGen tree (counter + 1) (element::list)
    else
      GetSubEvenGen tree (counter + 1) (list)
  with 
    Subscript -> List.rev(list);;

let getSubsOfEvens tree = GetSubEvenGen tree 1 [];;

I tried running this code, I expected it to be syntactically correct, however a syntax error was raised.


Solution

  • Function names in OCaml must begin with lowercase letters. Your GetSubEvenGen name causes the syntax error.

    Fixing this, your code compiles without issue:

    # type 'a tree =
        | Lf
        | Br of 'a * 'a tree * 'a tree
    
      exception Subscript
    
      let rec look = function
        | Lf, _ -> raise Subscript
        | Br (v, t1, t2), k ->
          if k = 1 then v
          else if k mod 2 = 0 then
            look (t1, k / 2)
          else
            look (t2, k / 2)
    
      let rec getSubEvenGen tree counter list =
        try
          let element = look (tree, counter) in
          if element mod 2 = 0 then
            getSubEvenGen tree (counter + 1) (element::list)
          else
            getSubEvenGen tree (counter + 1) (list)
        with
          Subscript -> List.rev(list)
    
      let getSubsOfEvens tree = 
        getSubEvenGen tree 1 [];;
    type 'a tree = Lf | Br of 'a * 'a tree * 'a tree
    exception Subscript
    val look : 'a tree * int -> 'a = <fun>
    val getSubEvenGen : int tree -> int -> int list -> int list = <fun>
    val getSubsOfEvens : int tree -> int list = <fun>