Search code examples
haskellcustom-data-type

Haskell Type Matching Error in custom data type with List/Tuple Construction


I do not understand why this does not work. My data type is as follows:

data IndexedTree a = Leaf [a] | Node [(IndexedTree a, a)]

first (x, _ ) = x
test :: IndexedTree a -> Bool
test (Leaf x) = True
test (Node (x:xs)) = test first(x)

yields to

Could not match expected type IndexedTree a0
with actual type (t0,t1)-> t0

in the last LOC. I dont get why this is happening and how to avoid this.


Solution

  • Your definition of test should be:

    test :: IndexedTree a -> Bool
    test (Leaf x) = True
    test (Node (x:xs)) = test (first x)
    

    first (x) is the same as first x, and since function application associates to the left

    test first (x)
    

    is parsed as

    (test first) x
    

    test expects an IndexedTree a argument but first has type (a, b) -> a, hence the error.

    You should also handle the case where the node list is empty.