Skip to content

Instantly share code, notes, and snippets.

@atomictom
Created January 15, 2015 08:19
Show Gist options
  • Select an option

  • Save atomictom/ae95b4b606cf011b4700 to your computer and use it in GitHub Desktop.

Select an option

Save atomictom/ae95b4b606cf011b4700 to your computer and use it in GitHub Desktop.
import System.IO
import Data.List.Split (chunksOf)
import Data.List (foldl')
import Control.Monad (forever)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
type State = String
type Symbol = String
type TransitionTable = Map (State, Symbol) State
main :: IO ()
main = do
let start = "q0"
final = Set.singleton "q0"
transitions = Map.fromList
[ (("q0", "0"), "q0")
, (("q0", "1"), "q1")
, (("q1", "0"), "q2")
, (("q1", "1"), "qc")
, (("q2", "0"), "q1")
, (("q2", "1"), "q2")
, (("qc", "0"), "q0")
, (("qc", "1"), "q1")
]
my_dfa = dfa start final transitions
let loop = do
input <- prompt "Enter a string to test >>> "
print $ my_dfa (chunksOf 1 input)
forever loop
dfa :: State -> Set State -> TransitionTable -> [Symbol] -> Bool
dfa start final transitions input = Set.member finalState final
where
finalState = foldl' getNextState start input
getNextState cur str = transitions Map.! (cur, str)
prompt :: String -> IO String
prompt str = do
putStr str
hFlush stdout
getLine
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment