Created
July 10, 2016 12:29
-
-
Save derekmorr/a6df1bf5b33e622ee92f36fb294f4d8b to your computer and use it in GitHub Desktop.
Haskell implementation of text processing DSL
This file contains hidden or 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 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