Skip to content

Instantly share code, notes, and snippets.

@natec425
Created October 26, 2016 15:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natec425/6a357de640fec2b5ddacb6a1f337f137 to your computer and use it in GitHub Desktop.
Save natec425/6a357de640fec2b5ddacb6a1f337f137 to your computer and use it in GitHub Desktop.
Elm - Json.Decode reuse with Extensible Records
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