Search code examples
adtrecordpurescript

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

Solution

  • 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