简体   繁体   中英

Get a newtype'd records underlying type in purescript

I'm trying to see if there's an easy way to get the type of a newtype'd record to put in function signatures.

newtype T1 = T1 { foo:: Int}
derive instance newtypeT1 :: Newtype T1 _ 
... other classes that require me to newtype the record ...

I know I can access a records members with _.property and I can compose that with unwrap unwrap >>> _.property to get a function for that property, but I'd like to write a function similar to

testFoo :: forall a. (_ -> a) -> Effect a
testFoo accessor = (unwrap >>> accessor) <$> loadT1

This works but the wildcard symbol gives an warning, but I'm not sure how to get that record definition from T1. (This is a minimal example, I have a massive property object that is from an external source.

A workaround I've been using for now has been to declare my type like

 type InnerT1 = { foo ::Int}
 newtype T1 = T1 InnerT1

and exporting that InnerT1 so it can be used in my test file, but this seems a bit clunky and I am wondering if there is a better way?

You can use the Newtype class to get at the inner type:

testFoo :: forall a inner. Newtype T1 inner => (inner -> a) -> Effect a 
testFoo accessor = (unwrap >>> accessor) <$> loadT1

This works without additional annotations, because the class has a functional dependency Newtype ab | a -> b Newtype ab | a -> b , which means that the inner type is uniquely determined by the outer type.

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