我是Purescript的新手,并尝试使用purescript-simple-json:
User
的记录Comment
记录数组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
的类型签名,但推断的类型然后变得与上面的错误消息中的未命名记录相同,这不是期望的结果。对我做错了什么的想法?非常感谢你看看这个!
我想你差不多了。错误告诉您正在返回“解包”记录而不是User
值。尝试在最后一个函数中添加User
构造函数:
addComments :: User -> Array Comment -> User
addComments (User u) cs = User $ u { comments = cs }