Namespaces for functions and variables in Swift - swift

If you run this code, the variable f seems to shadow the function f. Is there anyway to reach the function f?
func f (a:Int)->Int{
return a + 43
}
var f = {(a:Int) in a + 42}
var z = f(1)
println(z)

No.
In Swift, function declarations are simply shortcuts for what you did with that closure + variable thing. That is, function names are essentially constants and should always be viewed as such (you can even pass around the function name, without brackets, as a reference).
What you're doing is you're redeclaring the name f to the variable closure. It seems Swift has a compiler issue not complaining about this. However, this problem would never occur in good code, so it's not a real problem.
It can be a bit confusing, though.

Related

Inheritance with hump in love2D

I'm trying to do OOP using the hump library in Lua for a game coded in löve 2D. Everything is working fine. However, when I try to play with my code the way bellow, a message error tells me that "self" is a nill value. Can someone tell me what I did wrong please?
Item=Class{
init=function(x,y,size)
self.x=x
self.y=y
self.size=size
self.dx=dx
self.dy=dy
self.dx2=dx2
self.dy2=dy2
end;
update=function(dt)
self.dx=self.dx+self.dx2
self.x=self.x+self.dx*dt
self.dy=self.dy+self.dy2
self.y=self.y+self.dy*dt
end;
coliide=function(ball)
return math.sqrt((self.x-ball.x)^2+(self.y-ball.y)^2)<self.size
end;
reset=function()
self.x=love.graphics.getWidth()/2
self.y=love.graphics.getHeight()/2
self.dy=0
self.dx=0
self.dy2=0
self.dx2=0
end
}
Thank you and regards
In the given snippet
Item = Class{}
Item.init=function(x,y,size)
self.x = x
end
self is nil because you did not define it.
In order to do what you want you have to define the function like that:
Item.init = function(self, x, y, size)
self.x = x
end
and call it like that
Item.init(Item, x, y, size)
Then self equals Item and you may index it without an error.
To make this a bit more convenient we can use something called Syntactic Sugar
Let's have a look into the Lua 5.3 Reference Manual:
3.4.10 - Function Calls
A call v:name(args) is syntactic sugar for v.name(v,args), except that
v is evaluated only once.
3.4.11 - Function Definitions
The colon syntax is used for defining methods, that is, functions that
have an implicit extra parameter self. Thus, the statement
function t.a.b.c:f (params) body end
is syntactic sugar for
t.a.b.c.f = function (self, params) body end
Using this knowledge we can simply write:
function Item:init(x,y,size)
self.x = x
end
and call it like so:
Item:init(x,y)
The implicit self argument is available to function when it was declared using colon syntax. E.g.:
Item=Class{}
function Item:init(x,y,size)
self.x = x
self.y = y
-- ...
end
Alternatively you could just add self argument explicitly in your existing code. Just make sure you're calling it with colon syntax.

Are Scala closures as flexible as C++ lambdas?

