Skip to content

Commit 9cb64eb

Browse files
Ben Fordpaf31
authored andcommitted
Add ^?! and ^@?! (#53)
* Add ^?! and ^@?! * User fromMaybe' to avoid crashed caused by strict execution * Add a test for ^?! * Use unwrap as runFirst doesn't exist * Add forgotten import * Use Tuple instead of KV. Better error messages * Forgot to replace a KV. I iz coding too late! * Add unsafePartial call
1 parent 7513c16 commit 9cb64eb

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

src/Data/Lens/Prism/Partial.purs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
module Data.Lens.Prism.Partial
2+
( unsafeViewPrism, (^?!)
3+
, unsafeIndexedFold, (^@?!)
4+
)
5+
where
6+
7+
import Prelude
8+
9+
import Data.Lens.Fold (Fold, ifoldMapOf, previewOn)
10+
import Data.Lens.Types (IndexedFold)
11+
import Data.Maybe (fromMaybe', Maybe(..))
12+
import Data.Maybe.First (First(..))
13+
import Data.Tuple(Tuple(..))
14+
import Data.Newtype (unwrap)
15+
import Partial.Unsafe (unsafeCrashWith)
16+
17+
unsafeViewPrism :: forall s t a b. Partial => s -> Fold (First a) s t a b -> a
18+
unsafeViewPrism s l = fromMaybe' (crash "unsafeViewPrism: Empty fold") $ previewOn s l
19+
20+
infixl 8 unsafeViewPrism as ^?!
21+
22+
23+
unsafeIndexedFold
24+
:: forall i s t a b. Partial
25+
=> s
26+
-> IndexedFold ((First (Tuple i a))) i s t a b
27+
-> (Tuple i a)
28+
unsafeIndexedFold s l = fromMaybe' (crash "unsafeIndexedFold: empty Fold")
29+
$ unwrap
30+
$ ifoldMapOf l (\i a -> First $ Just (Tuple i a)) s
31+
32+
infixl 8 unsafeIndexedFold as ^@?!
33+
34+
35+
crash :: forall a. String -> Unit -> a
36+
crash msg _ = unsafeCrashWith msg

test/Main.purs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,12 @@ import Data.Lens.Index (ix)
77
import Data.Lens.Setter (iover)
88
import Data.Lens.Lens (ilens, IndexedLens, cloneIndexedLens)
99
import Data.Lens.Fold ((^?))
10+
import Data.Lens.Prism.Partial ((^?!))
1011
import Data.Lens.Zoom (Traversal, Traversal', Lens, Lens', zoom)
1112
import Data.Tuple (Tuple(..))
1213
import Data.Maybe (Maybe(..))
1314
import Data.Either (Either(..))
15+
import Partial.Unsafe (unsafePartial)
1416

1517
import Control.Monad.Eff (Eff)
1618
import Control.Monad.Eff.Console (CONSOLE, logShow)
@@ -50,6 +52,7 @@ _1bars :: Traversal' Bar Int
5052
_1bars = _0Justbar <<< _Left <<< bar <<< ix 1
5153

5254

55+
5356
-- Tests state using zoom
5457
stateTest :: Tuple Int String
5558
stateTest = evalState go (Tuple 4 ["Foo", "Bar"]) where
@@ -66,5 +69,6 @@ main :: forall e. Eff (console :: CONSOLE | e) Unit
6669
main = do
6770
logShow $ view bars doc
6871
logShow $ doc2 ^? _1bars
72+
logShow $ unsafePartial $ doc2 ^?! _1bars
6973
logShow stateTest
7074
logShow cloneTest

0 commit comments

Comments
 (0)