scalahaskellpartial-functions

Scala's Partial Functions in Haskell


Scala has a very nice support of partial functions, mainly because in Scala when you define a partial function it also defines an isDefinedAt function for it. And also Scala has orElse and andThen functions to work with partial functions.

Haskell does support partial functions by simply non-exhaustively defining a function (though they are strongly discouraged in Haskell community). But to define isDefinedAt function in general you have to use some sort of exception handling, which I'm not being able to figure out. Once isDefinedAt function is defined then it can be used to define orElse and andThen function is already there as (.).

In short, I want to define a function,

isDefinedAt :: (a -> b) -> a -> Bool
isDefinedAt f x = -- returns True if f is defined at x else False

Can anyone please tell me how such a function can be written.

Note, I can define a function with signature

isDefinedAt :: (a -> b) -> a -> IO Bool

for generic b. But I want a function without IO in co-domain.

A nice article on Scala's Partial Functions is - How to create and use partial functions in Scala By Alvin Alexander


Solution

  • I recommend that, like in Scala, you use a separate type for partial functions.

    import Control.Arrow
    import Data.Maybe
    
    type Partial = Kleisli Maybe
    
    isDefinedAt :: Partial a b -> a -> Bool
    isDefinedAt f x = isJust $ runKleisli f x
    -- laziness should save some of the work, if possible
    
    orElse :: Partial a b -> Partial a b -> Partial a b
    orElse = (<+>)
    
    andThen :: Partial a b -> Partial b c -> Partial a c
    andThen = (>>>)