Skip to content
This repository has been archived by the owner on Oct 4, 2020. It is now read-only.

Creating maps from (homogeneous) records #125

Open
sharkdp opened this issue Sep 4, 2017 · 4 comments
Open

Creating maps from (homogeneous) records #125

sharkdp opened this issue Sep 4, 2017 · 4 comments

Comments

@sharkdp
Copy link
Contributor

sharkdp commented Sep 4, 2017

I thought it would be nice if we could use record-syntax to create Maps. Using the new RowToList mechanism, we can now turn this:

numbers  Map String Number
numbers = fromFoldable
  [ Tuple "pi" 3.14159
  , Tuple "e" 2.71828
  , Tuple "ultimate_answer" 42.0
  , Tuple "alpha" 0.00729735
  ]

into this:

numbers  Map String Number
numbers = fromRecord
  { pi: 3.14159
  , e: 2.71828
  , ultimate_answer: 42.0
  , alpha: 0.00729735
  }

The implementation could look like this:

class HomogeneousRecord (row ∷ # Type) (listRowList) a | list  row
  where
    toMap  RLProxy list  Record row  Map String a

instance homogeneousRecordNilHomogeneousRecord () Nil a where
  toMap _ _ = empty

instance homogeneousRecordCons ∷
  ( RowToList row list
  , IsSymbol l
  , RowLacks l row'
  , RowCons l a row' row
  , RowToList row' list'
  , HomogeneousRecord row' list' a
  )
  ⇒ HomogeneousRecord row (Cons l a list') a where
  toMap _ record = insert key value (toMap (RLProxy  RLProxy list') record')
    where
      keyS = SProxySProxy l
      key = reflectSymbol keyS
      value = R.get keyS record
      record' :: Record row'
      record' = R.delete keyS record

fromRecord   row list a
           . RowToList row list
            HomogeneousRecord row list a
            Record row
            Map String a
fromRecord = toMap (RLProxy :: RLProxy list)

Calling fromRecord with a heterogeneous record leads to a compile-time error, as expected.

@paf31
Copy link
Contributor

paf31 commented Sep 4, 2017

👍 @paulyoung has been working on a Homogeneous constraint in purescript-typelevel-prelude already actually.

@sharkdp
Copy link
Contributor Author

sharkdp commented Sep 4, 2017

Oh, nice! I wasn't sure how to call this, but it seems like I guessed the correct name ;-)

@paulyoung
Copy link

This is the PR: purescript/purescript-typelevel-prelude#20

@matthewleon
Copy link
Contributor

Just adding a note to this Issue that those who want this functionality in PureScript 0.11 can get it here: https://github.com/matthewleon/purescript-homogeneous-records

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants