Skip to content

Commit 81bb38f

Browse files
zlh20040308sabine
andauthored
(exercises) implement tree_of_string function for problem 70A (#3135)
* feat: implement tree_of_string function for problem 70A * break up into three REPL statements --------- Co-authored-by: sabine <6594573+sabine@users.noreply.github.com>
1 parent 1fc33bb commit 81bb38f

File tree

1 file changed

+27
-3
lines changed

1 file changed

+27
-3
lines changed

data/exercises/070A_create_mtree.md

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,13 +19,37 @@ type 'a mult_tree = T of 'a * 'a mult_tree list
1919
let rec add_string_of_tree buf (T (c, sub)) =
2020
Buffer.add_char buf c;
2121
List.iter (add_string_of_tree buf) sub;
22-
Buffer.add_char buf '^'
23-
let string_of_tree t =
22+
Buffer.add_char buf '^';;
23+
val add_string_of_tree : Buffer.t -> char mult_tree -> unit = <fun>
24+
25+
# let string_of_tree t =
2426
let buf = Buffer.create 128 in
2527
add_string_of_tree buf t;
2628
Buffer.contents buf;;
27-
val add_string_of_tree : Buffer.t -> char mult_tree -> unit = <fun>
29+
2830
val string_of_tree : char mult_tree -> string = <fun>
31+
32+
# let tree_of_string s =
33+
let rec parse_node chars =
34+
match chars with
35+
| [] -> failwith "Unexpected end of input (expecting node)"
36+
| c :: rest ->
37+
let (children, rest') = parse_children rest in
38+
(T (c, children), rest')
39+
and parse_children chars =
40+
match chars with
41+
| [] -> failwith "Unexpected end of input (expecting ^)"
42+
| '^' :: rest -> ([], rest)
43+
| _ ->
44+
let (child, rest') = parse_node chars in
45+
let (siblings, rest'') = parse_children rest' in
46+
(child :: siblings, rest'')
47+
in
48+
let (tree, remaining) = parse_node (List.of_seq (String.to_seq s)) in
49+
match remaining with
50+
| [] -> tree
51+
| _ -> failwith "Extra input after tree";;
52+
val tree_of_string : string -> char mult_tree = <fun>
2953
```
3054

3155
# Statement

0 commit comments

Comments
 (0)