[Haskell-beginners] Reducing local variable duplication

Michael Orlitzky michael at orlitzky.com
Tue Aug 30 14:15:02 CEST 2011


On 08/29/2011 03:58 PM, Brent Yorgey wrote:
> 
> 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.


Correct, these are trivial cases. There is one expensive function that I
would like to avoid recomputing, but no simple examples I could give of it.

This is actually the solution that kmc gave me on #haskell, but my home
connection has been hurricaned and I haven't been able to reply. I
wouldn't mind the list/tuple solution otherwise; but, this is the best I
could come up with haddock-wise:

> -- | Check the value of c0030 for tetrahedron0 belonging to the cube
> --   centered on (1,1,1) with a grid constructed from the trilinear
> --   values. See example one in the paper.
> test_trilinear_c0030 :: Assertion    
> test_trilinear_c0030 = test_trilinear_c0030'
>                        
> [test_trilinear_c0030'] = [test_trilinear_c0030'']
>   where
>     g = make_grid 1 trilinear
>     cube = cube_at g 1 1 1
>     t = tetrahedron0 cube
>             
>     test_trilinear_c0030'' :: Assertion
>     test_trilinear_c0030'' =
>       assertAlmostEqual "c0030 is correct" (c t 0 0 3 0) (17/8)


It /works/, but gives me that "what the hell is he doing.." feeling when
re-reading my own code.



More information about the Beginners mailing list