I know the question seems a bit heretical. Indeed, having much appreciated lambdas in C++11, I was quite thrilled to learn a language which was built to support them from the beginning rather than as a contrived addition.
However, I cannot figure out how to do with Scala all I can do with C++11 lambdas.
Suppose I want to make a function which adds to a number passed as a parameter some value contained in a variable a. In C++, I can do both
int a = 5;
auto lambdaVal = [ a](int par) { return par + a; };
auto lambdaRef = [&a](int par) { return par + a; };
Now, if I change a, the second version will change its behavior; but the first will keep adding 5.
In Scala, if I do this
var a = 5
val lambdaOnly = (par:Int) => par + a
I essentially get the lambdaRef model: changing a will immediately change what the function does.
(which seems somewhat specious to me given that this time a isn't even mentioned in the declaration of the lambda, only in its code. But let it be)
Am I missing the way to obtain lambdaVal? Or do I have to first copy a to a val to be free to modify it afterwards without side effects?
The a in the function definition refers the variable a. If you want to use the current value of a when the lambda has been created, you have to copy the value like this:
val lambdaConst = {
val aNow = a
(par:Int) => par + aNow
}

Swift Hoisting? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
As everyone knows, JavaScript "Hoists" the variables to the top of the file or scope. But from my understanding, using let is the same as var only let is confined to the scope it is defined in.
Being a compiled language instead of an interpreted, can we assume Swift does NOT do this?
For example:
x = 10
var y = x + 10
var x
can we assume Swift does NOT do this?
You can assume whatever you want, but no matter the programming language, your absolute best bet it to just try it and find out. If you would have pasted your sample code into a Playground or in any Swift-capable IDE, or just tried running it through the command line, you'd quickly find out that this simply does not work.
Your question is somewhat confusing, but I think I can address all or at least most of your questions.
x = 10
var y = x + 10
var x
Assuming there is no other code to go with your original sample, it simply does not compile. All three lines have a problem.
The first two lines complain about the use of an unresolved identified 'x'. In English, this means Swift can't figure out what variable you're talking about. Variables in Swift must be declared before they are used, so the declaration on line three doesn't help the next two lines.
The third line complains that it can't figure out what type x should be. "Type annotation missing in pattern". In some cases, Swift can figure out what type our variable should be. For example, with var x = 10, Swift can figure out that x's type should be Int. If we want something else, we must specify. But if we aren't assigning a value in the declaration, Swift has no idea and must be told: var x: Int?
What about the case where x exists at a different scope?
Well, Swift allows variable shadowing. That is to say, a variable declared at one scope hides a variable declared at another scope.
So, for example:
class Foo {
let x = 10
func foo(value: Int) -> Int {
let a = value * self.x
let x = 10
return a * x
}
}
Now we can use some x before we've declared a locally scoped x, but these are different variables. Also, perhaps most importantly, notice the self. prepended to x here. It's required. Without it, Swift will refuse to compile this code and will complain: "Use of local variable 'x' before its declaration."
However, within functions of classes is not the only place we can shadow variables. We can also do it within if blocks (among other places) which is where things can get a little more confusing. Consider this:
class Foo {
let x = 10
func foo(value: Int) -> Int {
print(x)
if x > 3 {
let x = 2
print(x)
}
return x
}
}
Here, we've used x twice before declaring it. And we didn't have to make use of the self. and it doesn't complain and compiles perfectly fine. But it's important to note that outside the if block (including the x > 3 conditional) the x we're referencing is the instance variable, but inside the if block, we've created a new variable called x which shadows the instance variable. We can also create the same sort of shadowing by using if let and if var constructs (but not guard let).
The result of calling this function will be that the value 10 is printed, we enter the if block, the value of 2 is printed, then we exit the if block and the value of 10 is returned.
Now let's through var into the mix here. First, if you aren't already aware, you should start by reading this which explains the difference between let and var (one is a constant, the other is not).
Let's combine let vs var with scoping and variable shadowing to see how it effects things.
class Foo {
let x = 10
func foo(value: Int) -> Int {
print(x)
if x > 3 {
var x = 2
while x < 10 {
print(x)
x += 3
}
return x
}
return x
}
}
Okay, so this is the same as before but with a slightly more complicated bit within the if block.
Here, our locally-scoped variable is declared as a var while our instance variable remains a constant let. We cannot modify the instance variable, but we can modify the local variable. And we do so, on each iteration of the while loop.
But importantly, this variable is an entirely different variable from the instance variable. It might as well have a completely different name (and in practice, it basically always should have a different name). So modifying our local variable x doesn't change anything about our more broadly scoped instance variable x. They're different variables that reside in different memory locations. And once a variable is declared as a let or a var, that variable cannot be changed to the other.
'let' and 'var' do not have a difference in scope.
Global variables are variables that are defined outside of any
function, method, closure, or type context. Local variables are
variables that are defined within a function, method, or closure
context.

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.

Scala closures on wikipedia

Found the following snippet on the Closure page on wikipedia
//# Return a list of all books with at least 'threshold' copies sold.
def bestSellingBooks(threshold: Int) = bookList.filter(book => book.sales >= threshold)
//# or
def bestSellingBooks(threshold: Int) = bookList.filter(_.sales >= threshold)
Correct me if I'm wrong, but this isn't a closure? It is a function literal, an anynomous function, a lambda function, but not a closure?
Well... if you want to be technical, this is a function literal which is translated at runtime into a closure, closing the open terms (binding them to a val/var in the scope of the function literal). Also, in the context of this function literal (_.sales >= threshold), threshold is a free variable, as the function literal itself doesn't give it any meaning. By itself, _.sales >= threshold is an open term At runtime, it is bound to the local variable of the function, each time the function is called.
Take this function for example, generating closures:
def makeIncrementer(inc: Int): (Int => Int) = (x: Int) => x + inc
At runtime, the following code produces 3 closures. It's also interesting to note that b and c are not the same closure (b == c gives false).
val a = makeIncrementer(10)
val b = makeIncrementer(20)
val c = makeIncrementer(20)
I still think the example given on wikipedia is a good one, albeit not quite covering the whole story. It's quite hard giving an example of actual closures by the strictest definition without actually a memory dump of a program running. It's the same with the class-object relation. You usually give an example of an object by defining a class Foo { ... and then instantiating it with val f = new Foo, saying that f is the object.
-- Flaviu Cipcigan
Notes:
Reference: Programming in Scala, Martin Odersky, Lex Spoon, Bill Venners
Code compiled with Scala version 2.7.5.final running on Java 1.6.0_14.
I'm not entirely sure, but I think you're right. Doesn't a closure require state (I guess free variables...)?
Or maybe the bookList is the free variable?
As far as I understand, this is a closure that contains a formal parameter, threshold and context variable, bookList, from the enclosing scope. So the return value(List[Any]) of the function may change while applying the filter predicate function. It is varying based on the elements of List(bookList) variable from the context.