在下面的代码中,我很满意功能,即代码生成我期望的输出。但是,比较至Col至至Int的长度 - 我有兴趣了解您是否可以提供某些内容(即至Col)。非常感谢!Excel列到Int,反之亦然 - 寻求改进
-- given a spreadsheet column as a string
-- returns integer giving the position of the column
-- ex:
-- toInt "A" = 1
-- toInt "XFD" = 16384
toInt :: String -> Int
toInt = foldl fn 0
where
fn = \a c -> 26*a + ((ord c)-64)
-- given a integer returns
-- the column to be found at that position as a [Char]
-- ex:
-- toCol 1 = "A"
-- toCol 16384 = "XFD"
toCol :: Int -> [Char]
toCol n = toCol' n []
where
toCol' 0 a = a
toCol' n a =
let r = mod n 26 in
case (r == 0) of
True -> toCol' (div (n-1) 26) ('Z':a)
False -> toCol' (div n 26) (chr(r + 64) : a)
建议无关你的问题:(1)你应该使用'foldl''(从'Data.List模块')而不是'toInt'中的'foldl' - 参见[* foldr与foldl(或foldl')*]的影响(http://stackoverflow.com/q/384797/2751851)。 (2)你可能想考虑使用'toInt :: String - > Maybe Int',这样如果给出一个无效的字符串(例如'“@#!”'),你就不会被迫返回无稽之谈。 – duplode