Created
July 20, 2023 01:42
-
-
Save JakobBruenker/d994ad7d3789d1ef2f5656e6d05d86f8 to your computer and use it in GitHub Desktop.
Generic Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
alternative type signature:
filter' :: (Strong p, Choice p, Applicative (p ((a, a), [a]))) => p a Bool -> p [a] [a]