How do I get this Scala count down function to work? - function

Basically what I want this code to do is define a function, timeCount, and each time it is called I want 1 to be subtracted from 21, have the result be printed out, and have the result equal timeNum. So, I want 1 to be subtracted from 21, resulting in 20, printing out 20, then making timeNum equal to 20. Then the next time the function is called, it would be equal to 19, 18, etc, etc, ...
However, this code does not work. How can I get what I want to happen?
def timeCount() = {
var timeNum = 21
var timeLeft = timeNum-1
println(timeLeft)
var timeNum = timeLeft
}
}

class TimeCount(initial: Int) extends Function0[Int] {
var count = initial
def apply = {
count = count - 1
count
}
}
Use it like this:
scala> val f = new TimeCount(21)
f: TimeCount = <function0>
scala> f()
res0: Int = 20
scala> f()
res1: Int = 19
scala> f()
res2: Int = 18
I made two changes from what you were asking for, I made the number to start with a parameter to the constructor of the function, and I returned the count instead of printing it, because these seem more useful If you really just want to print it, change Function0[Int] to Function0[Unit] and change count to println(count.toString)
This is, of course, not threadsafe.

As the compiler error below states, you defined the same var twice.
console>:11: error: timeNum is already defined as variable timeNum
var timeNum = timeLeft
^
Keep in mind, one can modify the value of a var, but not to define it again.
Additionally, you declare and initialize the timeNum var in the function call. The result being that once it does compile you will print the same value (20) repeatedly.
Also, the timeLeft var is superfluous.

Related

Is there a single Apps Script function equivalent to MATCH() with TRUE?

I need to write some functions that involve the same function as the Sheets function MATCH() with parameter 'sort type' set to TRUE or 1, so that a search for 35 in [10,20,30,40] will yield 2, the index of 30, the next lowest value to 35.
I know I can do this by looping over the array to search, and testing each value against my search value until a value greater than the search value is found, but it seems to me there must be a shorthand way of doing this. We don't have to do this when seeking an exact value; we can just use indexOf(). I was surprised when I first learned that indexOf() does not have a parameter for search type, but can only return a -1 if an exact value is not found.
Is there no function akin to indexOf() that will do this, or is it actually necessary to loop over the array every time you need to do this?
Probably you're looking for the array.find() method. The impelentation could be something like this:
var arr = [10,20,30,40]
// make a copy of the array, reverse it and do find with condition
var value = arr.slice().reverse().find(x => x < 35)
console.log(value) // output --> 30 (first element less than 35 in the reversed array)
var index = arr.indexOf(value)
console.log(index) // output --> 2 (index of the element in the original array)
https://www.w3schools.com/jsref/jsref_find.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
There is another method array.findIndex(). Probably you can use it as well:
var arr = [10,20,30,40]
// find more or equal 35 and return previous index
var index = arr.findIndex(x => x >= 35) - 1
console.log(index) // output --> 2
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Try this:
function lfunko(tgt = 35) {
Logger.log([10,20,30,40].reduce((a,c,i) => { a.r = (a.x >= c)? i:a.r;return a;},{x:tgt}).r)
}

Using 2 different outputs of 'return' of a function in separate elements of a plot

I am drawing a plot of voltage per time. For the voltage values, I want the values to be evaluated by a 'scaling' function which converts the values from volts to kilovolts if the biggest element is higher than 1000 volts (11000 volts to 11 KILOvolts).
This function is supposed to return 2 separate outputs; one for (new) values of voltage and one for the unit. The values are fed into the y axis values of the plot and the unit is given to the labeling line of that axis. For example:
import numpy as np
time = np.array([0, 1, 2, 3])
system_voltage1 = np.array([110, 120, 130, 150])
system_voltage2 = np.array([11000, 12000, 13000, 15000])
scaling_function(input)
if np.amax(input) < 1000:
output = input/1
Voltage_label = 'Voltage in Volts'
if np.amax(input) > 1000:
output = input/1000
Voltage_label = 'Voltage in KILOVolts'
return(output, Voltage_label)
fig14 = plt.figure(figsize=(16,9))
ax1 = fig14.add_subplot(111)
l1, = ax1.plot(time, scaling_function(system_voltage), color='r')
ax1.set_xlabel("time in second", color='k')
ax1.set_ylabel(Voltage_label, color='k')
Now, I am having trouble, calling this function properly. I need the function to only receive the output for scaling_function(system_voltage), and receive Voltage_label in ax1.set_ylabel(Voltage_label, color='k'). Now:
A) My problem: I don't know how to write the code so only the first output is received and used for scaling_function(system_voltage) , and the second element for the labeling line.
B) Something I tried but didn't work:Voltage_label does not recognize the value of voltage_label from scaling_function, as it is located in an outer loop than the function. I mean, I cannot access voltage_label as its value is not globally assigned.
Can anyone help me with this?
y,l = scaling_function(system_voltage)
l1, = ax1.plot(time, y, color='r')
ax1.set_xlabel("time in second", color='k')
ax1.set_ylabel(l, color='k')

