[Haskell-beginners] "downcasting"

Emmanuel Touzery etouzery at gmail.com
Thu Oct 25 00:00:59 CEST 2012


Hello,

     using the Text.Json library (and I'm reading I should be using 
Aeson instead... I'll migrate to it later), I'm a bit frustrated.

     At one point I'm getting a JSValue object, which could be anything, 
including a JSObject.
     But in this case I know I'm looking at a JSObject. I don't mind if 
Haskell crashes if that's not the case (for now), either it's a JSObject 
or the JSON I'm parsing is invalid.

     I hoped to do that conversion using pattern matching by giving 
non-exhaustive pattern match, considering only cases where the JSValue 
is in fact a JSONObject but somehow I can't make it...

getObject :: JSValue -> JSObject JSValue
getObject x@(JSObject _) = x

--> doesn't compile the function returns a JSValue, I somehow wanted to 
point out to the compiler that if it gets there it's in fact a JSObject.

getObject :: JSValue -> JSObject JSValue
getObject (JSObject x) = JSObject x

-> same as with the other attempt.. the compiler is saying the function 
is returning a JSValue:

  Couldn't match expected type `JSObject JSValue'
              with actual type `JSValue'
  In the return type of a call of `JSObject'
  In the expression: JSObject x
  In an equation for `getObject': getObject (JSObject x) = JSObject x

  I think I'm missing an obvious pattern in Haskell here, probably 
something I've already used elsewhere too, but somehow I don't make it.

   Otherwise answers saying that if I need to make such a "cast" then 
I'm using that library the wrong way are welcome (together to maybe a 
link to a tutorial explaining it the right way), but by curiosity I 
would still be interested in how to actually do that "cast" in this case.

    Thank you!

Emmanuel



More information about the Beginners mailing list