Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Other Programming Languages (http://www.programmingforums.org/forum38.html)
-   -   ocaml pattern matching (http://www.programmingforums.org/showthread.php?t=9084)

Sysop_fb Mar 28th, 2006 12:49 PM

ocaml pattern matching
 
Kind of confused for some reason... give the following...

:

type expr = Plus of expr * expr        (* means a + b *)
          | Minus of expr * expr      (* means a - b *)
          | Times of expr * expr      (* means a * b *)
          | Divide of expr * expr      (* means a / b *)
          | Value of string            (* "x", "y", "n", etc. *)
          ;;


let rec to_string e =
  match e with
    Plus (left, right)  -> "(" ^ (to_string left) ^ " + " ^ (to_string right) ^ ")"
  | Minus (left, right)  -> "(" ^ (to_string left) ^ " - " ^ (to_string right) ^ ")"
  | Times (left, right)  -> "(" ^ (to_string left) ^ " * " ^ (to_string right) ^ ")"
  | Divide (left, right) -> "(" ^ (to_string left) ^ " / " ^ (to_string right) ^ ")"
  | Value v -> v
  ;;

let print_expr e =
  print_endline (to_string e);;


the matching in to_string is where I'm getting confused a tad
So given this :
Times (Value "n", Plus (Value "x", Value "y"))

Okay while looking it at I think I figured it out... When that goes through the matching I was getting confused on why it called to_string again with each parameter after it found a match but I guess it does it because the parameter can be folded such as the Plus and needs to be recycled to the function.
Right?


All times are GMT -5. The time now is 12:54 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC