如何将文件中的数据结构转换为函数
问题描述:
这是我在Haskell中做DFA的尝试。 DFA的作品,但现在我想它读取一些文件,而不是硬编码表。使用foldl
完成。现在问题是我需要定义函数table
,我希望函数t
不需要定义table
,只需从内存中取出。如果我在t
中使用3个参数,那么我不能使用foldl
。如何将文件中的数据结构转换为函数
module DFA where
data DFA = DFA { intialState :: String
, isAccepting :: String -> Bool
, transition :: String -> Char -> String
}
-- estado inicial
i = "Q1"
-- criterio de aceptación
a = (`elem` ["Q1"])
table :: [((String, Char), String)]
table = [(("Q1",'A'), "Q2")
,(("Q1",'B'), "Q1")
,(("Q2",'A'), "Q1")
,(("Q2",'B'), "Q2")]
strToRow :: [String] -> [((String, Char), String)]
strToRow str = map crea_tupla por_espacios
where
crea_tupla [x,y,z] = ((x, head y), z)
por_espacios = map words str
readDFA :: String -> IO()
readDFA filename = do
contenidos <- readFile filename
print . strToRow . lines $ contenidos
t n c = case lookup (n,c) table of
Just x -> x
_ -> error "transición errónea"
dfa = DFA i a t
testDFA :: DFA -> [Char] -> Bool
testDFA (DFA i a t) = a . foldl t i
文件格式很简单,只有一个状态字符:
Q1 A Q2
Q1 B Q1
Q2 A Q1
Q2 B Q2
答
您可以使用foldl
即使添加第三个参数。假设你在新的参数,而不是tab
的固定table
定义
t tab n c = case lookup (n,c) tab of
Just x -> x
_ -> error "transición errónea"
使t
行为。要使用foldl
你现在需要使用
dfa = DFA i a (t table)
这是因为t tab
是通过固定的第一个参数一个双参数功能,从以上三个参数功能t
获得。为了实际工作,table
必须是您刚刚从文件中读取的内容。也许你需要像(完全未经测试):
readDFA :: String -> IO()
readDFA filename = do
contenidos <- readFile filename
let table = strToRow . lines $ contenidos
dfa = DFA i a (t table)
print (testDFA dfa "some string")
工作就像一个魅力。谢谢。 – freinn 2015-04-05 13:37:19