Skip to content

Commit a888fdb

Browse files
authored
Add unsafePartsOf (#530)
1 parent f03ef0d commit a888fdb

File tree

1 file changed

+19
-2
lines changed

1 file changed

+19
-2
lines changed

optics-core/src/Optics/Traversal.hs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ module Optics.Traversal
6666
-- * Combinators
6767
, backwards
6868
, partsOf
69+
, unsafePartsOf
6970
, singular
7071

7172
-- * Monoid structure
@@ -379,7 +380,7 @@ backwards o = traversalVL $ \f -> forwards #. traverseOf o (Backwards #. f)
379380
-- So technically, this is only a 'Lens' if you do not change the number of
380381
-- results it returns.
381382
partsOf
382-
:: forall k is s t a. Is k A_Traversal
383+
:: Is k A_Traversal
383384
=> Optic k is s t a a
384385
-> Lens s t [a] [a]
385386
partsOf o = lensVL $ \f s -> evalState (traverseOf o update s)
@@ -390,6 +391,22 @@ partsOf o = lensVL $ \f s -> evalState (traverseOf o update s)
390391
[] -> pure a
391392
{-# INLINE partsOf #-}
392393

394+
-- | A variant of 'partsOf' that allows changing the type of elements.
395+
--
396+
-- /Warning:/ if you don't supply at least as many @b@'s as you were given @a@'s,
397+
-- the reconstruction of @t@ will result in an error.
398+
unsafePartsOf
399+
:: Is k A_Traversal
400+
=> Optic k is s t a b
401+
-> Lens s t [a] [b]
402+
unsafePartsOf o = lensVL $ \f s -> evalState (traverseOf o update s)
403+
<$> f (toListOf (getting $ castOptic @A_Traversal o) s)
404+
where
405+
update _ = get >>= \case
406+
b : bs -> put bs >> pure b
407+
[] -> error "unsafePartsOf: not enough elements were supplied"
408+
{-# INLINE unsafePartsOf #-}
409+
393410
-- | Convert a traversal to an 'AffineTraversal' that visits the first element
394411
-- of the original traversal.
395412
--
@@ -400,7 +417,7 @@ partsOf o = lensVL $ \f s -> evalState (traverseOf o update s)
400417
--
401418
-- @since 0.3
402419
singular
403-
:: forall k is s a. Is k A_Traversal
420+
:: Is k A_Traversal
404421
=> Optic' k is s a
405422
-> AffineTraversal' s a
406423
singular o = atraversalVL $ \point f s ->

0 commit comments

Comments
 (0)