method to treat string as Object name in IO? - iolanguage

In Io, there is a getSlot() method which allows you to convert a string to a slot reference, but is there something similar to get a reference to an Object? For example:
myObject := Object clone
myObject myMethod := method("Hello World!" println)
targetObject := "myObject"
a := getObject(targetObject) clone
getObject() doesn't exist, so what can go in its place such that "a" ends up being a clone of "myObject"?

You actually answered yourself!
In Io you have objects which have slots, and these slots can be objects themselves.
So for your code to work properly you simply call getSlot on the current scope.
myObject := Object clone
myObject myMethod := method("Hello World!" println)
targetObject := "myObject"
a := getSlot(targetObject) clone
a myMethod
==> Hello World!

Related

Why is it allowed to put methods inside blocks, and statements inside objects in Scala?

I'm learning Scala and I don't really understand the following example :
object Test extends App {
def method1 = println("method 1")
val x = {
def method2 = "method 2" // method inside a block
"this is " + method2
}
method1 // statement inside an object
println(x) // same
}
I mean, it feels inconsistent to me because here I see two different concepts :
Objects/Classes/Traits, which contains members.
Blocks, which contains statements, the last statement being the value of the block.
But here we have a method part of a block, and statements part of an object. So, does it mean that blocks are objects too ? And how are handled the statements part of an object, are they members too ?
Thanks.
Does it mean that blocks are objects too?
No, blocks are not objects. Blocks are used for scoping the binding of variables. Scala enables not only defining expressions inside blocks but also to define methods. If we take your example and compile it, we can see what the compiler does:
object Test extends Object {
def method1(): Unit = scala.Predef.println("method 1");
private[this] val x: String = _;
<stable> <accessor> def x(): String = Test.this.x;
final <static> private[this] def method2$1(): String = "method 2";
def <init>(): tests.Test.type = {
Test.super.<init>();
Test.this.x = {
"this is ".+(Test.this.method2$1())
};
Test.this.method1();
scala.Predef.println(Test.this.x());
()
}
}
What the compiler did is extract method2 to an "unnamed" method on method2$1 and scoped it to private[this] which is scoped to the current instance of the type.
And how are handled the statements part of an object, are they members
too?
The compiler took method1 and println and calls them inside the constructor when the type is initialized. So you can see val x and the rest of the method calls are invoked at construction time.
method2 is actually not a method. It is a local function. Scala allows you to create named functions inside local scopes for organizing your code into functions without polluting the namespace.
It is most often used to define local tail-recursive helper functions. Often, when making a function tail-recursive, you need to add an additional parameter to carry the "state" on the call stack, but this additional parameter is a private internal implementation detail and shouldn't be exposed to clients. In languages without local functions, you would make this a private helper alongside the primary method, but then it would still be within the namespace of the class and callable by all other methods of the class, when it is really only useful for that particular method. So, in Scala, you can instead define it locally inside the method:
// non tail-recursive
def length[A](ls: List[A]) = ls match {
case Nil => 0
case x :: xs => length(xs) + 1
}
//transformation to tail-recursive, Java-style:
def length[A](ls: List[A]) = lengthRec(ls, 0)
private def lengthRec[A](ls: List[A], len: Int) = ls match {
case Nil => len
case x :: xs => lengthRec(xs, len + 1)
}
//tail-recursive, Scala-style:
def length[A](ls: List[A]) = {
//note: lengthRec is nested and thus can access `ls`, there is no need to pass it
def lengthRec(len: Int) = ls match {
case Nil => len
case x :: xs => lengthRec(xs, len + 1)
}
lengthRec(ls, 0)
}
Now you might say, well I see the value in defining local functions inside methods, but what's the value in being able to define local functions in blocks? Scala tries to as simple as possible and have as few corner cases as possible. If you can define local functions inside methods, and local functions inside local functions … then why not simplify that rule and just say that local functions behave just like local fields, you can simply define them in any block scope. Then you don't need different scope rules for local fields and local functions, and you have simplified the language.
The other thing you mentioned, being able to execute code in the bode of a template, that's actually the primary constructor (so to speak … it's technically more like an initializer). Remember: the primary constructor's signature is defined with parentheses after the class name … but where would you put the code for the constructor then? Well, you put it in the body of the class!

Pass copy of object to method

I've run into an issue where, when using a loop and passing an object into a method, my object is being modified when the method returns, breaking the next iteration.
The code I'm using is quite elaborate, so I'll simplify with the following:
val car: Car = expensiveMethod("greenCar")
for (i <- 1 to 5) {
foo(car)
}
def foo (car: Car) = {
assert(car.name == "greenCar")
car.name = "redCar"
}
expensiveMethod is, as it sounds, expensive, so I'd prefer not to call it inside the for loop every time.
Car is also not a case class, so I can't use the built in copy method.
Is there a simple way to send a copy of car into foo, or an alternate approach?
It may be that name member of your Car class is public and mutable.
Also from definition of foo function the signature is foo: (car: Car)Unit, which could mean that it is not a pure function, a side effecting function (or procedure) in this case as its modifying the parameter. You should explicitly create a copy of parameter and mutate the copy.

What is the shortest notation to define an operator as a method alias in Scala?

