Purescript Simple JSON,结合记录类型

Purescript Simple JSON, combining record types

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

  1. 取一些JSON转换成User
  2. 的记录
  3. 再取一些JSON,转换成Comment
  4. 的记录数组
  5. 取2.的结果,放入1.生成的用户记录的comments字段

下面是我的尝试:

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 [=12=] { comments = cs
                                  }              
  has type User
in value declaration addComments

where t0 is an unknown type

我不确定如何解释此错误消息。我可以删除 addComments 的类型签名,但推断的类型会与上面错误消息中的未命名记录相同,这不是预期的结果。对我做错了什么有什么想法吗?非常感谢您查看此内容!

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

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