![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Oct 2005
Location: Missouri
Posts: 9
Rep Power: 0
![]() |
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? |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|