Function to access record fields

I am using Data.Exists. I notice that runExists takes a function that operates on the Exists field.

Let’s say I have

newtype ObjectF s =
  { n1   :: Number
  , ns   :: s }

type Object = Exists ObjectF


and I want to run runExists to obtain the n1 field.

getN1 :: ObjectF s -> Number
getN1 (ObjectF o) = o.n1

var :: Object -> Number
var o = runExists getN1 o


My question is, is there a way to define the function ‘getN1’ automatically or obtain a function on a newtype that accesses a particular field?

If you derive a Newtype instance for ObjectF you could use _.n1 <<< unwrap or _.n1 <<< un ObjectF.

1 Like

Ah, I think that’s what I was missing, knowing about the syntactic sugar

_.fieldName

to create a function that accesses a particular field.

There’s a couple of other syntax forms for shortcuts involving records you might be interested in too: https://github.com/purescript/documentation/blob/master/language/Syntax.md#records :slightly_smiling_face:

1 Like