How can I lazily load a Perl variable? - perl

I have a variable that I need to pass to a subroutine. It is very possible that the subroutine will not need this variable, and providing the value for the variable is expensive. Is it possible to create a "lazy-loading" object that will only be evaluated if it is actually being used? I cannot change the subroutine itself, so it must still look like a normal Perl scalar to the caller.

You'll want to look at Data::Lazy and Scalar::Defer. Update: There's also Data::Thunk and Scalar::Lazy.
I haven't tried any of these myself, but I'm not sure they work properly for an object. For that, you might try a Moose class that keeps the real object in a lazy attribute which handles all the methods that object provides. (This wouldn't work if the subroutine does an isa check, though, unless it calls isa as a method, in which case you can override it in your class.)

Data::Thunk is the most transparent and robust way of doing this that i'm aware of.
However, I'm not a big fan of it, or any other similar modules or techniques that try to hide themself from the user. I prefer something more explicit, like having the code using the value that's hard to compute simply call a function to retrieve it. That way you don't need to precompute your value, your intent is more clearly visible, and you can also have various options to avoid re-computing the value, like lexical closures, perl's state variables, or modules like Memoize.

You might look into tying.

I would suggest stepping back and rethinking how you are structuring your program. Instead of passing a variable to a method that it might not need, make that value available in some other way, such as another method call, that can be called as needed (and not when it isn't).
In Moose, data like this is ideally stored in attributes. You can make attributes lazily built, so they are not calculated until they are first needed, but after that the value is saved so it does not need to be calculated a second time.

Related

Scala legacy code: how to access input parameters at different points in execution path?

I am working with a legacy scala codebase, and as is always the case modifying the code is quite difficult without touching different parts.
One of my new requirement in to make several decisions based on some input parameters. Problem is that these decisions are to be made at various points along the execution. So either I encapsulate all those parameters in a case class instance and pass it along. But it means I would have to modify multiple methods signatures, and I want to avoid this approach as much as possible.
Another approach can be to create a global object containing all those input parameters and accessible from different points in the execution. Is it a good approach in Scala?
No, using global mutable variables to pass “hidden” parameters is not a good idea, not in Scala and not in any other programming language. It makes the code hard to understand and modify, because a function's behaviour will now depend on which functions were invoked earlier. And it's extremely fragile, because you might forget setting one of those global parameters before invoking the function, which means that it will use whatever value was stored there before. This is the kind of thing that can appear to work for years, and then break when you modify a completely unrelated part of the program.
I can't stress this enough: do not use global mutable variables, period. The solution is to man up and change those method signatures. Depending on the details, dependency injection may or may not help in your particular case.

Where to define typecast to struct in MATLAB OOP?

In the MATLAB OOP framework, it can be useful to cast an object to a struct, i.e., define a function that takes an object and returns a struct with equivalent fields.
What is the appropriate place to do this? I can think of several options:
Build a separate converter object that takes care of conversions between various classes
Add a function struct to the class that does the conversion to struct, and make the constructor accept structs
Neither option seems to be very elegant: the first means that logic about the class itself is moved to another class. On the other hand, in the second case, it provokes users to use the struct function for any object, which will in general give a warning (structOnObject).
Are there altenatives?
Personally I'd go with the second option, and not worry about provoking users to call struct on other classes; you can only worry about your own code, not that of a third-party, even if the third party is MathWorks. In any case, if they do start to call struct on an arbitrary class, it's only a warning; nothing actually dangerous is likely to happen, it's just not a good practice.
But if you're concerned about that, you can always call your converter method toStruct rather than struct. Or perhaps the best (although slightly more complex) way might be to overload cast for your class, accepting and handling the option 'struct', and passing any other option through to builtin('cast',....
PS The title of your question refers to typecasting, but what your after here is casting. In MATLAB, typecasting is a different operation, involving taking the exact bits of one type and reinterpreting them as bits of another type (possibly an array of the output type). See doc cast and doc typecast for more information on the distinction.
The second option sounds much better to me.
A quick and dirty way to get rid of the warning would be disabling it by calling
warning('off', 'MATLAB:structOnObject')
at the start of your program.
The solutions provided in Sam Roberts' answer are however much cleaner. I personally would go for the toStruct() method.

Overloading '=' in Perl

Since simply overloading '=' in Perl does not act as one would expect, what is the proper way to do this?
Quote from overload perldoc:
Simple assignment is not overloadable (the '=' key is used for the Copy Constructor). Perl does have a way to make assignments to an object do whatever you want, but this involves using tie(), not overload - see tie and the COOKBOOK examples below.
I have read through the COOKBOOK and the documentation for tie and am having trouble figuring out how you could use it in this way.
I want to be able to create an object like so: my $object = Object->new() Then when I assign it to something I want it to do some special processing.
For example: $object = 3 would internally do something like $object->set_value(3);
I know this isn't necessarily good practice. This is more of an educational question. I just want to know how this can be done. Not whether it should be done.
You can't do that. You can add magic to a variable so that a sub is called after a value is assigned to the variable, but that's a far cry from what you asked.
Besides, what you asked doesn't really make sense. What should the following do?
my $object;
$object = Object->new();
$object = Object->new();
The perl documentation quoted above is somewhat poorly worded. There is no way to overload assignment into some storage location (i.e. variable) that currently contains some specific object or other; the current value of a variable is never important for assignment.
However, what you can do is add magic to that variable directly, that captures the attempt to store into it (SET magic, implemented by the STORE method of the tied class). But it is important to realise this is magic on the variable itself, and not the value that it currently contains.

Why to use empty parentheses in Scala if we can just use no parentheses to define a function which does not need any arguments?

As far as I understand, in Scala we can define a function with no parameters either by using empty parentheses after its name, or no parentheses at all, and these two definitions are not synonyms. What is the purpose of distinguishing these 2 syntaxes and when should I better use one instead of another?
It's mostly a question of convention. Methods with empty parameter lists are, by convention, evaluated for their side-effects. Methods without parameters are assumed to be side-effect free. That's the convention.
Scala Style Guide says to omit parentheses only when the method being called has no side-effects:
http://docs.scala-lang.org/style/method-invocation.html
Other answers are great, but I also think it's worth mentioning that no-param methods allow for nice access to a classes fields, like so:
person.name
Because of parameterless methods, you could easily write a method to intercept reads (or writes) to the 'name' field without breaking calling code, like so
def name = { log("Accessing name!"); _name }
This is called the Uniform Access Principal
I have another light to bring to the usefulness of the convention encouraging an empty parentheses block in the declaration of functions (and thus later in calls to them) with side effects.
It is with the debugger.
If one add a watch in a debugger, such as, say, process referring for the example to a boolean in the focused debug context, either as a variable view, or as a pure side-effect free function evaluation, it creates a nasty risk for your later troubleshooting.
Indeed, if the debugger keeps that watch as a try-to-evaluate thing whenever you change the context (change thread, move in the call stack, reach another breakpoint...), which I found to be at least the case with IntelliJ IDEA, or Visual Studio for other languages, then the side-effects of any other process function possibly found in any browsed scope would be triggered...
Just imagine the kind of puzzling troubleshooting this could lead to if you do not have that warning just in mind, because of some innocent regular naming. If the convention were enforced, with my example, the process boolean evaluation would never fall back to a process() function call in the debugger watches; it might just be allowed in your debugger to explicitly access the () function putting process() in the watches, but then it would be clear you are not directly accessing any attribute or local variables, and fallbacks to other process() functions in other browsed scopes, if maybe unlucky, would at the very least be very less surprising.

iPhone -- context parameters vs. global variables

In my iPhone development, I've always used global variables for lots of stuff. The style guide in my new job says we should use context parameters instead. So I need to figure out what that means and how to do that.
Can anyone explain in more detail what this means -- or point me to some code that works this way?
Thanks
It sounds like there may be a clash in nomenclature. From this definition of Context Parameters, they seem to be concerned storing global state for the duration of a session. Perhaps, you could use a 'contextParameters' NSDictionary within NSUserDefaults to store your globals. To the extent that your globals might need to be exported in their entirety (for debugging, for state saving) this might be useful in the long run.
The style guide might just be generically saying to keep your variables scoped based on the context of their usage. For example if you have a variable that you need for the lifetime of a class instance then make it a member variable of that class. If it is something that you need for the lifetime of the app then put it in an application wide object (but not a global variable).
If you use a global object (which could mostly be a big C struct containing all your former global variables) instead of individual naked global variables, you might be able to copy the object, serialize it to save it or create a unified core dump, eventually add setters/listeners, etc.
If you break the global object up, based on the shared scope or the required context of groupings of instance/struct variables, then the fractional objects might end up being good candidates for the M portion of an MVC repartitioning of your code for better reuse, extensibility, etc.