Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding extensible records in Elm

Tags:

decode

elm

I have been using extensible records in elm (0.18). My model contains these types:

type alias Cat c =
    { c
        | color : String
        , age : Int
        , name : String
        , breed : String
    }

type alias SimpleCat =
    Cat {}

type alias FeralCat =
    Cat
        { feral : Bool
        , spayed : Bool
        }

Now I want to be able to pass these types into a decoder. I typically use the elm-decode-pipeline library "NoRedInk/elm-decode-pipeline": "3.0.0 <= v < 4.0.0".

I set up this type:

catDecoder : Decode.Decoder SimpleCat
catDecoder = 
  Pipeline.decode SimpleCat
    |> Pipeline.required "color" Decode.string
    |> Pipeline.required "age" Decode.int
    |> Pipeline.required "name" Decode.string
    |> Pipeline.required "breed" Decode.string

But I get this error:

-- NAMING ERROR --------------------------------------------- ./src/Decoders.elm

Cannot find variable `SimpleCat`

141|     Pipeline.decode SimpleCat

This doesn't happen with my non-extensible types. Is there any way to use these types with decoders? (elm-decode-pipeline preferred, but I'd like to know if there is another way)

like image 812
Mark Karavan Avatar asked Feb 19 '26 09:02

Mark Karavan


1 Answers

Extensible records unfortunately do not currently (as of Elm 0.18) allow for creating them using their alias name as a constructor. You could instead write your own constructor function:

simpleCatConstructor : String -> Int -> String -> String -> SimpleCat
simpleCatConstructor color age name breed =
    { color = color, age = age, name = name, breed = breed }

Then you can substitute that in the call to decode:

catDecoder = 
    Pipeline.decode simpleCatConstructor
        |> Pipeline.required "color" Decode.string
        ...
like image 144
Chad Gilbert Avatar answered Feb 24 '26 15:02

Chad Gilbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!