Skip to content

Instantly share code, notes, and snippets.

@stevedonovan
Created March 26, 2012 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevedonovan/2204798 to your computer and use it in GitHub Desktop.
Save stevedonovan/2204798 to your computer and use it in GitHub Desktop.
Covariance with pl.class: a specialized List of numbers
require 'pl'
class.Array(List)
function Array.__add (a1,a2)
return a1:map2('+',a2)
end
function Array.__sub (a1,a2)
return a1:map2('-',a2)
end
function Array.__mul (a1,a2)
if type(a1) == 'number' then
a1,a2 = a2,a1
end
return a1:map('*',a2)
end
function Array.__div (a,num)
return a:map('/',num)
end
function Array:sum ()
return self:reduce '+', #self
end
function Array:length ()
local res = 0.0
for i = 1,#self do
res = self[i]^2
end
return res
end
a1 = Array {1,2,3}
a2 = Array {10,20,30}
print(a1 + a2, a2 - a1)
print(3*(a1 + a2), a2/2)
print(a1:slice(1,2)+a2:slice(1,2))
print(a1:sum())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment