-
-
Save remusao/7179709 to your computer and use it in GitHub Desktop.
Julia examples
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
################## | |
# Calling C code # | |
################## | |
# Simple function that wrap a call to libc clock function | |
clock() = ccall( (:clock, "libc"), Int32, ()) | |
t = clock() | |
# Do some stuff | |
println(clock() - t) | |
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
################# | |
# Multi-methods # | |
################# | |
# Method declaration | |
# foo is a function taking one argument of any type | |
function foo(bar) | |
println(bar) | |
end | |
# Shorter function declaration | |
baz(x) = println(x) | |
# Multimethod | |
# Takes an argument of type Int (Haskelish syntax) | |
myprint(x::Int) = println("Int") | |
# Takes an argument of type Matrix (of any type) | |
myprint(x::Matrix) = println("Matrix") | |
# Take an argument of type Matrix of Float64 | |
myprint(x::Matrix{Float64}) = println("Matrix of Float64") | |
myprint(42) # First one is called | |
myprint([1 2 3]) # Second one is called | |
myprint([0.5 0.42]) # Third one is called |
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
########################## | |
# Variable and iteration # | |
########################## | |
# Dynamic type | |
a = 42 # Int | |
a = "toto" # String | |
a = [1, 2, 3] # Vector | |
a = [1 2 3] # 1x3 Matrix | |
a = [1:3] # same 1x3 Matrix | |
for e in a | |
println(test) | |
end | |
# Output | |
# 1 | |
# 2 | |
# 3 |
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
################################### | |
# Templating and type constraints # | |
################################### | |
function printtype(m) | |
println("Any type") | |
end | |
# Takes argument of type T, in julia a type | |
# is an object, so you can print it | |
function printtype{T}(m::T) | |
println(T) | |
end | |
# Takes an argument of type T, with the constraint FloatingPoint | |
function printtype{T <: FloatingPoint}(m::T) | |
println("Floating Point") | |
end | |
printtype(42) | |
printtype(0.42) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment