2017-12-18 38 views
1

나는 elm (0.18)에서 확장 가능한 레코드를 사용 해왔다. 내 모델에 다음 유형이 있습니다.Elm에서 확장 가능한 레코드 디코딩

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 
     } 

이제 이러한 유형을 디코더에 전달할 수 있기를 바랍니다. 필자는 일반적으로 elm-decode-pipeline 라이브러리 "NoRedInk/elm-decode-pipeline": "3.0.0 <= v < 4.0.0"을 사용합니다.

나는이 유형 설정 :

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 

을하지만이 오류 얻을 :

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

Cannot find variable `SimpleCat` 

141|  Pipeline.decode SimpleCat 

이 내 비 확장 유형과 발생하지 않습니다. 이러한 유형의 디코더를 사용하는 방법이 있습니까? (엘름 - 디코드 - 파이프 라인 선호,하지만 다른 방법이 있는지 알고 싶습니다.)

답변

4

확장 가능 레코드는 불행히도 현재 (Elm 0.18 현재) 별칭 이름을 생성자로 사용하여 생성 할 수 없습니다.

catDecoder = 
    Pipeline.decode simpleCatConstructor 
     |> Pipeline.required "color" Decode.string 
     ... 
+0

난 그 두려워 :

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

는 그런 다음 decode에 대한 호출에 있음을 대체 할 수 있습니다 : 당신은 대신 자신의 생성자 함수를 작성할 수 있습니다. 이러한 모든 유형의 디코더가 필요하다고 가정하면이 기술은 확장 성이없는 레코드를 만드는 것 이상의 이점을 제공합니까? –

+1

/Elm이 확장 가능한 방식으로 정의 된 유형을 생성자로 사용할 수있게 될 때까지'Cat a' 별칭과 여전히 일치하므로'FeralCat' 정의에서 모든 속성을 나열하는 것이 좋습니다. –