Skip to content

Commit 2306af9

Browse files
authored
Merge pull request #6 from sharkdp/unsafe-partial-because
Add unsafePartialBecause
2 parents 5f29f44 + c104f4f commit 2306af9

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

src/Partial/Unsafe.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,14 @@
55
exports.unsafePartial = function (f) {
66
return f();
77
};
8+
9+
exports.unsafePartialBecause = function (reason) {
10+
return function (f) {
11+
try {
12+
return exports.unsafePartial(f);
13+
} catch (err) {
14+
throw new Error("unsafePartial failed. The following " +
15+
"assumption was incorrect: '" + reason + "'.");
16+
}
17+
};
18+
};

src/Partial/Unsafe.purs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
-- | Utilities for working with partial functions.
22
module Partial.Unsafe
33
( unsafePartial
4+
, unsafePartialBecause
45
, unsafeCrashWith
56
) where
67

@@ -9,6 +10,11 @@ import Partial (crashWith)
910
-- | Discharge a partiality constraint, unsafely.
1011
foreign import unsafePartial :: forall a. (Partial => a) -> a
1112

13+
-- | Discharge a partiality constraint, unsafely. Raises an exception with a
14+
-- | custom error message in the (unexpected) case where `unsafePartial` was
15+
-- | used incorrectly.
16+
foreign import unsafePartialBecause :: forall a. String -> (Partial => a) -> a
17+
1218
-- | A function which crashes with the specified error message.
1319
unsafeCrashWith :: forall a. String -> a
1420
unsafeCrashWith msg = unsafePartial (crashWith msg)

test/Main.purs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
module Test.Main where
22

33
import Partial (crashWith)
4-
import Partial.Unsafe (unsafePartial)
4+
import Partial.Unsafe (unsafePartial, unsafePartialBecause)
55

66
f :: Partial => Int -> Int
77
f 0 = 0
@@ -10,5 +10,8 @@ f _ = crashWith "f: partial function"
1010
safely :: Int
1111
safely = unsafePartial (f 0)
1212

13+
safely2 :: Int
14+
safely2 = unsafePartialBecause "calling f with argument 0 is guaranteed to be safe" (f 0)
15+
1316
main :: forall a. a -> {}
1417
main _ = {}

0 commit comments

Comments
 (0)