Skip to content

Instantly share code, notes, and snippets.

@derekmorr
Created July 10, 2016 12:29
Show Gist options
  • Save derekmorr/a6df1bf5b33e622ee92f36fb294f4d8b to your computer and use it in GitHub Desktop.
Save derekmorr/a6df1bf5b33e622ee92f36fb294f4d8b to your computer and use it in GitHub Desktop.
Haskell implementation of text processing DSL
module DSLFSM where
import Data.Char (toLower, toUpper)
-- a DSL for basic text processing
-- and a FSM for implementing that DSL.
-- adapted to Haskell from https://www.youtube.com/watch?v=7D9GE3-o54o
data MachineState = Normal | Comment | Upper | Lower
machineCycle :: MachineState -> Char -> (Maybe Char, MachineState)
machineCycle Normal '#' = (Nothing, Comment)
machineCycle Normal '^' = (Nothing, Upper)
machineCycle Normal '_' = (Nothing, Lower)
machineCycle Normal ch = (Just ch, Normal)
machineCycle Comment '#' = (Nothing, Normal)
machineCycle Comment ch = (Nothing, Comment)
machineCycle Upper '^' = (Nothing, Normal)
machineCycle Upper ch = (Just $ toUpper ch, Upper)
machineCycle Lower '_' = (Nothing, Normal)
machineCycle Lower ch = (Just $ toLower ch, Lower)
processText :: String -> String
processText str = outString
where (outString, _) = foldr step ("", Normal) str
step :: Char -> (String, MachineState) -> (String, MachineState)
step ch (str, state) = (newStr, newState)
where (maybeChar, newState) = machineCycle state ch
newStr = appendChar maybeChar str
appendChar Nothing str = str
appendChar (Just c) str = c : str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment