Last active
August 29, 2015 14:04
-
-
Save kenchangh/c9f3763b7699e9f55514 to your computer and use it in GitHub Desktop.
A practice on 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
# This is just for practice! | |
# Single line comment | |
#= | |
This is a multiline comment | |
=# | |
# Function syntax | |
function name(x, args...) | |
# do something | |
end | |
# More terse way to write function | |
name(x, args...) = (x = 10; y = 5) | |
# Control flow | |
if x == 5 | |
elseif x == 4 | |
else | |
end | |
# Ternary operator | |
x > 5 ? "x is bigger than 5" : "x is smaller than 5" | |
# Compound Expressions | |
y = (x = 5; z = 3) | |
# Alternative syntax with begin | |
y = begin | |
x = 5 | |
z = 3 | |
end | |
# do operator to pass function as parameter | |
map([1, 2, 3, 4]) do | |
curve(x) = x^2 + x + 1 | |
end | |
# alternative do | |
map(curve(x) -> | |
x^2 + x + 1 | |
end, [1, 2, 3, 4]) | |
# try, catch, finally | |
f = open("file") | |
try | |
# do something with file | |
catch | |
# do something on error | |
finally | |
close(f) | |
end | |
# Loops | |
while i < 5 | |
end | |
# If for loop is empty, will increment value | |
for i = 1:5 | |
end | |
for i in array | |
end | |
# Type constructor with optional type parameter | |
type Name{T} | |
# Assertion on foo's type | |
foo::T | |
end | |
function saysomething{T<:String}(something) | |
println(something::T) | |
end | |
# Constructing types | |
myname = Name("Maverick") | |
# Importing the whole module | |
using HTTPServer | |
# Importing only certain functions and types | |
import Datetime: datetime, time | |
# Modules and exports | |
module # don't indent the rest of the lines inside | |
export Name, curve | |
type Name | |
x | |
end | |
curve(x) = x^2 + x + 3 | |
end | |
# A very good example of macros and expressions | |
macro time(ex) | |
return quote | |
local t0 = time() | |
local val = $(esc(ex)) | |
local t1 = time() | |
println("elapsed time: ", t1-t0, " seconds") | |
val | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment