[Haskell-beginners] shortening code
Felipe Lessa
felipe.lessa at gmail.com
Tue Jun 29 20:50:06 EDT 2010
(Sorry, rizwan, first e-mail wasn't sent to the list)
On Tue, Jun 29, 2010 at 8:35 PM, rizwan hudda <rizwanhudda at gmail.com> wrote:
> I have recently started learning haskell, and was trying to write a code for
> this problem http://www.spoj.pl/problems/KAMIL in haskell. The aim is to
> write a shortest possible code for the given task. I have previously solved
> this in c,c++,perl,python.My best was 57 characters using perl. So here's my
> code in HASKELL:
>
> main = interact $ unlines. map (show.foldl (\a x-> if null $ filter (==x)
> "TDLF" then a else a+a) 1) .lines
>
> It is 107 characters [ non white space and newline ]. I was interested in
> knowing how i could further optimize the size of this code.
Well, we have:
null (filter (== x) cs) = x `notElem` cs = not (x `elem` cs)
So we get:
main = interact $ unlines . map (show . foldl (\a x -> if elem x
"TDLF" then a+a else a) 1) . lines
I'm not looking at the problem, but if I understood the line above
correctly, each line should print 2^n where n is the number of
elements TDLF in that line:
main = interact $ unlines . map (show . (2^) . length . filter
(`elem` "TDLF")) . lines
That's 70 non-whitespace characters. This one-liner is pretty
readable, probably more than the Perl one ;D.
Cheers,
--
Felipe.
More information about the Beginners
mailing list