开发者

What is the inverse of this function?

flattern :: [(Char, Int)] -> String
flattern [] = ""
flattern ((w,l):xs) = show l ++ w : flattern xs

What would be th开发者_开发技巧e inverse function of this? Is there any way of be able to work this out?


It's not invertible:

  1. There are strings that cannot be reproduced by this function (any string not starting with a digit).

  2. It's not even partially invertible. There are also strings that correspond to multiple inputs: "1111" can be produced by either [('1',1),('1',1)] or [('1',111)].

Are you sure that this was the function to invert, and not something like flattern ((w,l):xs) = replicate l w ++ flattern xs?


If you really want, you could parse the output of the function to try and reconstruct what the arguments must have been.

import Text.ParserCombinators.Parsec

unflat1 :: Parser (Char, Int)
unflat1 = do
           c <- anyChar
           n <- many1 digit
           return (c, read n) 

readExpr :: String -> Either String [(Char, Int)]
readExpr input = case parse (many unflat1) "unflat" input of
    Left err -> Left ("No match: " ++ show err)
    Right val -> Right val

This sorta works, as long as flattern does not have numbers as the first input. Something like flattern [('a',1), ('2',3)] will be parsed as [(a, 123)].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