Isn't this supposed to be implemented like this:
import Html exposing (text)
import Json.Decode exposing (..)
type alias Circle = { radius : Float }
type alias Rectangle = { width: Float, height: Float }
type Shape =
CircleAsShape Circle
| RectangleAsShape Rectangle
circleDecoder =
map Circle (field "radius" float)
rectangleDecoder =
map2 Rectangle
(field "width" float)
(field "height" float)
shapeDecoder =
field "@type" string
|> andThen toShape
toShape str =
case str of
"Circle" ->
map CircleAsShape circleDecoder
"Rectangle" ->
map RectangleAsShape rectangleDecoder
_ ->
fail ("unknown shape: " ++ str)
rawJSON = """
[ { "@type" : "Circle", "radius": 3}
, { "@type" : "Rectangle", "width" : 1, "height": 2 }
]
"""
main =
text <| toString <| decodeString (list shapeDecoder) rawJSON
On Wed, Dec 21, 2016 at 1:38 PM, 'Rupert Smith' via Elm Discuss <
[email protected]> wrote:
> Struggling to figure this out, but it may be because I'm in an open plan
> office and its just too noisy to concentrate...
>
> Suppose I have decoders for two records:
>
> type alias Circle = { radius : Float }
> type alias Rectangle = { width: Float, height: Float }
>
> On the server side though, these are actually a class hierarchy, with
>
> Circle <: Shape
> Rectangle <: Shape
>
> Where <: means 'subtype of'.
>
> When serializing over json, a discriminator field is added, so the json
> looks like:
>
> {
> @type : "Circle",
> radius : ...
> }
>
> {
> @type : "Rectangle",
> width : ...
> }
>
> I have decoders for circles and rectangles already defined:
>
> circleDecoder : Decoder Circle
> rectangleDecoder : Decoder Rectangle
>
> and am now trying to write the decoder for Shape:
>
> type Shape =
> CircleAsShape Circle
> | RectangleAsShape Rectangle
>
> shapeDecoder : Decoder Shape
> shapeDecoder =
> succeed (some function from '@type' to circle or rectangle decoder
> mapped to shape decoder)
> |: (field "@type" Decode.string)
>
> Feels about the right form for it. Exception this will return a Decoder
> (Decoder Shape) instead of a Decoder Shape.
>
> Can someone explain how to do this?
>
> --
> You received this message because you are subscribed to the Google Groups
> "Elm Discuss" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> For more options, visit https://groups.google.com/d/optout.
>
--
There is NO FATE, we are the creators.
blog: http://damoc.ro/
--
You received this message because you are subscribed to the Google Groups "Elm
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.