How to convert partial functions to safe(Maybe) functions?

287 Views Asked by At

I want it to use library-defined partialfunc more convenient, or write callback with partial pattern-matching.
like this,

partialMaybe :: forall a b. (Partial => a -> b) -> a -> Maybe b

I couldn't find similar in some major libraries.
How to define it? or already defined in libs?

data ABC a = A a | B a | C a

f1 = someHigherOrderFunc $ partialMaybe \(A a) -> someFunc a -- if not 'A', return Nothing.

-- same as
f2 = someHigherOrderFunc $ case _ of A a -> Just $ someFunc a
                                     _   -> Nothing -- requires line break, seems syntax redundant...

using: purescript 0.11.6


Edit:

I did it...

partialMaybe :: forall a b. (Partial => a -> b) -> a -> Maybe b
partialMaybe f a = runPure $ catchException (const $ pure Nothing) (Just <<< unsafePartial f <$> pure a)

this is...umm...very ugly. it's not.
'Failed pattern match' exception is thrown by the purescript.
so I think it should be able to handle by purescript.
Can't do it?

1

There are 1 best solutions below

1
On BEST ANSWER

If you want an exception if a case is missed, use Partial. If you want otherwise, use Maybe or Either or another appropriate sum type.

You can catch the exception thrown from a failed pattern match. There is no way for a failed pattern match to not throw an exception.