如何使用值构造函数在 PureScript 中创建记录

How to use Value constructors to create records in PureScript

我正在尝试基于数据数组创建记录,函数如下所示:

type Address = {
  street :: String,
  city :: String,
  state :: String
}

convertToAddress :: Array String -> Maybe Address
convertToAddress [street, city, state] = Just (Address { street: street, city: city, state: state })
convertToAddress _ = Nothing

在这里,我尝试使用 Address 值构造函数创建一个 Address 类型的 Record,但它在编译时抛出错误:

Unknown data constructor Address

type 只定义了一个类型别名,所以 Address

{
  street :: String,
  city :: String,
  state :: String
}

其实是同一种类型。如果要生成构造函数,则必须使用 newtype:

newtype Address = Address {
  street :: String,
  city :: String,
  state :: String
}

或者,您可以去掉代码中的构造函数,只使用记录类型:

convertToAddress :: Array String -> Maybe Address
convertToAddress [street, city, state] = Just { street: street, city: city, state: state }
convertToAddress _ = Nothing