Given the generic register method below I would like to define the := operator as a symbolic alias.
def register[Prop <: Property[_]](prop: Prop): Prop
#inline
final def :=[Prop <: Property[_]] = register[Prop] _
Originally I wanted to write something like this:
val := = register _
But that gives me the function signature Nothing => Nothing. My next attempt was to parameterize it with the type Prop but that apparently works only if I make it a def, which can take type parameters and pass them onwards.
Ideally I would like to omit the #inline annotation but I am not sure what object code the Scala compiler makes out of it.
Most important my goal is it not to have the := method duplicate all parts of the register method's signature except for the name and then simply let the former delegate to the latter.
def :=[Prop <: Property[_]](prop: Prop) = register(prop)
should work.
I don't believe that there's any way to achieve what you're after (basically what alias gives you in Ruby) in Scala as it currently stands. The autoproxy plugin is an attempt to address this kind of problem, but it's not really ready for production use yet due to various issues with generating code in compiler plugins.
You can do this:
def := : Prop => Prop = register
So basically here you define a function of type (Prop => Prop) that just references another function.

Groovy 'def' keyword and scope problem in Eclipse

I'm following a groovy tutorial and there is a code like this:
def fruit = ["apple", "orange" , "pear"] //list
def likeIt = { String fruit -> println "I like " + fruit + "s" } //closure
fruit.each(likeIt)
Eclipse reports an error at closure definition line:
Line breakpoint:SimpleClosuresTest
[line: 27] The current scope already
contains a variable of the name fruit
# line 27, column 14.
If i omit 'def' from 'def fruit' Eclipse doesn't complaint and code runs fine.
Could someone explain what is going on with the scopes in both cases?
Thanks.
first a general review of a groovy script:
// file: SomeScript.groovy
x = 1
def x = 2
println x
println this.x
is roughly compiled as:
class SomeScript extends groovy.lang.Script {
def x
def run() {
x = 1
def x = 2
println x // 2
println this.x // 1
}
}
in a groovy script (roughly speaking, a file without the class declaration), assigning a value to an undefined variable is interpreted as a field assignment.
your example tries to defines a closure with a parameter named fruit.
if you defined fruit with the def keyword you get an error message because the name is already taken as a local variable, and you can't duplicate a local variable name.
when you leave the def keyword out, you are actually assigning the value to a field of the class generated for the script, and thus the name fruit can be redefined as a local variable.
regarding scopes, it's pretty much like java...
in the example, you can see x is defined first as a field and then as a variable local to the run() method. there's nothing wrong with that and you can access both the variable and the field.
but once you define a local variable, you cannot create duplicates.
edit --
had to add this before anyone gets me wrong: the translation is not exactly like this (thus the "roughly"). Instead of a field you add a value to the binding of the script, quite like args for commandline scripts or request, session or response for groovlets.
but that is much a longer story...
ok if you really want to know just ask again and i'll explain it better
edit 2 --
i just can't leave it like this, if you ever need more info...
every groovy script has a field named binding, an instance of groovy.lang.Binding or one of its a subclasses.
this binding is basically a map, with methods setVariable and setVariable.
when you omit the def keyword when assigning a value in a script you are actually calling the method setVariable, and when you do something like this.x you are calling the getVariable method.
this is actually because class groovy.lang.Script overrides the methods getProperty and setProperty to call those methods first. that's the reason they behave like fields.
you might have also noticed that there is no type associated to those variables... that's because we are dealing with just a Map inside the binding.
standard groovy scrips are created with an instance of a binding with the args set to the array of parameters.
others, like groovy.servlet.ServletBinding define more variables and behavior, like block the assignment of certain variables, or adding a lazy initialization capabilities...
then the real reason behind the error is... if the def keyword is not used, fruits is not a real variable. still, i believe the behavior is somewhat analog to a field.
sorry about all that.
i was not satisfied with my own oversimplification :S
That String fruit shouldn't be having the same name as your def fruit. (you are defining first a list and then a string with the same name)
def likeIt = { String fruit -> println "I like " + fruit + "s" }
In the second case you are defining the type of the variable with def a posteriori, so it works but it is not a good practice as far as I know.
I think that you don't even need to write ->. The groovy manual says that "The -> token is optional and may be omitted if your Closure definition takes fewer than two parameters", which is the case here.
Second line
String fruit
the same variable name 'fruit' is being used again

How to associate an iterator to a collection in OCaml

I have these two classes in OCaml
class type ['a] collection =
object
method add : 'a -> unit
method clear : unit -> unit
method iterator : unit -> 'a iterator
method remove : 'a -> unit
end
class type ['a] iterator =
object
method hasNext : unit -> bool
method next : unit -> 'a
end
And I need to create two concrete classes ['a] queue subtype of collection and ['a] iterator_queue a subtype of iterator.
I want mainly to know how to define the method iterator : unit -> 'a iterator because I don't see how the two types can be connected, Does the ['a] iterator_queue has to be inherited from both the abstract ones? or should I proceed differently.
Probably the easiest way to do this is to define the iterator as an object within the scope of the definition of the queue (in Java, this would be called an "inner class"). For example:
class ['a] queue : ['a] collection =
object
val q = ref []
(* definitions of add, clear, remove *)
method iterator () : 'a iterator =
object
val lst = ref !q
(* definitions of hasNext and next *)
end
end
Note that lst is a reference to the (immutable) value of q at the time that iterator is called. Subsequent changes to the queue won't be reflected in the iterator.
I suspect this might simply be a test of mutually recursive class definitions.
class ['a] queue =
object
inherit 'a container
method iterator = new iterator_queue args
...
end
and ['a] iterator_queue args =
object
...
end