You are not logged in.
Pages: 1
Hi!
Have a q on pattern matching.
How do I change all strings in a file that look like this:
StringWords, RestOfString
into:
NewStringWords, RestOfString
I have this textfile:
table=training
values=year, month, date, day, type, duration
2010, July, 9th, Friday, MTB, 160
Now, I want to convert this textfile, and similar textfiles into this:
insert into table=training(year, month, date, day, type, duration) values ('2010', 'July', '9th', 'Friday', 'MTB', '160');
Greatful for input.
EDIT: massive simplification of question.
Last edited by Reploid (2010-07-09 16:04:12)
Offline
Based on chapter 4 of "Real World Haskell", section "Code Reuse Through Composition":
-- Convert the string into a list of strings and then foldr over it
-- to convert it row for row. After the fold, convert the list of strings back
-- into a string.
convertTableTraining :: String -> String
convertTableTraining = unwords . foldr convertRows [] . lines
where convertRows x xs
| "table=" `isPrefixOf` x =
insertIntoTable x xs
| "values=" `isPrefixOf` x =
getValueNames x : xs
| otherwise =
getValues x : xs
-- This is just there to have no whitespace between "training" and
-- the left parenthesis. If this isn't crucial, you can just omit
-- this function and cons "insert into table=training" to the list
-- above.
insertIntoTable :: String -> [String] -> [String]
insertIntoTable _ xs = ("insert into table=training" ++ head xs) : tail xs
-- Add the parentheses and drop "values=".
getValueNames :: String -> String
getValueNames xs = "(" ++ valueNames xs ++ ")"
where valueNames = drop 7
-- Add "values ( )" and add "\n" at the end so that there is an
-- end-of-line.
getValues :: String -> String
getValues xs = "values (" ++ values xs ++ ");\n"
-- Filter the commas out since they get in the way after the quotes
-- have been added. This assumes that there is always a whitespace
-- after a comma. If you want to be safe, you could use the 'replace'
-- function in Data.String.Utils of the MissingH library. (Didn't try
-- it)
where values xs = let filteredWords = words $ filter (/= ',') xs
in unwords $ foldr addQuotes [] filteredWords
addQuotes x [] = ("'" ++ x ++ "'" ) : []
addQuotes x xs = ("'" ++ x ++ "',") : xs
So you basically read your file and use such a function on the input. This input gets converted into a list of strings and is being processed with a fold. After that the list of strings needs to be converted back into a single string which you can write to whatever output file you want.
Note that I'm not really experienced myself. I'm pretty sure there are better ways to accomplish this.
Offline
Pages: 1