Problem 67

Consider a string representation of a tree such as:

a(b(d,e),c(,f(g,)))

Write a function to generate a string representation of a tree.

Example

tree = 
    Node 'x' 
        (Node 'y' Empty Empty) 
        (Node 'a' 
            Empty 
            (Node 'b' Empty Empty))

s = "x(y,a(,b))"

toString tree == "x(y,a(,b))"

Unit test

import Html
import List
import String


type Tree a
    = Empty
    | Node a (Tree a) (Tree a)


treeToString : Tree a -> String
treeToString tree =
    -- your implementation goes here
    ""


noQuotes : Char -> Bool
noQuotes c = 
    (c /= '\'') && (c /= '\"')


main =
    Html.text
        (if (test) then
            "Your implementation passed all tests."
         else
            "Your implementation failed at least one test."
        )


test : Bool
test =
    List.all ((==) True)
      [ treeToString tChar == "x(y,a(,b))" 
      , treeToString (Node 'z' Empty tChar) == "z(,x(y,a(,b)))" 
      , treeToString (Node 'z' tChar Empty) == "z(x(y,a(,b)),)" 
      , treeToString tString == "x(y,a(,b))" 
      , treeToString tInt == "8(9,1(,2))"
      , treeToString (Node 3 (Node 4 tInt Empty) Empty) 
          == "3(4(8(9,1(,2)),),)"
      ]

tChar = 
    Node 'x' 
        (Node 'y' Empty Empty) 
        (Node 'a' 
            Empty 
            (Node 'b' Empty Empty))

tString = 
    Node "x" 
        (Node "y" Empty Empty) 
        (Node "a" 
            Empty 
            (Node "b" Empty Empty))

tInt = 
    Node 8 
        (Node 9 Empty Empty) 
        (Node 1 
            Empty 
            (Node 2 Empty Empty))

Hints

  1. Solve the problem for just one Tree type first, Tree Int for example.

Solutions

Solutions

results matching ""

    No results matching ""