[Haskell-cafe] Hints for Euler Problem 11
Jules Bean
jules at jellybean.co.uk
Fri Jul 20 03:29:39 EDT 2007
> I came up with this function to try to extract the main diagonal.
>
> > getDiag :: [[a]] -> [a]
> > getDiag = map (head . head) . iterate (tail . map tail)
>
> The problem is, this function doesn't work unless I have an infinite
> grid.
>
> Could anyone provide me with some hints to lead me in the right direction?
I think Dan's hint is pretty good, but a hint for this *specific* part
of the problem, rather than the whole thing.
'head' and 'tail' blow up on empty lists. So any kind of solution
involving iterate and similar with them tends to eventually blow up on
finite lists.
(take 1) and (drop 1) are rather similar functions, but they simply give
[] on [] instead of blowing up. Then, on a finite list, you just keep
getting []s after a while, which you can trim with takeWhile (not . null).
Another approach is to replace iterate with an unfoldr; an unfoldr is
rather like a 'general iterate' which 'knows when to stop' : it stops
when your unfolding function gives Nothing.
Jules
More information about the Haskell-Cafe
mailing list