Is it possible to make a collapsing variables without making individual functions?

I have a code that starts as a small amount of variables and makes more elements using those initial variables.
function new( x, y, width, height )
local object = {}
--border
object.border = { x = x, y = y, width = width, height = height }
--body
object.body = { x = x+1, y = y+1, width = width-2, height = height-2 }
--font
object.font = {}
object.font.size = (object.body.height+2)-(math.floor((object.body.height+2)/4)+1)
object.font.height = love.graphics.setNewFont( object.font.size ):getHeight()
--padding
object.padding = {}
object.padding.height = math.floor(object.border.height*(2/29))
object.padding.width = object.padding.height*3
--text
object.text = { input = '' }
object.text.centerHeight = math.ceil(object.body.y+((object.body.height-object.font.height)/2))
object.text.left = object.body.x+object.padding.width+object.padding.height
--backspacing
object.backspace = {key = false, rate = 3, time = 0, pausetime = 20, pause = true}
--config
object.config = { active = true, devmode = false, debug = false, id = gui.id(), type = 'textbox' }
gui.add(object)
return object.config.id
end
and when I modify something in the middle part, the whole thing becomes a mess because starting from the one i changed until the bottom ones value doesn't agree with each other
local x = gui.get(2)
x.body.height = 50
I'm looking if there's a way for these variables to be redefined, starting from them until the bottom, without: (a) making functions for each of the variables. and (b) editing the required parameters in the function.
and If there's none, are the an alternate way to do this efficiently?
EDIT:
the structure of the variables is as follow:
border->body->padding->font
what i needed is a way i can define any of them so that the one that follows also changes like:
object.body.x = 15
and it would collapse from that redefined variable until the bottom:
body->padding->font
i could just redefine them from the edited variable until the bottom like this:
--not the actual code, just an example of variables dependent on the variable above
object.body.x = 15
object.padding.width = object.body.x+1
object.font.size = object.padding.width+1
but that means I have to do the same when redefining the padding until the font which is extremely inefficient especially when I extended more elements.
example:
--padding->font
object.padding.width = 5
object.font.size = object.padding.width+1
I was bored and saw this question (again) along with a duplicate.
I started writing some code for fun, leading to this:
local function getNeededVars(tab,func)
local needed,this = {}
this = setmetatable({},{
__index = function(s,k)
-- See if the requested variable exists.
-- If it doesn't, we obviously complain.
-- If it does, we log it and return the value.
local var = tab.vars[k]
if not var then
error("Eh, "..k.." isn't registered (yet?)",5)
end needed[k] = true return tab.vals[k]
end;
}) func(this) return needed
end
local function updateStuff(self,key,done)
for k,v in pairs(self.levars) do
if v.needed and v.needed[key] then
if not done[v] then done[v] = true
self.vals[v.name] = v.func(self)
updateStuff(self,v.name,done)
end
end
end
end
local function createSubTable(self,key,tab)
return setmetatable({},{
__newindex = function(s,k,v)
tab[k] = v updateStuff(self,key,{})
end; __index = tab;
})
end
local dependenceMeta
dependenceMeta = {
__index = function(self,k)
-- Allow methods, because OOP
local method = dependenceMeta[k]
if method then return method end
local variable = self.vars[k]
if not variable then
error("Variable "..k.." not found",2)
end return self.vals[k]
end;
__newindex = function(self,k,v)
local variable = self.vars[k]
if not variable then
error("Use :Register() to add stuff",2)
elseif type(v) == "table" then
self.vals[k] = createSubTable(self,k,v)
return updateStuff(self,k,{})
end self.vals[k] = v updateStuff(self,k,{})
end
}
function dependenceMeta:Register(var,value)
local varobject = {func=value,name=var}
self.vars[var] = varobject
table.insert(self.levars,varobject)
if type(value) == "function" then
varobject.needed = getNeededVars(self,value)
self.vals[var] = value(self)
elseif type(value) == "table" then
self.vals[var] = createSubTable(self,var,value)
elseif value then
self.vals[var] = value
end
end
function dependenceMeta:RegisterAll(tab)
for k,v in pairs(tab) do
self:Register(k,v)
end
end
local function DependenceTable()
return setmetatable({
levars = {};
vars = {};
vals = {};
},dependenceMeta)
end
local test = DependenceTable()
test:Register("border",{
x=20; y=50;
height=200;
width=100;
})
test:Register("body",function(self)
return {x=self.border.x+1,y=self.border.y+1,
height=self.border.height-2,
width=self.border.width-2}
end)
test:Register("font",function(self)
local size = (self.body.height+2)-(math.floor((self.body.height+2)/4)+1);
return { size = size; -- Since we use it in the table constructor...
height = size-4; --love.graphics.setNewFont( self.font.size ):getHeight();
-- I don't run this on love, so can't use the above line. Should work though.
}
end)
test:Register("padding",function(self)
local height = math.floor(self.border.height*(2/29))
return { height = height; width = height*3 } -- again dependency
end)
test:Register("text",{input=""}) -- Need this initially to keep input
test:Register("text",function(self)
return { input = self.text.input;
centerHeight = math.ceil(self.body.y+((self.body.height-self.font.height)/2));
left = self.body.x+self.padding.width+self.padding.height;
}
end)
test:Register("backspace",{key = false, rate = 3, time = 0, pausetime = 20, pause = true})
-- Again, didn't use gui.id() on the line below because my lack of LÖVE
test:Register("config",{active=true,devmode=false,debug=false,id=123,type='textbox'})
print("border.x=20, test.text.left="..test.text.left)
test.border = {x=30; y=50; height=200; width=100;}
print("border.x=30, test.text.left="..test.text.left)
test.border.x = 40
print("border.x=40, test.text.left="..test.text.left)
It's a lot of code, but I liked writing it. It gives this nice output:
border.x=20, test.text.left=73
border.x=30, test.text.left=83
border.x=40, test.text.left=93
All properties only get recalculated when one of its dependencies is edited. I made it also work with subtables, which was a bit tricky, but at the end actually seems quite easy. You can edit (for example) the body field by setting it to a completely new table or by setting a field in the already existing table, as seen in the last few lines of the code snippet. When you assign it to a new table, it'll set a metatable on it. You can't use pairs (& co) neither, unless you use 5.2 and can use __pairs.
It might solve your problem. If not, I had fun writing it, so at least it'll always be something positive that I wrote this. (And you have to admit, that's some beautiful code. Well, the way it works, not the actual formatting)
Note: If you're gonna use it, uncomment the love.graphics and gui.id part, as I don't have LÖVE and I obviously had to test the code.
Here's a quick "summary" of my thing's API, as it might be confusing in the beginning:
local hmm = DependenceTable() -- Create a new one
print(hmm.field) -- Would error, "field" doesn't exist yet
-- Sets the property 'idk' to 123.
-- Everything except functions and tables are "primitive".
-- They're like constants, they never change unless you do it.
hmm:Register("idk",123)
-- If you want to actually set a regular table/function, you
-- can register a random value, then do hmm.idk = func/table
-- (the "constructor registering" only happens during :Register())
-- Sets the field to a constructor, which first gets validated.
-- During registering, the constructor is already called once.
-- Afterwards, it'll get called when it has to update.
-- (Whenever 'idk' changes, since 'field' depends on 'idk' here)
hmm:Register("field",function(self) return self.idk+1 end)
-- This errors because 'nonexistant' isn't reigstered yet
hmm:Register("error",function(self) return self.nonexistant end)
-- Basicly calls hmm:Register() twice with key/value as parameters
hmm:RegisterAll{
lower = function(self) return self.field - 5 end;
higher = function(self) return self.field + 5 end;
}
-- This sets the property 'idk' to 5.
-- Since 'field' depends on this property, it'll also update.
-- Since 'lower' and 'higher' depend on 'field', they too.
-- (It happens in order, so there should be no conflicts)
hmm.idk = 5
-- This prints 6 since 'idk' is 5 and 'field' is idk+1
print(hmm.field)
You could use setfenv (if Lua 5.1) to remove the need of 'self.FIELD'. With some environment magic you can have the constructor for 'field' (as an example) just be function() return idk+1 end.
You could make use of metatables, more specific, the __newindex field:
(Well, need to combine it with the __index field, but eh)
function new(x, y, width, height )
local object = {
font = {}, padding = {}, text = {input=''}, -- tables themself are static
-- also I assume text.input will change and has to stay the way it is
}
-- more static data here (yes yes, I know. The code is a bit ugly, but if it works fine...)
object.config = { active = true, devmode = false, debug = false, id = gui.id(), type = 'textbox' }
object.backspace = {key = false, rate = 3, time = 0, pausetime = 20, pause = true}
object.border = { x = x, y = y, width = width, height = height }
-- stuff that has to be calculated from the above variables goes below
local border = object.border
local function calculate()
--border
--body
object.body = { x = border.x+1, y = border.y+1, width = border.width-2, height = border.height-2 }
--font
object.font.size = height-(math.floor(height/4)+1)
object.font.height = love.graphics.setNewFont( object.font.size ):getHeight()
--padding
object.padding.height = math.floor(object.border.height*(2/29))
object.padding.width = object.padding.height*3
--text
object.text.centerHeight = math.ceil(object.body.y+((object.body.height-object.font.height)/2))
object.text.left = object.body.x+object.padding.width+object.padding.height
--backspacing
--config
end
calculate()
local proxy = setmetatable({},{
__index = object; -- proxy.abc returns object.abc (to get width, use proxy.border.width)
__newindex = function(s,k,v)
-- fires whenever 'proxy[k] = v' is done
-- I assume you'll only change x/y/width/height, as other properties are dynamic
-- Doing 'proxy.x = 123' is the same as 'object.border.x = 123' + recalculating
object.border[k] = v -- Actually apply the change
calculate() -- Recalculate the other properties that depends on the above
end;
})
gui.add(object)
return object.config.id
end
You can run code like proxy.x = 12 to edit the X property. All values will be recalculated. It's not the best, but your code a tiny bit annoying to improve. (But hey, if it works fine for you, it's good)
Note: You can only set x, y, width and height. You can get all properties the old way though, e.g. proxy.padding.width (Mind that proxy.x doesn't work. Use proxy.border.x)

how to increase a variable which name You give

how do i create a function where i put the name of the variable I want to make Math with,
what i mean is :
so somewhere in a enterFrameFunction i call effectOne and give its 1st parameter to be with the name of "myGravity"
private function effectOne(TriggeringVariable:String, minYposition:Number = 300, maxYposition:Number = 100):Number
{
var myReturnVariable:Number = minYposition + maxYposition;
TriggeringVariable +=10;
if(TriggeringVariable > 980) TriggeringVariable = 980;
if(TriggeringVariable > 500) minYposition = minYposition / 2;
if(TriggeringVariable > 980) maxYposition = maxYposition / 2;
return myReturnVariable;
}
but it gives me ->
1067: Implicit coercion of a value of type String to an unrelated type Number.
how do i make this ?
you can do it like this:
this[triggeringVariable]+=10;
That will get the variable by the name you gave, so if triggeringVariable is "x", it will increase the x value of your instance.
But that will only work when that variable actually exists, and that cannot be checked at compile time. So if you make mistakes, you'll get runtime errors.

matlab functions

helo, I have the following function called stat.m
function [mean,stdev] = stat(x)
n = length(x)
mean = sum(x)/n
stdev = sqrt(sum((x-mean).^2/n))
I defined x as a vector which is [1,2,5,7,9]
how come when I type a = stat(x), matlab returns a = 5 for the last line at command prompt?
If you want to get both return values, you have to do this:
[a, b] = stat(x);
If you just do a = stat(x), MATLAB interprets that to mean that you only want the first return value.
because a gets the first argument mean
try to call it [a,b] = stat(x)