Created
March 27, 2013 00:42
-
-
Save jayschwa/5250636 to your computer and use it in GitHub Desktop.
ImmutableArrays prototype using metaprogramming
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
module ImmutableArrays | |
export Vector2, Vector3, Vector4 | |
importall Base | |
for n = 2:4 | |
local Typ = symbol(string("Vector", n)) | |
local TypT = Expr(:curly, Typ, :T) | |
local definition = :(immutable $TypT <: AbstractVector{T} end) | |
for i = 1:n | |
element = symbol(string("e", i)) | |
push!(definition.args[3].args, :($element::T)) | |
end | |
eval(definition) | |
@eval function getindex(x::$Typ, i::Integer) | |
element = symbol(string("e", i)) | |
return x.(element) | |
end | |
@eval -(a::$Typ) = $Typ(ntuple($n, x-> -a[x])...) | |
@eval +(a::$Typ, b::$Typ) = $Typ(ntuple($n, x-> a[x]+b[x])...) | |
@eval -(a::$Typ, b::$Typ) = $Typ(ntuple($n, x-> a[x]-b[x])...) | |
@eval .*{T}(a::$TypT, b::Number) = $TypT(ntuple($n, x-> convert(T, a[x]*b))...) | |
@eval .*(a::Number, b::$Typ) = .*(b, a) | |
@eval ./{T}(a::$TypT, b::Number) = $TypT(ntuple($n, x-> convert(T, a[x]/b))...) | |
@eval similar{T}(::$TypT, t::DataType, dims::Dims) = Array(t, dims) | |
@eval size(::$Typ) = ($n,) | |
end | |
end |
@dronir: Would you mind retrying this exercise with what I put in the repo. Even better, if you could make a benchmark script to go in the test directory to automate what you've done here, that would be awesome.
I've defined the arithmetic in terms of a higher-order function (zipWith) that I guess I'm hoping gets inlined away. If it doesn't we'll brute force the inlining in the automatic code generation.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Forgot to add, it's probably not about the
getindex
. I tried to get rid of it that by replacing thentuple($n, x-> a[x]+b[x])
byntuple($n, x-> a.(symbol(string("e", x)))+b.(symbol(string("e", x))))
and it didn't affect the numbers. But I'm not sure if I did that right.