how to pass a method but not activate it in io language - iolanguage

I want to implement a method dim(x,y) which will assign spaces for a matrix(y rows, x cols).
I want to make "dim(x,y)" more powerful by passing an optional function 'filler' to it and then 'dim' will set the element located at (x,y) to filler(x,y)
my code goes as below:
List2D dim := method(x, y, z,
target := list()
filler := if(z == nil,
method(return nil),
z)
for(i, 1, y,
subTarget := list()
for(j, 1, x,
subTarget append( filler(i,j) ))
target append(subTarget) )
return target)
it worked well when 'dim' is called with 2 arguments,
but failed with
List2D dim(3,2, method(x,y, 10*x+y))
which throwed an exception at line filler := if(z == nil
The exception said nil does not respond to '*'
I realized the argument 'z' got activated undesirably when comparing with nil.
So I'm wondering how to get my 'List2D dim' work properly?

Alright so basically, you'll want something like this:
List2D dim := method(x, y,
target := list
blk := call evalArgAt(2) # Get the third argument, and evaluate it in the context of the sender
if(blk isNil, blk := block setScope(call sender))
for(i, 1, y,
subTarget := list
for(j, 1, x,
subTarget append(blk call(i, j))
target append(subTarget)
)
)
target
)
Basically, what's going on here is since your filler, you want to give it arguments, the easiest method is just to pass in a Block. You can do this with messages, but you in effect, end up setting up your own duplicate of Block anyway if you introduce a new scope, which you should. If the third argument evaluates to nil, then we'll just create a new function and set its scope to the calling context; as if the user had passed in an empty function, which has no argument arty and as such, you can pass arguments to it even if it doesn't define any parameters. The fact we scope it to the caller isn't really needed, but you should always scope blocks to the calling context if you're creating the blocks inside your method call. This will give access to the lexical scope of the calling context inside that block; which you're probably shoving some message the user has supplied in it. When ready, just call that method explicitly using the call method.
If your filler method didn't require any arguments, I'd just grab the raw message argument at the 2nd index, instead of evaluating it. This would yield some major performance improvements for some large matrices.

Related

error: "struct" expression not at top level

function check(str,arg;type=DataType,max=nothing,min=nothing,description="")
#argcheck typeof(arg)==type
#argcheck arg>min
#argcheck arg<max
#argcheck typeof(description)==String
return arg
end
function constr(name,arg,field)
return :(function $name($arg,$field)
new(check($name,$arg,$field))
end)
end
macro creatStruct(name,arg)
code = Base.remove_linenums!(quote
struct $name
end
end)
print(arg)
append!(code.args[1].args[3].args,[constr(name,arg.args[1].args[1],arg.args[1].args[2])])
code
end
macro myStruct(name,arg)
#creatStruct name arg
end
#myStruct test12 (
(arg1,(max=10))
)
In my code above I'm trying to build a macro that Creates a struct, and within the struct, you can define an argument with boundaries (max, min) and description, etc.
I'm getting this error:
syntax: "#141#max = 10" is not a valid function argument name
and every time I'm trying to solve it, I get another error like:
LoadError: syntax: "struct" expression not at top level
So, I think my Code/Approach is not that cohesive. Anybody can suggest tips and/or another Approche.
You're attempting to make an argument name max with a default value of 10. The error is about max=10 not being a valid name (Symbol), while max is. The bigger issue is you're trying to put this in the struct expression instead of a constructor method:
struct Foo
bar::Float64
max::Int64
end
# constructor
Foo(bar, max=10) = Foo(bar, max)
So you have to figure out how to make an expression for a method with default values, too.
Your second error means that structs must be defined in the top-level. "Top-level" is like global scope but stricter in some contexts; I don't know the exact difference, but it definitely excludes local scopes (macro, function, etc). It looks like the issue is the expression returned by creatStruct being evaluated as code in myStruct, but the LoadError I'm getting has a different message. In any case, the error goes away if I make sure things stay as expressions:
macro myStruct(name,arg)
:(#creatStruct $name $arg)
end

Scala characteristic function

We got three functions. The first one defines type alias for Boolean condition
type Set = Int => Boolean
I understand that this is the alias definition. Now the second fucntion
def contains(set: Set, elem: Int): Boolean = set(elem)
calls the (Int=>Boolean) on elem:Int.
QUESTION 1: Where is the logic of the function under Set?
I mean, do I have to pass the Set function actual parameter (in which case the contains is a higher order function) when calling contains eg. for even numbers set:
val in:Boolean = contains({x=>(x%2)==0},2)
In the third function:
def singletonSet(elem: Int): Set = set => set == elem
Question 2: Where does the set come form? Its not in the formal parameter list.
QUESTION 1: Yes, you have to pass a Set which would be the "implementation" of the function. The point of this exercise (Odersky's course?) is to show that a Set can be defined not as a collection of items (the "usual" definition of a set), but rather as a function that says whether an item is included in the set or not. So the Set is the function.
QUESTION 2: set is the name given to the argument of the anonymous function we're returning here: Since singletonSet's return type is Set, which as we've said is actually a function of type Int => Boolean, we return an (anonymous) function. To create such a function, one uses the syntax x => f(x), where x is any name you'd like and f(x) is an expression using it (or not).
1) Since a Set is a function, contains is indeed a higher order function which takes a function and an element of the appropriate type and applies the function to the element. The logic of it is that sets are being represented by Boolean-valued functions where an element evaluates to true if and only if it is in the corresponding set. The function contains evaluates the function at the element and returns its value, which is either true or false depending on whether or not it is in the set.
2) singleton returns an anonymous function, one that evaluates to true if and only if the input (set) equals the element in question.

Lua - How to pass object's function as parameter to another function

local a = {}
function a:test1(value)
print(value)
end
local b = {}
function b:test2(v1, v2)
v2(100);
end
b:test2(_, a.test1)
Doesn't work. Value is nil. I could find a solution doing an encapsulation in an anonymous function
b:test2(variable, function(value) a:test1(value) end)
But I find it pretty bad mkay
What is the correct syntax ?
anotherObject:aFunction(variable, object.doStuff) is the correct syntax.
Using a colon : with a function is just syntactic sugar for a call or declaration with an implicit self parameter as the first argument. If you would like to follow the pattern you've shown in your example in a cleaner way, you could use a helper function.
local function bind(t, k)
return function(...) return t[k](t, ...) end
end
You then apply it like so.
anotherObject:aFunction(variable, bind(object, 'doStuff'))
Edit: I believe the solution to your problem will require binding at some level, without resorting to modifying the Lua interpreter or using a code translation step.
This is fundamentally because functions in Lua do not carry any information about their origin. I.e., tables do not inherently own the functions that they store.
For example, the following is perfectly legitimate Lua code.
function Circle:area() -- function Circle.area(self)
-- ...
end
-- Evaluate the function in the "area" slot with Square as the self parameter.
Circle.area(Square)
Of course, you could try a paradigm shift, but it may be too late for that if you're building an entire application based on the idea of functions being tied to the table that they have been indexed from, as you said.
Therefore, I propose the following crazy solution.
local mt = {}
function mt:__index(k)
local v = self._slots[k]
if v == nil then
-- Ascend the inheritance tree.
-- This has to be done with rawget all the way up,
-- otherwise inherited functions would be repeatedly bound.
local p = self
repeat
p = rawget(p, '_parent')
if not p then break end
v = p._slots[k]
until v
end
if type(v) == 'function' then
-- Return a self-bound version of the function.
return function(...) return v(self, ...) end
end
return v
end
function mt:__newindex(k, v)
self._slots[k] = v
end
--- Demo & Tests ---
local function Object(parent)
local o = setmetatable({_slots = {}}, mt)
if parent then rawset(o, '_parent', parent) end
return o
end
local o1 = Object()
local o2 = Object(o1)
assert(o1.abc == nil, 'o1.abc should be nil')
o1.abc = 3
assert(o1.abc == 3, 'o1.abc should be 3')
assert(o2.abc == 3, 'o2.abc should be 3, inherited from o1')
o2.abc = 7
assert(o2.abc == 7, 'o2.abc should be 7, overriding o1')
assert(o1.abc == 3, 'o1.abc should be 3, unaffected by o2 setter')
function o1:test(bar)
return self.abc + bar
end
assert(type(o1.test) == 'function', 'o1.test should be a function')
assert(type(o2.test) == 'function', 'o2.test should be a function, inherited from o1')
assert(o1.test(5) == 8, 'o1.test(5) should return 3 + 5 = 8')
assert(o2.test(11) == 18, 'o2.test(11) should return 7 + 11 = 18')
function o2:test2(fn)
return self.abc + fn(7)
end
assert(o2.test2(o1.test) == 17, 'o2.test2(o1.test) should return 7 + (3 + 7) = 17')
o2.test3 = o1._slots.test -- proper function copying
assert(o2.test3(11) == 18, 'o2.test3(5) should return 7 + 11 = 18')
o2.abc = nil
assert(o2.abc == 3, 'o2.abc should be 3 again, inherited from o1 after clearing')
o2.abc = false
assert(o2.abc == false, 'o2.abc should be false, __index needs to differentiate between nil and false')
This metatable will provide you with what you want, with inherited and bound functions to boot. You will just need to make sure that all of the tables that you want to follow this pattern also follow the method of object creation shown in the example code.
To explain, each table made in this way has any new assignment redirected into the _slots sub-table and any new retrieval checked up the _parent inheritance tree. If the type of the value is a function, then it returns a new closure with the original self that started the check bound to the function found.
Obviously, calling a function from one of these objects with the : colon syntax is going to be a silly idea, since it would evaluate to o.fn(o, o), and that is probably not what you want. Another caveat is that copying functions onto these objects, from these objects, will not work as expected. o1.newfn = o2.fn will put an o2 bound function into o1, which in turn will be re-bound to o1. The end result would be something like o2.fn(o2, o1). You will have to copy functions from the _slots table.
In conclusion: Even though this works, I would not personally recommend it in the long run, since it may be confusing to anyone used to how Lua works with tables, indexing, and functions, and there will be overhead. You might be able to do away with some it via memoizing the closures, but I'll leave that decision up to you. Good luck!
Object method declared with : needs object instance as the first parameter. It gets added automatically if you call it with :, but as you passed just a function pointer, you need to pass this as well. This means whenever you pass a function in some object somewhere, you also have to pass object instance. This works:
local a = {}
function a:test1(value)
print(value)
end
local b = {}
function b:test2(obj, v2)
v2(obj, 100); -- object instance is always the first param of a ":"-style func
end
b:test2(a, a.test1) -- passing object instance and a function
Building on #ryan-stein's neat bind() solution, in a module I've found this to be slightly more concise:
local m = {}
m.__index = m
m.word = 'bar'
function m:bind(fn)
return function(...) return self[fn](self, ...) end
end
function m:foo(fn)
print("Foo " .. self.word)
end
function m:start()
hs.timer.new(42, self:bind('foo'))
end
your code will be work. the reason Ryan has said.
I doubt that in the function anotherObject:aFunction(), you were using a wrong way to call the object.stuff.The correct way as this:
local a = {}
function a:test1()
print(1)
end
local b = {}
function b:test2(v1, v2)
v2();
end
b:test2(_, a.test1)

