Advertisement
Yurry

Simple server #Haskell #SpecialOlympics

Jan 14th, 2014
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Control.Applicative
  2. import Control.Concurrent
  3. import Data.Attoparsec.Char8
  4. import qualified Data.ByteString.Char8 as BS
  5. import Network
  6. import System.IO
  7.  
  8. chainl1 elem op = elem >>= rest where
  9.     rest s1 = do {f <- op; s2 <- chainl1 elem op; return $ f s1 s2} <|> return s1
  10.    
  11. expr = chainl1 term $ (char '+' >> return (+)) <|> (char '-' >> return (-))
  12.  
  13. term = chainl1 factor $ char '*' >> return (*)
  14.  
  15. factor = (char '(' *> expr <* char ')') <|> decimal
  16.    
  17. calc str = case parseOnly (expr <* endOfInput) str of
  18.     Right res -> BS.pack $ show res
  19.     Left err -> BS.pack "error"
  20.  
  21. process handle = do
  22.     str <- BS.hGetLine handle
  23.     BS.hPutStrLn handle $ calc str
  24.     process handle
  25.  
  26. handler sock = do
  27.     (handle, host, port) <- accept sock
  28.     hSetBuffering handle LineBuffering
  29.     forkIO $ process handle
  30.     handler sock
  31.  
  32. main = do
  33.     sock <- listenOn (PortNumber 65535)
  34.     handler sock
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement