Created
October 26, 2016 15:08
-
-
Save natec425/6a357de640fec2b5ddacb6a1f337f137 to your computer and use it in GitHub Desktop.
Elm - Json.Decode reuse with Extensible Records
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Scratch exposing (..) | |
import Json.Decode exposing (..) | |
type alias Item a = | |
{ a | |
| field1 : String | |
, field2 : String | |
, field3 : String | |
} | |
type alias Foo = | |
{ foo : String } | |
type alias ItemConstructor a = | |
String -> String -> String -> a -> Item a | |
emptyItem : ItemConstructor {} | |
emptyItem f1 f2 f3 _ = | |
{ field1 = f1 | |
, field2 = f2 | |
, field3 = f3 | |
} | |
fooItem : ItemConstructor Foo | |
fooItem f1 f2 f3 a = | |
{ field1 = f1 | |
, field2 = f2 | |
, field3 = f3 | |
, foo = a.foo | |
} | |
decodeItem : ItemConstructor a -> Json.Decode.Decoder a -> Json.Decode.Decoder (Item a) | |
decodeItem constructor decodeA = | |
Json.Decode.object4 constructor | |
("field1" := Json.Decode.string) | |
("field2" := Json.Decode.string) | |
("field4" := Json.Decode.string) | |
decodeA | |
decodeEmptyItem : Json.Decode.Decoder (Item {}) | |
decodeEmptyItem = | |
decodeItem emptyItem (Json.Decode.succeed {}) | |
decodeFooItem : Json.Decode.Decoder (Item Foo) | |
decodeFooItem = | |
decodeItem fooItem decodeFoo | |
decodeFoo : Json.Decode.Decoder Foo | |
decodeFoo = | |
("foo" := Json.Decode.string) | |
|> Json.Decode.map Foo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment