Covariance with pl.class: a specialized List of numbers
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
| 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