0
votes

In purescript, let's say I have a type.

newtype Person = Person {name::String,age:Int}

I want to create a function which takes this record and a string specifying the field name, e.g. name, and returns the value of that field.

My use case is that I will have a record and I want concatanation of some of those fields. I want to pass an array of strings which will be the field names, and then using fold get it done in one line. Is such a thing possible?

1
Does it have to be strings? Or can you hard-code functions, e.g. \p -> p.name?stholzm
I got suggested the same and I think that's the next best solution. But is there a way to achieve what I asked for?Himanshu Prasad
Have a look at a similar question: stackoverflow.com/questions/44758148/…stholzm
Thanks, I will have a look.Himanshu Prasad

1 Answers

0
votes

With get from purescript-record: get (SProxy ∷ SProxy "x") { x: "y" } reduces to "y". Note that this requires the string to be known statically, as well as the record type.

If you wish to dynamically index a JavaScript object, you can use readProp from purescript-foreign. However, the Foreign library cannot safely operate on PureScript records.

An option to dynamically index a PureScript record is to simply do case analysis on the string.

getProp ∷ ∀ a b r. String → { x ∷ a, y ∷ b | r } → Maybe (Either a b)
getProp "x" rec = Just (Left rec.x)
getProp "y" rec = Just (Right rec.y)
getProp _ _ = Nothing