Skip to content

Instantly share code, notes, and snippets.

@Koitaro
Created March 6, 2010 21:49
Show Gist options
  • Save Koitaro/323966 to your computer and use it in GitHub Desktop.
Save Koitaro/323966 to your computer and use it in GitHub Desktop.
/* Concurrent Clean code for ini file */
:: INI = {section :: String, key :: String, value :: String}
instance toString INI where
toString ini = ini.section +++ "\t" +++ ini.key +++ "\t" +++ ini.value
toStringINIList :: [INI] -> String
toStringINIList ini = f "" "" ini where
f str _ [] = str
f str section [x:xs]
| x.section == section = f (str +++ kv) section xs
| otherwise = f (str +++ sec +++ kv) x.section xs
where
kv = x.key +++ "=" +++ x.value +++ "\n"
sec = "[" +++ x.section +++ "]\n"
getINI :: [INI] String String -> String
getINI [] _ _ = ""
getINI xs section key
| (length droped) == 0 = ""
| otherwise = (hd droped).value
where
droped = dropWhile (\x = x.section <> section || x.key <> key) xs
parseINI :: [INI] String [[Char]] -> [INI]
parseINI res _ [] = res
parseINI res section [x:xs]
| is comment = parseINI res section xs
| is sect = parseINI res sectionNew xs
| is keyVal = parseINI (res ++ [kv]) section xs
| otherwise = parseINI res section xs
where
is (Succ _) = True
is (Err _ _ _) = False
succValue (Succ x) = hd x
comment = parse commentParser x "" ""
sect = parse sectionParser x "" ""
sectionNew = toString (succValue sect)
keyVal = parse keyValParser x "" ""
(k,v) = succValue keyVal
kv = {INI | section = section, key = toString k, value = toString v}
commentParser = symbol ';'
sectionParser = (symbol '[') &> grazeTo (symbol ']')
keyValParser = grazeOver (symbol '=') <&&> grazeTo empty
readINI :: File -> [INI]
readINI file = parseINI [] "" (mklines (charsRead file)) where
charsRead file
| not ok = []
| otherwise = [char : charsRead fp]
where
(ok,char,fp) = sfreadc file
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment