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?