Last active
July 19, 2022 13:31
-
-
Save pedrominicz/fc3e55f6c83da4246ec5baa8695215f4 to your computer and use it in GitHub Desktop.
Alex: strict and lazy bytestrings
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
{ | |
module Lazy where | |
import Data.Foldable | |
import qualified Data.ByteString.Lazy as B | |
} | |
%wrapper "basic-bytestring" | |
$alpha = [a-zA-Z] | |
words :- | |
$white+ ; | |
$alpha+ { \word -> B.snoc word 10 } | |
{ | |
scanner :: B.ByteString -> Maybe [B.ByteString] | |
scanner str = go (AlexInput '\n' str 0) | |
where | |
go :: AlexInput -> Maybe [B.ByteString] | |
go input@(AlexInput _ str _) = | |
case alexScan input 0 of | |
AlexEOF -> return [] | |
AlexError _ -> Nothing | |
AlexSkip input _ -> go input | |
AlexToken input len act -> do | |
rest <- go input | |
return $ act (B.take (fromIntegral len) str) : rest | |
main :: IO () | |
main = do | |
str <- B.takeWhile (/= 10) <$> B.getContents | |
case scanner str of | |
Just words -> traverse_ B.putStr words | |
Nothing -> return () | |
} |
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
{ | |
module Strict where | |
import Data.Foldable | |
import qualified Data.ByteString as B | |
} | |
%wrapper "strict-bytestring" | |
$alpha = [a-zA-Z] | |
words :- | |
$white+ ; | |
$alpha+ { \word -> B.snoc word 10 } | |
{ | |
scanner :: B.ByteString -> Maybe [B.ByteString] | |
scanner str = go (AlexInput '\n' str 0) | |
where | |
go :: AlexInput -> Maybe [B.ByteString] | |
go input@(AlexInput _ str _) = | |
case alexScan input 0 of | |
AlexEOF -> return [] | |
AlexError _ -> Nothing | |
AlexSkip input _ -> go input | |
AlexToken input len act -> do | |
rest <- go input | |
return $ act (B.take len str) : rest | |
main :: IO () | |
main = do | |
str <- B.getLine | |
case scanner str of | |
Just words -> traverse_ B.putStr words | |
Nothing -> return () | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment