daily pastebin goal
67%
SHARE
TWEET

Untitled

a guest May 16th, 2018 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# OPTIONS_GHC -fno-warn-tabs -fno-warn-orphans #-}
  2. {-# LANGUAGE FlexibleInstances #-}
  3. {-# LANGUAGE IncoherentInstances #-}
  4.  
  5. module Math.Vector where
  6.  
  7.  
  8. data Vec2 a = Vec2 a a deriving (Read, Show, Eq, Ord)
  9.  
  10. instance Functor Vec2 where
  11.   fmap f (Vec2 x y) = Vec2 (f x) (f y)
  12.  
  13. instance Applicative Vec2 where
  14.   pure a = Vec2 a a
  15.   (Vec2 f g) <*> (Vec2 x y) = Vec2 (f x) (g y)
  16.  
  17. instance Foldable Vec2 where
  18.     foldr f a (Vec2 x y) = f x $ f y $ a
  19.  
  20.  
  21. class (Foldable v, Applicative v) => Vector v
  22.  
  23. instance Vector Vec2
  24.  
  25. instance (Vector v, Num a) => Num (v a) where
  26.   v + v2 = pure (+) <*> v <*> v2
  27.   v - v2 = pure (-) <*> v <*> v2
  28.   v * v2 = pure (*) <*> v <*> v2
  29.   signum v = pure signum <*> v
  30.   abs v = pure abs <*> v
  31.   fromInteger i = pure (fromInteger i)
  32.  
  33.  
  34. --dot :: (Vector v, Num a, Num (v a)) => v a -> v a -> a -- works without IncoherentInstances
  35. dot :: (Vector v, Num a) => v a -> v a -> a
  36. dot v v2 = sum $ v*v2
RAW Paste Data
Top