Purescript Simple JSON,结合记录类型

问题描述 投票:2回答:1

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

  1. 拿一些JSON并将其转换为User的记录
  2. 拿一些JSON并将其转换为Comment记录数组
  3. 取结果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 $0 { comments = cs
                                  }              
  has type User
in value declaration addComments

where t0 is an unknown type

我不知道如何解释此错误消息。我可以删除addComments的类型签名,但推断的类型然后变得与上面的错误消息中的未命名记录相同,这不是期望的结果。对我做错了什么的想法?非常感谢你看看这个!

json purescript
1个回答
3
投票

我想你差不多了。错误告诉您正在返回“解包”记录而不是User值。尝试在最后一个函数中添加User构造函数:

addComments :: User -> Array Comment -> User
addComments (User u) cs = User $ u { comments = cs }
© www.soinside.com 2019 - 2024. All rights reserved.