Question

I'm new to Haskell and want to get the values of the leafs of a self-defined Tree into a record. I started with this.

data MyTree = A Int | B Int MyTree | C Double | D Double MyTree 

test = B 1 ( B 1( D 0.02(A 2)))


data MyRecord = MyRecord {A, B :: Int, C :: Double, D :: (Int,Double)}
emptyRecord = MyRecord{a = 0, b = 0, c = 0, d =(0,0)}

Now i started like this:

MyTree2MyRecord :: MyTree -> MyRecord
MyTree2MyRecord(A a1) = emptyRecord{a = a1}
MyTree2MyRecord(B b1 myTree) = emptyRecord {b = b1}
MyTree2MyRecord(C c1) = emptyRecord {c = c1}
MyTree2MyRecord(D d1 myTree) = emptyRecord {d = d1}
 where mytree = MyTree2MyRecord -{dont know the recursive call to iterate through the tree and get the values of the leafs} 

I understand the simple examples like sum up the leafs of a tree etc, but cant figure out a solution for this problem. I would really appreciate a small hint. Thanks guys

Was it helpful?

Solution

There are some problems with your code:

  • Function name should start with small case letters. Hence the record data structure should be like this:

data MyRecord = MyRecord {a, b :: Int, c :: Double, d :: (Int,Double)}

  • And your function name should be like this:

myTree2MyRecord :: MyTree -> MyRecord

Now going through your actual code, you seem to be in almost right path. But in order to find the solution, you have to answer some of these questions:

  • What exactly does the Int denote in d :: (Int, Double) ?

  • When you are pattern matching for data constructors like A, B etc., you seem to be assigning the values of the MyTree ADT to the record. Think about the recursive case there. What output do you want for input like this:

myTree2MyRecord (B 1 (B 1 (A 1)))

Your current implementation just discards the value of MyTree in it:

myTree2MyRecord(B b1 myTree) = emptyRecord {b = b1}

Instead of discarding think what should happen to myTree in this case. This will lead to a recursive solution.

And finally, formulate what output do you want for the input which you have given for the question:

test = B 1 ( B 1( D 0.02(A 2)))

Once you answer these question, I think you will refactor the code and solve this problem yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top