Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PureScript - Access Properties of a NewType

Tags:

purescript

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?

like image 323
Code Whisperer Avatar asked Nov 19 '25 13:11

Code Whisperer


2 Answers

You have to do

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

Since newtype is really, a new type.

like image 54
equt Avatar answered Nov 21 '25 09:11

equt


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)
like image 43
Saravanan M Avatar answered Nov 21 '25 10:11

Saravanan M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!