0

I am trying to implement a function treeToString that uses this data type:

datatype Tree = LEAF of string | NODE of Tree list;

and this tree:

val L1a = LEAF "a"
val L1b = LEAF "b"
val L1c = LEAF "c"
val L2a = NODE [L1a, L1b, L1c]
val L2b = NODE [L1b, L1c, L1a]
val L3 = NODE [L2a, L2b, L1a, L1b]
val L4 = NODE [L1c, L1b, L3]
val L5 = NODE [L4]

The function takes an argument like treeToString L5 which will output the string ((cb((abc)(bca)ab)))

The problem is I cannot figure out the correct way to differentiate between when the function takes in a LEAF or a NODE type. I wrote the code below to try and test this but I am getting errors. Anyone know the syntax in order to get this to work? Once I get the parameters down, the actual recursion should be easy.

(* treeToString *)
fun treeToString(LEAF str) = str
|   treeToString(NODE h::t) = 
    h;

2 Answers 2

1

This function is what I used to get it working. Just needed to add parenthesis around my arguments

fun treeToString f Node = let
    fun helperFun (LEAF(v)) = [f v]
    |   helperFun (NODE(h::t)) = ["("] @ List.concat (map helperFun(h::t)) @ [")"]
    in
        String.concat(helperFun Node)
end;
Sign up to request clarification or add additional context in comments.

Comments

1

Change this:

|   treeToString(NODE h::t) = ...

To this:

  | treeToString (NODE (h::t)) = ...

The reason is that (NODE h::t) can be interpreted as either ((NODE h)::t) (where NODE h is the first item in a list of NODE's) or as (NODE (h::t)), which is what you want.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.