Skip to content

Instantly share code, notes, and snippets.

@JakobBruenker
Created July 20, 2023 01:42
Show Gist options
  • Save JakobBruenker/d994ad7d3789d1ef2f5656e6d05d86f8 to your computer and use it in GitHub Desktop.
Save JakobBruenker/d994ad7d3789d1ef2f5656e6d05d86f8 to your computer and use it in GitHub Desktop.
Generic Filter
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE LambdaCase #-}
module Filter where
import Data.Profunctor
import Data.Profunctor.Product
import Prelude hiding (filter)
import Control.Applicative
filter :: (Strong p, Choice p, ProductProfunctor p) => p a Bool -> p [a] [a]
filter = dimap \case [] -> Left ()
(x:xs) -> Right ((x,x), xs)
\case Left () -> []
Right ((c, x), xs) | c -> x : xs
| otherwise -> xs
. right' . liftA2 (***!) first' filter
example1 :: [Int]
example1 = filter even [1..10]
example2 :: IO [Int]
example2 = (runStar . filter . Star) f [1,2,3]
where f :: Int -> IO Bool
f x = do
putStr $ "line " <> show x <> ": "
(>= 4) . length <$> getLine
filterA :: Applicative f => (a -> f Bool) -> [a] -> f [a]
filterA = runStar . filter . Star
@JakobBruenker
Copy link
Author

JakobBruenker commented Jul 20, 2023

alternative type signature: filter' :: (Strong p, Choice p, Applicative (p ((a, a), [a]))) => p a Bool -> p [a] [a]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment