1 module Vectors(Vector,vec,x,y,z,inpr,mulv,len,norm) where
    2 import Numbers
    3 {- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    4 -- section 2: Vectors
    5 
    6 Vectors can be added to each other (+), subtracted (-),
    7 you can build the outer product of two vectors (*)
    8 and there is a denotation for the zero vector (0).
    9 To be able to use the symbols + - * and 0 we make
   10 vectors an instance of Num.
   11 
   12 Further we have the operations
   13 - vec, to build a vector from a list of coordinates
   14 - coordinate selection x,y and z
   15 - inner product
   16 - multiply a vector by a scalar (mulv)
   17 - length
   18 - norm
   19 
   20 -}
   21 
   22 data Vector = Vec [Number] deriving (Eq)
   23 -- if you are not using the Chalmers Haskell B compiler then remove the @
   24 {- needed for GOFER
   25    remove the deriving and add:
   26 instance Eq Vector where
   27         v == w = len(v-w) == 0
   28 -}
   29 instance Num Vector where
   30         Vec v + Vec w  = Vec (zipWith (+) v w)
   31         Vec v - Vec w  = Vec (zipWith (-) v w)
   32         v * w  = Vec    [y(v)*z(w) - y(w)*z(v)
   33                         ,z(v)*x(w) - z(w)*x(v)
   34                         ,x(v)*y(w) - x(w)*y(v)]
   35         negate (Vec v) = Vec (map negate v)
   36         abs v   = Vec [len v]
   37         signum v       = norm v
   38         fromInteger 0  = Vec [0,0,0]
   39 
   40 instance Show Vector where
   41         showsPrec p (Vec v) = showParen (p>9) (showString "vec ". showList v)
   42 instance Read Vector where
   43         readsPrec p = readParen (p>9) rd
   44                       where rd s = [(Vec ns,u) | ("vec",t) <- lex s,
   45                                                  (ns,u)    <- readList t,
   46                                                  length ns >= 2]
   47 
   48 vec :: [Number] -> Vector
   49 vec = Vec
   50 
   51 x,y,z :: Vector -> Number
   52 x(Vec v) = v !! 0
   53 y(Vec v) = v !! 1
   54 z(Vec v) = v !! 2
   55 
   56 inpr :: Vector -> Vector -> Number
   57 Vec v1 `inpr` Vec v2 = sum (zipWith (*) v1 v2)
   58 
   59 mulv :: Number -> Vector -> Vector
   60 c `mulv` (Vec v) = Vec (map (c*) v)
   61 
   62 len :: Vector -> Number
   63 len v = sqrt (v `inpr` v)
   64 
   65 norm :: Vector -> Vector
   66 norm v = (1/len v) `mulv` v