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

201 views Asked by At

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.

1

There are 1 answers

1
Alec On BEST ANSWER

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
             | ...