PureScript - Access Properties of a NewType

Viewed 52

Consider the following code sample, which creates a new type to represent a customer model:

module Main where

import Effect (Effect)
import Effect.Console ( logShow )
import Prelude (Unit,(+),(/),(*),(-), (<>),discard)

newtype Customer 
  = Customer
  { firstname :: String
  }

sample :: Customer
sample = Customer
  { firstname : "Average"
  }

first :: Customer -> String
first a = _.firstname a

main = do
  logShow ( first sample )

The expected output would be the value Average, which is equal to sample.name, but instead an error is produced:

 Could not match type
  
    { firstname :: t0
    | t1
    }
  
  with type
  
    Customer
  

while checking that type Customer
  is at least as general as type { firstname :: t0
                                 | t1
                                 }
while checking that expression a
  has type { firstname :: t0
           | t1
           }
in value declaration first

where t0 is an unknown type
      t1 is an unknown type

This is a good error, but doesn't explain how to actually access this value.

How do you access the value of an object created as a newType?

2 Answers

You have to do

first :: Customer -> String
first (Customer a) = _.firstname a

Since newtype is really, a new type.

One another way is to derive Newtype instance for that particular newtype, which exposes certain functions that will let you work on the data wrapped by the newtype.

derive instance newtypeCustomer :: Newtype Customer _
 
first :: Customer -> String
first  = (_.firstname <<< unwrap)
Related