[Haskell-beginners] Shorten this code

Gesh hseG gesh at gesh.uni.cx
Thu Aug 1 17:09:11 CEST 2013


On Wed, Jul 24, 2013 at 4:18 PM, Henk-Jan van Tuyl <hjgtuyl at chello.nl> wrote:
> On Tue, 23 Jul 2013 12:41:32 +0200, Nadav Chernin <nadavchernin at gmail.com>
> wrote:
>
>> Hi, all
>> Below is my solution to SPOJ->Polybius
>> square<http://www.spoj.com/problems/POLYBIUS>
>>
>>
>> Please try to shorten it:
>>
>> *import Data.Maybe*
>> *d=[1..5]*
>> *f s=unwords$map(\c->fromJust$lookup c(('
>> ',""):('J',"24"):zip(['A'..'I']++['K'..'Z'])[show(x+10*y)|y<-d,x<-d]))s*
>> *main=getLine>>(interact$unlines.map f.lines)*
> d="12345"
> f s = unwords $ map (\c -> let (Just x) = lookup c ((' ',"") : ('J',"24") :
> zip (['A'..'I'] ++ ['K'..'Z']) [y : [x] | y <- d, x <- d]) in x) s
> main = getLine >> (interact $ unlines . map f . lines)

Note that you can point-freeify that solution a little and sacrifice totality,
yielding an even shorter solution. (I didn't remove the lambda expression,
as it ends up being shorter than flipping lookup)
Inline the definitions and remove redundant spaces and newlines
in the code below:
d = "12345"
f = unwords . map $
\c -> fromJust $ lookup c ((' ',"") : ('J',"24") : zip
(['A'..'Z']\\"J") [[y,x] | y <- d, x <- d])
main = interact $ unlines . map f . drop 1 . lines

Just my two cents.
Gesh




More information about the Beginners mailing list