Skip to content

Instantly share code, notes, and snippets.

@nonowarn
Created November 9, 2009 05:09
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 nonowarn/229708 to your computer and use it in GitHub Desktop.
Save nonowarn/229708 to your computer and use it in GitHub Desktop.
Applicative Awky
import Control.Applicative
import Control.Monad
import Data.Maybe
-- Line oriented parser
newtype Awky a = Awky { app :: String -> Maybe a }
f :: Int -> Awky String
f n = Awky $ \str -> let ws = words str; len = length ws
in guard (n < len) >> Just (ws !! n)
runAwky :: Awky a -> String -> [a]
runAwky awky str = catMaybes . map (app awky) . lines $ str
instance Functor Awky where
fmap f awky = Awky $ \s -> fmap f (app awky s)
instance Applicative Awky where
pure a = Awky (const . Just $ a)
f <*> x = Awky $ \str -> do
f' <- app f str
x' <- app x str
return (f' x')
data Access = Access Addr Path Time deriving (Show)
type Addr = String
type Path = String
type Time = String
-- Assume the format of log is like
-- <id> <addr> <path> <time(epoch)>
-- 1234 123.xxx.xxx.xxx / 1234567890
main = mapM_ print . runAwky (liftA3 Access (f 1) (f 2) (f 3)) =<< getContents
0001 123.45.67.8 / 2354656547
0002 23.54.1.2 /about 2358679567
0003 67.21.210.9 /help 2358743439
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment