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

时间:2017-09-25 12:26:16

标签: adt record 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类型的记录,但在编译时会抛出错误:

Unknown data constructor Address

1 个答案:

答案 0 :(得分:5)

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