vam*_*olu 2 record adt 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
Run Code Online (Sandbox Code Playgroud)
在这里,我试图使用Address值构造函数创建Address类型的Record,但是在编译时会引发错误:
Unknown data constructor Address
Run Code Online (Sandbox Code Playgroud)
type只定义类型别名,所以Address和
{
street :: String,
city :: String,
state :: String
}
Run Code Online (Sandbox Code Playgroud)
实际上是同一类型。如果要生成构造函数,则必须使用newtype:
newtype Address = Address {
street :: String,
city :: String,
state :: String
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以在代码中摆脱构造函数,而只使用记录类型:
convertToAddress :: Array String -> Maybe Address
convertToAddress [street, city, state] = Just { street: street, city: city, state: state }
convertToAddress _ = Nothing
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
106 次 |
| 最近记录: |