Last active
October 4, 2018 18:26
-
-
Save Willmo36/47faf63d30f92e2f14007b333b524159 to your computer and use it in GitHub Desktop.
Haskell Vector learnings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data Vec = Vec [Int] | |
deriving (Show, Eq) | |
instance Monoid Vec where | |
mempty = (Vec mempty) | |
mappend = vecAdd | |
vecAdd (Vec a) (Vec b) = Vec $ zipWith (+) a b | |
vecSubtract (Vec a) (Vec b) = Vec $ zipWith (-) a b | |
scalarMultiply :: Int -> Vec -> Vec | |
scalarMultiply s (Vec v) = Vec $ map (s*) v | |
vecFold :: Vec -> Int | |
vecFold (Vec v) = foldr (+) 0 v | |
dotProduct :: Vec -> Vec -> Int | |
dotProduct (Vec a) (Vec b) = foldr (+) 0 zipped | |
where | |
zipped = zipWith (*) a b | |
-- Produces a matrix as*bs instead of a zip | |
-- dotProduct' :: Vec -> Vec -> Int | |
-- dotProduct' (Vec as) (Vec bs) = sum [ a*b | a <- as, b <- bs] | |
--using let instead of where | |
dotProduct' :: Vec -> Vec -> Int | |
dotProduct' (Vec a) (Vec b) = | |
let zipped = zipWith (*) a b | |
in foldr (+) 0 zipped | |
vecSquare :: Int -> Vec -> Vec | |
vecSquare n v = foldr mappend v vs | |
where | |
vs = replicate (n -1) v | |
vecLength :: Floating a => Vec -> a | |
vecLength v = sqrt $ fromIntegral $ vecFold $ (vecSquare 2 v) | |
fromTuple :: (Int, Int, Int) -> Vec | |
fromTuple (a,b,c) = Vec [a,b,c] | |
crossProduct :: (Int, Int, Int) -> (Int, Int, Int) -> (Int, Int, Int) | |
crossProduct (a1, a2, a3) (b1, b2, b3) = (c1, c2, c3) | |
where | |
c1 = (a2*b3) - (a3*b2) | |
c2 = (a3*b1) - (a1*b3) | |
c3 = (a1*b2) - (a2*b1) | |
a = Vec [1,2,3] | |
b = Vec [1,5,7] | |
c = (1,2,3) | |
d = (1,5,7) | |
cIsOrthoganal = (fromTuple $ crossProduct c d) `dotProduct` (fromTuple c) == 0 | |
dIsOrthoganal = (fromTuple $ crossProduct c d) `dotProduct` (fromTuple d) == 0 | |
main = do | |
putStrLn $ "Addition: " ++ (show $ vecAdd a b) | |
putStrLn $ "Subtraction: " ++ (show $ vecSubtract a b) | |
putStrLn $ "Scalar Multiply: " ++ (show $ scalarMultiply 3 a) | |
putStrLn $ "Dot Product: " ++ (show $ dotProduct a b) | |
putStrLn $ "Dot Product List comp: " ++ (show $ dotProduct' a b) | |
putStrLn $ "Length: " ++ (show $ vecLength a) | |
putStrLn $ "Cross Product: " ++ (show $ crossProduct c d) | |
putStrLn $ "Cross Product is orthoganal: " ++ (show cIsOrthoganal) ++ " & " ++ (show dIsOrthoganal) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment