Perl Christmas Quiz

Hakim Cassimally hakim.cassimally at gmail.com
Mon Dec 15 13:38:03 GMT 2008


On 15/12/2008, Avleen Vig <avleen at gmail.com> wrote:
> On Dec 15, 2008, at 10:04, "James Laver" <james.laver at gmail.com> wrote:
> > On Sun, Dec 14, 2008 at 3:15 PM, Avleen Vig <avleen at gmail.com> wrote:
> > > On Fri, Dec 12, 2008 at 9:50 AM, Chris Jack <chris_jack at msn.com> wrote:
> > > > 3) Write a Perl function that takes two references to arrays and
> returns the intersect of them. If an entry appears n times in array 1 and m
> times in array 2, the output should list that entry min(n,m) times. Bonus
> mark for one line solutions.
> > > >
> > > In the spirit of sharing, I offer this solution, from your neighbours
> > > in the Python community:
<snip>
> > > :-)
> > Using other languages is really cheating.
>
>  Well duh. There were alreay multiple Perl solution out there. And I didn't
> know a better one.
>
>  Plus I just wanted to be a snob with my four-line solution.

In the same spirit (and once pndc had corrected me on the spec...
d'oh!) I attempted in Haskell... but pretty much failed at a compact
solution:

import Data.List
minIntersect :: Ord a => [a] -> [a] -> [a]
minIntersect a1 a2 = let gs = group .sort
          in aux (gs a1) (gs a2)
          where aux is'@(i'@(i:_):is) js'@(j'@(j:_):js) =
                    case (i `compare` j) of
                        EQ -> (zipWith const i' j') ++ (aux is js)
                        LT -> aux is  js'
                        GT -> aux is' js
                aux _ _ = []

On the plus side, I think the nested @patterns give perl's line noise
a run for it's money :-)

osf'


More information about the london.pm mailing list