Skip to content

Instantly share code, notes, and snippets.

@pedrominicz
Created July 27, 2022 16:12
Show Gist options
  • Save pedrominicz/ed6741e82293b720ed79340d874e423b to your computer and use it in GitHub Desktop.
Save pedrominicz/ed6741e82293b720ed79340d874e423b to your computer and use it in GitHub Desktop.
Extremely simple Alex and Happy example
{
module Lex where
}
%wrapper "basic"
tokens :-
$white+ ;
[^ $white]+ { id }
{
scanner :: String -> Maybe [String]
scanner str = go ('\n', [], str)
where
go input@(_, _, str) =
case alexScan input 0 of
AlexEOF -> Just []
AlexError _ -> Nothing
AlexSkip input _ -> go input
AlexToken input len act -> do
rest <- go input
return $ act (take len str) : rest
}
module Main where
import Lex
import Parse
main :: IO ()
main = do
putStrLn "simple"
str <- getLine
print $ scanner str >>= parse
{
module Parse where
}
%tokentype { String }
%monad { Maybe } { (>>=) } { return }
%error { const Nothing }
%name parse words
%token
word { $$ }
%%
words :: { [String] }
: { [] }
| word words { $1 : $1 : $2 }
#!/usr/bin/bash
set -e
trap clean 0 1 2 3 6
clean() {
rm -f Lex.hs Parse.hs
}
alex Lex.x
happy Parse.y
export RLWRAP_HOME="$HOME/.local/share/rlwrap"
rlwrap runhaskell -Wall -Wno-name-shadowing Main.hs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment