`UnsafePartial` method works on non-partial function too - Purescript?

88 Views Asked by At

I'm trying to do something similar to what Partial type class does, so to understand Partial constraint better I started experimenting with it...

I created a normal function,

goodFn :: Int -> Effect Int
goodFn a = pure $ a + 1

and I tried applying unsafePartial function on it...

unsafePartial $ goodFn 1

It worked, that's my question how it worked even though goodFn isn't partial?

unsafePartial :: forall a. (Partial => a) -> a

The function I pass goodFn doesn't have Partial constraint, then why the compiler didn't complain?

If that's the correct behaviour, how do I enforce my function to be always called after applying it to a unwrapper function.

Like how unsafePartial function always need to be applied to partial functions(aka function with partial constraint) before actually calling the function

(Can we prevent calling a function directly? Make it callable only after applying it to a runner function, like unsafePartial)

1

There are 1 best solutions below

4
Saravanan On

I have a idea, I will pass an extra argument which I don't expose,

data PartialSecret = PartialSecret

then in the same file, I create my unwrapper function,

runPartialFn :: forall a. (PartialSecret -> a) -> a 
runPartialFn fn = fn PartialSecret 

Now I annotate all my function with my PartialSecret as first argument,

fn1 :: PartialSecret -> Int -> Int 
fn1 partial a = a+1 

I can also do recursion with it, without again using runPartialFn like,

fn1 :: PartialSecret -> Int -> Int 
fn1 partial 0 = 0
fn1 partial a = 1 + fn1 partial (a-1)

Now I can't call any of my function(from other place) without applying runPartialFn

Is it a good approach?