4

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?

acple
  • 65
  • 3
  • What library is this about? Is there a safe version of the function perhaps? – bklaric Sep 13 '17 at 08:44
  • Yes. almost certainly libraries have define both. My point is, how can purescript be handling partial functions safely? – acple Sep 14 '17 at 00:08
  • Unexplored idea: implement in FFI and catch exception at runtime and return `Nothing` in this case, otherwise wrap result in `Just`? – stholzm Sep 14 '17 at 20:55
  • that's great idea. but, bad implementation. in my opinion pattern handling should be without exception throwing. appended to my ask. – acple Sep 15 '17 at 01:49
  • My idea was to implement it in JS with a try-catch block. But not sure how to use Maybe in JS. – stholzm Sep 15 '17 at 06:36
  • pass Maybe constructor to ffi. :: forall a b. Maybe b -> (b -> Maybe b) -> (Partial => a -> b) -> a -> Maybe b – acple Sep 15 '17 at 07:15
  • purs makes 'Failed pattern match' error automatically, cannot avoid it? – acple Sep 15 '17 at 07:20

1 Answers1

0

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.

erisco
  • 14,154
  • 2
  • 40
  • 45
  • I'm sorry for leave this question for long time. I understood that the partial function has no way to remove Partial label, so partial function can be run only on unsafe context with unsafePartial. – acple Sep 18 '18 at 12:01