Loading ...
Sorry, an error occurred while loading the content.

4894Re: "ocaml_beginners"::[] unbound value

Expand Messages
  • Richard Jones
    Nov 1, 2005
    • 0 Attachment
      On Tue, Nov 01, 2005 at 12:59:21PM +0100, Java wrote:
      [...]

      Someone else has found the obvious error; I have a few other
      observations to make:

      > val insert: 'a * 'a tree -> 'a tree
      >
      > val search: 'a * 'a tree -> bool

      You're using tuples as parameters, like ML (IIRC). Your code will run
      significantly faster if you define functions with separate parameters,
      like this:

      (* interface: *)
      val search : 'a -> 'a tree -> bool

      (* implementation: *)
      let rec search x tree =
      match tree with
      | Empty -> false
      | Node (y, left, right) ->
      if (x = y) then true
      else if (x > y) then search x right
      else search x left

      Now, the above code can be made shorter (but probably not any faster)
      by writing instead:

      let rec search x = function
      | Empty -> false
      | Node (y, left, right) ->
      if (x = y) then true
      else if (x > y) then search x right
      else search x left

      and as a stylistic alternative you could use guards, although again
      this will not necessarily improve the speed of the code (might even
      make it slower):

      let rec search x = function
      | Empty -> false
      | Node (y, _, _) when x = y -> true
      | Node (y, _, right) when x > y -> search x right
      | Node (_, _, left) -> search x left

      > For the function "search" the interpreter returns me this error:
      > Characters 475-480:
      > Unbound value right

      You're using a rather ancient version of Ocaml. Since around 3.08,
      Ocaml has reported line number and position within line, which is a
      lot more useful for locating the source of errors.

      Rich.

      --
      Richard Jones, CTO Merjis Ltd.
      Merjis - web marketing and technology - http://merjis.com
      Team Notepad - intranets and extranets for business - http://team-notepad.com
    • Show all 15 messages in this topic