performance,for-loop,julia-lang

The answer taking "Is it always better to avoid such top-level variables?" literal is of course "No, it depends", but a useful remark is that declaring global variables as constant const N = 10000000 makes case 2 as fast as case 3....

Perhaps Julia's vcat and hcat functions will satisfy your requirements. julia> using DataFrames julia> df1 = DataFrame(a = 1, b = 1) 1x2 DataFrames.DataFrame | Row | a | b | |-----|---|---| | 1 | 1 | 1 | julia> df2 = DataFrame(b = 1, c = 1) 1x2 DataFrames.DataFrame...

The HDF5.jl package has to deal with this. It tackles it by parsing the string and then inspecting the result before evaling it. If the parsed string is what it considers to be a valid_type_expression then it knows that it should be safe to evaluate in the Main namespace. This...

Use for example plot(p1,0,10,p2,0,10,p3,0,10) When plotting a function with Winston you need to specify an xrange for the plot. The example above will generate a plot for an xrange 0...10....

Knowing nothing of 3D tensors with values of the "diagonal Gaussian", using thesquare comment from the original post, "typing" q (@code_warntype helps here: Big performance jump!), and further specializing the @nloops, this works much faster on the platforms I tried it on. julia> square(x::Float64) = x * x square (generic...

The simplest way is to read it as bytes and then convert: s = open(filename, "r") do f utf16(readbytes(f)) end Note that utf16 also checks for a byte-order-mark (BOM), so it will deal with endianness issues and won't include the BOM in the resulting s. If you really want to...

To convert a string to a regex, call the Regex function on the string. Typically, to get the length of an iterator you an use the length function. However, in this case that won't really work. The eachmatch function returns an object of type Base.RegexMatchIterator, which doesn't have a length...

This was a bug, issue filed here: https://github.com/JuliaLang/julia/issues/10997 It has been fixed since. As indicated in the comments on the question, there are some hacky workarounds if you're stuck on an unfixed Julia version, but hopefully you can upgrade....

julia> f(x::Number) = x < 1 ? 0 : 2 f (generic function with 1 method) julia> f(0) 0 julia> f(1) 2 julia> f(0.99) 0 ...

OK, thanks to jverzani's link, I was able to piece together a working example. I'm still a little shaky on the syntax in Julia for setting all the options for the plot. using PyPlot using PyCall @pyimport matplotlib.patches as patch cfig = figure() ax = cfig[:add_subplot](1,1,1) ax[:set_aspect]("equal") c = patch.Circle([0.5,0.5],0.4,fc="blue",ec="red",linewidth=.5,zorder=0)...

Use Ref{fakeCStruct}: r = Ref(fakeCStruct(3, 4)) ccall((:somefunction, "lib"), Void, (Ref{fakeCStruct},), r) From the Julia docs in the System Independent table here: C name: | Julia base type T* (where T represents an appropriately defined type) | Ref{T} ...

machine-learning,julia-lang,word2vec

The package provides a few shell scripts to pre-process the data and fit the model: you have to call them from the shell, i.e., outside Julia. # Install the package julia -e 'Pkg.clone("https://github.com/sbos/AdaGram.jl.git")' julia -e 'Pkg.build("AdaGram")' # Download some text wget http://www.gutenberg.org/ebooks/100.txt.utf-8 # Tokenize the text, and count the words...

callback,function-pointers,julia-lang,function-handle

According to the documentation, the objective function for NLOpt should be of the form: function f(x::Vector, grad::Vector): if length(grad) > 0: ...set grad to gradient, in-place... return ...value of f(x)... end Thus, the code would need to look something like: function myFun(a, b, c, d, grad) a - 3* b...

Undefined values are essentially null pointers, and there's no first-class way to "unset" an array element back to a null pointer. This becomes more difficult with very large arrays since you don't want to have much (or any) overhead for your sentinel values that represent unconnected nodes. On a 64...

julia-lang,arbitrary-precision,bigfloat

Not directly. My eventual plan is to make Distribution types parametric, which would also allow for Float32 arguments, but that is a while away yet. In the meantime, there is the non-exported φ which gives the result you wanted: Distributions.φ(x) - pdf(Normal(), x_small) ...

Formatted output to the REPL @sprintf and a loop is probably what you want Assuming test.dat contains the following: A 1 11 AT 2 12 ARE 3 13 Then using the julia @printf macro, which behaves like C printf, the following looks like what you want assuming you want 2...

Thanks Simon Byrne. My julia version is v0.3.8 less than v0.4. That's why julia prompts "@fastmath not defined".

performance,parallel-processing,julia-lang,hpc

This should get you started: function get_chunks(data::Vector, nchunks::Int) base_len, remainder = divrem(length(data),nchunks) chunk_len = fill(base_len,nchunks) chunk_len[1:remainder]+=1 #remained will always be less than nchunks function _it() for ii in 1:nchunks chunk_start = sum(chunk_len[1:ii-1])+1 chunk_end = chunk_start + chunk_len[ii] -1 chunk = data[chunk_start: chunk_end] produce(chunk) end end Task(_it) end function r_chunk_data(data::Vector) all_chuncks...

vectorization,julia-lang,nlopt

Yes, NLopt only understands vectors of decision variables. If your code is more naturally expressed in terms of matrices, then you should convert the vector into a matrix in the function and derivative evaluation callbacks using reinterpret.

well, I've just had to make: using PyPlot using Distributions function f(x) return (x[1]^2 + x[2]^2) #return sin(x[1]) + cos(x[2]) end n = 100 x = linspace(-1, 1, n) y = linspace(-1,1,n) xgrid = repmat(x',n,1) ygrid = repmat(y,1,n) z = zeros(n,n) for i in 1:n for j in 1:n z[i:i,j:j]...

