walk is a recursive function that walks the given tree and if walked over a file do something with it.
The "do something with it" should be changed.
I could use coroutine.yield(f) in walk but I wanted to know my mistake first.
As you see the argument lootfunc is given by a reference and should be called within walk.
But it gives me the error seen below. So why is the parameter lootfunc nil?
local KEYWORDS = {
"%.db[x]?",
"%.ojsn",
}
local function loot(d)
if MATCH == "path" then -- only look to the path not to the content
for i,keyword in pairs(KEYWORDS) do
if string.find(d,keyword) then
--coroutine.yield(d)
print(d)
end
end
end
end
local function walk (path,lootfunc)
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..'/'..file
local attr = lfs.attributes (f)
if(type(attr) == "table") then
if attr.mode == "directory" then
walk (f) -- next round
elseif attr.mode == "file" then
lootfunc(f)
end
end
end
end
end
walk("/path/",loot)
shadowed.lua:73: attempt to call local 'lootfunc' (a nil value)
stack traceback:
(command line):1: in function 'lootfunc'
shadowed.lua:73: in function 'walk'
shadowed.lua:71: in function 'walk'
shadowed.lua:71: in function 'walk'
shadowed.lua:88: in main chunk
[C]: in function 'dofile'
(command line):1: in function <(command line):1>
[C]: in function 'xpcall'
(command line):1: in main chunk
[C]: ?
You are calling walk(f) in the function walk, there's only one argument, the second argument is filled with nil, so change:
if attr.mode == "directory" then
walk(f) -- next round
to
if attr.mode == "directory" then
walk(f, lootfunc) -- next round
Related
This is the method that processes an input string
def process(input) do
list=String.split(input, "\n")
f3=fn(a) ->
String.split(a," ")
end
list=Enum.map(list, f3)
func3=fn(n) ->
length(n)==3
end
func2=fn(n) ->
length(n)<=2
end
system=for x <-list, func3.(x), do: x
input=for y <- list, func2.(y), do: y
input=Enum.slice(input,0..length(input)-2)
output=""
output(input,output, system)
end
This is the output function that uses recursion to edit a string and eventually return its value
def output(input, output, system) do
cond do
length(input)==0 ->
output
true ->
[thing|tail]=input
if length(thing)==2 do
output=output<>"From "<>Enum.at(thing, 0)<>" to "<>Enum.at(thing,1)<>" is "<>Integer.to_string(calculate(thing, system))<>"km\n"
output(tail, output, system)
end
if length(thing)==1 do
if Enum.at(thing,0)=="Sun" do
output=output<>"Sun orbits"
output(tail, output, system)
else
output=output<>orbits(thing, system)<>" Sun"
output(tail, output, system)
end
end
output(tail, output, system)
end
end
As you can see when the input is an empty list it should return the output string. Using inspect shows that the output string does indeed have the correct value. Yet when the function is called in process(), it only returns the empty string, or nil.
Any help is appreciated, I am new to elixir so apologies if my code is a bit messy.
This could be a case where using pattern matching in the function head will let you avoid essentially all of the conditionals. You could break this down as:
def output([], message, _) do
message
end
def output([[from, to] | tail], message, system) do
distance = Integer.to_string(calculate(thing, system))
new_message = "#{message}From #{from} to #{to} is #{distance} km\n"
output(tail, new_message, system)
end
def output([["Sun"] | tail], message, system) do
output(tail, "Sun orbits #{message}", system)
end
def output([[thing] | tail], message, system) do
new_message = "#{message}#{orbits([thing], system)} Sun"
output(tail, new_message, system)
end
This gets around some of the difficulties highlighted in the comments: reassigning output inside a block doesn't have an effect, and there aren't non-local returns so after an if ... end block completes and goes on to the next conditional, its result is lost. This will also trap some incorrect inputs, and your process will exit with a pattern-match error if an empty or 3-element list winds up in the input list.
I've renamed the output parameter to the output function to message. This isn't required – the code will work fine whether or not you change it – but I found it a little confusing reading through the function whether output is a function call or a variable.
I have some code here:
require "math"
local dozenDonuts
local oneDonut
local function roundToFirstDecimal(t)
return math.round(t*10)*0.1
end
When I run the code above, I get the following error:
lua: f:\my codes\donut.lua:6: attempt to call field 'round' (a nil value)
stack traceback:
f:\my codes\donut.lua:6: in function 'roundToFirstDecimal'
f:\my codes\donut.lua:17: in main chunk
[C]: ?
Is round not an attribute of math? How can I round to the first decimal?
math.round is not part of the standard Lua math library. But it is simple to write:
function math.round(x)
return math.floor(x+0.5)
end
My deep copy code:
function deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
I'm trying to implement this to oop using self, but couldn't get it to work, here is what I've tried so far
function block:deepcopy()
local orig_type = type(self)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, self, nil do
copy[self:deepcopy(orig_key)] = deepcopy(orig_value)
end
setmetatable(copy, self:deeepcopy(getmetatable(self)))
else
copy = orig
end
return copy
In the OOP version of the function, self:deepcopy(something) with the method syntax (colon) doesn't do what you want it to. It is equivalent to self.deepcopy(self, something); the second argument something is ignored and you just end up trying to re-copy the same self over and over until there's a stack overflow. You have to do self.deepcopy(something) with a dot to pass something as the self argument (the argument that is copied).
Calling self.deepcopy inside the definition of the deepcopy method assumes that every subtable has a self.deepcopy function. If not, you will get an "attempt to call a nil value" error. But you could do this if you want every subtable to have its own version of deepcopy that is used when copying the immediate children of that table (keys, values, metatable). For instance, you could have a subtable whose deepcopy method does not copy the metatable. Here is the basic version where the subtable has the same deepcopy method:
local block = {}
function block:deepcopy()
if type(self) == 'table' then
local copy = {}
for key, value in pairs(self) do
copy[self.deepcopy(key)] = self.deepcopy(value)
end
return setmetatable(copy, self.deepcopy(getmetatable(self)))
else
return self
end
end
block.a = { a = 10, deepcopy = block.deepcopy }
block:deepcopy() -- works
block.a = { a = 10 }
block:deepcopy() -- error: "attempt to call a nil value (field 'deepcopy')"
But you don't need to rewrite the function at all to use it in object-oriented style. Try using your first definition of deepcopy. Do object.deepcopy = deepcopy, and then call object:deepcopy() and you will get a copy of the object.
If I have a method
macro doarray(arr)
if in(:head, fieldnames(typeof(arr))) && arr.head == :vect
println("A Vector")
else
throw(ArgumentError("$(arr) should be a vector"))
end
end
it works if I write this
#doarray([x])
or
#doarray([:x])
but the following code rightly does not work, raising the ArgumentError(i.e. ArgumentError: alist should be a vector).
alist = [:x]
#doarray(alist)
How can I make the above to act similarly as #doarray([x])
Motivation:
I have a recursive macro(say mymacro) which takes a vector, operates on the first value and then calls recursively mymacro with the rest of the vector(say rest_vector). I can create rest_vector, print the value correctly(for debugging) but I don't know how to evaluate rest_vector when I feed it to the mymacro again.
EDIT 1:
I'm trying to implement logic programming in Julia, namely MiniKanren. In the Clojure implementation that I am basing this off, the code is such.
(defmacro fresh
[var-vec & clauses]
(if (empty? var-vec)
`(lconj+ ~#clauses)
`(call-fresh (fn [~(first var-vec)]
(fresh [~#(rest var-vec)]
~#clauses)))))
My failing Julia code based on that is below. I apologize if it does not make sense as I am trying to understand macros by implementing it.
macro fresh(varvec, clauses...)
if isempty(varvec.args)
:(lconjplus($(esc(clauses))))
else
varvecrest = varvec.args[2:end]
return quote
fn = $(esc(varvec.args[1])) -> #fresh($(varvecvest), $(esc(clauses)))
callfresh(fn)
end
end
end
The error I get when I run the code #fresh([x, y], ===(x, 42))(you can disregard ===(x, 42) for this discussion)
ERROR: LoadError: LoadError: UndefVarError: varvecvest not defined
The problem line is fn = $(esc(varvec.args[1])) -> #fresh($(varvecvest), $(esc(clauses)))
If I understand your problem correctly it is better to call a function (not a macro) inside a macro that will operate on AST passed to the macro. Here is a simple example how you could do it:
function recarray(arr)
println("head: ", popfirst!(arr.args))
isempty(arr.args) || recarray(arr)
end
macro doarray(arr)
if in(:head, fieldnames(typeof(arr))) && arr.head == :vect
println("A Vector")
recarray(arr)
else
throw(ArgumentError("$(arr) should be a vector"))
end
end
Of course in this example we do not do anything useful. If you specified what exactly you want to achieve then I might suggest something more specific.
Is there a way to get the file/name/line info for the caller of a Julia function?
I found this way to get some stacktrace info, and if the caller is another function (but not the main context) I get the file:line info:
module pd
global g_bTraceOn = true
export callerOfTraceIt
function callerOfTraceIt()
traceit( "hi" ) ;
end
function traceit( msg )
global g_bTraceOn
if ( g_bTraceOn )
bt = backtrace() ;
s = sprint(io->Base.show_backtrace(io, bt))
println( "debug: $s: $msg" )
end
end
end
using pd
callerOfTraceIt( )
This shows:
$ julia bt.jl
debug:
in traceit at C:\cygwin64\home\Peeter\julia\HarmonicBalance\bt.jl:15
in callerOfTraceIt at C:\cygwin64\home\Peeter\julia\HarmonicBalance\bt.jl:8
in include at boot.jl:245
in include_from_node1 at loading.jl:128
in process_options at client.jl:285
in _start at client.jl:354: hi
I'd really like just the second frame (caller of traceit()), and would also like the function name if it's available.
If you do #show bt inside traceit, you'll discover it's just a list of pointers, each corresponding to a single stack frame. Those stack frames that come from julia code (rather than C) are displayed by show_backtrace.
You can call Profile.lookup(uint(bt[1])) to extract file/function/line information from each element:
julia> Profile.lookup(uint(bt[1]))
LineInfo("rec_backtrace","/home/tim/src/julia-old/usr/bin/../lib/libjulia.so",-1,true,140293228378757)
julia> names(Profile.LineInfo)
5-element Array{Symbol,1}:
:func
:file
:line
:fromC
:ip
You likely want to ignore all elements with fromC == true.