Purescript Simple JSON,结合记录类型

时间:2018-01-04 08:46:53

标签: json purescript

我是Purescript的新手,并尝试使用purescript-simple-json:

  1. 获取一些JSON并将其转换为User
  2. 的记录
  3. 获取更多JSON并将其转换为Comment
  4. 的记录数组
  5. 取结果2.并将其放入从1生成的用户记录的comments字段中。
  6. 以下是我的尝试:

    module Test where
    
    import Prelude
    
    import Data.Either (Either)
    import Data.Foreign (ForeignError)
    import Data.Generic.Rep as Rep
    import Data.Generic.Rep.Show (genericShow)
    import Data.List.NonEmpty (NonEmptyList)
    import Simple.JSON (class ReadForeign, readJSON)
    
    newtype Comment = Comment
      { rating :: Int
      , username :: String
      }
    
    newtype User = User
      { username :: String
      , comments :: Array Comment
      }
    
    derive instance repGenericUser :: Rep.Generic User _
    instance showUser :: Show User where show = genericShow
    
    derive instance repGenericComment :: Rep.Generic Comment _
    instance showComment :: Show Comment where show = genericShow
    
    derive newtype instance rfUser :: ReadForeign User
    derive newtype instance rfComment :: ReadForeign Comment
    
    parseU :: String -> Either (NonEmptyList ForeignError) User
    parseU xs = readJSON xs
    
    parseC :: String -> Either (NonEmptyList ForeignError) Comment
    parseC xs = readJSON xs
    
    addComments :: User -> Array Comment -> User
    addComments (User u) cs = u { comments = cs }
    

    但是,当我尝试使用pulp repl在REPL中加载它时,我收到以下错误消息:

    Compiling Test
    Error found:
    in module Test
    at src/test.purs line 39, column 1 - line 39, column 45
    
      Could not match type
    
        { comments :: Array Comment
        , username :: String       
        }                          
    
      with type
    
        User
    
    
    while checking that type { comments :: Array Comment
                             | t0                       
                             }                          
      is at least as general as type User
    while checking that expression $0 { comments = cs
                                      }              
      has type User
    in value declaration addComments
    
    where t0 is an unknown type
    

    我不确定如何解释此错误消息。我可以删除addComments的类型签名,但推断的类型将与上面的错误消息中的未命名记录相同,这不是所需的结果。我对自己做错了什么的想法?非常感谢你看看这个!

1 个答案:

答案 0 :(得分:3)

我认为你快到了。错误告诉您正在返回"解开"记录而不是User值。 尝试在最后一个函数中添加User构造函数:

addComments :: User -> Array Comment -> User
addComments (User u) cs = User $ u { comments = cs }