Skip to content

Instantly share code, notes, and snippets.

@bradparker
Last active September 12, 2018 08:25
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 bradparker/b4a7624399754d398b57af35a001e1d4 to your computer and use it in GitHub Desktop.
Save bradparker/b4a7624399754d398b57af35a001e1d4 to your computer and use it in GitHub Desktop.
StateT Parser
Copyright (c) 2018, Brad Parker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Brad Parker nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module Main where
import Control.Monad (replicateM)
import Data.Char (isAlpha, isDigit, isSpace, isUpper)
import Data.Functor.Alt (many, some)
import Data.Maybe (listToMaybe)
import Parser
digit :: Parser Char
digit = satisfy isDigit
digits :: Parser String
digits = some digit
chunk :: Int -> Parser String
chunk = flip replicateM anyChar
between :: Parser a -> Parser b -> Parser c -> Parser c
between l r p = l *> p <* r
space :: Parser Char
space = satisfy isSpace
spaces :: Parser String
spaces = many space
data Person = Person Int String
deriving (Show)
readMaybe :: (Read a) => String -> Maybe a
readMaybe s = fst <$> listToMaybe (reads s)
ageParser :: Parser Int
ageParser = do
ds <- digits
case readMaybe ds of
Nothing -> unexpected ds
Just parsed -> pure parsed
nameParser :: Parser String
nameParser = (:) <$> satisfy isUpper <*> many (satisfy isAlpha)
personParser :: Parser Person
personParser =
Person
<$ spaces
<*> ageParser
<* some space
<*> nameParser
<* spaces
<* eof
main :: IO ()
main = do
print $ parse digits "123"
print $ parse digits "a123"
print $ parse (chunk 3) "12345"
print $ parse personParser "123 Abc"
print $ parse personParser "123 abc"
print $ parse personParser "123 Abc def"
name: Parser
version: 0.1.0.0
license: BSD3
license-file: LICENSE
author: Brad Parker
maintainer: hi@bradparker.com
build-type: Simple
cabal-version: >=1.10
executable Parser
main-is:
Main.hs
other-modules:
Parser
other-extensions:
GeneralizedNewtypeDeriving
build-depends:
base >=4.10 && <5,
mtl,
semigroupoids,
transformers
default-language:
Haskell2010
module Parser where
import Control.Monad.Except (MonadError, throwError)
import Control.Monad.Trans.State (StateT(..), evalStateT, get, gets, put)
import Data.Functor.Alt (Alt((<!>), many, some))
import Data.Maybe (listToMaybe)
data Error
= UnexpectedEof
| Unexpected String
deriving (Show)
type Parser = StateT String (Either Error)
parse :: Parser a -> String -> Either Error a
parse = evalStateT
unexpected :: String -> Parser a
unexpected = throwError . Unexpected
optional :: (Alt f, Applicative f) => f a -> f (Maybe a)
optional v = Just <$> v <!> pure Nothing
notFollowedBy :: Parser String -> Parser ()
notFollowedBy p = do
res <- optional p
case res of
Nothing -> pure ()
Just val -> unexpected val
anyChar :: Parser Char
anyChar = do
input <- get
case input of
[] -> throwError UnexpectedEof
(c:cs) -> do
put cs
pure c
eof :: Parser ()
eof = notFollowedBy (some anyChar)
satisfy :: (Char -> Bool) -> Parser Char
satisfy p = do
c <- anyChar
if p c
then pure c
else unexpected [c]
char :: Char -> Parser Char
char = satisfy . (==)
notChar :: Char -> Parser Char
notChar = satisfy . (/=)
string :: String -> Parser String
string = traverse char
import Distribution.Simple
main = defaultMain
{ nixpkgs ? import <nixpkgs> {}, compiler ? "default", doBenchmark ? false }:
let
inherit (nixpkgs) pkgs;
f = { mkDerivation, base, mtl, semigroupoids, stdenv
, transformers
}:
mkDerivation {
pname = "Parser";
version = "0.1.0.0";
src = ./.;
isLibrary = false;
isExecutable = true;
executableHaskellDepends = [ base mtl semigroupoids transformers ];
license = stdenv.lib.licenses.bsd3;
};
haskellPackages = if compiler == "default"
then pkgs.haskellPackages
else pkgs.haskell.packages.${compiler};
variant = if doBenchmark then pkgs.haskell.lib.doBenchmark else pkgs.lib.id;
drv = variant (haskellPackages.callPackage f {});
in
if pkgs.lib.inNixShell then drv.env else drv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment