Last active
December 5, 2016 02:08
-
-
Save fcard/b735e642e6613feffad2d00f3c4298bd to your computer and use it in GitHub Desktop.
A few simple metaprogramming exercises in julia
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
# All expressions must evaluate to true | |
# Swap the first two arguments of a call expression | |
@swap_arguments(1 - 2) == 2 - 1 | |
# "Invert" the operator of an expression | |
@invert_op(1 - 2) == 1 + 2 | |
@invert_op(1 + 2) == 1 - 2 | |
@invert_op(1 * 2) == 1 / 2 | |
@invert_op(1 / 2) == 1 * 2 | |
# Count the number of arguments to all function calls | |
@argcount(1 + 1) == 2 | |
@argcount(1 + 1 - 2) == 3 | |
@argcount((1 + 2) * (2 + 3)) == 4 | |
# Substitute a given name by a value in a call expressions | |
@subs(x=>1, x+2) == 1+2 | |
@subs(y=>2, (2y + 3y)) == 2*2 + 3*2 | |
# Simple case statement | |
@case 1 begin | |
1 => true | |
2 => false | |
3 => false | |
end | |
let x = 2 | |
@case x begin | |
1 => false | |
2 => true | |
3 => false | |
end | |
end | |
let x = 3 | |
@case x begin | |
1 => false | |
2 => false | |
3 => true | |
end | |
end | |
# A few differentiation rules: | |
@derivative((x) -> 1)(3) == ((x) -> 0)(3) | |
@derivative((x) -> x)(3) == ((x) -> 1)(3) | |
@derivative((x) -> 2x)(3) == ((x) -> 2*1)(3) | |
@derivative((x) -> x+2)(3) == ((x) -> 1+0)(3) | |
@derivative((x) -> x^2)(3) == ((x) -> 2x)(3) | |
@derivative((x) -> 2x^2)(3) == ((x) -> 2*2x)(3) | |
@derivative((x) -> 2x^3)(3) == ((x) -> 2*3x^2)(3) | |
let n = 2 | |
@derivative((y) -> n*y)(3) == ((y) -> n)(3) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment