[Haskell-beginners] Reducing local variable duplication

Brent Yorgey byorgey at seas.upenn.edu
Mon Aug 29 21:58:56 CEST 2011


On Mon, Aug 29, 2011 at 11:35:50AM -0400, Michael Orlitzky wrote:
> since later tests may need different values of p0,p3. What I would
> really like is something like the following. Is it possible?
> 
> > let p0 = (0, -0.5, 0)
> >     p3 = (1, 0, 1)
> > in
> >   test_volume1 :: Assertion
> >   test_volume1 =
> >     assertEqual "volume is correct" True (vol ~= (-1/3))
> >     where
> >       p1 = (0, 0.5, 0)
> >       p2 = (2, 0, 0)
> >       ...
> > 
> >   test_volume2 :: Assertion
> >   test_volume2 =
> >     assertEqual "volume is correct" True (vol ~= (1/3))
> >     where
> >       p1 = (2, 0, 0)
> >       p2 = (0, 0.5, 0)
> >       ...

No, this is not possible directly.  You have several options. As
someone else already suggested, one option is to declare p0, p3 in the
global scope and then shadow them in any local scopes where you would
like them to have different values.  Another option might be to do
something like this:

[test_volume1, test_volume2] =
  [ let p1 = (0, 0.5, 0)
        p2 = (2, 0, 0)
    in  assertEqual "volume is correct" True (vol ~= (-1/3))
   
  , assertEqual "volume is correct" True (vol ~= (1/3))

  ...
  
  ]
  where p0 = ...
        p3 = ...

However, this is a bit brittle if you ever want to reorder the tests
or insert new tests, since you have to update the list of names and
list of test bodies to stay in sync.

Also, am I correct in assuming the above is actually a stripped-down
version of the real code?  p0, p1, p2... etc. do not actually show up
in the tests you have written at all.

-Brent



More information about the Beginners mailing list