performance,optimization,input,julia-lang

So my baseline time on the large input (time cat A-large-practice.in | julia original.jl) was real 0m2.730s user 0m2.683s sys 0m0.351s On my system it takes Julia about 0.2 seconds to start running the file. Putting the code in a function is possibly the most important first step - this...

c,rabbitmq,activemq,julia-lang,message-handlers

I'm not aware of one but have only done a cursory search. There are many Julia libraries which simply wrap an existing and well-understood C API. While getting the package build and install correct this way can be slightly tricky, it saves re-implementing complex protocols. There doesn't seem to be...

Quoting from your follow-up comment: B is sometimes a matrix, sometimes a vector/1D matrix - that's the problem. You can convert a vector to a 2D array with the "slicing" operation [:;:]. In other words, if B has type Array{T,1}, then B[:,:] has type Array{T,2}: julia> B = [1; 2]...

Since readall returns a String, you want something that operates on a String, split fits the bill. Base.split(string, [chars]; limit=0, keep=true) Return an array of substrings by splitting the given string on occurrences of the given character delimiters, which may be specified in any of the formats allowed by "search"'s...

IIUC, you can use cumsum: julia> block_lengths = [2, 2, 2, 2, 3]; julia> cumsum(block_lengths) 5-element Array{Int32,1}: 2 4 6 8 11 julia> [0; cumsum(block_lengths)] 6-element Array{Int32,1}: 0 2 4 6 8 11 which should be O(N)....

r,julia-lang,cross-correlation

I assume that citing this excerpt here is ok by StackOverflow's terms of use? From page 390 (section 14.1) of Venables and Ripley (2002) you can find the definition that they use here for the acf() function: If you look at the source code of the ccf() function in R...

sorting,dictionary,data-structures,julia-lang

While SortedDict may be useful if it is necessary to keep the dictionary sorted, it is often only necessary to sort the dictionary for output, in which case, the following may be what is required: list1 = [1,2,3,4,5] list2 = [6,7,8,9,19] dictionary1 = Dict(zip(list1,list2)) sort(collect(dictionary1)) ... which produces: 5-element Array{(Int64,Int64),1}:...

Macros cannot do this, but generated functions can. Check out the docs here : http://julia.readthedocs.org/en/latest/manual/metaprogramming/#generated-functions...

I discovered the reason was because I did not understand the type being parsed. Here is an example: [3:999] |> println(typeof(x)) # Array{Int64,1} Meaning the value being parsed is an array of integer64. So evaluating the following: [1:999] % 3 == 0 # false So my answer was to instead...

I'm surprised I couldn't find a duplicate question about this on SO yet. I figure I'll answer this slightly differently than the FAQ in the manual since it's a common first question. Oops, I somehow missed: Factorial function works in Python, returns 0 for Julia Imagine you've been taught...

Your error is caused because the && operator has higher precedence than the assignment operator = so your line of code is executed as if you would write (x < 4 && x) = 5. For a solution you have to add parantheses. x < 4 && (x = 5)...

This is the expected behavior. Types in Julia are invariant rather than covariant or contravariant. See this section of the manual for a more detailed explanation: http://julia.readthedocs.org/en/latest/manual/types/#man-parametric-types...

Julia and Matlab actually give the same result (for instance, the bottom-left element is -1.4e-14 in both cases): it is not exactly the identity matrix because floating point arithmetic is not exact. You can explicitly round the result before displaying it. M1 = [ 1 3 4; 45 64 33;...

julia-lang,jupyter,ijulia-notebook

Here's what I have written up: using JSON get_code_cells(j::Dict) = filter(x->x["cell_type"] == "code", j["cells"]) function parse_code_cell(c::Dict) buf = IOBuffer() write(buf, "begin\n") map(x->write(buf, x), c["source"]) write(buf, "\nend") src = bytestring(buf) parse(src) end extract_code(cells::Vector) = Expr[parse_code_cell(c) for c in cells] extract_code(j::Dict) = extract_code(get_code_cells(j)) eval_code(j::Dict) = map(eval, extract_code(j)) # get filename, then parse...

Unfortunately there is no way to do this at this time, but it is a requested feature. See this Github issue and this mailing list thread.

graph,runtime-error,julia-lang

From Julia's Manual: Julia will even let you redefine built-in constants and functions if needed: julia> pi π = 3.1415926535897... julia> pi = 3 Warning: imported binding for pi overwritten in module Main 3 julia> pi 3 julia> sqrt(100) 10.0 julia> sqrt = 4 Warning: imported binding for sqrt overwritten...

What I ended up doing looks something like this using Dates function getWWFromDate(date) year = Dates.year(date+Dates.Day(6)) #How many days since the start of the first ww of the year startOfFirstWW = Dates.firstdayofweek(Date(year)) - Dates.Day(1) #How many days from the current date to that day? doy = Dates.days(date-startOfFirstWW) ww = floor(doy/7)+1...

It turns out that method_exists is (currently) the best way to check whether a method exists for a particular type, but one needs to be very careful. My example above just happened to stumble upon some slightly confusing (but internally consistent) behaviour in Julia's inner workings. Read on if you're...

I think replacing the following lines in the first code for iter = 1:max_it oldx = copy( x ) ... by oldx = zeros( N ) for iter = 1:max_it oldx[:] = x # or copy!( oldx, x ) ... will be more efficient because no array is allocated. Also,...

scope,metaprogramming,julia-lang

The scoping issue that you are running into is that eval always evaluates expressions in global scope (the current module, unless specified otherwise). In this particular case, you could deal with that by using println(obj) instead of eval(:(println("$obj"))); there's no evaluation necessary to look at the symbol itself! But if...

Here's an example using Julia's Metaprogramming: for op in (:+, :-, :.<) @eval ($op)(a::MyType, b::MyType) = ($op)(a.x, b.x) end ...

The answer is that things get funky with parametric types and inner constructors - in fact, I think its probably the most confusing thing in Julia. The immediate solution is to provide a suitable outer constructor: using Dates type EconData{T} values::Vector{T} dates::Array{Date} colnames::Array{ASCIIString} function EconData(values, dates, colnames) if size(values, 1)...

The code is actually correct, you just have the wrong field The eigenvalue result is true for unitary matrices (complex entries); based on the code from section 4.6 of the Edelman and Rao paper, if you replace the first line by X = randn(dim, dim) + im*randn(dim, dim) you get...

1.yeah you're right. Pkg.update() is used for updating julia's packages, not julia itself. So download the prebuild version and install again seems to be the only way to upgrade julia. Or you can build julia by yourself from source https://github.com/JuliaLang/julia. 2.you can find the release notes here: https://github.com/JuliaLang/julia/blob/master/NEWS.md...

dictionary,equality,julia-lang

But look at this: type Point{T} x::T y::T end P = Point(1., 2.) D = [P => 42] haskey(D, P) evaluates to true. It does work if you use the same object, but it does not work if you use 2 objects with the same field values. Note that objects...

linux,ubuntu,ubuntu-14.04,julia-lang

You can install different versions of Julia in different locations and set separate symlinks. For example, you could download the v0.3 Linux binaries and install them to one location, then clone the GitHub source for v0.4 and install that in another location. Then set symlinks such as julia3 for v0.3...

This is certainly not optimal, but it's functional. julia> function nested_loop{T <: Integer, V <: AbstractVector}(depth::T, n::T, symb_arr::V, len::T, k::T, num_arr::V, result::Array{V,1}) for i = k:len num_arr[depth-n+1] = symb_arr[i] n == 1 ? push!(result, deepcopy(num_arr)) : nested_loop(depth, n-1, symb_arr, len, i, num_arr, result) end end nested_loop (generic function with 1...

If I understand the question right, you can generate the plot you're looking for (minus the change in alpha value for different months) with using DataFrames, Gadfly data = DataFrame() data[:DrinkType] =["Coke","Coke","Coke","Coke","Pepsi","Pepsi","Pepsi","Pepsi"] data[:Country] = ["UK", "US", "UK", "US","UK", "US", "UK", "US"] data[:Month] = ["April", "April", "March", "March","April", "April", "March", "March"]...

It's to prevent _F_ from being visible in the global method cache. If you'll call clever_foo with the same n repeatedly, you can do even better by saving the compiled function in a Dict. That way you don't have to recompile it each time....

A more julian approach to add_structs_1 is to make the inner loop a separate function, this allows the compiler to specialize the function on each type in the SampleStruct and gives quite a speedup. By profiling the code it was visible that the time to execute names(SampleStruct) were quite significant,...

Yes you do need to supply a library name. The first argument to ccall is a tuple of the form (:function, "library"). So, if you were calling GetTickCount it would be (:GetTickCount, "kernel32"). You also need to specify the calling convention, return value type, and the parameter types. In the...

image,colors,type-conversion,julia-lang,color-space

Until Color.jl gets updated and more testing implemented/passed, you can make a single character change in Color/src/conversions.jl to most likely fix this particular issue. Change - to + on line 156. 150 # Everything to HSL 151 # ----------------- 152 153 function convert{T}(::Type{HSL{T}}, c::AbstractRGB) 154 c_min = min(c.r, c.g, c.b)...

arrays,data-structures,julia-lang

You can construct your array of arrays like so: # Initialize an array that can contain any values listOfLists = Any[] # Push some arrays into the array push!(listOfLists, [1, 2, 3]) push!(listOfLists, [4, 5]) push!(listOfLists, ["Julia", "rocks"]) # You now have an array containing arrays listOfLists # 3-element Array{Any,1}:...

Macro parsing (particularly within the context of a function call) is a little finicky. You can see how Julia parsed this simply by quoting it: julia> :(annotate(@printf "test : %5.2f" b, xy=[1;1])) :(annotate(@printf "test : %5.2f" (b,xy) = [1,1])) As you can see, the macro is "greedier" than function arguments....

The ability to define a function g{T, S<:T}(::T, ::S) has been referred to as "triangular dispatch" as an analogy to diagonal dispatch: f{T}(::T, ::T). (Imagine a table with a type hierarchy labelling the rows and columns, arranged such that the super types are to the top and left. The rows...

To make an element-by-element comparison, Julia requires that both arrays have the same number of elements. This can be achieved in this case with a comprehension: julia> x = Any[[1,2],[2,3],[3,4],[4,5]] 4-element Array{Any,1}: [1,2] [2,3] [3,4] [4,5] julia> x[x.==[[3,4] for i in 1:length(x)]] 1-element Array{Any,1}: [3,4] So the question in my...

There are a couple of things going on here. Firstly, unlike Matlab, the x is an array of machine integers, not floating point values. This appears to be the main difference in speed, as it is unable to use BLAS routines for linear algebra. You need to do either x...

A more numerically robust approach in Python, without having to do the matrix algebra yourself is to use numpy.linalg.lstsq to do the regression: In [29]: np.linalg.lstsq(X, y) Out[29]: (array([[ 188.40031942], [ 0.3866255 ], [ -56.13824955], [ -92.9672536 ], [ -3.73781915]]), array([], dtype=float64), 4, array([ 3.08487554e+03, 1.88409728e+01, 1.37100414e+00, 1.97618336e-01])) (Compare the...

for-loop,parallel-processing,julia-lang

The approach to return the function seems elegant but unfortunately, unlike JavaScript, Julia does not resolve all the variables when creating the functions. Technically, your training function could produce the source code of the function with literal values for all the trained parameters. Then pass it to each of the...

Static precompilation might happen for Julia 0.4, not 100% clear yet if it'll make it in. If you'd like to do it somewhat manually by baking it into your "system image", check out the handy package SystemImageBuilder.jl....

Bounds error reporting has improved in julia v0.4 via this pull request https://github.com/JuliaLang/julia/pull/9534. In julia 0.4 the array as well as the index you were trying to access get printed by default: julia> wrong() ERROR: BoundsError: attempt to access 158x4 Array{Float64,2}: NaN 0.0 0.0 0.0 0.0157085 0.0 0.0 0.0 0.0314201...

Note: the following paths may be Unix-specific. You can add the file .juliarc.jl to your home directory, and include the line @everywhere push!(LOAD_PATH,"/path/to/my/code") The @everywhere ensures that it will work even if you've started julia with multiple workers....

julia-lang,jupyter,ijulia-notebook

You can adjust the amount of characters to display before truncation by setting the global env options as shown below: ENV["LINES"] = 150 ENV["COLUMNS"] = 300 You may still have issues with its wrapping though....

The reason for your results is julias invariant typing system. This means, although ASCIIString <: String is true, Vector{ASCIIString} <: Vector{String} is false. To get around, use parametric types: import Base.ismatch function ismatch{T<:String}(vector::Vector{T}, regex::Regex) [ismatch(regex,string), for string in vector] end ...

constructor,constants,julia-lang

Looking at Constants.jl in Julia 0.3 and 0.4 Although it looks like you are using Julia 0.3, and these results are principally about Julia 0.4, it also has the same problem and the cause is the same which is unnecessary allocation of intermediates. To get an idea of what is...

Macros are very different beasts compared to functions. One of the differences is that they do not evaluate their arguments: http://docs.julialang.org/en/latest/manual/metaprogramming/#macro-invocation It is important to emphasize that macros receive their arguments as expressions, literals, or symbols. To see the implications compare the 2 outputs (left as an exercise): julia> macroexpand(:(@load...

The input expression to the macro needs to be quoted because a macro returns an expression, which are evaluated, while you would like to get the expression itself, hence you need an extra quoting. The quoting can be done as: macro mymacro(ex) Expr(:quote,ex) # this creates an expression that looks...

types,julia-lang,type-parameter

It is currently not possible to restrict type parameters like this, though there has been discussion to allow the syntax that you tried up at the top. I believe that the solution that you came up with of checking the type parameter in an inner constructor is considered the best...

Here's one way: julia> b = map(x->eval(parse(x)),readcsv("test.csv")) 2x1 Array{Complex{Float64},2}: 1.0+2.3im 2.3+0.0im ...

An answer to your specific question: When you define a new type in Julia, it is common to extend some of the standard methods in Base to your new type, including deepcopy. For example: type MyType x::Vector y::Vector end import Base.deepcopy Base.deepcopy(m::MyType) = MyType(deepcopy(m.x), deepcopy(m.y)) Now you can call deepcopy...

floating-point,julia-lang,multiplication

Some options: Use the inbuilt Rational type. The most accurate and fastest way would be 16//100 * 16//100 If you're using very big numbers these might overflow, in which case you can use BigInts instead, big(16)//big(100) * big(16)//big(100) (you don't actually need to wrap them all in bigs, as the...

time,timezone,julia-lang,strftime

Looks like gmtime is on Julia's TODO list. Until it gets included, will something like this work for you? julia> function gmtime(t::Real) t = floor(t) tm = TmStruct() ccall(:gmtime_r, Ptr{TmStruct}, (Ptr{Int}, Ptr{TmStruct}), &t, &tm) return tm end gmtime (generic function with 1 method) julia> strftime("%H:%M:%S", gmtime(0)) "00:00:00" ...

You can't enter commands into the console in Juno--that's for displaying output. Commands can be submitted from within the editor by setting your cursor in the line to submit and pressing Ctrl+Enter or Shift+Enter. The value will then be displayed in a small popup next to the line and the...

You have to make A.f and B.f the same function (in the example above they are just different functions with the same name). Then you can overload one method in each of the modules and multiple dispatch will do its job. The way to achieve this is either to have...

Use the string function: julia> string(0.5) "0.5" EDIT: For custom formatted strings, you can use the @sprintf macro: julia> @sprintf("%.2f",0.5) "0.50" ...

The docs have a brief mention of extendible dimensions in hdf5.md excerpted below. You can use extendible dimensions, d = d_create(parent, name, dtype, (dims, max_dims), "chunk", (chunk_dims), [lcpl, dcpl, dapl]) set_dims!(d, new_dims) where dims is a tuple of integers. For example b = d_create(fid, "b", Int, ((1000,),(-1,)), "chunk", (100,)) #-1...

In this case it's almost certainly a consequence of inlining: your printLength function is so short, it's almost certainly inlined into the call site, which is why you get the line number 8. Eventually, it is expected that inlining won't cause problems for backtraces. At the moment, your best bet---if...

dictionary,julia-lang,compositetype

There's a subtle difference in the syntax between types and instances. Dict() instantiates a dictionary, whereas Dict by itself is the type. When defining a composite type, the field definitions need to be of the form symbol::Type. That error message is a little confusing. What it's effectively saying is this:...

@Isaiah's answer is spot-on; perhaps even more-so after the edit to the original question. To elaborate and make this more specific to your case: I'd change your NeuralLayer type to be parametric: type NeuralLayer{func_type} weights::Matrix{Float32} biases::Vector{Float32} end Since func_type doesn't appear in the types of the fields, the constructor will...

python,matplotlib,plot,julia-lang

I've never used Julia, but you need to set the yticklabels. I think this should do it: ax1[:set_yticks]([0.2,0.4,0.6,0.8,1.0]) ax1[:set_yticklabels](["-40dB","-30dB","-20dB","-10dB","0dB"]) ...

multidimensional-array,slice,julia-lang

Broadcasting in Julia has been modelled pretty much on broadcasting in NumPy, so you should hopefully find that it obeys more or less the same simple rules (not sure if the way to pad dimensions when not all inputs have the same number of dimensions is the same though, since...

function,methods,types,julia-lang

When exploring the behavior of a function in Julia, it is important to understand which specific method is being called. Julia is organized around multiple dispatch, so a single name such as ndims may be associated with different implementations -- chosen by the type of the arguments. To see how...

The symbol your function returned where the symbol function, due to the last symbol in your qoute did not have $ in front. The second problem is you would like to return the symbol it self, which requires you make a quote inside the quote similar to this question Julia:...

Not directly. But you could roll your own type with something like: julia> type CView{A<:AbstractArray} <: AbstractArray a::A b::A end julia> import Base: size, getindex, setindex! julia> size(c::CView) = tuple([sa+sb for (sa, sb) in zip(size(c.a), size(c.b))]...) size (generic function with 57 methods) julia> getindex(c::CView, i::Int) = i <= length(c.a) ?...

You will also have to re-calculate y and generate a new plot: using Winston x=[0:0.1:2pi]; y=sin(x) plot(x,y) Generates the first plot and then x=[0:0.1:4pi]; #Re-define x y=sin(x) #Calculate new y plot(x,y) #Generate new plot will generate a new plot....

You can use an anonymous function as in mapslices(t -> [mean(t), median(t), iqr(t)], A, 1) but using comprehensions and splatting, as in your last example, is also fine. For very large arrays, you might want to avoid the temporary allocations introduced by transpose and splatting, but in most cases you...

types,floating-point,julia-lang

The one and zero functions are useful here: function f(x, c) if x <= 0 return zero(x) elseif x <= c return x/c else return one(x) end end This version is a bit more strict about the input types: function f{T<:FloatingPoint}(x::T, c::T) if x <= 0 return zero(T) elseif x...

Have you tried hcat: julia> column(j) = [j, j ,j] column (generic function with 1 method) julia> my_matrix = hcat([column(j) for j=1:4]...) 3x4 Array{Int64,2}: 1 2 3 4 1 2 3 4 1 2 3 4 ...

The /deps folder is not needed, that is correct but the simple thing to do is make install and that will create a directory julia-some hex number. That directory is all that is needed and it can be copied anywhere and everything else deleted afterwards, but the /deps folder will...

For practice I have also made trial-and-errors and the following patterns have worked for Julia0.4.0. With A = Int[1,2,3,2,3] and pat = Int[2,3], the first one is x = Int[ A[i:i+1] == pat ? i : 0 for i=1:length(A)-1 ] x[ x .> 0 ] # => [2,4] the second...

recursion,types,julia-lang,type-alias

Dose this work for what you are doing? typealias NestedTuple0{N,T} Tuple{Union(T,N),Union(T,N)} typealias NestedTuple{T} NestedTuple0{NestedTuple0{T},T} Note: I am only able to try this in 036, not 04 An exmple of use: function rnt(p) np = 0.95*p a=rand() <p ? rnt(np) : 1 b=rand() <p ? rnt(np) : 2 (a,b) end x=rnt(1.0)...

You need to define an appropriate show method: import Base.show show(io::IO, ::Type{MT}) = print(io, "MT") Your example then gives: julia> y1 + y2 ERROR: `+` has no method matching +(::MT, ::MT) ...

constructor,julia-lang,compositetype

Inner constructors are just the functions that appear inside the type block with the same name as the type. That means that you can use either function syntax to define them. You can use the short form (as you did above), or you can instead use the more verbose block...