简体   繁体   中英

How to use Value constructors to create records in PureScript

I am attempting to create a record based on an array of data, the function looks like this:

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

Here, I am trying to create a Record of the type Address using the Address value constructor but it throws an error when compiling:

Unknown data constructor Address

type only defines a type alias, so Address and

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

Are actually the same type. If you want to generate a constructor you will have to use newtype :

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

Or alternatively, you can just get rid of the constructor in your code and just use the record type:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM