Search code examples
haskellghcjs-dom

Map of GType to function transforming a type to an IO String


This map is between a GType and an function that transforms an instance of that GType to an IO String. I am making a function that takes an element and gets a string representation of that element.

mapping =
    [ (Types.gTypeHTMLSourceElement, HTMLSourceElement.getSrc   )
    , (Types.gTypeHTMLObjectElement, HTMLObjectElement.getData  )
    , (Types.gTypeHTMLTimeElement  , HTMLTimeElement.getDateTime)
    , (Types.gTypeHTMLElement      , HTMLElement.getInnerText   )
    , ...
    ]

Gives this error:

Couldn't match type ‘HTMLObjectElement’ with ‘HTMLSourceElement’

I am using ghcjs-dom. How can I get this code to compile without errors? Am I approaching the problem in the right way?

If anyone can come up with answer better than Alec's answer I will accept their answer.


Solution

  • I think the right way to approach the problem is to just make one toString function that does the branching based on the GType.

    toString :: GObjectClass obj => obj -> IO String
    toString obj | obj `isA` gTypeHTMLSourceElement = getSrc . castToHTMLSourceElement
                 | obj `isA` gTypeHTMLObjectElement = getData . castToHTMLObjectElement
                 | obj `isA` gTypeHTMLTimeElement = getDateTime . castToHTMLTimeElement
                 | obj `isA` gTypeHTMLElement = getInnerText . castToHTMLElement
                 | ...