Validating arguments in CoffeeScript?

I have a function with a bunch of arguments, and I just want to check if any of them are falsy (empty, undefined, null, etc.).
One option is obvious to just check every argument individually, but it's pretty repetitive:
if not arg1
response.send 400, 'Missing argument arg1'
if not arg2
response.send 400, 'Missing argument arg2'
I can simplify that a bit with this, but I still have to list out every every argument and argument name:
for key, value of { 'arg1': arg1, 'arg2': arg2 }
if not value
response.send 400, "Missing argument #{key}"
I was hoping to do something like this:
for key, value of arguments
if not value
response.send 400, "Missing argument #{key}"
But arguments is more like an array. Is there a way to get the arguments as an object, or get the argument names as an array? Am I going about this this wrong way?
What is a good way of validating a bunch of arguments without repeating myself?
You could write an check function that parses the parameter names from the string representation of your function (there is really no other way)
check = ()->
f = "" + arguments.callee.caller
r = /function \((.*)\)/
regres = r.exec(f)
pnames = regres[1].split(",")
params = (pn.trim() for pn in pnames)
for index in [0...arguments.length]
if arguments[index] == null || arguments[index] == undefined
console.log "argument: #{params[index]} is null"
handleRequest = (x, y, z)->
#give all your params in the correct order to the check function
check(x, y, z)
handleRequest(1, 2, "lala")
handleRequest(1, 2)
Now the fact that this is somehow possible shouldn't mean that you should do it. This solution is at best brittle and will create confusion if you change parameter position. Some would probably claim its evil - me included ;-)
I'd rather advise you that you change your API design.
From your response.send I would assume that you are in an web environment? Why dont you simply use the params hash that the framework you are using is handling to you? Most frameworks will do exactly this.
Another possibility would be to define default values for your parameter so that received parameters are always well defined?
handleRequest = (x, y = "somevalue", z = "anothervalue")->
I believe there is no clear way of achieving what you want, but a nasty way of doing this (based on similar threads for javascript, like this and this), which may be error prone, is to parse the function itself, get the names of the arguments and make them an array:
fn = (a,b,c,d,e,f) ->
fns = fn.toString()
args = fns.slice(fns.indexOf('(')+1, fns.indexOf(')')).split(', ')
for idx in [0...args.length]
console.log 400, "Missing argument #{args[idx]}" unless arguments[idx]
fn('', null, 'arg1', undefined, 'arg2')
#Output:
#400 'Missing argument a'
#400 'Missing argument b'
#400 'Missing argument d'
#400 'Missing argument f'

printing the function name in fortran 90

I wrote a code that finds the root of a function whose name is provided among the arguments, I think I took it from Numerical Recipes. Something like
double precision function rtsafe(x_init, x1, x2, xacc, func, dfunc)
where func and dfunc are two functions' names.
Of course I use rtsafe with different function func and dfunc.
I would like to print the name of the called functions func and dfunc when I am inside rtsafe, because when there is an error in rtsafe I would like to know which function I was using. Something like
write(,)"my func = ", func
(?)
Does anybody know how to do that?
You could add an optional argument in your functions that returns the name of the function:
FUNCTION f(x, fname) RESULT (fx)
IMPLICIT NONE
REAL :: x, fx
CHARACTER(LEN=*), OPTIONAL :: fname
CHARACTER(LEN=*), PARAMETER :: myfname='somename'
IF (present(fname)) fname=myfname
fx = x ! or whatever else
END FUNCTION f
In the first call to your function in rtsafe you get the name of the function for later printing in case of an error.
Did not test this but it should work more or less like this, and it the only way I can think of to do this in Fortran.
Maybe you can work up some manual solution (pass the name of the function, then print it with "OK" ... or something like that), but printing the names of the functions/subroutines (reflecting) is not possible.