Skip to content

Instantly share code, notes, and snippets.

@sjoerdvisscher
Created May 21, 2011 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sjoerdvisscher/984392 to your computer and use it in GitHub Desktop.
Save sjoerdvisscher/984392 to your computer and use it in GitHub Desktop.
Applicative van Laarhoven lenses
{-# LANGUAGE RankNTypes #-}
import Control.Applicative
import Data.Functor.Identity
type MultiLens a b = forall f. Applicative f => (b -> f b) -> a -> f a
get :: MultiLens a b -> a -> [b]
get l = getConst . l (Const . pure)
modify :: MultiLens a b -> (b -> b) -> a -> a
modify l f = runIdentity . l (Identity . f)
set :: MultiLens a b -> b -> a -> a
set l = modify l . const
interactive :: Show b => MultiLens a b -> (b -> b) -> a -> IO a
interactive l f = l $ \b -> do
putStr $ "Change " ++ show b ++ "? (y/n)"
c <- getChar
putStrLn ""
if c == 'y' then return (f b) else return b
list :: MultiLens [a] a
list _ [] = pure []
list f (x:xs) = (:) <$> f x <*> list f xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment