Here is some code https://gist.github.com/goretkin/967ca1bef0b07ee99ff8
(pasted at end of email too)
It declares a recursive data type TreeNode that has a field children which
is a Set of TreeNodes. The function nodes counts the number of nodes in the
tree recursively.
The code as shown (option 3) works well, but I am wondering if I really
need to type-annotate the list comprehension.
If I don't (option 2), then there is this output:
eltype of child comprehension: TreeNode{Array{Float64,1}}
eltype of nodes(child) comprehension: None
eltype of map(nodes,cc): Any
ERROR: argument is empty
in sum at reduce.jl:280
in nodes at none:5
in foo at none:4
because of the [favorable] resolution of issue
6554<https://github.com/JuliaLang/julia/issues/6554>
.
In option 1, which uses map instead of a list comprehension, there is the
following output:
eltype of child comprehension: TreeNode{Array{Float64,1}}
eltype of nodes(child) comprehension: Int64
eltype of map(nodes,cc): Any
ERROR: no method zero(Type{Any})
in sum at reduce.jl:288
in nodes at none:11
in foo at none:4
Which looks like a Catch-22 to me! Now the eltype of the list comprehension
is being type-inferred correctly, exactly when we're not using it.
Gustavo
code also in gist
type TreeNode{P}
children::Set{TreeNode{P}}
TreeNode() = new()
end
function make_tree{P}(data::Set{P})
tree =TreeNode{P}()
tree.children=Set{TreeNode{P}}()
tree
end
function nodes(tree::TreeNode) #can also do nodes{P}(tree::TreeNode{P})
without any difference.
cc = [child for child in tree.children]
println("eltype of child comprehension: \t\t$(eltype(cc))")
listcomp = [nodes(child) for child in cc]
println("eltype of nodes(child) comprehension: \t$(eltype(listcomp))")
listmap = map(nodes,cc)
println("eltype of map(nodes,cc): \t\t$(eltype(listmap))")
#s = sum(listmap) #won't work
#s = sum(listcomp) #won't work
s = sum(Int64[nodes(child) for child in cc]) #does work, but only if
you comment the above two. (type-entropy death of universe?)
return (1+s)::Int64
end
function foo()
d = Set{Array{Float64,1}}()
tree = make_tree(d)
nodes(tree)
end
foo()