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

Commit 034c9fe

Browse files
committed
StrMap.fromRecord
create a StrMap from a homogeneous record
1 parent e424494 commit 034c9fe

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

bower.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@
2626
"purescript-lists": "^4.0.0",
2727
"purescript-st": "^3.0.0",
2828
"purescript-gen": "^1.1.0",
29-
"purescript-foldable-traversable": "^3.6.1"
29+
"purescript-foldable-traversable": "^3.6.1",
30+
"purescript-typelevel-prelude": "^2.6.0"
3031
},
3132
"devDependencies": {
3233
"purescript-quickcheck": "^4.0.0",

src/Data/StrMap.purs

+7-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ module Data.StrMap
1616
, toAscUnfoldable
1717
, fromFoldable
1818
, fromFoldableWith
19+
, fromRecord
1920
, delete
2021
, pop
2122
, member
@@ -46,7 +47,6 @@ import Prelude
4647

4748
import Control.Monad.Eff (Eff, runPure, foreachE)
4849
import Control.Monad.ST as ST
49-
5050
import Data.Array as A
5151
import Data.Eq (class Eq1)
5252
import Data.Foldable (class Foldable, foldl, foldr, for_)
@@ -60,6 +60,8 @@ import Data.Traversable (class Traversable, traverse)
6060
import Data.TraversableWithIndex (class TraversableWithIndex, traverseWithIndex)
6161
import Data.Tuple (Tuple(..), fst, uncurry)
6262
import Data.Unfoldable (class Unfoldable)
63+
import Type.Row.Homogeneous (class Homogeneous)
64+
import Unsafe.Coerce (unsafeCoerce)
6365

6466
-- | `StrMap a` represents a map from `String`s to values of type `a`.
6567
foreign import data StrMap :: Type -> Type
@@ -235,6 +237,10 @@ fromFoldableWith f l = pureST (do
235237
for_ l (\(Tuple k v) -> runFn4 _lookupST v (f v) k s >>= SM.poke s k)
236238
pure s)
237239

240+
-- | Create a map from a homogeneous record (all attributes have the same type).
241+
fromRecord :: forall r t. Homogeneous r t => Record r -> StrMap t
242+
fromRecord = unsafeCoerce
243+
238244
foreign import toArrayWithKey :: forall a b . (String -> a -> b) -> StrMap a -> Array b
239245

240246
-- | Unfolds a map into a list of key/value pairs

test/Test/Data/StrMap.purs

+4
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,10 @@ strMapTests = do
160160
quickCheck (M.lookup "1" nums == Just 2 <?> "invalid lookup - 1")
161161
quickCheck (M.lookup "2" nums == Nothing <?> "invalid lookup - 2")
162162

163+
log "fromRecord"
164+
quickCheck (M.fromRecord {a: 1, b: 2, c: 3}
165+
== M.fromFoldable [Tuple "a" 1, Tuple "b" 2, Tuple "c" 3])
166+
163167
log "toUnfoldable . fromFoldable = id"
164168
quickCheck $ \arr -> let f x = M.toUnfoldable (M.fromFoldable x)
165169
in f (f arr) == f (arr :: L.List (Tuple String Int)) <?> show arr

0 commit comments

Comments
 (0)