Skip to content

Conversation

@sharkdp
Copy link
Contributor

@sharkdp sharkdp commented Jun 12, 2016

While updating code to PureScript 0.9, I find myself using unsafePartial quite a lot. This PR is a proposal to add a function unsafePartialBecause which would allow me to describe why using unsafePartial in a particular occasion is "guaranteed" to be safe:

-- only works for strictly positive input:
g :: Partial => Int -> Int
g n | n > 0 = 1

h :: Int -> Int
h x = unsafePartialBecause "the argument to g is strictly positive" $ g (x * x)

In the unexpected case where the usage of unsafePartial was indeed unsafe (I forgot about the x = 0 case ...), this would raise an exception with the custom error message:

> h 2
1

> h 0

Error: unsafePartial failed. The following assumption was incorrect:
'the argument to g is always positive'.

@sharkdp sharkdp force-pushed the unsafe-partial-because branch from 7f82243 to c104f4f Compare June 12, 2016 14:35
@sharkdp
Copy link
Contributor Author

sharkdp commented Jun 13, 2016

I just noticed that I should probably compare this with the crashWith-approach:

g :: Partial => Int -> Int
g n | n > 0 = 1
g _ = crashWith "g only works for strictly positive input"

h :: Int -> Int
h x = unsafePartial $ g (x * x)

The only difference is that unsafePartialBecause would allow to add a custom comment at the call site.

@garyb
Copy link
Member

garyb commented Jun 21, 2016

I like this 👍

@paf31 paf31 merged commit 2306af9 into purescript:master Dec 24, 2016
@paf31
Copy link
Contributor

paf31 commented Dec 24, 2016

Sorry for the delay!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants