다음 코드에서 알 수 있듯이 UserAlias를 디코딩하기가 쉽지만 UserType을 디코드하려고 시도하면 즉 D.map2 UserAlias
을 D.map2 UserType
으로 바꿉니다. 컴파일러가 소리내어 울립니다. 이 컴파일러 오류를 어떻게 수정합니까?Elm : Json이 단일 TypeConstructor로 Union 형식을 디코딩하는 방법은 무엇입니까?
import Json.Decode as D
import Html exposing (..)
import Result as R
type UserType = UserType {name:String, age:Int}
type alias UserAlias = {name:String, age:Int}
userDecoder = D.map2 UserAlias
(D.field "name" D.string)
(D.field "age" D.int)
decodeUser json = D.decodeString userDecoder json
json = """
{ "name": "Bob", "age": 40 }
"""
main = div [] [(text << toString << decodeUser) json]
위의 코드는 정상적으로 작동합니다. 이제 D.map2 UserType
그리고 컴파일러 D.map2 UserAlias
을 대체하는 것은 내가이 오류를 수정하려면 어떻게
Detected errors in 1 module.
==================================== ERRORS ====================================
-- TYPE MISMATCH ---------------------------------------------------------------
The 2nd argument to function `map2` is causing a mismatch.
13| D.map2 UserType
14|> (D.field "name" D.string)
15| (D.field "age" D.int)
Function `map2` is expecting the 2nd argument to be:
D.Decoder { age : Int, name : String }
But it is:
D.Decoder String
Hint: I always figure out the type of arguments from left to right. If an
argument is acceptable when I check it, I assume it is "correct" in subsequent
checks. So the problem may actually be in how previous arguments interact with
the 2nd.
-- TYPE MISMATCH ---------------------------------------------------------------
The 1st argument to function `map2` is causing a mismatch.
13|> D.map2 UserType
14| (D.field "name" D.string)
15| (D.field "age" D.int)
Function `map2` is expecting the 1st argument to be:
{ age : Int, name : String } -> b -> UserType
But it is:
{ age : Int, name : String } -> UserType
Hint: It looks like a function needs 1 more argument.
, 도와주세요 울고!
기본적으로 나는 내부 레코드 구조를 숨길 수 있고 공용 API를 손상시키지 않고 리팩터링 할 수 있도록 사용자 별 UserType 만 사용하고자한다.
감사합니다.
덕분에 많이, 당신은 보호기 항상 생명이다 : 이제 마지막으로 유형을 사용할 수 있습니다 D 구현 구조를 숨기는 생성자입니다. – Jigar
하지만 여전히 형식 별칭을 사용합니다. OP는 형식 별칭이없는 해결책을 찾고있었습니다 –