Skip to content

Instantly share code, notes, and snippets.

@lambdaknight
Created April 4, 2014 20:03
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 lambdaknight/9982115 to your computer and use it in GitHub Desktop.
Save lambdaknight/9982115 to your computer and use it in GitHub Desktop.
Lens-like Access to Dictionary-like Object
{-# LANGUAGE RankNTypes #-}
module AList where
import Control.Lens
type AList t = [(String, t)]
alistGet :: String -> AList t -> Maybe t
alistGet key ((k,v):xs)
| k == key = Just v
| otherwise = alistGet key xs
alistGet _ [] = Nothing
alistSet :: String -> AList t -> t -> AList t
alistSet key ((k,v):xs) value
| k == key = (key, value):xs
| otherwise = (k,v):(alistSet key xs value)
alistSet key [] value = [(key, value)]
-- Bad Lens. Violates Lens rules 1 and 2.
alistLens :: String -> Lens (AList t) (AList t) (Maybe t) t
alistLens key = lens (alistGet key) (alistSet key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment