Created
January 31, 2016 17:03
-
-
Save charles-cooper/0fed02084188dc5cf2f4 to your computer and use it in GitHub Desktop.
vectorised numeric instances in haskell
This file contains 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
-- These are straightforward. Just map or zipWith all operations. | |
-- The only interesting one is fromInteger, typically when people | |
-- do an operation on a vector and a scalar, they mean to run it | |
-- over the vector. E.g. [1,2,3] * 1. | |
instance Num a => Num [a] where | |
(+) = zipWith (+) | |
(*) = zipWith (*) | |
abs = map abs | |
signum = map signum | |
fromInteger = repeat . fromInteger | |
negate = map negate | |
-- It pretty much breaks down from here. The basic problem being it | |
-- is easy to define fromNum (just repeat . fromNum) but not toNum. | |
-- How does one coerce a vector to a scalar? | |
instance Real a => Real [a] where | |
toRational = toRational . head -- busted. | |
instance Enum a => Enum [a] where -- busted. | |
instance Integral a => Integral [a] where | |
quotRem xs ys = unzip $ zipWith quotRem xs ys | |
toInteger = toInteger . head -- busted. | |
instance Fractional a => Fractional [a] where | |
fromRational = repeat . fromRational | |
(/) = zipWith (/) | |
instance Floating a => Floating [a] where | |
pi = repeat pi | |
exp = map exp | |
log = map log | |
sin = map sin | |
cos = map cos | |
asin = map asin | |
acos = map acos | |
atan = map atan | |
sinh = map sinh | |
cosh = map cosh | |
asinh = map asinh | |
acosh = map acosh | |
atanh = map atanh | |
main = do | |
-- Num examples | |
print $ [1,2,3] + [4,5,6,7] | |
print $ [1,2,3] + 1 | |
let x = [1,2,-1] | |
print $ abs x * signum x -- should be id | |
-- integral | |
print $ [4,5,6] `div` [1,2,3] | |
-- fractional | |
print $ [4,5,6] / [1,2,3] | |
print $ [1,2,3] ** 3 | |
print $ [1,2,3] ** [1,2,3] | |
-- others | |
print $ even [2,3,4,5,6,7,8] -- busted. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment