[Haskell-cafe] Construction of short vectors

Roman Leshchinskiy rl at cse.unsw.edu.au
Sun Jun 27 05:55:21 EDT 2010


On 25/06/2010, at 06:41, Alexey Khudyakov wrote:

> Then constructor like one below arise naturally. And I don't know how to write
> them properly. It's possible to use fromList but then list could be allocated
> which is obviously wasteful.
> 
>> vector2 :: Double -> Double -> Vec2D
>> vector2 x y = ...
>> -- Vec2D is some wrapper around Vector data type

Your best bet is probably singleton x ++ singleton y. Unfortunately, GHC doesn't seem to provide any real way of specifying array literals.

> Another question is there any specific problems with short vectors? They could
> be just 2 elements long. I mean performance problems

A data type like this one should be faster:

data Vec2D = Vec2D {-# UNPACK #-} !Double {-# UNPACK #-} !Double

Firstly, this needs one less indirection for accessing the components. Secondly, GHC's simplifier knows a lot more about algebraic data types than it does about arrays so the above definition will often lead to better optimisations. Whether or not the difference is significant probably depends on the program.

Roman




More information about the Haskell-Cafe mailing list