5

I am implementing a nondeterministic finite automaton in Haskell and I am trying to implement the function that calculates the epsilon closure. To this purpose the NFA is implemented as:

data Transaction = Transaction {
     start_state :: Int, 
     symbol :: Maybe Char, 
     end_state :: Int
} deriving Show

data Automaton = Automaton {
     initial_state :: Int, 
     states :: Set.Set Int,
     transactions :: [Transaction],
     final_states :: Set.Set Int, 
     language :: Set.Set Char
} deriving Show 

while the closure:

--Perform the computations necessary to eclosure
getClosure :: [Transaction] ->  [Int]
getClosure [] = []
getClosure [tr] = [end_state tr]
getClosure (tr:trs) = end_state tr : getClosure trs 

--Get the ε-closure of a given state 
eclosure :: Automaton -> Int -> [Int]
eclosure a s
  = s : List.concat
         [ eclosure a st
         | st <- getClosure . List.filter (equal_transaction Nothing s)
                     $ transactions a ]

The problem is that if there is a cycle in the closure, the code runs forever. I understand the reasons behind this behavior, but I don't know how to fix it. Could you please help me?

leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
elena
  • 889
  • 2
  • 11
  • 19
  • 3
    You seem like you roughly know what’s going on so here’s a sketch: use sets instead of lists, this way you avoid duplicates (and know if you’ve added nothing new). Now do a standard breadth first pass over the graph following all epsilon transitions. Ie start with `known = {s}` and `edge = {s}` and each step you replace `edge` by `getClosure edge - known` (interpreted in the reasonable way) and simultaneously replace `known` by `union known (getClosure edge)`. Then keep going until `edge` is empty. `known` is then your epsilon-closure. – Dan Robertson Feb 18 '18 at 03:12
  • 1
    @DanRobertson I think you should write that up as an answer. – Paul Johnson Feb 18 '18 at 10:19
  • 1
    Here's a detailed exploration. https://stackoverflow.com/questions/28549336/is-there-way-to-represent-static-data-in-haskell-or-is-there-any-other-elegant – Gurkenglas Feb 19 '18 at 06:34

0 Answers0