Skip to content

Instantly share code, notes, and snippets.

@supki
Last active December 18, 2015 22:18
Show Gist options
  • Save supki/5853255 to your computer and use it in GitHub Desktop.
Save supki/5853255 to your computer and use it in GitHub Desktop.
M?
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Partial where
import Control.Exception (PatternMatchFail, catch, evaluate)
import Data.Maybe (mapMaybe)
import System.IO.Unsafe (unsafePerformIO)
class Partial a where
partial :: a -> a
instance Partial (a -> Bool) where
partial = partialWith False
instance Partial (a -> Maybe b) where
partial = partialWith Nothing
partialWith :: b -> (a -> b) -> a -> b
partialWith z f x = unsafePerformIO (evaluate (f x) `catchPatternMatchFail` \_ -> return z)
catchPatternMatchFail :: IO a -> (PatternMatchFail -> IO a) -> IO a
catchPatternMatchFail = catch
xs :: [Int]
xs = filter (partial $ \case 3 -> True; 7 -> True) [1..10]
ys :: [Int]
ys = mapMaybe (partial $ \case 3 -> Just 8; 7 -> Just 1) [1..10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment